diff --git a/projects/checkstyle.xml b/projects/checkstyle.xml index 3401cf5..72e7ecc 100644 --- a/projects/checkstyle.xml +++ b/projects/checkstyle.xml @@ -88,85 +88,85 @@ - - - - - - - - - + + + + + + + + + - - - + + + - - - - - + + + + + - - - - - - - - - - + + + + + + + + + + - - + + - - - - - + + + + + - - - - - - - - - - + + + + + + + + + + - - + + - - + + - + - - - + + + diff --git a/projects/pom.xml b/projects/pom.xml index 5d14966..511d9d4 100644 --- a/projects/pom.xml +++ b/projects/pom.xml @@ -30,6 +30,7 @@ dkhurtin ale3otik Pitovsky + simon23rus diff --git a/projects/simon23rus/dbTask.mv.db b/projects/simon23rus/dbTask.mv.db new file mode 100644 index 0000000..7215bfd Binary files /dev/null and b/projects/simon23rus/dbTask.mv.db differ diff --git a/projects/simon23rus/dbTask.trace.db b/projects/simon23rus/dbTask.trace.db new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/projects/simon23rus/dbTask.trace.db @@ -0,0 +1 @@ + diff --git a/projects/simon23rus/pom.xml b/projects/simon23rus/pom.xml new file mode 100644 index 0000000..d243e87 --- /dev/null +++ b/projects/simon23rus/pom.xml @@ -0,0 +1,113 @@ + + 4.0.0 + + + ru.mipt.diht.students + parent + 1.0-SNAPSHOT + + + ru.mipt.diht.students + simon23rus + 1.0-SNAPSHOT + simon23rus + http://maven.apache.org + + + + + + org.twitter4j + twitter4j-core + [4.0,) + + + + org.twitter4j + twitter4j-stream + [4.0,) + + + + com.beust + jcommander + 1.48 + + + + junit + junit + 4.12 + test + + + + org.mockito + mockito-core + 1.10.8 + test + + + objenesis + org.objenesis + + + + + com.h2database + h2 + 1.4.190 + + + com.google.guava + guava + 19.0 + + + org.powermock + powermock-module-junit4 + 1.6.1 + test + true + + + + org.powermock + powermock-api-mockito + 1.6.1 + test + true + + + mockito-all + org.mockito + + + + + + + commons-io + commons-io + 2.4 + test + + + + + + + maven-compiler-plugin + 3.1 + + 1.8 + 1.8 + + + + + mipt + + + diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/data/Aggregates.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/data/Aggregates.java new file mode 100644 index 0000000..4b2dd74 --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/data/Aggregates.java @@ -0,0 +1,60 @@ +package ru.mipt.diht.students.simon23rus.CQL.data; + +import ru.mipt.diht.students.simon23rus.CQL.implOfAggregators.Avg; +import ru.mipt.diht.students.simon23rus.CQL.implOfAggregators.Count; +import ru.mipt.diht.students.simon23rus.CQL.implOfAggregators.Max; +import ru.mipt.diht.students.simon23rus.CQL.implOfAggregators.Min; + +import java.util.function.Function; + +/** + * Aggregate functions. + */ +public class Aggregates { + + /** + * Maximum value for expression for elements of given collecdtion. + * + * @param expression + * @param + * @return + */ + public static Function max(Function expression) { + return new Max<>(expression); + } + + /** + * Minimum value for expression for elements of given collecdtion. + * + * @param expression + * @param + * @param + * @return + */ + public static > Function min(Function expression) { + return new Min<>(expression); + } + + /** + * Number of items in source collection that turns this expression into not null. + * + * @param expression + * @param + * @return + */ + public static Function count(Function expression) { + return new Count<>(expression); + } + + /** + * Average value for expression for elements of given collection. + * + * @param expression + * @param + * @return + */ + public static Function avg(Function expression) { + return new Avg<>(expression); + } + +} diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/data/CollectionQuery.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/data/CollectionQuery.java new file mode 100644 index 0000000..5606fc3 --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/data/CollectionQuery.java @@ -0,0 +1,179 @@ +package ru.mipt.diht.students.simon23rus.CQL.data; + +import ru.mipt.diht.students.simon23rus.CQL.impl.*; +import static ru.mipt.diht.students.simon23rus.CQL.data.Sources.list; + +import java.lang.reflect.InvocationTargetException; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; +import java.util.Objects; + +//import static ru.mipt.diht.students.simon23rus.data.CollectionQuery.Student.student; + + +public class CollectionQuery { + + +// +// public static void main(String[] args) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { +// +//// Iterable> mentorsByStudent = +//// FromStmt.from(list(Student.student("ivanov", LocalDate.parse("1985-08-06"), "494"))) +//// .join(list(new Group("494", "mr.sidorov"))) +//// .on((s, g) -> Objects.equals(s.getGroup(), g.getGroup())) +//// .select(sg -> sg.getFirst().getName(), sg -> sg.getSecond().getMentor()) +//// .execute(); +//// System.out.println(mentorsByStudent); +// } + + + public static class Student { + private final String name; + + private final LocalDate dateOfBirth; + + private final String group; + + public Student(String name, LocalDate dateOfBirth, String group) { + this.name = name; + this.dateOfBirth = dateOfBirth; + this.group = group; + } + + public Student(String name, String group) { + this.name = name; + this.group = group; + this.dateOfBirth = LocalDate.now(); + } + + public String getName() { + return name; + } + + public LocalDate getDateOfBirth() { + return dateOfBirth; + } + + public String getGroup() { + return group; + } + + public Double age() { + return ((double) ChronoUnit.YEARS.between(getDateOfBirth(), LocalDateTime.now())); + } + + public static Student student(String name, LocalDate dateOfBith, String group) { + return new Student(name, dateOfBith, group); + } + + @Override + public String toString() { + StringBuilder toReturn = new StringBuilder("Students{"); + if(!group.equals(0)) { + toReturn.append("group=").append(this.group).append(","); + } + if(!name.equals(0)) { + toReturn.append("name=").append(this.name).append(","); + } + if(!dateOfBirth.equals(0)) { + toReturn.append("dateOfBirth=").append(this.dateOfBirth).append(","); + } + toReturn.append("}"); + return toReturn.toString(); + } + } + + + public static class Statistics { + + private final String group; + private final Long count; + private final Double age; + + public String getGroup() { + return group; + } + + public Long getCount() { + return count; + } + + public Double getAge() { + return age; + } + + public Statistics(String group, Long count, Double age) { + this.group = group; + this.count = count; + this.age = age; + } + + public Statistics(String group, Long count) { + this(group, count, 18D); + } + + public Statistics(String group, Double age) { + this(group, 1L, age); + } + + public Statistics(String group) { + this(group, 1L, 2D); + } + + public Statistics(Double age) { + this("sad", 0L, age); + } + + @Override + public String toString() { + StringBuilder toReturn = new StringBuilder("Statistics{"); + if(!group.equals(0)) { + toReturn.append("group= ").append(this.group).append(""); + } + if(!count.equals(0)) { + toReturn.append("count= ").append(this.count).append(""); + } + if(!age.equals(0)) { + toReturn.append("age= ").append(this.age).append(""); + } + toReturn.append("}"); + return toReturn.toString(); + } + } + + public static class Group { + private final String group; + private final String mentor; + + public Group(String myGroup, String myMentor) { + this.group = myGroup; + this.mentor = myMentor; + } + + public String getGroup() { + return group; + } + + public String getMentor() { + return mentor; + } + public static Group group(String myGroup, String myMentor) { + return new Group(myGroup, myMentor); + } + + @Override + public String toString() { + StringBuilder result = new StringBuilder().append("Student{"); + if (group != null) { + result.append("group=").append(group).append(","); + } + if (mentor != null) { + result.append(", name=").append(mentor); + } + result.append("}\n"); + return result.toString(); + } + } + +} diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/data/Conditions.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/data/Conditions.java new file mode 100644 index 0000000..4bb81eb --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/data/Conditions.java @@ -0,0 +1,36 @@ +package ru.mipt.diht.students.simon23rus.CQL.data; + +import java.util.function.Function; +import java.util.function.Predicate; + +/** + * Where clause conditions. + */ +public class Conditions { + + /** + * Matches string result of expression against regexp pattern. + * + * @param expression expression result to match + * @param regexp pattern to match to + * @param source object type + * @return + */ + public static Predicate rlike(Function expression, String regexp) { + return elem -> expression.apply(elem).matches(regexp); + } + + /** + * Matches string result of expression against SQL like pattern. + * + * @param expression expression result to match + * @param pattern pattern to match to + * @param source object type + * @return + + */ +// public static Predicate like(Function expression, String pattern) { +// return Predicate.isEqual() +// } + +} diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/data/OrderByConditions.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/data/OrderByConditions.java new file mode 100644 index 0000000..99c905e --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/data/OrderByConditions.java @@ -0,0 +1,35 @@ +package ru.mipt.diht.students.simon23rus.CQL.data; + +import java.util.Comparator; +import java.util.function.Function; + +/** + * OrderBy sort order helper methods. + */ +public class OrderByConditions { + + /** + * Ascending comparator. + * + * @param expression + * @param + * @param + * @return + */ + public static > Comparator asc(Function expression) { + return (o1, o2) -> expression.apply(o1).compareTo(expression.apply(o2)); + } + + /** + * Descending comparator. + * + * @param expression + * @param + * @param + * @return + */ + public static > Comparator desc(Function expression) { + return (o1, o2) -> expression.apply(o2).compareTo(expression.apply(o1)); + } + +} diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/data/Sources.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/data/Sources.java new file mode 100644 index 0000000..ac22549 --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/data/Sources.java @@ -0,0 +1,49 @@ +package ru.mipt.diht.students.simon23rus.CQL.data; + +import java.util.Arrays; +import java.util.List; + +/** + * Helper methods to create collections. + */ +public class Sources { + + /** + * @param items + * @param + * @return + */ + @SafeVarargs + public static List list(T... items) { + return Arrays.asList(items); + } + +// /** +// * @param items +// * @param +// * @return +// */ +// @SafeVarargs +// public static Set set(T... items) { +// throw new UnsupportedOperationException(); +// } +// +// /** +// * @param inputStream +// * @param +// * @return +// */ +// public static Stream lines(InputStream inputStream) { +// throw new UnsupportedOperationException(); +// } +// +// /** +// * @param file +// * @param +// * @return +// */ +// public static Stream lines(Path file) { +// throw new UnsupportedOperationException(); +// } +// +} diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/impl/BestComparatorEver.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/impl/BestComparatorEver.java new file mode 100644 index 0000000..6dcbc1d --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/impl/BestComparatorEver.java @@ -0,0 +1,24 @@ +package ru.mipt.diht.students.simon23rus.CQL.impl; + +import java.util.Comparator; + +public class BestComparatorEver implements Comparator { + Comparator[] currentComparators; + + BestComparatorEver(Comparator... givenComparators) { + currentComparators = givenComparators; + } + + @Override + public int compare(R first, R second) { + for(Comparator thisComparator : currentComparators) { + int comparisonResult = thisComparator.compare(first, second); + if(comparisonResult != 0) { + return comparisonResult; + } + } + + return 0; + } + +} diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/impl/FromStmt.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/impl/FromStmt.java new file mode 100644 index 0000000..218f8f4 --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/impl/FromStmt.java @@ -0,0 +1,92 @@ +package ru.mipt.diht.students.simon23rus.CQL.impl; + +import java.util.*; +import java.util.function.BiPredicate; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + + +public class FromStmt { + + private List data = new ArrayList(); + + public List getData() { + return data; + } + + public FromStmt(Iterable toIterate) { + toIterate.forEach(e -> data.add(e)); + } + + public FromStmt(Stream myStream) { + myStream.forEach(e -> data.add(e)); + } + + + public static FromStmt from(Iterable iterable) { + return new FromStmt(iterable); + } + + public static FromStmt from(Stream stream) { + return new FromStmt(stream); + } + + @SafeVarargs + public final SelectStmt select(Class clazz, Function... s) { + return new SelectStmt<>(data, clazz, false, s); + } + + @SafeVarargs + public final SelectStmt selectDistinct(Class clazz, Function... s) { + return new SelectStmt<>(data, clazz, true, s); + } + + public final SelectStmt> select(Function first, Function second) { + return new SelectStmt<>(data, false, first, second); + } + + public JoinClause join(Iterable iterable) { + return new JoinClause(data, iterable); + } + + public class JoinClause { + + private List firstElements = new ArrayList<>(); + private List secondElements = new ArrayList<>(); + private List> joinedElements = new ArrayList<>(); + + public JoinClause(List firstElements, Iterable secondElements) { + this.firstElements + .addAll(firstElements.stream() + .collect(Collectors.toList())); + for (J curr : secondElements) { + this.secondElements.add(curr); + } + } + + public FromStmt> on(BiPredicate condition) { + firstElements.forEach(first -> + secondElements.forEach(second -> { + if (condition.test(first, second)) { + this.joinedElements.add(new Tuple<>(first, second)); + } + })); + return new FromStmt<>(joinedElements); + } + + public > FromStmt> on( + Function leftKey, + Function rightKey) { + Map> leftMap = firstElements.stream().collect(Collectors.groupingBy(leftKey)); + Map> rightMap = secondElements.stream().collect(Collectors.groupingBy(rightKey)); + leftMap.forEach((key, value) -> { + if (rightMap.containsKey(key)) { + value.forEach(fst -> rightMap.get(key).forEach(snd -> joinedElements.add(new Tuple(fst, snd)))); + } + }); + return new FromStmt<>(joinedElements); + } + } + +} diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/impl/SelectStmt.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/impl/SelectStmt.java new file mode 100644 index 0000000..e8cfe89 --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/impl/SelectStmt.java @@ -0,0 +1,253 @@ +package ru.mipt.diht.students.simon23rus.CQL.impl; + +import javafx.util.Pair; +import ru.mipt.diht.students.simon23rus.CQL.implOfAggregators.Aggregator; + +import java.lang.reflect.InvocationTargetException; +import java.util.*; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class SelectStmt { + public boolean isDistinct; + public boolean isUnion; + public boolean isJoin; + int maxRawsNeeded; + Predicate whereRestriction; + Predicate havingRestriction; + Function[] currentFunctions; + Function[] groupByExpressions; + Class toReturn; + Comparator[] orderByComparators; + BestComparatorEver bestComparatorEver; + List oldData; + List currentData; + Stream toStream; + + @SafeVarargs + public SelectStmt(List elements, Class returnClass, boolean isDistinct, Function... functions) { + this.oldData = new ArrayList<>(); + this.currentData = elements; + this.toReturn = returnClass; + this.isDistinct = isDistinct; + this.currentFunctions = functions; + this.maxRawsNeeded = -1; + this.isUnion = false; + this.isJoin = false; + } + + public SelectStmt(List elements, boolean isDistinct, Function first, Function second) { + this.oldData = new ArrayList<>(); + this.currentData = elements; + this.toReturn = elements.get(0).getClass(); + this.isDistinct = isDistinct; + this.currentFunctions = new Function[]{first, second}; + this.maxRawsNeeded = -1; + this.isUnion = false; + this.isJoin = true; + } + + @SafeVarargs + public SelectStmt(List pastElements, List elements, Class returnClass, + boolean isDistinct, Function... functions) { + this.currentData = elements; + this.toReturn = returnClass; + this.isDistinct = isDistinct; + this.currentFunctions = functions; + this.maxRawsNeeded = -1; + this.isUnion = true; + this.isJoin = false; + this.oldData = pastElements; + } + + public SelectStmt(List pastElements, List elements, boolean isDistinct, Function first, + Function second) { + this.currentData = elements; + this.toReturn = elements.get(0).getClass(); + this.isDistinct = isDistinct; + this.currentFunctions = new Function[]{first, second}; + this.maxRawsNeeded = -1; + this.isUnion = true; + this.isJoin = true; + this.oldData = pastElements; + } + + public int getMaxRawsNeeded() { + return maxRawsNeeded; + } + + public Class getToReturn() { + return toReturn; + } + + public Function[] getCurrentFunctions() { + return currentFunctions; + } + + public List getCurrentData() { + return currentData; + } + + + + public SelectStmt where(Predicate predicate) { + this.whereRestriction = predicate; + return this; + } + + public Iterable execute() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { + List execResult = new ArrayList<>(); + Class[] returnClasses = new Class[currentFunctions.length]; + Object[] arguments = new Object[currentFunctions.length]; + if(whereRestriction != null) { + //nuzhno otfiltrovat' dannie; + List filteredData = currentData.stream() + .filter(whereRestriction::test) + .collect(Collectors.toList()); + currentData = filteredData; + } + if(groupByExpressions != null) { + Map mapped = new HashMap<>(); + List> groupedElements = new ArrayList<>(); + List> grouped = new ArrayList<>(); + String[] results = new String[groupByExpressions.length]; + currentData.stream().forEach( + element -> { + for (int i = 0; i < groupByExpressions.length; i++) { + results[i] = (String) groupByExpressions[i].apply(element); + } + if (!mapped.containsKey(Objects.hash(results))) { + mapped.put(Objects.hash(results), mapped.size()); + } + grouped.add(new Pair(element, mapped.get(Objects.hash(results)))); + } + ); + //dlya togo chtoby kazhdomu elementu iz mapa sootvetstovalo otvetvleniye + for (int i = 0; i < mapped.size(); i++) { + groupedElements.add(new ArrayList()); + } + + for (Pair element : grouped) { + groupedElements.get(element.getValue()).add(element.getKey()); + } + for (List group : groupedElements) { + int counter = 0; + for (Function thisFunction : this.currentFunctions) { + arguments[counter] = (thisFunction instanceof Aggregator) ? ((Aggregator) thisFunction).apply(group) : thisFunction.apply(group.get(0)); + returnClasses[counter] = arguments[counter].getClass(); + ++counter; + } + if(isJoin) { + Tuple newElement = new Tuple(arguments[0], arguments[1]); + execResult.add((R) newElement); + } + else { + R newElement = (R) toReturn.getConstructor(returnClasses).newInstance(arguments); + execResult.add(newElement); + } + } + } + + + else { + + for(T elem : currentData) { + int counter = 0; + for (Function thisFunction : this.currentFunctions) { + List thisElement = new ArrayList<>(); + thisElement.add(elem); + arguments[counter] = (thisFunction instanceof Aggregator) ? ((Aggregator) thisFunction).apply(thisElement) : thisFunction.apply(elem); + returnClasses[counter] = arguments[counter].getClass(); + ++counter; + } + if(isJoin) { + Tuple newElement = new Tuple(arguments[0], arguments[1]); + execResult.add((R) newElement); + } + else { + R newElement = (R) toReturn.getConstructor(returnClasses).newInstance(arguments); + execResult.add(newElement); + } + } + + } + + if (havingRestriction != null) { + List filteredData = execResult.stream() + .filter(havingRestriction::test) + .collect(Collectors.toList()); + execResult = filteredData; + } + + if (isDistinct) { + System.out.println(execResult); + Set hashes = new HashSet<>(); + List distincted = new ArrayList<>(); + for (R element : execResult) { + if (!hashes.contains(element.toString().hashCode())) { + hashes.add(element.toString().hashCode()); + distincted.add(element); + } + } + execResult = distincted; + } + + if (orderByComparators != null) { + execResult.sort(bestComparatorEver); + } + + if (maxRawsNeeded != -1) { + if(maxRawsNeeded < execResult.size()) + execResult = execResult.subList(0, maxRawsNeeded); + } + + System.out.println(execResult.size()); + + if (isUnion) { + oldData.addAll(execResult); + execResult = oldData; + } + + System.out.println(execResult.size()); + + return execResult; + } + + @SafeVarargs + public final SelectStmt groupBy(Function... expressions) { + this.groupByExpressions = expressions; + return this; + } + + @SafeVarargs + public final SelectStmt orderBy(Comparator... comparators) { + this.orderByComparators = comparators; + this.bestComparatorEver = new BestComparatorEver(comparators); + return this; + } + + public SelectStmt having(Predicate condition) { + this.havingRestriction = condition; + return this; + } + + public SelectStmt limit(int amount) { + maxRawsNeeded = amount; + return this; + } + + public UnionStmt union() throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException { + this.isUnion = true; + List answer = (List) this.execute(); + System.out.println(answer.size()); + if (isJoin) { + return new UnionStmt<>(answer, true); + } else { + return new UnionStmt<>(answer); + } + } + + +} diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/impl/Tuple.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/impl/Tuple.java new file mode 100644 index 0000000..dbc54a3 --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/impl/Tuple.java @@ -0,0 +1,28 @@ +package ru.mipt.diht.students.simon23rus.CQL.impl; + + +//F for first, S for second +public class Tuple { + private final F first; + private final S second; + + public Tuple(F first, S second) { + this.first = first; + this.second = second; + } + + public F getFirst() { + return first; + } + public S getSecond() { + return second; + } + + @Override + public String toString() { + return "Tuple{" + + "first=" + first + + ", second=" + second + + "}"; + } +} diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/impl/UnionStmt.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/impl/UnionStmt.java new file mode 100644 index 0000000..00cd9c2 --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/impl/UnionStmt.java @@ -0,0 +1,103 @@ +package ru.mipt.diht.students.simon23rus.CQL.impl; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.BiPredicate; +import java.util.function.Function; +import java.util.stream.Collectors; + +public class UnionStmt { + + private List oldQueries = new ArrayList<>(); + private List currentQuery = new ArrayList<>(); + private List> oldTupleElements = new ArrayList<>(); + private boolean isTuple; + public UnionStmt(Iterable toIterate) { + toIterate.forEach(elem -> oldQueries.add(elem)); + } + public UnionStmt(Iterable toIterate, boolean isTuple) { + toIterate.forEach(elem -> oldQueries.add(elem)); + this.isTuple = true; + } + + public UnionStmt(Iterable current, Iterable old) { + old.forEach(elem -> oldQueries.add(elem)); + current.forEach(elem -> currentQuery.add(elem)); + } + + public FromMember from(Iterable elements) { + if (isTuple) { + return new FromMember(oldQueries, elements); + } else { + return new FromMember(oldQueries, elements); + } + } + + + public class FromMember { + public List getOldElements() { + return oldElements; + } + private List oldElements = new ArrayList<>(); + private List currentElements = new ArrayList<>(); + + public List getCurrentElements() { + return currentElements; + } + + public FromMember(Iterable pastElements, Iterable elements) { + pastElements.forEach(elem -> this.oldElements.add(elem)); + elements.forEach(elem -> this.currentElements.add(elem)); + } + @SafeVarargs + public final SelectStmt select(Class returnClass, Function... functions) { + return new SelectStmt((List) oldElements, currentElements, returnClass, false, functions); + } + + public final SelectStmt> select(Function first, Function second) { + return new SelectStmt>((List>) oldElements, currentElements, false, first, second); + } + + @SafeVarargs + public final SelectStmt selectDistinct(Class returnClass, Function... functions) { + return new SelectStmt((List) oldElements, currentElements, returnClass, true, functions); + } + + public JoinMember join(Iterable iterable) { + return new JoinMember(oldElements, currentElements, iterable); + } + } + + public class JoinMember { + + private List firstElements = new ArrayList<>(); + private List secondElements = new ArrayList<>(); + private List oldElements = new ArrayList<>(); + private List> currentElements = new ArrayList<>(); + + public JoinMember(List pastElements, List firstElements, Iterable secondElements) { + this.oldElements.addAll(pastElements.stream().collect(Collectors.toList())); + this.firstElements.addAll(firstElements.stream().collect(Collectors.toList())); + secondElements.forEach(elem -> this.secondElements.add(elem)); + } + + public FromMember, R> on(BiPredicate condition) { + firstElements.forEach(first -> + secondElements.forEach(second -> { + //esli udovletvoryaet predikatu, to ostavlyaem + if (condition.test(first, second)) { + this.currentElements.add(new Tuple<>(first, second)); + } + })); + return new FromMember<>(oldElements, currentElements); + } + + public > FromStmt> on( + Function leftKey, + Function rightKey) { + throw new UnsupportedOperationException(); + } + } +} + + diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/implOfAggregators/Aggregator.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/implOfAggregators/Aggregator.java new file mode 100644 index 0000000..a37e469 --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/implOfAggregators/Aggregator.java @@ -0,0 +1,12 @@ +package ru.mipt.diht.students.simon23rus.CQL.implOfAggregators; + + +import java.util.List; +import java.util.function.Function; + +public interface Aggregator extends Function { + default C apply(List currentElements) { + return null; + } +} + diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/implOfAggregators/Avg.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/implOfAggregators/Avg.java new file mode 100644 index 0000000..cbb9505 --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/implOfAggregators/Avg.java @@ -0,0 +1,31 @@ +package ru.mipt.diht.students.simon23rus.CQL.implOfAggregators; + +import java.util.List; +import java.util.function.Function; + + +public class Avg implements Aggregator { + + private Function thisFunction; + + public Avg(Function givenFunction) { + this.thisFunction = givenFunction; + } + + @Override + public Double apply(List givenElements) { + Double result = 0.0; + for (T elem : givenElements) { + result += ((Double) thisFunction.apply(elem)); + System.out.println(thisFunction.apply(elem)); + } + return result / givenElements.size(); + } + + @Override + public Double apply(T toCheck) { + if(thisFunction.apply(toCheck) != null) + return ((Double) thisFunction.apply(toCheck)); + return 0D; + } +} diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/implOfAggregators/Count.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/implOfAggregators/Count.java new file mode 100644 index 0000000..9beea63 --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/implOfAggregators/Count.java @@ -0,0 +1,36 @@ +package ru.mipt.diht.students.simon23rus.CQL.implOfAggregators; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Function; + + +public class Count implements Aggregator { + private Function thisFunction; + public Count(Function givenFunction) { + this.thisFunction = givenFunction; + } + + @Override + public Long apply(List givenElements) { + Set differentElements = new HashSet<>(); + for(T elem : givenElements) { + System.out.println(thisFunction.apply(elem) + "wqe"); + if(thisFunction.apply(elem) != null && !differentElements.contains(thisFunction.apply(elem))) { + differentElements.add(thisFunction.apply(elem)); + } + } + System.out.println(differentElements); + return ((long) differentElements.size()); + } + + + @Override + public Long apply(T elem) { + if(thisFunction.apply(elem) != null) { + return 1L; + } + return 0L; + } +} diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/implOfAggregators/Max.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/implOfAggregators/Max.java new file mode 100644 index 0000000..c9e98fd --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/implOfAggregators/Max.java @@ -0,0 +1,34 @@ +package ru.mipt.diht.students.simon23rus.CQL.implOfAggregators; + +import java.util.List; +import java.util.function.Function; + + +public class Max> implements Aggregator { + private Function thisFunction; + + public Max(Function givenFunction) { + this.thisFunction = givenFunction; + } + + @Override + public R apply(List elements) { + if(elements.size() == 0) { + return null; + } + else { + R ourMax = thisFunction.apply(elements.get(0)); + for(T elem : elements) { + if (ourMax.compareTo(thisFunction.apply(elem)) < 0) { + ourMax = thisFunction.apply(elem); + } + } + return ourMax; + } + } + + @Override + public R apply(T elem) { + return thisFunction.apply(elem); + } +} diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/implOfAggregators/Min.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/implOfAggregators/Min.java new file mode 100644 index 0000000..fe2954d --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/implOfAggregators/Min.java @@ -0,0 +1,36 @@ +package ru.mipt.diht.students.simon23rus.CQL.implOfAggregators; + +import java.util.List; +import java.util.function.Function; + +public class Min> implements Aggregator { + private Function thisFunction; + + public Min(Function givenFunction) { + this.thisFunction = givenFunction; + } + + @Override + public R apply(List elements) { + if(elements.size() == 0) { + return null; + } + else { + R ourMin = thisFunction.apply(elements.get(0)); + for(T elem : elements) { + if (ourMin.compareTo(thisFunction.apply(elem)) > 0) { + ourMin = thisFunction.apply(elem); + } + } + return ourMin; + } + } + + +// //pereopredelyayu t,k, compiler trebuet pereopredelit' abstraktniy method + @Override + public R apply(T elem) { + return thisFunction.apply(elem); + } +} + diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/DatabaseService/DatabaseService.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/DatabaseService/DatabaseService.java new file mode 100644 index 0000000..5bbf5de --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/DatabaseService/DatabaseService.java @@ -0,0 +1,302 @@ +package ru.mipt.diht.students.simon23rus.DatabaseService; + +import com.google.common.base.CaseFormat; +import javax.activation.DataSource; +import java.lang.reflect.Field; +import java.sql.*; +import java.util.ArrayList; +import java.util.List; + +import ru.mipt.diht.students.simon23rus.DatabaseService.TClassAnnotations.*; +/** + * Created by semenfedotov on 15.12.15. + */ +public class DatabaseService { + private DataSource dataBase; + private String dataBaseName; + private List columnNames; + private List sQLClasses; + private Class givenClass; + private Field[] allFields; + private StringBuilder allColumnNames; + private String myTableName; + private Field primaryKey; + private int primaryKeyPos = -1; + private boolean isCreated = false; + + public final DataSource getDataBase() { + return dataBase; + } + + public final String getDataBaseName() { + return dataBaseName; + } + + public final List getColumnNames() { + return columnNames; + } + + public final List getsQLClasses() { + return sQLClasses; + } + + public final Class getGivenClass() { + return givenClass; + } + + public final StringBuilder getAllColumnNames() { + return allColumnNames; + } + + public final Field[] getAllFields() { + return allFields; + } + + public final String getMyTableName() { + return myTableName; + } + + public final Field getPrimaryKey() { + return primaryKey; + } + + public final int getPrimaryKeyPos() { + return primaryKeyPos; + } + + DatabaseService(Class givenClass) throws ClassNotFoundException, SQLException { + Class.forName("org.h2.Driver"); + SQLTypeConverter myOwnConverter = new SQLTypeConverter(); + columnNames = new ArrayList(); + sQLClasses = new ArrayList(); + this.givenClass = givenClass; + myTableName = givenClass.getAnnotation(Table.class).name(); + allFields = givenClass.getDeclaredFields(); + if (myTableName.equals("")) { + //default name + //getSimpleName vozvraschaet name bez prefixa s packagami + //t.k nam dano s UpperCamel, perevedem v lower s podcherkivaniem with CaseFormat by google + myTableName = givenClass.getSimpleName(); + myTableName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, myTableName); + } + dataBaseName = myTableName; + + int index = 0; + for (Field givenField : givenClass.getDeclaredFields()) { + if (givenField.getAnnotation(PrimaryKey.class) != (null)) { + if (givenField.getAnnotation(Column.class) == (null)) { + System.out.println("error with primary key"); + } + primaryKey = givenField; + primaryKeyPos = index; + } + if (!givenField.getAnnotation(Column.class).equals(null)) { + System.out.println(givenField.getType()); + System.out.println(givenField.getName()); + sQLClasses.add(myOwnConverter.convertToSQLType(givenField.getType())); + columnNames.add(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, givenField.getName())); + } + ++index; + } + Connection myFirstConnection = DriverManager.getConnection("jdbc:h2:./dbTask"); + //proverim suschestvuet li tablica + System.out.println(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_UNDERSCORE, dataBaseName) + "SECRET"); + ResultSet answer = myFirstConnection.getMetaData().getTables(null, null, dataBaseName, null); + if (answer.next()) { + isCreated = true; + } + myFirstConnection.close(); + } + + public List resultSetHandler(ResultSet result) throws SQLException, IllegalAccessException, InstantiationException { + List answer = new ArrayList<>(); + while (result.next()) { + T currentElement = givenClass.newInstance(); + for(int i = 0; i < columnNames.size(); ++i) { + String currentSQLType = sQLClasses.get(i); + Class currentClass = allFields[i].getType(); + if(currentSQLType == "VARCHAR(20)") { + if(currentClass.equals(String.class)) { + String toSet = result.getString(i + 1); + allFields[i].set(currentElement, toSet); + } + else { + char toSet = result.getString(i + 1).charAt(0); + allFields[i].set(currentElement, toSet); + } + } + else if(currentSQLType == "INTEGER") { + Integer toSet = result.getInt(i + 1); + allFields[i].set(currentElement, toSet); + } + else if(currentSQLType == "BIGINT") { + Long toSet = result.getLong(i + 1); + allFields[i].set(currentElement, toSet); + } + else if(currentSQLType == "TINYINT") { + byte toSet = result.getByte(i + 1); + allFields[i].set(currentElement, toSet); + } + else if(currentSQLType == "BOOLEAN") { + boolean toSet = result.getBoolean(i + 1); + allFields[i].set(currentElement, toSet); + } + else if(currentSQLType == "DOUBLE") { + Double toSet = result.getDouble(i + 1); + allFields[i].set(currentElement, toSet); + } + else if(currentSQLType == "REAL") { + float toSet = result.getFloat(i + 1); + allFields[i].set(currentElement, toSet); + } + else if(currentSQLType == "DATE") { + Date toSet = result.getDate(i + 1); + allFields[i].set(currentElement, toSet); + } + else if(currentSQLType == "TIME") { + Time toSet = result.getTime(i + 1); + allFields[i].set(currentElement, toSet); + } + else if(currentSQLType == "ARRAY") { + Array toSet = result.getArray(i + 1); + allFields[i].set(currentElement, toSet); + } + else { + System.out.println("Your class is non-supported"); + } + } + answer.add(currentElement); + } + return answer; + } + + public T queryById(K thisPrimaryKey) throws SQLException, IllegalAccessException, InstantiationException { + if(primaryKey == null) { + System.out.println("There is no primary Key in the Table"); + } + Connection queryConnection = DriverManager.getConnection("jdbc:h2:./dbTask"); + StringBuilder query = new StringBuilder(); + query.append("SELECT * FROM ").append(dataBaseName).append(" WHERE ").append(columnNames.get(primaryKeyPos)).append("=?"); + PreparedStatement queryStmt = queryConnection.prepareStatement(query.toString()); + queryStmt.setString(1, thisPrimaryKey.toString()); + ResultSet result = queryStmt.executeQuery(); + List answer = resultSetHandler(result); + queryConnection.close(); + if(answer.size() == 0) { + System.out.println("Error while gettting query by primKey AnswerSize is null"); + return null; + } + else { + return answer.get(0); + } + + } + List queryForAll() throws SQLException, InstantiationException, IllegalAccessException { + Connection queryConnection = DriverManager.getConnection("jdbc:h2:./dbTask"); + StringBuilder query = new StringBuilder(); + query.append("SELECT * FROM ").append(dataBaseName); + List queryResult = resultSetHandler(queryConnection + .createStatement() + .executeQuery(query.toString())); + queryConnection.close(); + return queryResult; + } + void insert(T toInsert) throws SQLException, IllegalAccessException { + Connection insertingConnection = DriverManager.getConnection("jdbc:h2:./dbTask"); + StringBuilder buildValues = new StringBuilder(); + buildValues.append("INSERT INTO ").append(dataBaseName).append(" VALUES ("); + for (int i = 0; i < columnNames.size(); ++i) { + buildValues.append("?"); + if (i != columnNames.size() - 1) { + buildValues.append(", "); + } + } + buildValues.append(")"); + PreparedStatement insertionStatement = insertingConnection.prepareStatement(buildValues.toString()); + for (int i = 0; i < columnNames.size(); ++i) { + insertionStatement.setObject(i + 1, allFields[i].get(toInsert)); + } + int diff = insertionStatement.executeUpdate(); + assert (diff != 0); + insertingConnection.close(); + } + void update(T toUpdate) throws SQLException, IllegalAccessException { + Connection updateConnection = DriverManager.getConnection("jdbc:h2:./dbTask"); + StringBuilder updateValues = new StringBuilder(); + updateValues.append("UPDATE ").append(dataBaseName).append(" SET "); + for (int i = 0; i < columnNames.size(); ++i) { + updateValues.append(columnNames.get(i)).append("=?"); + if (i != columnNames.size() - 1) { + updateValues.append(", "); + } + } + updateValues.append(" WHERE ").append(columnNames.get(primaryKeyPos)).append("=?"); + PreparedStatement updateStmt = updateConnection.prepareStatement(updateValues.toString()); + for (int i = 0; i < columnNames.size(); ++i) { + updateStmt.setObject(i + 1, allFields[i].get(toUpdate)); + } + updateStmt.setObject(columnNames.size() + 1, allFields[primaryKeyPos].get(toUpdate)); + int diff = updateStmt.executeUpdate(); + assert (diff != 0); + updateConnection.close(); + } + void delete(T toDelete) throws SQLException, IllegalAccessException { + Connection deletionConnection = DriverManager.getConnection("jdbc:h2:./dbTask"); + StringBuilder deleteValues = new StringBuilder(); + deleteValues.append("DELETE FROM ") + .append(dataBaseName) + .append(" WHERE ") + .append(columnNames.get(primaryKeyPos)) + .append("=?"); + PreparedStatement deletionStmt = deletionConnection.prepareStatement(deleteValues.toString()); + deletionStmt.setObject(1, allFields[primaryKeyPos].get(toDelete)); + int diff = deletionStmt.executeUpdate(); + assert (diff != 0); + deletionConnection.close(); + } + void createTable() throws SQLException, ClassNotFoundException { + if(isCreated) { + System.out.println("Table has already created!"); + return; + } + Connection creatingConnection = DriverManager.getConnection("jdbc:h2:./dbTask"); + Statement creatingStatement = creatingConnection.createStatement(); + StringBuilder creatingQuery = new StringBuilder(); + creatingQuery.append("CREATE TABLE IF NOT EXISTS ") + .append(dataBaseName).append("("); + System.out.println(dataBaseName); + for (int i = 0; i < columnNames.size(); ++i) { + creatingQuery.append(columnNames.get(i)).append(" ").append(sQLClasses.get(i)); + if (i == primaryKeyPos) { + creatingQuery.append(" NOT NULL PRIMARY KEY"); + } + if (i != columnNames.size() - 1) { + creatingQuery.append(", "); + } + } + creatingQuery.append(")"); + System.out.println(creatingQuery.toString()); + int diff = creatingStatement.executeUpdate(creatingQuery.toString()); + isCreated = true; + creatingConnection.close(); + } + void dropTable() throws SQLException { + if (!isCreated) { + System.out.println("Dropping of non-existing table"); + return; + } + Connection droppingConnection = DriverManager.getConnection("jdbc:h2:./dbTask"); + Statement droppingStatement = droppingConnection.createStatement(); + StringBuilder droppingQuery = new StringBuilder(); + droppingQuery.append("DROP TABLE ").append(dataBaseName); + int diff = droppingStatement.executeUpdate(droppingQuery.toString()); + droppingConnection.close(); + } + + public static void main(String[] args) { + List results = new ArrayList(); + results.add("dsad"); + results.add("fsdqwe"); + System.out.println(results.toString()); + } +} diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/DatabaseService/TClassAnnotations/Column.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/DatabaseService/TClassAnnotations/Column.java new file mode 100644 index 0000000..439ac7f --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/DatabaseService/TClassAnnotations/Column.java @@ -0,0 +1,13 @@ +package ru.mipt.diht.students.simon23rus.DatabaseService.TClassAnnotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.FIELD) +@Retention(RetentionPolicy.RUNTIME) +public @interface Column +{ + String name() default ""; +} diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/DatabaseService/TClassAnnotations/PrimaryKey.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/DatabaseService/TClassAnnotations/PrimaryKey.java new file mode 100644 index 0000000..fc7bfd4 --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/DatabaseService/TClassAnnotations/PrimaryKey.java @@ -0,0 +1,11 @@ +package ru.mipt.diht.students.simon23rus.DatabaseService.TClassAnnotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.FIELD) +@Retention(RetentionPolicy.RUNTIME) +public @interface PrimaryKey { +} diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/DatabaseService/TClassAnnotations/SQLTypeConverter.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/DatabaseService/TClassAnnotations/SQLTypeConverter.java new file mode 100644 index 0000000..8ce5592 --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/DatabaseService/TClassAnnotations/SQLTypeConverter.java @@ -0,0 +1,44 @@ +package ru.mipt.diht.students.simon23rus.DatabaseService.TClassAnnotations; +import java.sql.*; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + +/** + * Created by semenfedotov on 15.12.15. + */ +public class SQLTypeConverter { + static Map classSQLEquivalents = new HashMap<>(); + static { + classSQLEquivalents.put(String.class, "VARCHAR(20)"); + classSQLEquivalents.put(java.math.BigDecimal.class, "NUMERIC"); + classSQLEquivalents.put(boolean.class, "BOOLEAN"); + classSQLEquivalents.put(byte.class, "TINYINT"); + classSQLEquivalents.put(short.class, "SHORTINT"); + classSQLEquivalents.put(int.class, "INTEGER"); + classSQLEquivalents.put(Integer.class, "INTEGER"); + classSQLEquivalents.put(long.class, "BIGINT"); + classSQLEquivalents.put(Long.class, "BIGINT"); + classSQLEquivalents.put(float.class, "REAL"); + classSQLEquivalents.put(double.class, "DOUBLE"); + classSQLEquivalents.put(Double.class, "DOUBLE"); + classSQLEquivalents.put(Date.class, "DATE"); + classSQLEquivalents.put(Time.class, "TIME"); + classSQLEquivalents.put(Timestamp.class, "TIMESTAMP"); + classSQLEquivalents.put(Clob.class, "CLOB"); + classSQLEquivalents.put(Blob.class, "BLOB"); + classSQLEquivalents.put(Array.class, "ARRAY"); + } + + public static String convertToSQLType(Class toConvert) { + if (classSQLEquivalents.containsKey(toConvert)) { + return classSQLEquivalents.get(toConvert); + } + else { + return "SQL doesn't support your Class"; + } + + } +} + + diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/DatabaseService/TClassAnnotations/Table.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/DatabaseService/TClassAnnotations/Table.java new file mode 100644 index 0000000..6d1bc80 --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/DatabaseService/TClassAnnotations/Table.java @@ -0,0 +1,15 @@ +package ru.mipt.diht.students.simon23rus.DatabaseService.TClassAnnotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Created by semenfedotov on 13.12.15. + */ +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface Table { + String name() default ""; +} diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/Threads/Asker.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/Threads/Asker.java new file mode 100644 index 0000000..4f39d54 --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/Threads/Asker.java @@ -0,0 +1,56 @@ +package ru.mipt.diht.students.simon23rus.Threads; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.BrokenBarrierException; +import java.util.concurrent.CyclicBarrier; + +/** + * Created by semenfedotov on 07.12.15. + */ +public class Asker { + private final String READY = "Are you ready?"; + private final int threadsNumber; + private boolean isEnd = false; + List myAnswerers; + public CyclicBarrier myBarrier; + + public boolean getEnding(){ + return isEnd; + } + + public Asker (int threadsNumber) { + this.threadsNumber = threadsNumber; + myAnswerers = new ArrayList(); + myBarrier = new CyclicBarrier(threadsNumber + 1, new Runnable() { + public void run() { + isEnd = true; + for(int i = 0; i < myAnswerers.size(); ++i) { + isEnd &= myAnswerers.get(i).getIsGoodAnswer(); + System.out.println("This is the end? " + isEnd); + } + if(isEnd == false) { + System.out.println(READY); + } + } + }); + } + + + + public void create() { + System.out.println(READY); + for(int i = 0; i < threadsNumber; ++i) { + myAnswerers.add(new RollCallThread(this)); + myAnswerers.get(i).start(); + } + System.out.println("myAnswerers Size" + myAnswerers.size()); + while(!isEnd) { + try { + myBarrier.await(); + } catch (InterruptedException e) { + } catch (BrokenBarrierException e) { + } + } + } +} diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/Threads/BlockingQueue.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/Threads/BlockingQueue.java new file mode 100644 index 0000000..22ff33b --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/Threads/BlockingQueue.java @@ -0,0 +1,151 @@ +package ru.mipt.diht.students.simon23rus.Threads; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +//atomarno +public class BlockingQueue { + Queue myBlockingQueue; + private int elementsBound; + private static Lock insertLocker; + private static Lock deleteLocker; + private static Lock footLocker; + private static Condition nonEmpty; + private static Condition nonFull; + + public List getData() { + return new ArrayList<>(myBlockingQueue); + } + + public BlockingQueue(int elementsBound) { + this.elementsBound = elementsBound; + this.myBlockingQueue = new LinkedList(); + this.insertLocker = new ReentrantLock(true); + this.deleteLocker = new ReentrantLock(true); + this.footLocker = new ReentrantLock(true); + this.nonEmpty = footLocker.newCondition(); + this.nonFull = footLocker.newCondition(); + } + + void printQueue() { + System.out.println(myBlockingQueue); + } + + //dobavit' v konec + void offer(List toAdd) { + footLocker.lock(); + try { + while (myBlockingQueue.size() + toAdd.size() > elementsBound) { + try { + nonFull.await(); + } catch (InterruptedException e) { + System.out.println("Interrupted"); + } + } + myBlockingQueue.addAll(toAdd); + nonEmpty.signal(); + } finally { + footLocker.unlock(); + } + } + + + void offer(List toAdd, long timeout) { + try { + long currentTime = System.currentTimeMillis(); + if (footLocker.tryLock(timeout, TimeUnit.MILLISECONDS)) { + try { + while (myBlockingQueue.size() + toAdd.size() > elementsBound) { + timeout -= System.currentTimeMillis() - currentTime; + currentTime = System.currentTimeMillis(); + if (nonFull.await(timeout, TimeUnit.MILLISECONDS) == false) { + throw new TimeoutException(); + } + } + myBlockingQueue.addAll(toAdd); + nonEmpty.signal(); + } finally { + footLocker.unlock(); + } + } else { + throw new TimeoutException(); + } + } catch (TimeoutException e) { + System.out.println("Time limit exceeded"); + return; + } catch (InterruptedException e) { + System.out.println("InterruptedException"); + } + return; + + } + + //vzyat iz nachala + List take(int numberOfElements) { + List takenElements = new ArrayList(); + try { + deleteLocker.lock(); + for(int i = 0; i < numberOfElements; ++i) { + try { + footLocker.lock(); + while (myBlockingQueue.size() == 0) { + nonEmpty.await(); + } + takenElements.add(myBlockingQueue.poll()); + nonFull.signal(); + } catch (InterruptedException e) { + } + finally { + footLocker.unlock(); + } + } + } + finally { + deleteLocker.unlock(); + return takenElements; + } + } + + public List take(int numberOfElements, long timeout) { + try { + List taken = new ArrayList<>(); + long currentTime = System.currentTimeMillis(); + if (footLocker.tryLock(timeout, TimeUnit.MILLISECONDS)) { + try { + while (myBlockingQueue.size() < numberOfElements) { + timeout -= (System.currentTimeMillis() - currentTime); + currentTime = System.currentTimeMillis(); + if (!nonEmpty.await(timeout, TimeUnit.MILLISECONDS)) { + throw new TimeoutException(); + } + } + for (int i = 0; i < numberOfElements; ++i) { + taken.add(myBlockingQueue.poll()); + } + nonFull.signal(); + return taken; + } catch (InterruptedException e) { + System.out.println("Interrupted"); + } finally { + footLocker.unlock(); + } + } else { + throw new TimeoutException(); + } + + } catch (TimeoutException e) { + return null; + } catch (InterruptedException e) { + System.out.println("Interrupted"); + } + return null; + } + +} diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/Threads/BlockingQueueRunner.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/Threads/BlockingQueueRunner.java new file mode 100644 index 0000000..7a7bcbc --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/Threads/BlockingQueueRunner.java @@ -0,0 +1,19 @@ +package ru.mipt.diht.students.simon23rus.Threads; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by semenfedotov on 13.12.15. + */ +public class BlockingQueueRunner { + public static void main(String[] args) throws InterruptedException { + BlockingQueue forExample = new BlockingQueue(3); + List myList = new ArrayList(); + myList.add(1); myList.add(2); myList.add(3); + forExample.offer(myList); + List returned = forExample.take(2); + forExample.printQueue(); + System.out.println(returned); + } +} diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/Threads/Counter.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/Threads/Counter.java new file mode 100644 index 0000000..af2d002 --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/Threads/Counter.java @@ -0,0 +1,51 @@ +package ru.mipt.diht.students.simon23rus.Threads; + + +public class Counter extends Thread { + private int numberOfThreads; + private static volatile int currentThread = 0; + private int myThreadNumber; + private static Object footLocker = new Object(); + + public Counter(int numberOfThreads, int myThreadNumber) { + this.numberOfThreads = numberOfThreads; + this.myThreadNumber = myThreadNumber; + } + + public synchronized void setNextThread() { + this.currentThread = (this.currentThread + 1) % numberOfThreads; + } + + public void run() { + while (true) { + synchronized (footLocker) { + if (currentThread == myThreadNumber) { + System.out.println("Thread-" + (myThreadNumber + 1)); + setNextThread(); + footLocker.notifyAll(); + } + try { + footLocker.wait(); + } catch (InterruptedException exception) { + } + } + + } + } + + + public static void callCounter(int threadsNumber) { + for(int i = 0; i < threadsNumber; ++i) { + new Counter(threadsNumber, i).start(); + } + } + + public static void main(String[] args) { + + int threadsNumber = Integer.parseInt(args[1]); + callCounter(threadsNumber); + + } + + +} diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/Threads/RollCallRunner.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/Threads/RollCallRunner.java new file mode 100644 index 0000000..9355445 --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/Threads/RollCallRunner.java @@ -0,0 +1,12 @@ +package ru.mipt.diht.students.simon23rus.Threads; + +/** + * Created by semenfedotov on 07.12.15. + */ +public class RollCallRunner { + public static void main(String[] args) { + int numberOfThreads = Integer.valueOf(args[1]); + Asker mainAsker = new Asker(numberOfThreads); + mainAsker.create(); + } +} diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/Threads/RollCallThread.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/Threads/RollCallThread.java new file mode 100644 index 0000000..6d8069e --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/Threads/RollCallThread.java @@ -0,0 +1,42 @@ +package ru.mipt.diht.students.simon23rus.Threads; + +import java.util.Random; +import java.util.concurrent.BrokenBarrierException; + + +public class RollCallThread extends Thread { + private boolean isGoodAnswer; + private Asker myAsker; + + public RollCallThread(Asker questionMan) { + this.myAsker = questionMan; + } + + + public boolean getIsGoodAnswer() { + return isGoodAnswer; + } + + + @Override + public void run() { + while (!myAsker.getEnding()) { + Random myAnswer = new Random(); + if(myAnswer.nextInt(10) == 0) { + System.out.println("No"); + isGoodAnswer = false; + } + else { + System.out.println("Yes"); + isGoodAnswer = true; + } + try { + //ozhidaem otveta vseh threadov + myAsker.myBarrier.await(); + } catch (InterruptedException e) {} + catch (BrokenBarrierException e) {} + } + } +} + + diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/TwitterStream/GeoCodeConverter.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/TwitterStream/GeoCodeConverter.java new file mode 100644 index 0000000..c7879b3 --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/TwitterStream/GeoCodeConverter.java @@ -0,0 +1,82 @@ +package ru.mipt.diht.students.simon23rus.TwitterStream; + +import twitter4j.*; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.net.URLConnection; + +import static java.lang.Double.parseDouble; + + +/** + * Created by semenfedotov on 05.12.15. + */ +public class GeoCodeConverter { + + + public static String webSource() throws IOException, JSONException { + URL newUrl = new URL("http://ip-api.com/json"); + URLConnection urlConnecter = newUrl.openConnection(); + BufferedReader in = new BufferedReader(new InputStreamReader( + urlConnecter.getInputStream(), "UTF-8")); + JSONObject givenSource = new JSONObject(in.readLine()); + String mySource; + mySource = givenSource.getString("city"); + in.close(); + System.out.println(mySource.toString()); + return mySource.toString(); + } + + + public static GeoLocation getCoordinates(String place) throws IOException, InterruptedException, + JSONException { + //if (place != "Moscow") System.out.println(place); + if (place.equals("nearby")) { + place = webSource(); + } + URL getTheLL = new URL("https://maps.googleapis.com/maps/api/geocode/json?address=" + place + "&apikey=" + + "AIzaSyCSLjuyawVt4lZAlb8t0EwuxKQWvRCaqsY"); + String city; + //System.out.println(getTheLL); + try (InputStream yandexIn = getTheLL.openStream()) { + //System.out.println(getTheLL); + JSONTokener tokenizer = new JSONTokener(yandexIn); + JSONObject jsonParse = new JSONObject(tokenizer); + if (jsonParse.getString("status").equals("OK")) { + JSONArray places = jsonParse.getJSONArray("results"); + JSONObject myPlace = places.getJSONObject(0); + JSONObject geometry = myPlace.getJSONObject("geometry"); + JSONObject location = geometry.getJSONObject("location"); + System.out.println(parseDouble(location.getString("lat"))); + System.out.println(parseDouble(location.getString("lng"))); + return new GeoLocation(parseDouble(location.getString("lat")), parseDouble(location.getString("lng"))); + } else { + return new GeoLocation((double) -5, (double) -5); + } + } + } + + + static double sqr(double number) { + return number * number; + } + static final double EARTH_DIAMETER_POPOLAM = 6371; + public static boolean near(GeoLocation first, GeoLocation second, double radius) { + double firstLatitude = Math.toRadians(first.getLatitude()); + double firstLongtitute = Math.toRadians(first.getLongitude()); + double secondLatitude = Math.toRadians(second.getLatitude()); + double secondLongtitude = Math.toRadians(second.getLongitude()); + double deltaPhi = secondLatitude - firstLatitude; + double deltaLambda = secondLongtitude - firstLongtitute; + + double distance = 2 * Math.asin(Math.sqrt(sqr(Math.sin(deltaPhi / 2)) + + Math.cos(firstLatitude) * Math.cos(secondLatitude) * sqr(Math.sin(deltaLambda / 2)))) * EARTH_DIAMETER_POPOLAM; + return distance < radius; + } +} + + diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/TwitterStream/MyJCommander.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/TwitterStream/MyJCommander.java new file mode 100644 index 0000000..9ed247a --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/TwitterStream/MyJCommander.java @@ -0,0 +1,50 @@ +package ru.mipt.diht.students.simon23rus.TwitterStream; + +/** + * Created by semenfedotov on 22.09.15. + */ +import com.beust.jcommander.Parameter; + +/* [--query|-q ] \ + [--place|-p ] \ + [--stream|-s] \ + [--hideRetweets] \ + [--limit|-l ] \ + [--help|-h] +*/ + + +public class MyJCommander { + private static final int MAX_TWEETS_NUMBER = 100; + + @Parameter(names = "--post", description = "Just to post some tweets") + public String toPost; + + + @Parameter(names = { "--query", "-q" }, description = "Parameters for query search") + public String query = ""; + + public String[] getClearQuery() { + if(query == null) { + String[] emptyString = {}; + return emptyString; + } + return query.split("\\s"); + } + + @Parameter(names = { "--place", "-p" }, description = "Places what are you looking for") + public String place = "nearby"; + + @Parameter(names = {"--stream", "-s"}, description = "To print smth with 1sec delay") + public boolean stream = false; + + @Parameter(names = "--hideRetweets", description = "Thing which just hide Retweets") + public boolean hideRetweets = false; + + @Parameter(names = {"--limit", "-l"}, description = "How many tweets to show") + public int tweetsByQuery = MAX_TWEETS_NUMBER; + + + @Parameter(names = { "--help", "-h"}, description = "Just piece of help 4 User", help = true) + public boolean help = false; +} diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/TwitterStream/TimeTransformer.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/TwitterStream/TimeTransformer.java new file mode 100644 index 0000000..af13f96 --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/TwitterStream/TimeTransformer.java @@ -0,0 +1,111 @@ +package ru.mipt.diht.students.simon23rus.TwitterStream; + + + +import java.time.LocalDate; +import java.time.ZoneId; +import java.time.temporal.ChronoUnit; +import java.util.Calendar; +import java.util.Date; + +/** + * Created by semenfedotov on 05.12.15. + */ +public class TimeTransformer { + + private static final int SECONDS_IN_YEAR = 60 * 60 * 24 * 365; + private static final int SECONDS_IN_MONTH = 60 * 60 * 24 * 30; + private static final int SECONDS_IN_DAY = 60 * 60 * 24; + private static final int SECONDS_IN_HOUR = 60 * 60; + private static final int SECONDS_IN_MINUTE = 60; + private static final int TEN = 10; + private static final int FIFTEEN = 15; + private static final int TWO = 2; + private static final int ONE = 1; + private static final int THREE = 3; + private static final int FOUR = 4; + private static final int TWENTY_FOUR = 24; + private static boolean isItYesterday; + + + public static String correctRussianText(long deltaInSeconds) { + System.out.println(deltaInSeconds + "delta"); + if (deltaInSeconds < TWO * SECONDS_IN_MINUTE) { + return "[<Только что>] "; + } + else if (deltaInSeconds < SECONDS_IN_HOUR) { + long minutes = deltaInSeconds / SECONDS_IN_MINUTE; + if (minutes >= FIFTEEN || minutes <= TEN) { + if (minutes % TEN == ONE) { + return "[<" + minutes + " минуту назад>] "; + } + else if (minutes % TEN == TWO || minutes % TEN == THREE || minutes % TEN == FOUR) { + return "[<" + minutes + " минуты назад>] "; + } + else { + return "[<" + minutes + " минут назад>] "; + } + } + else { + return "[<" + minutes + " минут назад>] "; + } + } + + else if (isItYesterday) { + return "[<вчера>] "; + } + + else if (deltaInSeconds < TWENTY_FOUR * SECONDS_IN_HOUR) { + long hours = deltaInSeconds / SECONDS_IN_HOUR; + if (hours >= FIFTEEN || hours <= TEN) { + if (hours % TEN == ONE) { + return "[<" + hours + " час назад>] "; + } + else if (hours % TEN == TWO || hours % TEN == THREE || hours % TEN == FOUR) { + return "[<" + hours + " часа назад>] "; + } + else { + return "[<" + hours + " часов назад>] "; + } + } + else { + return "[<" + hours + " часов назад>] "; + } + } + else { + long days = deltaInSeconds / SECONDS_IN_DAY; + if (days >= FIFTEEN || days <= TEN) { + if (days % TEN == ONE) { + return "[<" + days + " день назад>] "; + } + else if (days % TEN == TWO || days % TEN == THREE || days % TEN == FOUR) { + return "[<" + days + " дня назад>] "; + } + else { + return "[<" + days + " дней назад>] "; + } + } + else { + return "[<" + days + " дней назад>] "; + } + } + } + + public static boolean isItYesterdayTweet(Date tweetDate) { + Date currentDate1 = Calendar.getInstance().getTime(); + LocalDate currentDate = LocalDate.now(); + LocalDate tweetCreationDate = tweetDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); + long result = ChronoUnit.DAYS.between(tweetCreationDate, currentDate); + if(result == 1) { + isItYesterday = true; + return true; + } + else { + isItYesterday = false; + return false; + } + + + } + +} diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/TwitterStream/TwitterPrinter.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/TwitterStream/TwitterPrinter.java new file mode 100644 index 0000000..ef511f1 --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/TwitterStream/TwitterPrinter.java @@ -0,0 +1,43 @@ +package ru.mipt.diht.students.simon23rus.TwitterStream; + +import twitter4j.Status; + +import java.util.Date; + +/** + * Created by semenfedotov on 05.12.15. + */ +public class TwitterPrinter { + public static String makeBlue(String toPaint) { + return (char)27 + "[34;1m@" + toPaint; + } + + public static String printStringWithFormat(Date currentTime, Status tweet, boolean timeIsNeeded) { + TimeTransformer myOwnTransformer = new TimeTransformer(); + String tweetToShow = ""; + if(timeIsNeeded) { + long delta = currentTime.getTime() - tweet.getCreatedAt().getTime(); + myOwnTransformer.isItYesterdayTweet(tweet.getCreatedAt()); + tweetToShow += (char)27 + "[35;1;4m" + myOwnTransformer.correctRussianText(delta / 1000); + } + tweetToShow += makeBlue(tweet.getUser().getScreenName()); + if (tweet.isRetweet()) { + tweetToShow += ":" + (char)27 + "[33;4m" + " ретвитнул "; + tweetToShow += (char)27 + "[31;1m@" + tweet.getRetweetedStatus().getUser().getScreenName(); + tweetToShow += (char)27 + "[0m" + ":"; + tweetToShow += tweet.getText(); +// tweetToShow += tweet.getText().substring(5 + tweet.getRetweetedStatus().getUser().getScreenName().length()); + } + else { + tweetToShow += (char)27 + "[0m" + ":" + tweet.getText(); + } + if (!tweet.isRetweet()) { + tweetToShow += (char)27 + "[42m" + "(<" + tweet.getRetweetCount() + "> Ретвитов)" + (char) 27 + "[0m"; + } + System.out.println(tweetToShow); + return tweetToShow; + } + + + +} diff --git a/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/TwitterStream/TwitterStreamer.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/TwitterStream/TwitterStreamer.java new file mode 100644 index 0000000..2351cbe --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/TwitterStream/TwitterStreamer.java @@ -0,0 +1,122 @@ +package ru.mipt.diht.students.simon23rus.TwitterStream; + + +import com.beust.jcommander.JCommander; +import twitter4j.*; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + + +public class TwitterStreamer { + + private static final int SECONDS_IN_YEAR = 60 * 60 * 24 * 365; + private static final int SECONDS_IN_MONTH = 60 * 60 * 24 * 30; + private static final int SECONDS_IN_DAY = 60 * 60 * 24; + private static final int SECONDS_IN_HOUR = 60 * 60; + private static final int SECONDS_IN_MINUTE = 60; + private static final String EXCLUDE_RETWEETS = " +exclude:retweets"; + private static final String AROUND_THE_WORLD = "nearby"; + private static boolean isItYesterday; + + + public static StatusAdapter listener = new StatusAdapter(){ + private TwitterPrinter myOwnPrinter; + public void onStatus(Status givenTweet) { + Date currentDate = Calendar.getInstance().getTime(); + myOwnPrinter.printStringWithFormat(currentDate,givenTweet, false); + try { + Thread.sleep(1000); //1000=1. + } catch(InterruptedException ex) { + System.out.println("Current Thread has interrupted"); + } + } + }; + + + + + + + public static void main(String[] args) throws TwitterException, IOException, InterruptedException, JSONException { + + MyJCommander jct = new MyJCommander(); + new JCommander(jct, args); + + GeoCodeConverter myOwnConverter = new GeoCodeConverter(); + TwitterPrinter myOwnPrinter = new TwitterPrinter(); + if (jct.help) { + System.out.println("Now you are getting hints for usage this applocation" + + "\n[--query|-q ]\n" + + "[--place|-p ]\n" + + "[--stream|-s]\n" + + "[--hideRetweets]\n" + + "[--limit|-l ]\n" + + "[--help|-h]\n"); + return; + } + + Twitter twitter = new TwitterFactory().getInstance(); + if (jct.toPost != null) { + twitter.updateStatus(jct.toPost); + } + + + System.out.println("It is your searching place " + jct.place); + + + if (jct.stream) { + TwitterStream myTwitterStream = new TwitterStreamFactory().getInstance(); + myTwitterStream.addListener(listener); + FilterQuery myFilter = new FilterQuery(); + ArrayList toTrack = new ArrayList(); + toTrack.add(jct.query); + myFilter.track(toTrack.toArray(new String[toTrack.size()])); + myTwitterStream.filter(myFilter); + } + else { + if (jct.hideRetweets) { + jct.query += EXCLUDE_RETWEETS; + } + Query query = new Query(jct.query); + QueryResult result; + query.setCount(jct.tweetsByQuery); + System.out.println("bu"); + +// query.setGeoCode(myOwnConverter.getCoordinates(jct.place), 400, Query.Unit.km); + GeoLocation queryLocation = myOwnConverter.getCoordinates(jct.place); + int counter = 0; + do { + result = twitter.search(query); + List tweetsFound = result.getTweets(); + for (Status tweet : tweetsFound) { + GeoLocation tweetLocation; + if(tweet.getGeoLocation() != null) { + tweetLocation = new GeoLocation(tweet.getGeoLocation().getLatitude(), tweet.getGeoLocation().getLongitude()); + } + else { + continue; + } + if(queryLocation == null) { + System.out.println("Can't resolve your Location"); + return; + } + if(myOwnConverter.near(queryLocation, tweetLocation, 40)) { + Date currentDate = Calendar.getInstance().getTime(); + myOwnPrinter.printStringWithFormat(currentDate, tweet, true); + + ++counter; + if (counter == jct.tweetsByQuery) { + return; + } + } + } + } while ((counter < jct.tweetsByQuery) && (query = result.nextQuery()) != null); + } + + } + +} diff --git a/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/CQL/data/AggregatesTest.java b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/CQL/data/AggregatesTest.java new file mode 100644 index 0000000..e9e67a8 --- /dev/null +++ b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/CQL/data/AggregatesTest.java @@ -0,0 +1,74 @@ +package ru.mipt.diht.students.simon23rus.CQL.data; + +import ru.mipt.diht.students.simon23rus.CQL.implOfAggregators.*; +import junit.framework.TestCase; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.runners.MockitoJUnitRunner; + + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; + +@RunWith(MockitoJUnitRunner.class) +public class AggregatesTest extends TestCase { + + List toTest; + List emptyTest; + Function functionAge; + Function functionName, functionGroup; + CollectionQuery.Student student; + + @Before + public void setUp() throws Exception { + toTest = new ArrayList<>(); + emptyTest = new ArrayList<>(); + toTest.add(new CollectionQuery.Student("sobaka", LocalDate.parse("2007-08-06"), "123")); + toTest.add(new CollectionQuery.Student("sinitsa", LocalDate.parse("2007-08-18"), "456")); + toTest.add(new CollectionQuery.Student("vorobey", LocalDate.parse("1996-03-14"), "789")); + toTest.add(new CollectionQuery.Student("drakon", LocalDate.parse("1000-02-13"), "223")); + functionAge = CollectionQuery.Student::age; + functionName = CollectionQuery.Student::getName; + functionGroup = CollectionQuery.Student::getGroup; + student = new CollectionQuery.Student("zhiraf", LocalDate.parse("1996-10-29"), "788"); + } + + @Test + public void testMax() throws Exception { + assertEquals("789", ((Aggregator) Aggregates.max(functionGroup)).apply(toTest)); + assertEquals("vorobey", ((Aggregator) Aggregates.max(functionName)).apply(toTest)); + assertEquals(1015D, ((Aggregator) Aggregates.max(functionAge)).apply(toTest)); + + assertEquals(19D, ((Aggregator) Aggregates.max(functionAge)).apply(student)); + assertEquals(null, ((Aggregator) Aggregates.max(functionAge)).apply(emptyTest)); + } + + @Test + public void testMin() throws Exception { + assertEquals("123", ((Aggregator) Aggregates.min(functionGroup)).apply(toTest)); + assertEquals("drakon", ((Aggregator) Aggregates.min(functionName)).apply(toTest)); + assertEquals(8D, ((Aggregator) Aggregates.min(functionAge)).apply(toTest)); + + assertEquals(19D, ((Aggregator) Aggregates.min(functionAge)).apply(student)); + assertEquals(null, ((Aggregator) Aggregates.min(functionAge)).apply(emptyTest)); + } + + @Test + public void testCount() throws Exception { + assertEquals(4L,((Aggregator) Aggregates.count(functionGroup)).apply(toTest)); + assertEquals(4L,((Aggregator) Aggregates.count(functionName)).apply(toTest)); + assertEquals(3L,((Aggregator) Aggregates.count(functionAge)).apply(toTest)); + + assertEquals(1L,((Aggregator) Aggregates.count(functionAge)).apply(student)); + } + + @Test + public void testAvg() throws Exception { + assertEquals(262.5,(Double)((Aggregator) Aggregates.avg(functionAge)).apply(toTest) ,0.1); + + assertEquals(19D, ((Aggregator) Aggregates.avg(functionAge)).apply(student)); + } +} \ No newline at end of file diff --git a/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/CQL/data/ConditionsTest.java b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/CQL/data/ConditionsTest.java new file mode 100644 index 0000000..ccbea0a --- /dev/null +++ b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/CQL/data/ConditionsTest.java @@ -0,0 +1,35 @@ +package ru.mipt.diht.students.simon23rus.CQL.data; + +import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.runners.MockitoJUnitRunner; +import ru.mipt.diht.students.simon23rus.CQL.data.CollectionQuery; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; + +import static ru.mipt.diht.students.simon23rus.CQL.data.CollectionQuery.Student.student; +import static ru.mipt.diht.students.simon23rus.CQL.data.Conditions.rlike; + +@RunWith(MockitoJUnitRunner.class) +public class ConditionsTest extends TestCase { + Function function = CollectionQuery.Student::getName; + + @Test + public void testRlike() throws Exception { + List toTest = new ArrayList<>(); + toTest.add(student("pushkin", LocalDate.parse("1966-02-01"), "123")); + toTest.add(student("kagawa", LocalDate.parse("1976-04-03"), "456")); + toTest.add(student("sobaka", LocalDate.parse("1916-05-05"), "789")); + toTest.add(student("boss", LocalDate.parse("1236-08-07"), "101")); + + assertEquals(true, rlike(function, ".*in").test(toTest.get(0))); + assertEquals(true, rlike(function, ".*awa").test(toTest.get(1))); + assertEquals(false, rlike(function, ".*ov").test(toTest.get(2))); + assertEquals(false, rlike(function, ".*ov").test(toTest.get(3))); + } + +} \ No newline at end of file diff --git a/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/CQL/data/OrderByConditionsTest.java b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/CQL/data/OrderByConditionsTest.java new file mode 100644 index 0000000..741d452 --- /dev/null +++ b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/CQL/data/OrderByConditionsTest.java @@ -0,0 +1,45 @@ +package ru.mipt.diht.students.simon23rus.CQL.data; + +import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.runners.MockitoJUnitRunner; + + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; + +import static ru.mipt.diht.students.simon23rus.CQL.data.CollectionQuery.Student.student; + +@RunWith(MockitoJUnitRunner.class) +public class OrderByConditionsTest extends TestCase { + Function nameFunction = CollectionQuery.Student::getName; + + @Test + public void testAsc() throws Exception { + List toTest = new ArrayList<>(); + toTest.add(student("pushkin", LocalDate.parse("1966-02-01"), "123")); + toTest.add(student("kagawa", LocalDate.parse("1976-04-03"), "456")); + toTest.add(student("sobaka", LocalDate.parse("1916-05-05"), "789")); + toTest.add(student("boss", LocalDate.parse("1236-08-07"), "101")); + assertTrue(OrderByConditions.asc(nameFunction).compare(toTest.get(0), toTest.get(1)) > 0); + assertTrue(OrderByConditions.asc(nameFunction).compare(toTest.get(1), toTest.get(0)) < 0); + assertTrue(OrderByConditions.asc(nameFunction).compare(toTest.get(2), toTest.get(2)) == 0); + assertTrue(OrderByConditions.asc(nameFunction).compare(toTest.get(2), toTest.get(3)) > 0); + } + + @Test + public void testDesc() throws Exception { + List toTest = new ArrayList<>(); + toTest.add(student("pushkin", LocalDate.parse("1966-02-01"), "123")); + toTest.add(student("kagawa", LocalDate.parse("1976-04-03"), "456")); + toTest.add(student("sobaka", LocalDate.parse("1916-05-05"), "789")); + toTest.add(student("boss", LocalDate.parse("1236-08-07"), "101")); + assertTrue(OrderByConditions.desc(nameFunction).compare(toTest.get(0), toTest.get(1)) < 0); + assertTrue(OrderByConditions.desc(nameFunction).compare(toTest.get(1), toTest.get(0)) > 0); + assertTrue(OrderByConditions.desc(nameFunction).compare(toTest.get(2), toTest.get(2)) == 0); + assertTrue(OrderByConditions.desc(nameFunction).compare(toTest.get(2), toTest.get(3)) < 0); + } +} \ No newline at end of file diff --git a/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/CQL/data/SourcesTest.java b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/CQL/data/SourcesTest.java new file mode 100644 index 0000000..e589f9d --- /dev/null +++ b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/CQL/data/SourcesTest.java @@ -0,0 +1,37 @@ +package ru.mipt.diht.students.simon23rus.CQL.data; + +import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.runners.MockitoJUnitRunner; + + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; + +import static ru.mipt.diht.students.simon23rus.CQL.data.CollectionQuery.Student.student; + + +@RunWith(MockitoJUnitRunner.class) +public class SourcesTest extends TestCase { + + @Test + public void testList() throws Exception { + List toTest = new ArrayList<>(); + toTest.add(student("pushkin", LocalDate.parse("1966-02-01"), "123")); + toTest.add(student("kagawa", LocalDate.parse("1976-04-03"), "456")); + toTest.add(student("sobaka", LocalDate.parse("1916-05-05"), "789")); + toTest.add(student("boss", LocalDate.parse("1236-08-07"), "101")); + + List toReturn = Sources.list( + student("pushkin", LocalDate.parse("1966-02-01"), "123"), + student("kagawa", LocalDate.parse("1976-04-03"), "456"), + student("sobaka", LocalDate.parse("1916-05-05"), "789"), + student("boss", LocalDate.parse("1236-08-07"), "101")); + assertEquals(toReturn.size(), toTest.size()); + for (int i = 0; i < toTest.size(); i++) { + assertEquals(toReturn.get(i).toString(), toTest.get(i).toString()); + } + } +} \ No newline at end of file diff --git a/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/CQL/impl/FromStmtTest.java b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/CQL/impl/FromStmtTest.java new file mode 100644 index 0000000..a93701b --- /dev/null +++ b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/CQL/impl/FromStmtTest.java @@ -0,0 +1,114 @@ +package ru.mipt.diht.students.simon23rus.CQL.impl; + +import junit.framework.TestCase; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.runners.MockitoJUnitRunner; +import ru.mipt.diht.students.simon23rus.CQL.data.CollectionQuery; + +import java.lang.reflect.InvocationTargetException; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.function.Function; + +import static ru.mipt.diht.students.simon23rus.CQL.data.CollectionQuery.Student.student; +import static ru.mipt.diht.students.simon23rus.CQL.data.Sources.list; +import static ru.mipt.diht.students.simon23rus.CQL.impl.FromStmt.from; + +@RunWith(MockitoJUnitRunner.class) +public class FromStmtTest extends TestCase { + + List toTest; + List emptyTest; + Function functionAge; + Function functionName, functionGroup; + CollectionQuery.Student student; + + @Before + public void setUp() throws Exception { + toTest = new ArrayList<>(); + emptyTest = new ArrayList<>(); + toTest.add(student("pushkin", LocalDate.parse("1966-02-01"), "123")); + toTest.add(student("kagawa", LocalDate.parse("1966-04-03"), "456")); + toTest.add(student("sobaka", LocalDate.parse("1916-05-05"), "789")); + toTest.add(student("boss", LocalDate.parse("1236-08-07"), "101")); + functionAge = CollectionQuery.Student::age; + functionName = CollectionQuery.Student::getName; + functionGroup = CollectionQuery.Student::getGroup; + student = new CollectionQuery.Student("zhiraf", LocalDate.parse("1800-02-15"), "222"); + } + + @Test + public void testFrom() throws Exception { + FromStmt fromStmt = from(toTest); + assertEquals(fromStmt.getData().size(), toTest.size()); + for (int i = 0; i < toTest.size(); i++) { + assertEquals(toTest.get(i),fromStmt.getData().get(i)); + } + } + + @Test + public void testSelect() throws Exception { + SelectStmt select = + from(toTest) + .select(CollectionQuery.Student.class, CollectionQuery.Student::age); + assertEquals(-1, select.getMaxRawsNeeded()); + assertEquals(CollectionQuery.Student.class, select.getToReturn()); + assertEquals(false, select.isDistinct); + assertEquals(false, select.isUnion); + Function function; + function = CollectionQuery.Student::age; + assertEquals(1, select.getCurrentFunctions().length); + for (CollectionQuery.Student element : toTest) { + assertEquals(function.apply(element), + select.getCurrentFunctions()[0].apply(element)); + } + assertEquals(4, select.getCurrentData().size()); + for (int i = 0; i < toTest.size(); i++) { + assertEquals(select.getCurrentData().get(i), toTest.get(i)); + } + } + + @Test + public void joinTest() throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { + Iterable> mentorsByStudent = + from(list(student("kagawa", LocalDate.parse("1985-08-06"), "123"), + student("sobaka", LocalDate.parse("2000-08-06"), "123"))) + .join(list(new CollectionQuery.Group("123", "mr.proper"), + new CollectionQuery.Group("123", "mr.test"))) + .on((s, g) -> Objects.equals(s.getGroup(), g.getGroup())) + .select(sg -> sg.getFirst().getName(), sg -> sg.getSecond().getMentor()) + .execute(); + +// System.out.println(mentorsByStudent); + assertEquals("[Tuple{first=kagawa, second=mr.proper}, Tuple{first=kagawa, second=mr.test}, Tuple{first=sobaka, second=mr.proper}, Tuple{first=sobaka, second=mr.test}]", + mentorsByStudent.toString()); + } + + @Test + public void testSelectDistinct() throws Exception { + SelectStmt select = from(toTest) + .selectDistinct(CollectionQuery.Student.class, CollectionQuery.Student::getName, + CollectionQuery.Student::getGroup); + assertEquals(-1,select.getMaxRawsNeeded()); + assertEquals(CollectionQuery.Student.class, select.getToReturn()); + assertEquals(true,select.isDistinct); + assertEquals(false,select.isUnion); + Function[] functions = new Function[2]; + functions[0] = CollectionQuery.Student::getName; + functions[1] = CollectionQuery.Student::getGroup; + assertEquals(select.getCurrentFunctions().length, functions.length); + for (int i = 0; i < functions.length; i++) { + for (CollectionQuery.Student element : toTest) { + assertEquals(functions[i].apply(element), select.getCurrentFunctions()[i].apply(element)); + } + } + assertEquals(toTest.size(), select.getCurrentData().size()); + for (int i = 0; i < toTest.size(); i++) { + assertEquals(toTest.get(i), select.getCurrentData().get(i)); + } + } +} \ No newline at end of file diff --git a/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/CQL/impl/SelectStmtTest.java b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/CQL/impl/SelectStmtTest.java new file mode 100644 index 0000000..b3dea65 --- /dev/null +++ b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/CQL/impl/SelectStmtTest.java @@ -0,0 +1,200 @@ +package ru.mipt.diht.students.simon23rus.CQL.impl; + +import junit.framework.TestCase; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.runners.MockitoJUnitRunner; +import ru.mipt.diht.students.simon23rus.CQL.data.Aggregates; +import ru.mipt.diht.students.simon23rus.CQL.data.CollectionQuery; +import ru.mipt.diht.students.simon23rus.CQL.data.OrderByConditions; + + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.function.Function; + +import static ru.mipt.diht.students.simon23rus.CQL.data.CollectionQuery.Student.student; + +@RunWith(MockitoJUnitRunner.class) +public class SelectStmtTest extends TestCase { + + List toTest, emptyExampleList, distinctTest; + Function functionAge; + Function functionName, functionGroup; + CollectionQuery.Student student; + SelectStmt select, distinctSelect; + SelectStmt groupSelect; + + @Before + public void setUp() throws Exception { + toTest = new ArrayList<>(); + emptyExampleList = new ArrayList<>(); + distinctTest = new ArrayList<>(); + toTest.add(student("pushkin", LocalDate.parse("1966-02-01"), "123")); + toTest.add(student("kagawa", LocalDate.parse("1966-04-03"), "456")); + toTest.add(student("sobaka", LocalDate.parse("1916-05-05"), "789")); + toTest.add(student("boss", LocalDate.parse("1236-08-07"), "123")); + distinctTest.add(student("pushkin", LocalDate.parse("1966-02-01"), "123")); + distinctTest.add(student("pushkin", LocalDate.parse("1966-02-01"), "123")); + distinctTest.add(student("sobaka", LocalDate.parse("1916-05-05"), "789")); + distinctTest.add(student("sobaka", LocalDate.parse("1916-05-05"), "789")); + functionAge = CollectionQuery.Student::age; + functionName = CollectionQuery.Student::getName; + functionGroup = CollectionQuery.Student::getGroup; + student = new CollectionQuery.Student("zhiraf", LocalDate.parse("1996-02-12"), "123"); + select = FromStmt.from(toTest).select(CollectionQuery.Student.class, CollectionQuery.Student::getName, + CollectionQuery.Student::getGroup); + distinctSelect = FromStmt.from(distinctTest).selectDistinct(CollectionQuery.Student.class, + CollectionQuery.Student::getName, CollectionQuery.Student::getGroup); + groupSelect = FromStmt.from(toTest).select(CollectionQuery.Statistics.class, + CollectionQuery.Student::getGroup, Aggregates.count(CollectionQuery.Student::getName)); + } + + @Test + public void testWhere() throws Exception { + List result = (List) select + .where(s -> Objects.equals(s.getGroup(), "456")) + .execute(); + List resultList = new ArrayList<>(); + resultList.add(new CollectionQuery.Student("kagawa", "456")); + assertEquals(resultList.size(), result.size()); + for (int i = 0; i < resultList.size(); i++) { + assertEquals(resultList.get(i).toString(), result.get(i).toString()); + } + } + + @Test + public void testGroupBy() throws Exception { + List result = (List) groupSelect + .groupBy(CollectionQuery.Student::getGroup) + .execute(); + List resultList = new ArrayList<>(); + resultList.add(new CollectionQuery.Statistics("123", 2L)); + resultList.add(new CollectionQuery.Statistics("456", 1L)); + resultList.add(new CollectionQuery.Statistics("789", 1L)); + assertEquals(resultList.size(), result.size()); + for (int i = 0; i < resultList.size(); i++) { + assertEquals(resultList.get(i).toString(), result.get(i).toString()); + } + } + + @Test + public void testOrderBy() throws Exception { + List result = (List) select + .orderBy(OrderByConditions.desc(CollectionQuery.Student::getGroup)) + .execute(); + List resultList = new ArrayList<>(); + resultList.add(new CollectionQuery.Student("sobaka", "789")); + resultList.add(new CollectionQuery.Student("kagawa", "456")); + resultList.add(new CollectionQuery.Student("pushkin", "123")); + resultList.add(new CollectionQuery.Student("boss", "123")); + assertEquals(resultList.size(), result.size()); + for (int i = 0; i < resultList.size(); i++) { + assertEquals(resultList.get(i).toString(), result.get(i).toString()); + } + } + + @Test + public void testHaving() throws Exception { + List result = (List) groupSelect + .groupBy(CollectionQuery.Student::getGroup) + .having(s -> Objects.equals(s.getGroup(), "123")) + .execute(); + System.out.println(result); + List resultList = new ArrayList<>(); + resultList.add(new CollectionQuery.Statistics("123", 2L)); + assertEquals(resultList.size(), result.size()); + for (int i = 0; i < resultList.size(); i++) { + assertEquals(resultList.get(i).toString(), result.get(i).toString()); + } + } + + @Test + public void testLimit() throws Exception { + List result = (List) select + .limit(2) + .execute(); + List resultList = new ArrayList<>(); + resultList.add(new CollectionQuery.Student("pushkin", "123")); + resultList.add(new CollectionQuery.Student("kagawa", "456")); + assertEquals(resultList.size(), result.size()); + for (int i = 0; i < resultList.size(); i++) { + assertEquals(resultList.get(i).toString(), result.get(i).toString()); + } + + result = (List) select + .limit(5) + .execute(); + resultList.clear(); + resultList.add(new CollectionQuery.Student("pushkin", "123")); + resultList.add(new CollectionQuery.Student("kagawa", "456")); + resultList.add(new CollectionQuery.Student("sobaka", "789")); + resultList.add(new CollectionQuery.Student("boss", "123")); + assertEquals(resultList.size(), result.size()); + for (int i = 0; i < resultList.size(); i++) { + assertEquals(resultList.get(i).toString(), result.get(i).toString()); + } + } + + @Test + public void testExecute() throws Exception { + List result = (List) select.execute(); + List resultList = new ArrayList<>(); + resultList.add(new CollectionQuery.Student("pushkin", "123")); + resultList.add(new CollectionQuery.Student("kagawa", "456")); + resultList.add(new CollectionQuery.Student("sobaka", "789")); + resultList.add(new CollectionQuery.Student("boss", "123")); + assertEquals(resultList.size(), result.size()); + for (int i = 0; i < resultList.size(); i++) { + assertEquals(resultList.get(i).toString(), result.get(i).toString()); + } + + List resultWithAggr = (List) groupSelect.execute(); + List resultListWithAggr = new ArrayList<>(); + resultListWithAggr.add(new CollectionQuery.Statistics("123", 1L)); + resultListWithAggr.add(new CollectionQuery.Statistics("456", 1L)); + resultListWithAggr.add(new CollectionQuery.Statistics("789", 1L)); + resultListWithAggr.add(new CollectionQuery.Statistics("123", 1L)); + assertEquals(resultListWithAggr.size(), resultWithAggr.size()); + for (int i = 0; i < resultWithAggr.size(); i++) { + assertEquals(resultListWithAggr.get(i).toString(), resultWithAggr.get(i).toString()); + } + } + + @Test + public void testUnion() throws Exception { + List result = (List) select.union(). + from(toTest). + select(CollectionQuery.Student.class, CollectionQuery.Student::getName, + CollectionQuery.Student::getGroup). + execute(); + List resultList = new ArrayList<>(); + resultList.add(new CollectionQuery.Student("pushkin", "123")); + resultList.add(new CollectionQuery.Student("kagawa", "456")); + resultList.add(new CollectionQuery.Student("sobaka", "789")); + resultList.add(new CollectionQuery.Student("boss", "123")); + resultList.add(new CollectionQuery.Student("pushkin", "123")); + resultList.add(new CollectionQuery.Student("kagawa", "456")); + resultList.add(new CollectionQuery.Student("sobaka", "789")); + resultList.add(new CollectionQuery.Student("boss", "123")); + assertEquals(resultList.size(), result.size()); + for (int i = 0; i < resultList.size(); i++) { + assertEquals(resultList.get(i).toString(), result.get(i).toString()); + } + } + + @Test + public void testIsDistinct() throws Exception { + List result = (List) distinctSelect.execute(); + List resultList = new ArrayList<>(); + resultList.add(new CollectionQuery.Student("pushkin", "123")); + resultList.add(new CollectionQuery.Student("sobaka", "789")); + assertEquals(resultList.size(), result.size()); + for (int i = 0; i < resultList.size(); i++) { + assertEquals(resultList.get(i).toString(), result.get(i).toString()); + } + } +} \ No newline at end of file diff --git a/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/DatabaseService/DatabaseServiceTest.java b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/DatabaseService/DatabaseServiceTest.java new file mode 100644 index 0000000..8c9c74a --- /dev/null +++ b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/DatabaseService/DatabaseServiceTest.java @@ -0,0 +1,210 @@ +package ru.mipt.diht.students.simon23rus.DatabaseService; + +import junit.framework.TestCase; +import org.junit.Test; +import ru.mipt.diht.students.simon23rus.DatabaseService.TClassAnnotations.Column; +import ru.mipt.diht.students.simon23rus.DatabaseService.TClassAnnotations.PrimaryKey; +import ru.mipt.diht.students.simon23rus.DatabaseService.TClassAnnotations.Table; + +import junit.framework.TestCase; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.internal.rules.JunitRuleImpl; +import org.mockito.runners.MockitoJUnitRunner; + +import java.sql.*; +import java.util.*; +import java.util.Date; + +/** + * Created by semenfedotov on 16.12.15. + */ +@RunWith(MockitoJUnitRunner.class) +public class DatabaseServiceTest extends TestCase { + @Table + public static class Player { + @Column + @PrimaryKey + int id; + + @Column + String lastName; + @Column + Long salary; + @Column + String club; + + Player() {} + + Player(String id, String lastName, String salary, String club) { + this.id = Integer.valueOf(id); + this.lastName = lastName; + this.salary = Long.valueOf(salary); + this.club = club; + } + + Player(int id, String lastName, Long salary, String club) { + this.id = id; + this.lastName = lastName; + this.salary = salary; + this.club = club; + } + + @Override + public String toString() { + return id + " | " + lastName + " | " + salary + " | " + club + " | "; + } + } + + @Test + public void createTableTest() throws SQLException, ClassNotFoundException { + //мб autoincrement? + System.out.println("VSEM PEIVET"); + DatabaseService myFirstService = new DatabaseService<>(Player.class); + Connection myFirstConnection = DriverManager.getConnection("jdbc:h2:./dbTask"); + StringBuilder dropper = new StringBuilder(); + myFirstConnection.createStatement().executeUpdate("DROP TABLE IF EXISTS PLAYER"); + myFirstService.createTable(); + DatabaseMetaData myMeta = myFirstConnection.getMetaData(); + ResultSet existence = myMeta.getTables(null, null, "PLAYER", null); + if(existence.next()) { + myFirstConnection.close(); + System.out.println("CREATED!"); + assert (true); + } + else { + myFirstConnection.close(); + assert (false); + } + } + + @Test + public void dropBoxTest() throws SQLException, ClassNotFoundException { + DatabaseService mySecondService = new DatabaseService<>(Player.class); + Connection mySecondConnection = DriverManager.getConnection("jdbc:h2:./dbTask"); + mySecondConnection.createStatement().executeUpdate("CREATE TABLE IF NOT EXISTS player(id INTEGER NOT NULL PRIMARY KEY, last_name VARCHAR(20), salary BIGINT, club VARCHAR(20))"); + mySecondService.dropTable(); + DatabaseMetaData myMeta = mySecondConnection.getMetaData(); + ResultSet existence = myMeta.getTables(null, null, "player", null); + if (existence.next()) { + mySecondConnection.close(); + assert false; + } + else { + mySecondConnection.close(); + assert true; + } + } + + @Test + public void insertTest() throws SQLException, ClassNotFoundException, IllegalAccessException { + DatabaseService myThirdService = new DatabaseService<>(Player.class); + Connection myThirdCOnnection = DriverManager.getConnection("jdbc:h2:./dbTask"); + System.out.println("UUU"); + myThirdService.createTable(); + List team = new ArrayList<>(); + team.add(new Player(1, "Ter Stegen", 55000L, "FCB")); + team.add(new Player(2, "Douglas", 35000L, "FCB")); + team.add(new Player(3, "Pique", 130000L,"FCB")); + team.add(new Player(4, "Rakitic", 75000L, "FCB")); + team.add(new Player(5, "Busquets", 120000L, "FCB")); + team.add(new Player(6, "Dani Alves", 120000L, "FCB")); + team.add(new Player(7, "David Villa", 100000L, "New York City")); + team.add(new Player(8, "Iniesta", 150000L ,"FCB")); + team.add(new Player(9, "Suarez", 200000L, "FCB")); + team.add(new Player(10, "Messi", 256000L, "FCB")); + team.add(new Player(11, "Neymar", 150000L, "FCB")); + + for(int i = 0; i < team.size(); ++i) { + myThirdService.insert(team.get(i)); + } + Statement selectZvezdochka = myThirdCOnnection.createStatement(); + ResultSet selectResult = selectZvezdochka.executeQuery("SELECT * FROM player"); + int rowNumber = 0; + List added = new ArrayList<>(); + while (selectResult.next()) { + added.add(new Player( + selectResult.getString(1), + selectResult.getString(2), + selectResult.getString(3), + selectResult.getString(4)) + ); + ++rowNumber; + } + assertEquals(11, rowNumber); + for(int i = 0; i < rowNumber; ++i) { + assertEquals(team.get(i).toString(), added.get(i).toString()); + } + myThirdCOnnection.close(); + } + + @Test + public void updateTest() throws SQLException, ClassNotFoundException, IllegalAccessException, InstantiationException { + DatabaseService myFourthService = new DatabaseService<>(Player.class); + Connection myFourthConnection = DriverManager.getConnection("jdbc:h2:./dbTask"); + Player updater = new Player(7, "Sanek", 123456L, "FC Vodnik"); + myFourthService.update(updater); + Player result = myFourthService.queryById(7); + System.out.println(result.toString()); + assertEquals(updater.toString(), result.toString()); + myFourthConnection.close(); + } + + @Test + public void deleteTest() throws SQLException, ClassNotFoundException, IllegalAccessException, InstantiationException { + DatabaseService myFourthService = new DatabaseService<>(Player.class); + Connection myFourthConnection = DriverManager.getConnection("jdbc:h2:./dbTask"); + Player toDelete = new Player(1, "Ter Stegen", 55000L, "FCB"); + myFourthService.delete(toDelete); + assertEquals(null, myFourthService.queryById(1)); + myFourthConnection.close(); + } + + @Test + public void queryByIdTest() throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException { + DatabaseService myFourthService = new DatabaseService<>(Player.class); + Connection myFourthConnection = DriverManager.getConnection("jdbc:h2:./dbTask"); + int key = 4; + assertEquals(new Player(4, "Rakitic", 75000L, "FCB").toString(), myFourthService.queryById(key).toString()); + myFourthConnection.close(); + } + + @Test + public void queryAllTest() throws SQLException, ClassNotFoundException, IllegalAccessException, InstantiationException { + DatabaseService myFourthService = new DatabaseService<>(Player.class); + Connection myFourthConnection = DriverManager.getConnection("jdbc:h2:./dbTask"); + Statement selectZvezdochka = myFourthConnection.createStatement(); + System.out.println("We R Here"); + ResultSet selectResult = selectZvezdochka.executeQuery("SELECT * FROM player"); + + List answer = new ArrayList<>(); + answer = myFourthService.queryForAll(); +// while (selectResult.next()) { +// answer.add((new Player( +// selectResult.getString(1), +// selectResult.getString(2), +// selectResult.getString(3), +// selectResult.getString(4)) +// )); +// } + List team = new ArrayList<>(); + team.add(new Player(2, "Douglas", 35000L, "FCB")); + team.add(new Player(3, "Pique", 130000L,"FCB")); + team.add(new Player(4, "Rakitic", 75000L, "FCB")); + team.add(new Player(5, "Busquets", 120000L, "FCB")); + team.add(new Player(6, "Dani Alves", 120000L, "FCB")); + team.add(new Player(7, "Sanek", 123456L, "FC Vodnik")); + team.add(new Player(8, "Iniesta", 150000L ,"FCB")); + team.add(new Player(9, "Suarez", 200000L, "FCB")); + team.add(new Player(10, "Messi", 256000L, "FCB")); + team.add(new Player(11, "Neymar", 150000L, "FCB")); + assertEquals(team.size(), answer.size()); + for(int i = 0; i < team.size(); ++i) { + assertEquals(team.get(i).toString(), answer.get(i).toString()); + } +// List selectZvezdochkaResult = myFourthService.queryForAll(); +// System.out.println(selectZvezdochkaResult.toString()); + } +} + diff --git a/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/DatabaseService/TClassAnnotations/SQLTypeConverterTest.java b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/DatabaseService/TClassAnnotations/SQLTypeConverterTest.java new file mode 100644 index 0000000..d77e5d9 --- /dev/null +++ b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/DatabaseService/TClassAnnotations/SQLTypeConverterTest.java @@ -0,0 +1,83 @@ +package ru.mipt.diht.students.simon23rus.DatabaseService.TClassAnnotations; + +import junit.framework.TestCase; + +import junit.framework.TestCase; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.internal.rules.JunitRuleImpl; +import org.mockito.runners.MockitoJUnitRunner; +import ru.mipt.diht.students.simon23rus.CQL.data.CollectionQuery; +import ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseService; +import ru.mipt.diht.students.simon23rus.TwitterStream.TwitterStreamer; + +import java.math.BigDecimal; +import java.sql.*; +import java.util.AbstractList; +import java.util.ArrayList; +import java.util.List; + +/** + * Created by semenfedotov on 16.12.15. + */ +@RunWith(MockitoJUnitRunner.class) +public class SQLTypeConverterTest extends TestCase { + List toTest = new ArrayList<>(); + + @Before + public void setUp() { + toTest.add(String.class); + toTest.add(BigDecimal.class); + toTest.add(boolean.class); + toTest.add(byte.class); + toTest.add(short.class); + toTest.add(int.class); + toTest.add(Integer.class); + toTest.add(Long.class); + toTest.add(long.class); + toTest.add(float.class); + toTest.add(double.class); + toTest.add(Double.class); + toTest.add(Date.class); + toTest.add(Time.class); + toTest.add(Timestamp.class); + toTest.add(Blob.class); + toTest.add(Clob.class); + toTest.add(Array.class); + toTest.add(AbstractList.class); + toTest.add(Thread.class); + toTest.add(Exception.class); + toTest.add(CollectionQuery.class); + toTest.add(DatabaseService.class); + toTest.add(TwitterStreamer.class); + } + + @Test + public void convertToSQLTypeTest() { + assertEquals("VARCHAR(20)", SQLTypeConverter.convertToSQLType(toTest.get(0))); + assertEquals("NUMERIC", SQLTypeConverter.convertToSQLType(toTest.get(1))); + assertEquals("BOOLEAN", SQLTypeConverter.convertToSQLType(toTest.get(2))); + assertEquals("TINYINT", SQLTypeConverter.convertToSQLType(toTest.get(3))); + assertEquals("SHORTINT", SQLTypeConverter.convertToSQLType(toTest.get(4))); + assertEquals("INTEGER", SQLTypeConverter.convertToSQLType(toTest.get(5))); + assertEquals("INTEGER", SQLTypeConverter.convertToSQLType(toTest.get(6))); + assertEquals("BIGINT", SQLTypeConverter.convertToSQLType(toTest.get(7))); + assertEquals("BIGINT", SQLTypeConverter.convertToSQLType(toTest.get(8))); + assertEquals("REAL", SQLTypeConverter.convertToSQLType(toTest.get(9))); + assertEquals("DOUBLE", SQLTypeConverter.convertToSQLType(toTest.get(10))); + assertEquals("DOUBLE", SQLTypeConverter.convertToSQLType(toTest.get(11))); + assertEquals("DATE", SQLTypeConverter.convertToSQLType(toTest.get(12))); + assertEquals("TIME", SQLTypeConverter.convertToSQLType(toTest.get(13))); + assertEquals("TIMESTAMP", SQLTypeConverter.convertToSQLType(toTest.get(14))); + assertEquals("BLOB", SQLTypeConverter.convertToSQLType(toTest.get(15))); + assertEquals("CLOB", SQLTypeConverter.convertToSQLType(toTest.get(16))); + assertEquals("ARRAY", SQLTypeConverter.convertToSQLType(toTest.get(17))); + assertEquals("SQL doesn't support your Class", SQLTypeConverter.convertToSQLType(toTest.get(18))); + assertEquals("SQL doesn't support your Class", SQLTypeConverter.convertToSQLType(toTest.get(19))); + assertEquals("SQL doesn't support your Class", SQLTypeConverter.convertToSQLType(toTest.get(20))); + assertEquals("SQL doesn't support your Class", SQLTypeConverter.convertToSQLType(toTest.get(21))); + assertEquals("SQL doesn't support your Class", SQLTypeConverter.convertToSQLType(toTest.get(22))); + assertEquals("SQL doesn't support your Class", SQLTypeConverter.convertToSQLType(toTest.get(23))); + } +} diff --git a/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/Threads/BlockingQueueTest.java b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/Threads/BlockingQueueTest.java new file mode 100644 index 0000000..73b8f75 --- /dev/null +++ b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/Threads/BlockingQueueTest.java @@ -0,0 +1,182 @@ +package ru.mipt.diht.students.simon23rus.Threads; + + +import junit.framework.TestCase; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.runners.MockitoJUnitRunner; + +import java.sql.Array; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Created by semenfedotov on 14.12.15. + */ +@RunWith(MockitoJUnitRunner.class) +public class BlockingQueueTest extends TestCase { + BlockingQueue myBlockingQueue; + + @Test + public void additionTest() { + myBlockingQueue = new BlockingQueue(5); + List toAdd = Arrays.asList(1, 8, 9, 9); + myBlockingQueue.offer(toAdd); + List myQueueElements = myBlockingQueue.getData(); + assertEquals(toAdd.size(), myQueueElements.size()); + for(int i = 0; i < myQueueElements.size(); ++i) { + assertEquals(toAdd.get(i), myQueueElements.get(i)); + } + } + + @Test + public void deletionTest() { + myBlockingQueue = new BlockingQueue(5); + List toAdd = Arrays.asList(1, 8, 9, 9, 1); + myBlockingQueue.offer(toAdd); + List yearOfFoundationFCB = myBlockingQueue.take(4); + List myQueueElements = myBlockingQueue.getData(); + assertEquals(toAdd.size(), myQueueElements.size() + 4); + List toCheck = Arrays.asList(1, 8, 9, 9); + assertEquals(toCheck.size(), yearOfFoundationFCB.size()); + for(int i = 0; i < toCheck.size(); ++i) { + assertEquals(toCheck.get(i), yearOfFoundationFCB.get(i)); + } + } + + @Test + public void notFullLockTest() throws InterruptedException { + myBlockingQueue = new BlockingQueue(5); + List toAdd = Arrays.asList(1, 8, 9, 9, 1, -1); + Thread adder = new Thread(() -> myBlockingQueue.offer(toAdd)); + adder.start(); + adder.join(567); + if(adder.isAlive()) { + //znachit vse ploho, on ozhidaet sihnala na zapis'; + assert(true); + } + else + assert(false); + } + + + @Test + public void notEmptyLockTest() throws InterruptedException { + myBlockingQueue = new BlockingQueue(5); + Thread adder = new Thread(() -> myBlockingQueue.take(3)); + adder.start(); + adder.join(567); + if(adder.isAlive()) { + //znachit vse ploho, on ozhidaet sihnala na zapis'; + assert(true); + } + else + assert(false); + } + + @Test + public void hardUsageTest() throws InterruptedException { + myBlockingQueue = new BlockingQueue(5); + List toAdd = Arrays.asList(1, 8, 9, 9); + Integer numberForDeletion = 2; + List deletionResult = new ArrayList(); + Thread deleter = new Thread(() -> {deletionResult.addAll(myBlockingQueue.take(numberForDeletion));}); + Thread adder = new Thread(() -> myBlockingQueue.offer(toAdd)); + deleter.start(); adder.start(); + adder.join(); + deleter.join(); + assertEquals(2, deletionResult.size()); + for(int i = 0; i < 2; ++i) { + assertEquals(toAdd.get(i), deletionResult.get(i)); + } + assertEquals(2, myBlockingQueue.getData().size()); + for(int i = 0; i < 2; ++i) { + assertEquals(toAdd.get(i + numberForDeletion), myBlockingQueue.getData().get(i)); + } + System.out.println(myBlockingQueue.getData()); + + } + + @Test + public void timedAdditionTest() { + myBlockingQueue = new BlockingQueue(5); + List toAdd = Arrays.asList(1, 8, 9, 9); + myBlockingQueue.offer(toAdd, 500L); + List myQueueElements = myBlockingQueue.getData(); + assertEquals(toAdd.size(), myQueueElements.size()); + for(int i = 0; i < myQueueElements.size(); ++i) { + assertEquals(toAdd.get(i), myQueueElements.get(i)); + } + } + + @Test + public void timedDeletionTest() { + myBlockingQueue = new BlockingQueue(5); + List toAdd = Arrays.asList(1, 8, 9, 9, 1); + myBlockingQueue.offer(toAdd, 500L); + List yearOfFoundationFCB = myBlockingQueue.take(4); + List myQueueElements = myBlockingQueue.getData(); + assertEquals(toAdd.size(), myQueueElements.size() + 4); + List toCheck = Arrays.asList(1, 8, 9, 9); + assertEquals(toCheck.size(), yearOfFoundationFCB.size()); + for(int i = 0; i < toCheck.size(); ++i) { + assertEquals(toCheck.get(i), yearOfFoundationFCB.get(i)); + } + } + + @Test + public void timedTLNotFullLockTest() throws InterruptedException { + myBlockingQueue = new BlockingQueue(5); + List toAdd = Arrays.asList(1, 8, 9, 9, 1, -1); + Thread adder = new Thread(() -> myBlockingQueue.offer(toAdd, 500L)); + adder.start(); + adder.join(800); + if(adder.isAlive()) { + //znachit vse horosho, on poluchil TL'; + assert(false); + } + else + assert(true); + } + + + + @Test + public void timedTLNotEmptyLockTest() throws InterruptedException { + myBlockingQueue = new BlockingQueue(5); + Thread adder = new Thread(() -> myBlockingQueue.take(3, 500L)); + adder.start(); + adder.join(1000); + if(adder.isAlive()) { + //znachit vse horosho, on poluchil TL'; + assert(false); + } + else + assert(true); + } + + @Test + public void timedHardUsageTest() throws InterruptedException { + myBlockingQueue = new BlockingQueue(5); + List toAdd = Arrays.asList(1, 8, 9, 9); + Integer numberForDeletion = 2; + List deletionResult = new ArrayList(); + Thread deleter = new Thread(() -> {deletionResult.addAll(myBlockingQueue.take(numberForDeletion, 500L));}); + Thread adder = new Thread(() -> myBlockingQueue.offer(toAdd, 500L)); + deleter.start(); adder.start(); + adder.join(); + deleter.join(); + assertEquals(2, deletionResult.size()); + for(int i = 0; i < 2; ++i) { + assertEquals(toAdd.get(i), deletionResult.get(i)); + } + assertEquals(2, myBlockingQueue.getData().size()); + for(int i = 0; i < 2; ++i) { + assertEquals(toAdd.get(i + numberForDeletion), myBlockingQueue.getData().get(i)); + } + System.out.println(myBlockingQueue.getData()); + + } +} diff --git a/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/TwitterStream/GeoCodeConverterTest.java b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/TwitterStream/GeoCodeConverterTest.java new file mode 100644 index 0000000..b198182 --- /dev/null +++ b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/TwitterStream/GeoCodeConverterTest.java @@ -0,0 +1,82 @@ +package ru.mipt.diht.students.simon23rus.TwitterStream; + + +import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.runners.MockitoJUnitRunner; +import twitter4j.GeoLocation; +import twitter4j.JSONException; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * Created by semenfedotov on 06.12.15. + */ +@RunWith(MockitoJUnitRunner.class) +public class GeoCodeConverterTest extends TestCase { + + @Test + public void getCoordinatesTest() throws InterruptedException, JSONException, IOException { + List citys = new ArrayList(); + citys.add("Краснодар"); + citys.add("Сочи"); + citys.add("Barcelona"); + citys.add("Deerfield_Beach"); + citys.add("lkjasdwoqeo"); + List coordinates = new ArrayList(); + coordinates.add(new Double[]{45.03926740000001, 38.987221}); + coordinates.add(new Double[]{43.60280789999999, 39.7341543}); + coordinates.add(new Double[]{41.3850639, 2.1734035}); + coordinates.add(new Double[]{26.3184123, -80.09976569999999}); + List locations = new ArrayList(); + locations.add(new GeoLocation(coordinates.get(0)[0], coordinates.get(0)[1])); + locations.add(new GeoLocation(coordinates.get(1)[0], coordinates.get(1)[1])); + locations.add(new GeoLocation(coordinates.get(2)[0], coordinates.get(2)[1])); + locations.add(new GeoLocation(coordinates.get(3)[0], coordinates.get(3)[1])); + assertEquals(locations.get(0), GeoCodeConverter.getCoordinates(citys.get(0))); + assertEquals(locations.get(1), GeoCodeConverter.getCoordinates(citys.get(1))); + assertEquals(locations.get(2), GeoCodeConverter.getCoordinates(citys.get(2))); + assertEquals(locations.get(3), GeoCodeConverter.getCoordinates(citys.get(3))); + assertEquals(new GeoLocation((double)-5, (double)-5), GeoCodeConverter.getCoordinates(citys.get(4))); + } + + @Test + public void sqrTest() { + List dataProvided = new ArrayList(); + for(double i = 0; i < 10000D; ++i) { + dataProvided.add(i * i); + assertEquals(dataProvided.get((int)i), GeoCodeConverter.sqr(i)); + } + + } + + @Test + public void nearTest() { + List citys = new ArrayList(); + citys.add("Краснодар"); + citys.add("Сочи"); + citys.add("Долгопрудный"); + citys.add("Khimki"); + citys.add("Москва"); + List coordinates = new ArrayList(); + coordinates.add(new Double[]{45.03926740000001, 38.987221}); + coordinates.add(new Double[]{43.60280789999999, 39.7341543}); + coordinates.add(new Double[]{55.947064, 37.4992755}); + coordinates.add(new Double[]{55.8940553, 37.4439487}); + coordinates.add(new Double[]{55.755826, 37.6173}); + + List locations = new ArrayList(); + locations.add(new GeoLocation(coordinates.get(0)[0], coordinates.get(0)[1])); + locations.add(new GeoLocation(coordinates.get(1)[0], coordinates.get(1)[1])); + locations.add(new GeoLocation(coordinates.get(2)[0], coordinates.get(2)[1])); + locations.add(new GeoLocation(coordinates.get(3)[0], coordinates.get(3)[1])); + locations.add(new GeoLocation(coordinates.get(4)[0], coordinates.get(4)[1])); + + assertEquals(false, GeoCodeConverter.near(locations.get(0), locations.get(1), 170)); //Krasnodar-Sochi + assertEquals(true, GeoCodeConverter.near(locations.get(0), locations.get(1), 171)); + assertEquals(true, GeoCodeConverter.near(locations.get(2), locations.get(3), 10));//Dolgoprudniy-Khrimki + } +} diff --git a/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/TwitterStream/TimeTransformerTest.java b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/TwitterStream/TimeTransformerTest.java new file mode 100644 index 0000000..12cdef0 --- /dev/null +++ b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/TwitterStream/TimeTransformerTest.java @@ -0,0 +1,76 @@ +package ru.mipt.diht.students.simon23rus.TwitterStream; + + +import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.runners.MockitoJUnitRunner; + +import java.time.LocalDate; +import java.util.*; + + +/** + * Created by semenfedotov on 06.12.15. + + */ + + +@RunWith(MockitoJUnitRunner.class) +public class TimeTransformerTest extends TestCase { +// private final List deltasInSecondsForRussian = new ArrayList<>(); +// List deltasInSecondsForYesterday = new ArrayList<>(); + + +// @Before +// public static void setUpDeltasInSecondsForRussian() { +// +// } +// +// @Before +// public static void setUpIsItYesterdayTweet() { +// +// } + @Test + public void testCorrectRussianText() { + final int SECONDS_IN_MINUTE = 60; + List deltasInSeconds = new ArrayList(); + deltasInSeconds.add(2L); + deltasInSeconds.add((2L + 2 * SECONDS_IN_MINUTE)); + deltasInSeconds.add((2L + 10 * SECONDS_IN_MINUTE)); + deltasInSeconds.add((2L + 70 * SECONDS_IN_MINUTE)); + deltasInSeconds.add((2L + 60 * 60 * SECONDS_IN_MINUTE)); + deltasInSeconds.add((2L + 200 * 24 * 60 * SECONDS_IN_MINUTE)); + + assertEquals("[<Только что>] ", TimeTransformer.correctRussianText(deltasInSeconds.get(0))); + assertEquals("[<2 минуты назад>] ", TimeTransformer.correctRussianText(deltasInSeconds.get(1))); + assertEquals("[<10 минут назад>] ", TimeTransformer.correctRussianText(deltasInSeconds.get(2))); + assertEquals("[<1 час назад>] ", TimeTransformer.correctRussianText(deltasInSeconds.get(3))); + assertEquals("[<2 дня назад>] ", TimeTransformer.correctRussianText(deltasInSeconds.get(4))); + assertEquals("[<200 дней назад>] ", TimeTransformer.correctRussianText(deltasInSeconds.get(5))); + } + + @Test + public void testIsYesterdayTweet() { + System.out.println("Testim"); + final int SECONDS_IN_MINUTE = 60; + List tweetsDates = new ArrayList(); + tweetsDates.add(new GregorianCalendar(2015, Calendar.DECEMBER, 12).getTime()); + tweetsDates.add(new GregorianCalendar(2015, Calendar.NOVEMBER, 12).getTime()); + tweetsDates.add(new GregorianCalendar(2015, Calendar.MARCH, 12).getTime()); + tweetsDates.add(new GregorianCalendar(2015, Calendar.DECEMBER, 11).getTime()); + tweetsDates.add(new GregorianCalendar(2015, Calendar.DECEMBER, 10).getTime()); + tweetsDates.add(new GregorianCalendar(1998, Calendar.DECEMBER, 12).getTime()); + tweetsDates.add(new GregorianCalendar(2015, Calendar.DECEMBER, 12).getTime()); + + + LocalDate today = LocalDate.now(); + assertEquals(false, TimeTransformer.isItYesterdayTweet(tweetsDates.get(0))); + assertEquals(false, TimeTransformer.isItYesterdayTweet(tweetsDates.get(1))); + assertEquals(false, TimeTransformer.isItYesterdayTweet(tweetsDates.get(2))); + assertEquals(false, TimeTransformer.isItYesterdayTweet(tweetsDates.get(3))); + assertEquals(false, TimeTransformer.isItYesterdayTweet(tweetsDates.get(4))); + assertEquals(false, TimeTransformer.isItYesterdayTweet(tweetsDates.get(5))); + assertEquals(false, TimeTransformer.isItYesterdayTweet(tweetsDates.get(6))); + } +} \ No newline at end of file diff --git a/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/TwitterStream/Twitter4jTestUtilsTest.java b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/TwitterStream/Twitter4jTestUtilsTest.java new file mode 100644 index 0000000..fb0f7c8 --- /dev/null +++ b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/TwitterStream/Twitter4jTestUtilsTest.java @@ -0,0 +1,14 @@ +package ru.mipt.diht.students.simon23rus.TwitterStream; + + +import junit.framework.TestCase; + +/** + * Created by semenfedotov on 13.12.15. + */ +public class Twitter4jTestUtilsTest extends TestCase { + + public void testTweetsFromJson() throws Exception { + + } +} \ No newline at end of file diff --git a/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/TwitterStream/TwitterPrinterTest.java b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/TwitterStream/TwitterPrinterTest.java new file mode 100644 index 0000000..efb89d1 --- /dev/null +++ b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/TwitterStream/TwitterPrinterTest.java @@ -0,0 +1,73 @@ +package ru.mipt.diht.students.simon23rus.TwitterStream; + + +import junit.framework.TestCase; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.runners.MockitoJUnitRunner; +import twitter4j.Status; +import twitter4j.User; + +import java.util.*; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Created by semenfedotov on 06.12.15. + */ +@RunWith(MockitoJUnitRunner.class) +public class TwitterPrinterTest extends TestCase { + + @Test + public void makeBlueTest() { + List toPaint = new ArrayList(); + toPaint.add("Снег в лесу закутал елку,"); + toPaint.add("Спрятал елку от ребят."); + toPaint.add("Ночью елка втихомолку"); + toPaint.add("Пробежала в детский сад."); + toPaint.add("А у нас в саду веселье,"); + toPaint.add("Пляшет шумный хоровод."); + toPaint.add("Под молоденькой елью"); + toPaint.add("Мы встречаем Новый год!"); + System.out.println(toPaint); + assertEquals(((char) 27 + "[34;1m@" + toPaint.get(0)).toString(), TwitterPrinter.makeBlue(toPaint.get(0))); + assertEquals(((char)27 + "[34;1m@" + toPaint.get(1)).toString(), TwitterPrinter.makeBlue(toPaint.get(1))); + assertEquals(((char)27 + "[34;1m@" + toPaint.get(2)).toString(), TwitterPrinter.makeBlue(toPaint.get(2))); + assertEquals(((char)27 + "[34;1m@" + toPaint.get(3)).toString(), TwitterPrinter.makeBlue(toPaint.get(3))); + assertEquals(((char)27 + "[34;1m@" + toPaint.get(4)).toString(), TwitterPrinter.makeBlue(toPaint.get(4))); + assertEquals(((char)27 + "[34;1m@" + toPaint.get(5)).toString(), TwitterPrinter.makeBlue(toPaint.get(5))); + assertEquals(((char)27 + "[34;1m@" + toPaint.get(6)).toString(), TwitterPrinter.makeBlue(toPaint.get(6))); + assertEquals(((char)27 + "[34;1m@" + toPaint.get(7)).toString(), TwitterPrinter.makeBlue(toPaint.get(7))); + + + } + + @Test + public void printStringWithFormatTest() { + //testing tweet + Status tweet = mock(Status.class); + Status secondTweet = mock(Status.class); + Status retweet = mock(Status.class); + User user = mock(User.class); + when(tweet.getCreatedAt()).thenReturn(new GregorianCalendar(2007, Calendar.SEPTEMBER, 7).getTime()); + when(tweet.isRetweet()).thenReturn(false); + when(tweet.getText()).thenReturn("p^k ili logarithm"); + when(tweet.getRetweetCount()).thenReturn(497); + when(tweet.getUser()).thenReturn(user); + when(secondTweet.getCreatedAt()).thenReturn(new GregorianCalendar(2007, Calendar.SEPTEMBER, 7).getTime()); + when(secondTweet.isRetweet()).thenReturn(true); + when(secondTweet.getText()).thenReturn("p^k ili logarithm"); + when(secondTweet.getRetweetCount()).thenReturn(497); + when(secondTweet.getRetweetedStatus()).thenReturn(retweet); + when(secondTweet.getUser()).thenReturn(user); + when(retweet.getUser()).thenReturn(user); + when(user.getScreenName()).thenReturn("sobaka"); + + Date currentTime = new GregorianCalendar(2007, Calendar.OCTOBER, 22).getTime(); + assertEquals("\u001B[35;1;4m[<45 дней назад>] \u001B[34;1m@sobaka\u001B[0m:p^k ili logarithm\u001B[42m(<497> Ретвитов)\u001B[0m", TwitterPrinter.printStringWithFormat(currentTime, tweet, true)); + assertEquals("\u001B[35;1;4m[<45 дней назад>] \u001B[34;1m@sobaka:\u001B[33;4m ретвитнул \u001B[31;1m@sobaka\u001B[0m:p^k ili logarithm", TwitterPrinter.printStringWithFormat(currentTime, secondTweet, true)); + assertEquals("\u001B[34;1m@sobaka\u001B[0m:p^k ili logarithm\u001B[42m(<497> Ретвитов)\u001B[0m", TwitterPrinter.printStringWithFormat(currentTime, tweet, false)); + } + +} diff --git a/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/TwitterStream/TwitterStreamerTest.java b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/TwitterStream/TwitterStreamerTest.java new file mode 100644 index 0000000..4b5d62a --- /dev/null +++ b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/TwitterStream/TwitterStreamerTest.java @@ -0,0 +1,13 @@ +package ru.mipt.diht.students.simon23rus.TwitterStream; + + +/** + * Created by semenfedotov on 06.12.15. + */ +//@RunWith(MockitoJUnitRunner.class) +//@PrepareForTest({TwitterStream.class, TwitterFactory.class, GeoCodeConverter.class, TwitterPrinter.class}) +//public class TwitterStreamerTest extends TestCase { +// +// private List tweets; +// +//} diff --git a/projects/simon23rus/src/test/java/twitter4j/Twitter4jTestUtils.java b/projects/simon23rus/src/test/java/twitter4j/Twitter4jTestUtils.java new file mode 100644 index 0000000..6980004 --- /dev/null +++ b/projects/simon23rus/src/test/java/twitter4j/Twitter4jTestUtils.java @@ -0,0 +1,29 @@ +package twitter4j; + +import twitter4j.*; + import org.apache.commons.io.IOUtils; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +/** + * Created by semenfedotov on 13.12.15. + */ +public class Twitter4jTestUtils { + public static List tweetsFromJson(String resource) { + try (InputStream inputStream = twitter4j.Twitter4jTestUtils.class.getResourceAsStream(resource)) { + JSONObject json = new JSONObject(IOUtils.toString(inputStream)); + JSONArray array = json.getJSONArray("statuses"); + List tweets = new ArrayList<>(array.length()); + for (int i = 0; i < array.length(); i++) { + JSONObject tweet = array.getJSONObject(i); + tweets.add(new StatusJSONImpl(tweet)); + } + return tweets; + } catch (IOException | JSONException | TwitterException e) { + throw new RuntimeException(e); + } + } +} \ No newline at end of file diff --git a/solutions/simon23rus/TwitterStream/twitterMiptStream/pom.xml b/solutions/simon23rus/TwitterStream/twitterMiptStream/pom.xml new file mode 100644 index 0000000..c821d02 --- /dev/null +++ b/solutions/simon23rus/TwitterStream/twitterMiptStream/pom.xml @@ -0,0 +1,81 @@ + + 4.0.0 + mipt + mipt + war + 1.0-SNAPSHOT + mipt Maven Webapp + http://maven.apache.org + + + + + + junit + junit + 3.8.1 + test + + + + org.apache.commons + commons-lang3 + 3.0 + + + + org.slf4j + slf4j-api + 1.5.6 + jar + + + + org.slf4j + slf4j-simple + 1.5.6 + + + + org.twitter4j + twitter4j-core + [4.0,) + + + + org.twitter4j + twitter4j-stream + [4.0,) + + + + com.beust + jcommander + 1.48 + + + + com.google.code.geocoder-java + geocoder-java + 0.16 + + + + + + src + + + maven-compiler-plugin + 3.1 + + 1.7 + 1.7 + + + + mipt + + + diff --git a/solutions/simon23rus/TwitterStream/twitterMiptStream/src/myJCommander.java b/solutions/simon23rus/TwitterStream/twitterMiptStream/src/myJCommander.java new file mode 100644 index 0000000..d39e5da --- /dev/null +++ b/solutions/simon23rus/TwitterStream/twitterMiptStream/src/myJCommander.java @@ -0,0 +1,53 @@ +/** + * Created by semenfedotov on 22.09.15. + */ +import com.beust.jcommander.Parameter; + +import java.util.ArrayList; +import java.util.List; + +/* [--query|-q ] \ + [--place|-p ] \ + [--stream|-s] \ + [--hideRetweets] \ + [--limit|-l ] \ + [--help|-h] +*/ + + +public class myJCommander { + + @Parameter + private List parameters = new ArrayList<>(); + + @Parameter(names = "--post", description = "Just to post some tweets") + public String toPost; + + + @Parameter(names = { "--query", "-q" }, description = "Parameters 4 query search") + public String query; + + public String[] getClearQuery() { + if(query == null) { + String[] emptyString = {}; + return emptyString; + } + return query.split("\\s"); + } + + @Parameter(names = { "--place", "-p" }, description = "Places what R U looking 4") + public String place = "aroundtheworld"; + + @Parameter(names = {"--stream", "-s"}, description = "To print smth with 1sec delay") + public boolean stream = false; + + @Parameter(names = "--hideRetweets", description = "thing which just hide Retweets") + public boolean hideRetweets = false; + + @Parameter(names = {"--limit", "-l"}, description = "How many tweets to show") + public int tweetsByQuery = 100; + + + @Parameter(names = { "--help", "-h"}, description = "Just piece of help 4 User", help = true) + public boolean help = false; +} diff --git a/solutions/simon23rus/TwitterStream/twitterMiptStream/src/twitterStreamer.java b/solutions/simon23rus/TwitterStream/twitterMiptStream/src/twitterStreamer.java new file mode 100644 index 0000000..b2f0094 --- /dev/null +++ b/solutions/simon23rus/TwitterStream/twitterMiptStream/src/twitterStreamer.java @@ -0,0 +1,267 @@ + +import com.beust.jcommander.JCommander; +import twitter4j.*; +import twitter4j.util.TimeSpanConverter; + +import java.lang.String; +import java.lang.System; +import java.net.URLConnection; +import java.text.SimpleDateFormat; +import java.util.*; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URL; +import com.google.code.geocoder.*; +import com.google.code.geocoder.model.*; + + +public class twitterStreamer { + + private static final short countryCodeSize = 2; + private static String searchingPlace; + private static boolean retweetCollapse; + private static int tweetsLimit; + private static final int SECONDS_IN_YEAR = 60 * 60 * 24 * 365; + private static final int SECONDS_IN_MONTH = 60 * 60 * 24 * 30; + private static final int SECONDS_IN_DAY = 60 * 60 * 24; + private static final int SECONDS_IN_HOUR = 60 * 60; + private static final int SECONDS_IN_MINUTE = 60; + private static boolean isItYesterday; + + + + + public static String correctRussianText(int deltaInSeconds) { + if(deltaInSeconds < 2 * SECONDS_IN_MINUTE) + return "[<Только что>] "; + else if(deltaInSeconds < SECONDS_IN_HOUR) { + int minutes = deltaInSeconds / SECONDS_IN_MINUTE; + if(minutes >= 15 || minutes <= 10) { + if (minutes % 10 == 1) + return "[<" + minutes + " минуту назад>] "; + else if (minutes % 10 == 2 || minutes % 10 == 3 || minutes % 10 == 4) + return "[<" + minutes + " минуты назад>] "; + else + return "[<" + minutes + " минут назад>] "; + } + else + return "[<" + minutes + " минут назад>] "; + } + + else if(isItYesterday) + return "[<вчера>] "; + + else if(deltaInSeconds < 24 * SECONDS_IN_HOUR) { + int hours = deltaInSeconds / SECONDS_IN_HOUR; + if (hours >= 15 || hours <= 10) { + if (hours % 10 == 1) + return "[<" + hours + " час назад>] "; + else if (hours % 10 == 2 || hours % 10 == 3 || hours % 10 == 4) + return "[<" + hours + " часа назад>] "; + else + return "[<" + hours + " часов назад>] "; + } else + return "[<" + hours + " часов назад>] "; + } + else { + int days = deltaInSeconds / SECONDS_IN_DAY; + if (days >= 15 || days <= 10) { + if (days % 10 == 1) + return "[<" + days + " день назад>] "; + else if (days % 10 == 2 || days % 10 == 3 || days % 10 == 4) + return "[<" + days + " дня назад>] "; + else + return "[<" + days + " дней назад>] "; + } else + return "[<" + days + " дней назад>] "; + } + } + + public static StatusListener listener = new StatusListener(){ + public void onStatus(Status givenTweet) { + printStringWithFormat(givenTweet, false); + try { + Thread.sleep(1000); //1000=1. + } catch(InterruptedException ex) { + Thread.currentThread().interrupt(); + } + } + public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {} + public void onTrackLimitationNotice(int numberOfLimitedStatuses) {} + public void onException(Exception ex) { + //ex.printStackTrace(); + } + @Override + public void onStallWarning(StallWarning x){} + @Override + public void onScrubGeo(long first, long second){} + }; + + public static int getDeltaInTime(Status tweet) { + TimeSpanConverter converter = new TimeSpanConverter(); + System.out.println(converter.toTimeSpanString(tweet.getCreatedAt())); + + Date currentDate = Calendar.getInstance().getTime(); + + Date tweetDate = tweet.getCreatedAt(); + String currentYear = new SimpleDateFormat("yy").format(currentDate); + String currentMonth = new SimpleDateFormat("MM").format(currentDate); + String currentDay = new SimpleDateFormat("dd").format(currentDate); + String currentHour = new SimpleDateFormat("HH").format(currentDate); + String currentMinute = new SimpleDateFormat("mm").format(currentDate); + String currentSecond = new SimpleDateFormat("ss").format(currentDate); + + long firstSec = currentDate.getTime(); + long tweetSec = tweetDate.getTime(); + System.out.println(firstSec - tweetSec + "d9y3129"); + + String tweetYear = new SimpleDateFormat("yy").format(tweetDate); + String tweetMonth = new SimpleDateFormat("MM").format(tweetDate); + String tweetDay = new SimpleDateFormat("dd").format(tweetDate); + String tweetHour = new SimpleDateFormat("HH").format(tweetDate); + String tweetMinute = new SimpleDateFormat("mm").format(tweetDate); + String tweetSecond = new SimpleDateFormat("ss").format(tweetDate); + + System.out.println(new SimpleDateFormat("yyyy MM dd hh mm ss").format(currentDate)); + System.out.println(tweetYear + " " + tweetMonth + " " + tweetDay + " " + tweetHour + " " + tweetMinute + " " + tweetSecond); + + int secondsDelta = + (Integer.valueOf(currentYear) - Integer.valueOf(tweetYear)) * SECONDS_IN_YEAR + + (Integer.valueOf(currentMonth) - Integer.valueOf(tweetMonth)) * SECONDS_IN_MONTH + + (Integer.valueOf(currentDay) - Integer.valueOf(tweetDay)) * SECONDS_IN_DAY + + (Integer.valueOf(currentHour) - Integer.valueOf(tweetHour)) * SECONDS_IN_HOUR + + (Integer.valueOf(currentMinute) - Integer.valueOf(tweetMinute)) * SECONDS_IN_MINUTE + + Integer.valueOf(currentSecond) - Integer.valueOf(tweetSecond); + + System.out.println(secondsDelta); + + int todaySeconds = Integer.valueOf(currentSecond) + Integer.valueOf(currentMinute) * SECONDS_IN_MINUTE + Integer.valueOf(currentHour) * SECONDS_IN_HOUR; + System.out.println(todaySeconds); + if(secondsDelta < SECONDS_IN_DAY + todaySeconds && secondsDelta > todaySeconds) + isItYesterday = true; + else + isItYesterday = false; + + return secondsDelta; + } + + + public static void printStringWithFormat(Status tweet, boolean timeIsNeeded) { + String tweetToShow = ""; + System.out.println(tweet.getText() + "etotext\n"); + if(timeIsNeeded) { + int delta = getDeltaInTime(tweet); + tweetToShow += (char) 27 + "[35;1;4m" + correctRussianText(delta); + } + tweetToShow += (char) 27 + "[34;1m@" + tweet.getUser().getScreenName(); + if(tweet.isRetweet()) + tweetToShow += ":" + (char) 27 + "[33;4m" + " ретвитнул " + (char) 27 + "[31;1m@" + tweet.getRetweetedStatus().getUser().getScreenName() + (char) 27 + "[0m" + ":" + tweet.getText().substring(5 + tweet.getRetweetedStatus().getUser().getScreenName().length()); + else + tweetToShow += (char) 27 + "[0m" + ":" + tweet.getText(); + if(!tweet.isRetweet()) + tweetToShow += (char) 27 + "[42m" + "(<" + tweet.getRetweetCount() + "> Ретвитов)" + (char) 27 + "[0m"; + System.out.println(tweetToShow); + + + } + + + + private static String webSource() throws IOException, JSONException { + URL newUrl = new URL("http://ip-api.com/json"); + URLConnection urlConnecter = newUrl.openConnection(); + BufferedReader in = new BufferedReader(new InputStreamReader( + urlConnecter.getInputStream(), "UTF-8")); + JSONObject givenSource = new JSONObject(in.readLine()); + StringBuilder mySourse = new StringBuilder(); + mySourse.append(givenSource.getString("city")); + in.close(); + return mySourse.toString(); + } + + public static GeoLocation convertToGeoCode(String thisPlace) throws IOException, JSONException { + if ("nearby".equals(thisPlace)) { + thisPlace = webSource(); + System.out.println("thisplac" + thisPlace); + } + try { + final Geocoder geocoder = new Geocoder(); + GeocoderRequest geocoderRequest = new GeocoderRequestBuilder().setAddress(thisPlace).getGeocoderRequest(); + GeocodeResponse geocoderResponse = geocoder.geocode(geocoderRequest); + List geocoderResult = geocoderResponse.getResults(); + float latitude = geocoderResult.get(0).getGeometry().getLocation().getLat().floatValue(); + float longitude = geocoderResult.get(0).getGeometry().getLocation().getLng().floatValue(); + System.out.printf("%f, \n %f", latitude, longitude); + GeoLocation gl = new GeoLocation(latitude, longitude); + return gl; + } catch (Exception ge) { + System.out.println("Error in Geocoder: " + ge.getMessage()); + } + return null; + } + + + + + public static void main(String[] args) throws TwitterException, IOException, InterruptedException, JSONException { + + myJCommander jct = new myJCommander(); + new JCommander(jct, args); + + if(jct.getClearQuery().equals(null) || jct.help) { + System.out.println("Now U R getting hints 4 usage dat" + + "\n[--query|-q ]\n" + + "[--place|-p ]\n" + + "[--stream|-s]\n" + + "[--hideRetweets]\n" + + "[--limit|-l ]\n" + + "[--help|-h]\n"); + return; + } + + Twitter twitter = new TwitterFactory().getInstance(); + if(jct.toPost != null) + twitter.updateStatus(jct.toPost); + searchingPlace = jct.place; + retweetCollapse = jct.hideRetweets; + tweetsLimit = jct.tweetsByQuery; + + + System.out.println("It is your searching place " + searchingPlace); + + System.out.println("city, where you are surfing now " + webSource()); + + if(jct.stream) { + TwitterStream myTwitterStream = new TwitterStreamFactory().getInstance(); + myTwitterStream.addListener(listener); + FilterQuery myFilter = new FilterQuery(); + String[] toTrack = {jct.query}; + myFilter.track(toTrack); + myTwitterStream.filter(myFilter); + } + else { + if(retweetCollapse) + jct.query += " +exclude:retweets"; + Query query = new Query(jct.query); + QueryResult result; + query.setCount(tweetsLimit); + if(!searchingPlace.equals("aroundtheworld")) + query.setGeoCode(convertToGeoCode(searchingPlace), 40, Query.Unit.km); + int counter = 0; + do { + result = twitter.search(query); + List tweetsFound = result.getTweets(); + for(Status tweet : tweetsFound) { + printStringWithFormat(tweet, true); +// System.out.println(tweet.getPlace()); + ++counter; + if (counter == tweetsLimit) + return; + } + } while ((counter < tweetsLimit) && (query = result.nextQuery()) != null); + } + + } + +} \ No newline at end of file