From 3ca58c47ab6c10c03f28afe35902e97703d7bd2b Mon Sep 17 00:00:00 2001 From: Semyon Fedotov Date: Fri, 2 Oct 2015 20:45:23 +0300 Subject: [PATCH 01/13] TwitterStream Added --- .../TwitterStream/twitterMiptStream/pom.xml | 81 ++++++ .../src/main/webapp/WEB-INF/web.xml | 7 + .../src/main/webapp/index.jsp | 5 + .../twitterMiptStream/src/myJCommander.java | 53 ++++ .../src/twitterStreamer.java | 267 ++++++++++++++++++ .../twitterMiptStream/twitter4j.properties | 5 + 6 files changed, 418 insertions(+) create mode 100644 solutions/simon23rus/TwitterStream/twitterMiptStream/pom.xml create mode 100644 solutions/simon23rus/TwitterStream/twitterMiptStream/src/main/webapp/WEB-INF/web.xml create mode 100644 solutions/simon23rus/TwitterStream/twitterMiptStream/src/main/webapp/index.jsp create mode 100644 solutions/simon23rus/TwitterStream/twitterMiptStream/src/myJCommander.java create mode 100644 solutions/simon23rus/TwitterStream/twitterMiptStream/src/twitterStreamer.java create mode 100644 solutions/simon23rus/TwitterStream/twitterMiptStream/twitter4j.properties 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/main/webapp/WEB-INF/web.xml b/solutions/simon23rus/TwitterStream/twitterMiptStream/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..9f88c1f --- /dev/null +++ b/solutions/simon23rus/TwitterStream/twitterMiptStream/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,7 @@ + + + + Archetype Created Web Application + diff --git a/solutions/simon23rus/TwitterStream/twitterMiptStream/src/main/webapp/index.jsp b/solutions/simon23rus/TwitterStream/twitterMiptStream/src/main/webapp/index.jsp new file mode 100644 index 0000000..c38169b --- /dev/null +++ b/solutions/simon23rus/TwitterStream/twitterMiptStream/src/main/webapp/index.jsp @@ -0,0 +1,5 @@ + + +

Hello World!

+ + 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 diff --git a/solutions/simon23rus/TwitterStream/twitterMiptStream/twitter4j.properties b/solutions/simon23rus/TwitterStream/twitterMiptStream/twitter4j.properties new file mode 100644 index 0000000..5c97e03 --- /dev/null +++ b/solutions/simon23rus/TwitterStream/twitterMiptStream/twitter4j.properties @@ -0,0 +1,5 @@ +debug=true +oauth.consumerKey=hAFkeVBysLVa7jYrk9jeCxd54 +oauth.consumerSecret=ZHtTTNz2fXsdBIvCwfV0KFf9SP1CZKo0vpsQGSrgrK1oW239ry +oauth.accessToken=396146643-H0feNnHqXAl6p3fdFMfREc0KPOwme6h7wwb9Ekih +oauth.accessTokenSecret=YHiDyJG8qdfFrE4jKBzwpaiaiZz2QgVgjQWJMrjk98lQU \ No newline at end of file From ea01ddd2ab5abe69089e5492f1137cdb3e1cc36c Mon Sep 17 00:00:00 2001 From: simon23rus Date: Fri, 2 Oct 2015 20:49:17 +0300 Subject: [PATCH 02/13] Delete twitter4j.properties --- .../TwitterStream/twitterMiptStream/twitter4j.properties | 5 ----- 1 file changed, 5 deletions(-) delete mode 100644 solutions/simon23rus/TwitterStream/twitterMiptStream/twitter4j.properties diff --git a/solutions/simon23rus/TwitterStream/twitterMiptStream/twitter4j.properties b/solutions/simon23rus/TwitterStream/twitterMiptStream/twitter4j.properties deleted file mode 100644 index 5c97e03..0000000 --- a/solutions/simon23rus/TwitterStream/twitterMiptStream/twitter4j.properties +++ /dev/null @@ -1,5 +0,0 @@ -debug=true -oauth.consumerKey=hAFkeVBysLVa7jYrk9jeCxd54 -oauth.consumerSecret=ZHtTTNz2fXsdBIvCwfV0KFf9SP1CZKo0vpsQGSrgrK1oW239ry -oauth.accessToken=396146643-H0feNnHqXAl6p3fdFMfREc0KPOwme6h7wwb9Ekih -oauth.accessTokenSecret=YHiDyJG8qdfFrE4jKBzwpaiaiZz2QgVgjQWJMrjk98lQU \ No newline at end of file From f03625dc8416781191615282d353bb2e833d9926 Mon Sep 17 00:00:00 2001 From: simon23rus Date: Fri, 2 Oct 2015 20:49:38 +0300 Subject: [PATCH 03/13] Delete index.jsp --- .../twitterMiptStream/src/main/webapp/index.jsp | 5 ----- 1 file changed, 5 deletions(-) delete mode 100644 solutions/simon23rus/TwitterStream/twitterMiptStream/src/main/webapp/index.jsp diff --git a/solutions/simon23rus/TwitterStream/twitterMiptStream/src/main/webapp/index.jsp b/solutions/simon23rus/TwitterStream/twitterMiptStream/src/main/webapp/index.jsp deleted file mode 100644 index c38169b..0000000 --- a/solutions/simon23rus/TwitterStream/twitterMiptStream/src/main/webapp/index.jsp +++ /dev/null @@ -1,5 +0,0 @@ - - -

Hello World!

- - From cd4328379048ebb4ebf29df4b77d4f9f57744e60 Mon Sep 17 00:00:00 2001 From: simon23rus Date: Fri, 2 Oct 2015 20:49:50 +0300 Subject: [PATCH 04/13] Delete web.xml --- .../twitterMiptStream/src/main/webapp/WEB-INF/web.xml | 7 ------- 1 file changed, 7 deletions(-) delete mode 100644 solutions/simon23rus/TwitterStream/twitterMiptStream/src/main/webapp/WEB-INF/web.xml diff --git a/solutions/simon23rus/TwitterStream/twitterMiptStream/src/main/webapp/WEB-INF/web.xml b/solutions/simon23rus/TwitterStream/twitterMiptStream/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 9f88c1f..0000000 --- a/solutions/simon23rus/TwitterStream/twitterMiptStream/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - Archetype Created Web Application - From a20aae4b0b7a9a03b450a8801a1d5218a373cd0a Mon Sep 17 00:00:00 2001 From: Semyon Fedotov Date: Wed, 4 Nov 2015 14:55:30 +0300 Subject: [PATCH 05/13] uhhhhhh --- projects/simon23rus/pom.xml | 95 +++++++ projects/simon23rus/src/MyJCommander.java | 51 ++++ projects/simon23rus/src/TwitterStreamer.java | 249 +++++++++++++++++++ 3 files changed, 395 insertions(+) create mode 100644 projects/simon23rus/pom.xml create mode 100644 projects/simon23rus/src/MyJCommander.java create mode 100644 projects/simon23rus/src/TwitterStreamer.java diff --git a/projects/simon23rus/pom.xml b/projects/simon23rus/pom.xml new file mode 100644 index 0000000..1fb5ac0 --- /dev/null +++ b/projects/simon23rus/pom.xml @@ -0,0 +1,95 @@ + + 4.0.0 + + + ru.mipt.diht.students + parent + 1.0-SNAPSHOT + + + ru.mipt.diht.students + simon23rus + 1.0-SNAPSHOT + simon23rus + 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 + + + + + maven-checkstyle-plugin + + true + + + + + mipt + + + diff --git a/projects/simon23rus/src/MyJCommander.java b/projects/simon23rus/src/MyJCommander.java new file mode 100644 index 0000000..12760bd --- /dev/null +++ b/projects/simon23rus/src/MyJCommander.java @@ -0,0 +1,51 @@ +/** + * 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 { + 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 = "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 = 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/TwitterStreamer.java b/projects/simon23rus/src/TwitterStreamer.java new file mode 100644 index 0000000..5e98c3b --- /dev/null +++ b/projects/simon23rus/src/TwitterStreamer.java @@ -0,0 +1,249 @@ + +import com.beust.jcommander.JCommander; +import twitter4j.*; +import twitter4j.util.TimeSpanConverter; +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 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 = "aroundtheworld"; + private static boolean isItYesterday; + + public static String correctRussianText(long deltaInSeconds) { + if (deltaInSeconds < 2 * SECONDS_IN_MINUTE) { + return "[<Только что>] "; + } + else if (deltaInSeconds < SECONDS_IN_HOUR) { + long 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) { + long 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 { + long 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 StatusAdapter listener = new StatusAdapter(){ + public void onStatus(Status givenTweet) { + printStringWithFormat(givenTweet, false); + try { + Thread.sleep(1000); //1000=1. + } catch(InterruptedException ex) { + System.out.println("Current Thread has interrupted"); + } + } + }; + + public static void isItYesterdayTweet(Status tweet, long delta) { + 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); + + int todaySeconds = Integer.valueOf(currentSecond) + Integer.valueOf(currentMinute) * SECONDS_IN_MINUTE + Integer.valueOf(currentHour) * SECONDS_IN_HOUR; + System.out.println(todaySeconds); + if(delta < SECONDS_IN_DAY + todaySeconds && delta > todaySeconds) + isItYesterday = true; + else + isItYesterday = false; + + } + + public static void makeBlue(String tweetToShow, String toPaint) { + tweetToShow += (char)27 + "[34;1m@" + toPaint; + } + + public static void printStringWithFormat(Status tweet, boolean timeIsNeeded) { + + String tweetToShow = ""; + if(timeIsNeeded) { + long delta = Calendar.getInstance().getTime().getTime() - tweet.getCreatedAt().getTime(); + isItYesterdayTweet(tweet, delta); + tweetToShow += (char)27 + "[35;1;4m" + correctRussianText(delta); + } + makeBlue(tweetToShow, 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().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()); + String mySourse; + mySourse = 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(); + 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.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); + + 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 (jct.hideRetweets) { + jct.query += EXCLUDE_RETWEETS; + } + Query query = new Query(jct.query); + QueryResult result; + query.setCount(jct.tweetsByQuery); + if (!jct.place.equals(AROUND_THE_WORLD) { + query.setGeoCode(convertToGeoCode(jct.place), 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 == jct.tweetsByQuery) { + return; + } + } + } while ((counter < jct.tweetsByQuery) && (query = result.nextQuery()) != null); + } + + } + +} From 44b4da643a1375e0e3e047d931ada99bc31ae3df Mon Sep 17 00:00:00 2001 From: Semyon Fedotov Date: Mon, 14 Dec 2015 16:14:41 +0300 Subject: [PATCH 06/13] ya vernulsya --- projects/simon23rus/pom.xml | 92 ++++--- projects/simon23rus/src/MyJCommander.java | 51 ---- projects/simon23rus/src/TwitterStreamer.java | 249 ----------------- .../simon23rus/CQL/data/Aggregates.java | 60 +++++ .../simon23rus/CQL/data/CollectionQuery.java | 179 +++++++++++++ .../simon23rus/CQL/data/Conditions.java | 36 +++ .../CQL/data/OrderByConditions.java | 35 +++ .../students/simon23rus/CQL/data/Sources.java | 49 ++++ .../CQL/impl/BestComparatorEver.java | 24 ++ .../simon23rus/CQL/impl/FromStmt.java | 86 ++++++ .../simon23rus/CQL/impl/SelectStmt.java | 253 ++++++++++++++++++ .../students/simon23rus/CQL/impl/Tuple.java | 28 ++ .../simon23rus/CQL/impl/UnionStmt.java | 103 +++++++ .../CQL/implOfAggregators/Aggregator.java | 12 + .../simon23rus/CQL/implOfAggregators/Avg.java | 31 +++ .../CQL/implOfAggregators/Count.java | 36 +++ .../simon23rus/CQL/implOfAggregators/Max.java | 34 +++ .../simon23rus/CQL/implOfAggregators/Min.java | 36 +++ .../simon23rus/CQL/data/AggregatesTest.java | 74 +++++ .../simon23rus/CQL/data/ConditionsTest.java | 35 +++ .../CQL/data/OrderByConditionsTest.java | 45 ++++ .../simon23rus/CQL/data/SourcesTest.java | 37 +++ .../simon23rus/CQL/impl/FromStmtTest.java | 94 +++++++ .../simon23rus/CQL/impl/SelectStmtTest.java | 200 ++++++++++++++ 24 files changed, 1541 insertions(+), 338 deletions(-) delete mode 100644 projects/simon23rus/src/MyJCommander.java delete mode 100644 projects/simon23rus/src/TwitterStreamer.java create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/data/Aggregates.java create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/data/CollectionQuery.java create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/data/Conditions.java create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/data/OrderByConditions.java create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/data/Sources.java create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/impl/BestComparatorEver.java create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/impl/FromStmt.java create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/impl/SelectStmt.java create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/impl/Tuple.java create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/impl/UnionStmt.java create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/implOfAggregators/Aggregator.java create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/implOfAggregators/Avg.java create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/implOfAggregators/Count.java create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/implOfAggregators/Max.java create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/implOfAggregators/Min.java create mode 100644 projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/CQL/data/AggregatesTest.java create mode 100644 projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/CQL/data/ConditionsTest.java create mode 100644 projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/CQL/data/OrderByConditionsTest.java create mode 100644 projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/CQL/data/SourcesTest.java create mode 100644 projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/CQL/impl/FromStmtTest.java create mode 100644 projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/CQL/impl/SelectStmtTest.java diff --git a/projects/simon23rus/pom.xml b/projects/simon23rus/pom.xml index 1fb5ac0..d615fed 100644 --- a/projects/simon23rus/pom.xml +++ b/projects/simon23rus/pom.xml @@ -17,60 +17,76 @@ - - 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 - + + + + junit + junit + 4.12 + test + - - com.google.code.geocoder-java - geocoder-java - 0.16 - + + org.mockito + mockito-core + 1.10.8 + test + + + objenesis + org.objenesis + + + + + + 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 + - src maven-compiler-plugin diff --git a/projects/simon23rus/src/MyJCommander.java b/projects/simon23rus/src/MyJCommander.java deleted file mode 100644 index 12760bd..0000000 --- a/projects/simon23rus/src/MyJCommander.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * 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 { - 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 = "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 = 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/TwitterStreamer.java b/projects/simon23rus/src/TwitterStreamer.java deleted file mode 100644 index 5e98c3b..0000000 --- a/projects/simon23rus/src/TwitterStreamer.java +++ /dev/null @@ -1,249 +0,0 @@ - -import com.beust.jcommander.JCommander; -import twitter4j.*; -import twitter4j.util.TimeSpanConverter; -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 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 = "aroundtheworld"; - private static boolean isItYesterday; - - public static String correctRussianText(long deltaInSeconds) { - if (deltaInSeconds < 2 * SECONDS_IN_MINUTE) { - return "[<Только что>] "; - } - else if (deltaInSeconds < SECONDS_IN_HOUR) { - long 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) { - long 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 { - long 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 StatusAdapter listener = new StatusAdapter(){ - public void onStatus(Status givenTweet) { - printStringWithFormat(givenTweet, false); - try { - Thread.sleep(1000); //1000=1. - } catch(InterruptedException ex) { - System.out.println("Current Thread has interrupted"); - } - } - }; - - public static void isItYesterdayTweet(Status tweet, long delta) { - 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); - - int todaySeconds = Integer.valueOf(currentSecond) + Integer.valueOf(currentMinute) * SECONDS_IN_MINUTE + Integer.valueOf(currentHour) * SECONDS_IN_HOUR; - System.out.println(todaySeconds); - if(delta < SECONDS_IN_DAY + todaySeconds && delta > todaySeconds) - isItYesterday = true; - else - isItYesterday = false; - - } - - public static void makeBlue(String tweetToShow, String toPaint) { - tweetToShow += (char)27 + "[34;1m@" + toPaint; - } - - public static void printStringWithFormat(Status tweet, boolean timeIsNeeded) { - - String tweetToShow = ""; - if(timeIsNeeded) { - long delta = Calendar.getInstance().getTime().getTime() - tweet.getCreatedAt().getTime(); - isItYesterdayTweet(tweet, delta); - tweetToShow += (char)27 + "[35;1;4m" + correctRussianText(delta); - } - makeBlue(tweetToShow, 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().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()); - String mySourse; - mySourse = 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(); - 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.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); - - 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 (jct.hideRetweets) { - jct.query += EXCLUDE_RETWEETS; - } - Query query = new Query(jct.query); - QueryResult result; - query.setCount(jct.tweetsByQuery); - if (!jct.place.equals(AROUND_THE_WORLD) { - query.setGeoCode(convertToGeoCode(jct.place), 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 == jct.tweetsByQuery) { - return; - } - } - } while ((counter < jct.tweetsByQuery) && (query = result.nextQuery()) != null); - } - - } - -} 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..a52b256 --- /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..5b7bab7 --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/impl/FromStmt.java @@ -0,0 +1,86 @@ +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; +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) { + throw new UnsupportedOperationException(); + } + } + +} 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..2f0ffab --- /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 + + "}\n"; + } +} 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/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..6c79edc --- /dev/null +++ b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/CQL/impl/FromStmtTest.java @@ -0,0 +1,94 @@ +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.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 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 = 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 = FromStmt + .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 testSelectDistinct() throws Exception { + SelectStmt select = FromStmt.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 From 6e26fa7ea06d2d466db0c2f778849b123cda51d2 Mon Sep 17 00:00:00 2001 From: Semyon Fedotov Date: Mon, 14 Dec 2015 16:34:37 +0300 Subject: [PATCH 07/13] ya vernulsya --- projects/pom.xml | 1 + 1 file changed, 1 insertion(+) 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 From c169543227f9aa03e6b71ee501c467cfe9f47c23 Mon Sep 17 00:00:00 2001 From: Semyon Fedotov Date: Mon, 14 Dec 2015 17:29:35 +0300 Subject: [PATCH 08/13] my first Tweet --- projects/simon23rus/pom.xml | 11 +- .../TwitterStream/GeoCodeConverter.java | 85 ++++++++++++ .../TwitterStream/MyJCommander.java | 50 +++++++ .../TwitterStream/TimeTransformer.java | 127 ++++++++++++++++++ .../TwitterStream/TwitterPrinter.java | 42 ++++++ .../TwitterStream/TwitterStreamer.java | 121 +++++++++++++++++ .../TwitterStream/GeoCodeConverterTest.java | 80 +++++++++++ .../TwitterStream/TimeTransformerTest.java | 76 +++++++++++ .../TwitterStream/Twitter4jTestUtilsTest.java | 14 ++ .../TwitterStream/TwitterPrinterTest.java | 62 +++++++++ .../TwitterStream/TwitterStreamerTest.java | 13 ++ .../java/twitter4j/Twitter4jTestUtils.java | 29 ++++ 12 files changed, 701 insertions(+), 9 deletions(-) create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/TwitterStream/GeoCodeConverter.java create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/TwitterStream/MyJCommander.java create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/TwitterStream/TimeTransformer.java create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/TwitterStream/TwitterPrinter.java create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/TwitterStream/TwitterStreamer.java create mode 100644 projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/TwitterStream/GeoCodeConverterTest.java create mode 100644 projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/TwitterStream/TimeTransformerTest.java create mode 100644 projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/TwitterStream/Twitter4jTestUtilsTest.java create mode 100644 projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/TwitterStream/TwitterPrinterTest.java create mode 100644 projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/TwitterStream/TwitterStreamerTest.java create mode 100644 projects/simon23rus/src/test/java/twitter4j/Twitter4jTestUtils.java diff --git a/projects/simon23rus/pom.xml b/projects/simon23rus/pom.xml index d615fed..abbd771 100644 --- a/projects/simon23rus/pom.xml +++ b/projects/simon23rus/pom.xml @@ -92,15 +92,8 @@ maven-compiler-plugin 3.1 - 1.7 - 1.7 - - - - - maven-checkstyle-plugin - - true + 1.8 + 1.8 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..83397b9 --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/TwitterStream/GeoCodeConverter.java @@ -0,0 +1,85 @@ +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(); + place = "Долгопрудный"; + } + 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 { + System.out.println("bu"); + } + } + return new GeoLocation((double) 0, (double) 0); + } + + + 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; + //System.out.println(distance); + 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..60e9b78 --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/TwitterStream/TimeTransformer.java @@ -0,0 +1,127 @@ +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; + } +// System.out.println(result + "STOL'KO"); +// +// String currentHour = new SimpleDateFormat("HH").format(currentDate1); +// String currentMinute = new SimpleDateFormat("mm").format(currentDate1); +// String currentSecond = new SimpleDateFormat("ss").format(currentDate1); +// +// int todaySeconds = Integer.valueOf(currentSecond) + Integer.valueOf(currentMinute) * SECONDS_IN_MINUTE + Integer.valueOf(currentHour) * SECONDS_IN_HOUR; +// System.out.println(todaySeconds); +// if(delta < SECONDS_IN_DAY + todaySeconds && delta > todaySeconds) { +// 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..3212358 --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/TwitterStream/TwitterPrinter.java @@ -0,0 +1,42 @@ +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().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..d104b7c --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/TwitterStream/TwitterStreamer.java @@ -0,0 +1,121 @@ +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); +// 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 { + tweetLocation = myOwnConverter.getCoordinates("nearby"); + } + if(queryLocation == null) { + System.out.println("bububuqueryloc"); + return; + } + if(myOwnConverter.near(queryLocation, tweetLocation, 40)) { + Date currentDate = Calendar.getInstance().getTime(); + myOwnPrinter.printStringWithFormat(currentDate, tweet, true); + +// System.out.println(tweet.getPlace()); + ++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/TwitterStream/GeoCodeConverterTest.java b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/TwitterStream/GeoCodeConverterTest.java new file mode 100644 index 0000000..d12b542 --- /dev/null +++ b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/TwitterStream/GeoCodeConverterTest.java @@ -0,0 +1,80 @@ +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"); + 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))); + } + + @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..ef5c3b0 --- /dev/null +++ b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/TwitterStream/TwitterPrinterTest.java @@ -0,0 +1,62 @@ +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); + 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(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[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 From 9e8149aedb2980d31d760e8a0f53da69c6c36e04 Mon Sep 17 00:00:00 2001 From: Semyon Fedotov Date: Tue, 15 Dec 2015 15:38:30 +0300 Subject: [PATCH 09/13] flow --- .../students/simon23rus/Threads/Asker.java | 56 ++++++++++ .../simon23rus/Threads/BlockingQueue.java | 89 +++++++++++++++ .../Threads/BlockingQueueRunner.java | 19 ++++ .../students/simon23rus/Threads/Counter.java | 51 +++++++++ .../simon23rus/Threads/RollCallRunner.java | 12 +++ .../simon23rus/Threads/RollCallThread.java | 42 ++++++++ .../simon23rus/Threads/BlockingQueueTest.java | 101 ++++++++++++++++++ 7 files changed, 370 insertions(+) create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/Threads/Asker.java create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/Threads/BlockingQueue.java create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/Threads/BlockingQueueRunner.java create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/Threads/Counter.java create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/Threads/RollCallRunner.java create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/Threads/RollCallThread.java create mode 100644 projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/Threads/BlockingQueueTest.java 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..3e1cce7 --- /dev/null +++ b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/Threads/BlockingQueue.java @@ -0,0 +1,89 @@ +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.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) { + try { + insertLocker.lock(); + for(int i = 0; i < toAdd.size(); ++i) { + try { + footLocker.lock(); + while (myBlockingQueue.size() == elementsBound) { + nonFull.await(); + } + myBlockingQueue.add(toAdd.get(i)); + nonEmpty.signalAll(); + } catch (InterruptedException e) { + + } finally { + footLocker.unlock(); + } + } + } + finally { + insertLocker.unlock(); + } + } + + + //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.signalAll(); + } catch (InterruptedException e) { + } + finally { + footLocker.unlock(); + } + } + } + finally { + deleteLocker.unlock(); + return takenElements; + } + } +} \ No newline at end of file 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..d6df977 --- /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) { + 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..7dada5a --- /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); + + } + + +} \ No newline at end of file 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/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..c26332f --- /dev/null +++ b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/Threads/BlockingQueueTest.java @@ -0,0 +1,101 @@ +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()); + + } +} From 52558cfa9acfb54b38c80969981da5dde7dd48c9 Mon Sep 17 00:00:00 2001 From: Semyon Fedotov Date: Wed, 16 Dec 2015 19:19:17 +0300 Subject: [PATCH 10/13] Make your Dreams come True --- .../DatabaseService/DatabaseService.java | 302 ++++++++++++++++++ .../TClassAnnotations/Column.java | 13 + .../TClassAnnotations/PrimaryKey.java | 11 + .../TClassAnnotations/SQLTypeConverter.java | 44 +++ .../TClassAnnotations/Table.java | 15 + .../simon23rus/Threads/BlockingQueue.java | 2 +- .../students/simon23rus/Threads/Counter.java | 2 +- 7 files changed, 387 insertions(+), 2 deletions(-) create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/DatabaseService/DatabaseService.java create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/DatabaseService/TClassAnnotations/Column.java create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/DatabaseService/TClassAnnotations/PrimaryKey.java create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/DatabaseService/TClassAnnotations/SQLTypeConverter.java create mode 100644 projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/DatabaseService/TClassAnnotations/Table.java 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/BlockingQueue.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/Threads/BlockingQueue.java index 3e1cce7..b3eaf93 100644 --- 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 @@ -86,4 +86,4 @@ List take(int numberOfElements) { return takenElements; } } -} \ No newline at end of file +} 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 index 7dada5a..af2d002 100644 --- 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 @@ -48,4 +48,4 @@ public static void main(String[] args) { } -} \ No newline at end of file +} From 595bed72ec71d7b7dcb798a04a8e3b52441bdd69 Mon Sep 17 00:00:00 2001 From: Semyon Fedotov Date: Wed, 16 Dec 2015 19:23:36 +0300 Subject: [PATCH 11/13] Make your Dreams come True --- projects/checkstyle.xml | 104 ++-- projects/simon23rus/dbTask.mv.db | Bin 0 -> 28672 bytes projects/simon23rus/dbTask.trace.db | 483 ++++++++++++++++++ projects/simon23rus/pom.xml | 11 +- .../DatabaseService/DatabaseServiceTest.java | 208 ++++++++ .../SQLTypeConverterTest.java | 83 +++ 6 files changed, 836 insertions(+), 53 deletions(-) create mode 100644 projects/simon23rus/dbTask.mv.db create mode 100644 projects/simon23rus/dbTask.trace.db create mode 100644 projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/DatabaseService/DatabaseServiceTest.java create mode 100644 projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/DatabaseService/TClassAnnotations/SQLTypeConverterTest.java 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/simon23rus/dbTask.mv.db b/projects/simon23rus/dbTask.mv.db new file mode 100644 index 0000000000000000000000000000000000000000..befdb81a6cff607768d245633c2154956e0b0596 GIT binary patch literal 28672 zcmeI4&u<$=6vua+Y}2?6$Omp9ZPMmPTi4wm{w)qTw%fRIoYZ!r=76H{?l`sL*ug(S zS|Jn(kPs3F#I1)4A%w(@6XIA24#1(RI2Cb0{R`j(7X-6Av+M2Jp>9lEgPsrG-PzsQ zx8Io^`}5|#U5YFIQnjw_#8tX1RPNxoEJ>1IyVb7k#A9W@*1)KR^|&085ei{78d3e_ zdSe&0;024p~PyiGF1wa8%02BZPKmkwy6aWQ4fs<8$P4eq32te^yagEIC z@1nhU$XFc2LnX;y!w0Q+*uRIiaWfwDH|q6PT!{oplz=3KbV>EMD!U|VK+$omggPMs zx;V(kh#q*v{dB|2DQYkjjtHlPNx>_e;e6vW%c**MyNa5^*B^PVT}>|f#?NKeDsQy0 z@bLEuT5x_jk9I1piYEN={WvX}%`Uc^z^Y%Z5VwThUi?qf&ke5QbEct^PZ z?ZnE}q_|PnYn2_}_`-6gR>92{5`O)7lGb_QdZCRP_>OS@?pa!LF|&f3&5CgN@I_j1 z>3R;|-bD@TBywNV{C6DBbKLxE9EbCC`P+lZ7X%`FAk1+dWh~B3a;MGa3B-`KQnFSw z^GMnJR?KhJ{0^Gmp;JaZA^AO?wJ)-RJZSq?EBknbG_D+#{Kop4*|MzNC9~Zln6-P5 zwR@PgdpK&gyDmlTb}y+hP4l;F?WPeX;_e3M9m|XoGb6~lnPrC42;=Ic^HC%0&KGiZ zzOdHa`BWq;M;cMuXHsa)hLFn!mGtwD6sq$Pu%)mb0ZWRAX@umILRS%rbshojr5YlS zMtu+0iVak2BCSQDWtwNr(soU+XY1Q^qlHRU9FWeKd#d%)3fi;R^SJzqSxyg9SxC-? z6?;?SI9~8Iuob!b@irCUmGA zGdAeJLkcx}j~0=XlN~9cc2EEm00lq+PyiGF1wa8%U~mPx_}h-B*E{j_vaae{SjU6V zbnkP$?D}OFADRfJJjwqS2ipAKg9@jn%s@jo4S82{5f z!2g5)7C{Z504M+ofC8WZC;$q80w=FP7k}IQ@5rZ@%ORvivD_y(Kf_^+|B>XHm^Jy| zm;*hC9|=G7kGFI3lYn1Y?Z6L`p23ptLka)$_xMl81Wr~2NstAF%=}M_b2kg=qL|F5 z6UFq_;(8{V66KggVgkgODTNk`>xFb)%v=?7t3@$=GgBxQ#F-hfkjNIr`FU|EQCKpT ziPTCaM5Q_c50j4C9$r@9grJNiOJPmp_oq) zORNeyC8S=*g%?Pb^5Ll)IsB%$ zS#Ru!$x7??zZj=6H+FYI;C!BG+2@&2e4cZHt$kr_Bj@D;->>JaYvp@2e(sNmMIN6DwUb$WWZ26yX_7oD)TqgZcGc`~rZ z8B4+!!F4VIt) zC;$q80-yjWa1sj8zmX39w*J|YBKv)Mv2s`<@6!u*GxDG%*8IPFe%R#y4!T9rh-_Z~MchWkd%xxES#WM7Q-eB2u=S8iwj+iT!A>5tI z5X3=McVtwU2^RL#9ks(cV$2LHd+6w}4rYX%)}gx7I=XX;NN!0)KGKMo71lA73>W*} zk;VT*$Y`-IS{e%fo4F(tAB-UXpGYnV?e&mLVh?7p0t$cvpa3WU3V;G9tpJ-w>hQPy zZ%^y+zpMo#S_ls|o!*nhE&g{0MLXjEkDUMSBlx-JHTx~3{Qt}IiT@uW|G!Q7|FRGe zt^og!8vlRh;{VGA{|5~IzhaLK(_?>9{y${=f7mtuzvAHk4((g~--!t5hyOci9YcX$ zE2HAS`C5lwt`PQS6MJMk#%moc{vSd{i~WnB4~75DT#||RN09$dB$tHF`9m&=J($4? oC;$q80-yjW01BM60*wDV{B8f+!w&w(;h+}5YQN;%|8d^G0T_0cz5oCK literal 0 HcmV?d00001 diff --git a/projects/simon23rus/dbTask.trace.db b/projects/simon23rus/dbTask.trace.db new file mode 100644 index 0000000..bfaee0c --- /dev/null +++ b/projects/simon23rus/dbTask.trace.db @@ -0,0 +1,483 @@ +2015-12-16 13:38:00 jdbc[4]: exception +org.h2.jdbc.JdbcSQLException: Синтаксическая ошибка в выражении SQL "CREATE TABLE IF NOT EXISTS NULL[*]( INTEGERNOT NULL PRIMARY KEY, VARCHAR(20), BIGINT, VARCHAR(20)) "; ожидалось "identifier" +Syntax error in SQL statement "CREATE TABLE IF NOT EXISTS NULL[*]( INTEGERNOT NULL PRIMARY KEY, VARCHAR(20), BIGINT, VARCHAR(20)) "; expected "identifier"; SQL statement: +CREATE TABLE IF NOT EXISTS null( INTEGERNOT NULL PRIMARY KEY, VARCHAR(20), BIGINT, VARCHAR(20)) [42001-190] +2015-12-16 13:38:16 jdbc[4]: exception +org.h2.jdbc.JdbcSQLException: Синтаксическая ошибка в выражении SQL "CREATE TABLE IF NOT EXISTS NULL[*]( INTEGERNOT NULL PRIMARY KEY, VARCHAR(20), BIGINT, VARCHAR(20)) "; ожидалось "identifier" +Syntax error in SQL statement "CREATE TABLE IF NOT EXISTS NULL[*]( INTEGERNOT NULL PRIMARY KEY, VARCHAR(20), BIGINT, VARCHAR(20)) "; expected "identifier"; SQL statement: +CREATE TABLE IF NOT EXISTS null( INTEGERNOT NULL PRIMARY KEY, VARCHAR(20), BIGINT, VARCHAR(20)) [42001-190] +2015-12-16 13:40:28 jdbc[4]: exception +org.h2.jdbc.JdbcSQLException: Неизвестный тип данных: "(" +Unknown data type: "("; SQL statement: +CREATE TABLE IF NOT EXISTS player( INTEGERNOT NULL PRIMARY KEY, VARCHAR(20), BIGINT, VARCHAR(20)) [50004-190] + at org.h2.message.DbException.getJdbcSQLException(DbException.java:345) + at org.h2.message.DbException.get(DbException.java:179) + at org.h2.message.DbException.get(DbException.java:155) + at org.h2.command.Parser.parseColumnWithType(Parser.java:4009) + at org.h2.command.Parser.parseColumnForTable(Parser.java:3872) + at org.h2.command.Parser.parseCreateTable(Parser.java:5808) + at org.h2.command.Parser.parseCreate(Parser.java:4167) + at org.h2.command.Parser.parsePrepared(Parser.java:349) + at org.h2.command.Parser.parse(Parser.java:304) + at org.h2.command.Parser.parse(Parser.java:276) + at org.h2.command.Parser.prepareCommand(Parser.java:241) + at org.h2.engine.Session.prepareLocal(Session.java:460) + at org.h2.engine.Session.prepareCommand(Session.java:402) + at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1188) + at org.h2.jdbc.JdbcStatement.executeUpdateInternal(JdbcStatement.java:126) + at org.h2.jdbc.JdbcStatement.executeUpdate(JdbcStatement.java:115) + at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseService.createTable(DatabaseService.java:235) + at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseServiceTest.createTableTest(DatabaseServiceTest.java:44) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:497) + at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) + at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) + at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) + at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) + at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) + at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) + at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) + at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) + at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) + at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) + at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) + at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) + at org.junit.runners.ParentRunner.run(ParentRunner.java:363) + at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37) + at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62) + at org.junit.runner.JUnitCore.run(JUnitCore.java:137) + at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78) + at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212) + at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:497) + at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140) +2015-12-16 13:41:29 jdbc[4]: exception +org.h2.jdbc.JdbcSQLException: Неизвестный тип данных: "NOT" +Unknown data type: "NOT"; SQL statement: +CREATE TABLE IF NOT EXISTS player( INTEGER NOT NULL PRIMARY KEY, VARCHAR(20), BIGINT, VARCHAR(20)) [50004-190] + at org.h2.message.DbException.getJdbcSQLException(DbException.java:345) + at org.h2.message.DbException.get(DbException.java:179) + at org.h2.message.DbException.get(DbException.java:155) + at org.h2.command.Parser.parseColumnWithType(Parser.java:4009) + at org.h2.command.Parser.parseColumnForTable(Parser.java:3872) + at org.h2.command.Parser.parseCreateTable(Parser.java:5808) + at org.h2.command.Parser.parseCreate(Parser.java:4167) + at org.h2.command.Parser.parsePrepared(Parser.java:349) + at org.h2.command.Parser.parse(Parser.java:304) + at org.h2.command.Parser.parse(Parser.java:276) + at org.h2.command.Parser.prepareCommand(Parser.java:241) + at org.h2.engine.Session.prepareLocal(Session.java:460) + at org.h2.engine.Session.prepareCommand(Session.java:402) + at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1188) + at org.h2.jdbc.JdbcStatement.executeUpdateInternal(JdbcStatement.java:126) + at org.h2.jdbc.JdbcStatement.executeUpdate(JdbcStatement.java:115) + at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseService.createTable(DatabaseService.java:235) + at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseServiceTest.createTableTest(DatabaseServiceTest.java:44) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:497) + at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) + at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) + at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) + at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) + at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) + at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) + at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) + at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) + at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) + at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) + at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) + at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) + at org.junit.runners.ParentRunner.run(ParentRunner.java:363) + at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37) + at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62) + at org.junit.runner.JUnitCore.run(JUnitCore.java:137) + at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78) + at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212) + at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:497) + at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140) +2015-12-16 13:42:57 jdbc[4]: exception +org.h2.jdbc.JdbcSQLException: Неизвестный тип данных: "NOT" +Unknown data type: "NOT"; SQL statement: +CREATE TABLE IF NOT EXISTS player( INTEGER NOT NULL PRIMARY KEY, VARCHAR(20), BIGINT, VARCHAR(20)) [50004-190] + at org.h2.message.DbException.getJdbcSQLException(DbException.java:345) + at org.h2.message.DbException.get(DbException.java:179) + at org.h2.message.DbException.get(DbException.java:155) + at org.h2.command.Parser.parseColumnWithType(Parser.java:4009) + at org.h2.command.Parser.parseColumnForTable(Parser.java:3872) + at org.h2.command.Parser.parseCreateTable(Parser.java:5808) + at org.h2.command.Parser.parseCreate(Parser.java:4167) + at org.h2.command.Parser.parsePrepared(Parser.java:349) + at org.h2.command.Parser.parse(Parser.java:304) + at org.h2.command.Parser.parse(Parser.java:276) + at org.h2.command.Parser.prepareCommand(Parser.java:241) + at org.h2.engine.Session.prepareLocal(Session.java:460) + at org.h2.engine.Session.prepareCommand(Session.java:402) + at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1188) + at org.h2.jdbc.JdbcStatement.executeUpdateInternal(JdbcStatement.java:126) + at org.h2.jdbc.JdbcStatement.executeUpdate(JdbcStatement.java:115) + at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseService.createTable(DatabaseService.java:236) + at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseServiceTest.createTableTest(DatabaseServiceTest.java:44) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:497) + at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) + at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) + at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) + at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) + at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) + at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) + at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) + at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) + at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) + at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) + at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) + at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) + at org.junit.runners.ParentRunner.run(ParentRunner.java:363) + at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37) + at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62) + at org.junit.runner.JUnitCore.run(JUnitCore.java:137) + at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78) + at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212) + at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:497) + at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140) +2015-12-16 13:44:41 jdbc[4]: exception +org.h2.jdbc.JdbcSQLException: Неизвестный тип данных: "NOT" +Unknown data type: "NOT"; SQL statement: +CREATE TABLE IF NOT EXISTS player( INTEGER NOT NULL PRIMARY KEY, VARCHAR(20), BIGINT, VARCHAR(20)) [50004-190] + at org.h2.message.DbException.getJdbcSQLException(DbException.java:345) + at org.h2.message.DbException.get(DbException.java:179) + at org.h2.message.DbException.get(DbException.java:155) + at org.h2.command.Parser.parseColumnWithType(Parser.java:4009) + at org.h2.command.Parser.parseColumnForTable(Parser.java:3872) + at org.h2.command.Parser.parseCreateTable(Parser.java:5808) + at org.h2.command.Parser.parseCreate(Parser.java:4167) + at org.h2.command.Parser.parsePrepared(Parser.java:349) + at org.h2.command.Parser.parse(Parser.java:304) + at org.h2.command.Parser.parse(Parser.java:276) + at org.h2.command.Parser.prepareCommand(Parser.java:241) + at org.h2.engine.Session.prepareLocal(Session.java:460) + at org.h2.engine.Session.prepareCommand(Session.java:402) + at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1188) + at org.h2.jdbc.JdbcStatement.executeUpdateInternal(JdbcStatement.java:126) + at org.h2.jdbc.JdbcStatement.executeUpdate(JdbcStatement.java:115) + at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseService.createTable(DatabaseService.java:236) + at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseServiceTest.createTableTest(DatabaseServiceTest.java:44) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:497) + at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) + at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) + at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) + at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) + at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) + at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) + at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) + at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) + at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) + at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) + at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) + at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) + at org.junit.runners.ParentRunner.run(ParentRunner.java:363) + at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37) + at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62) + at org.junit.runner.JUnitCore.run(JUnitCore.java:137) + at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78) + at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212) + at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:497) + at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140) +2015-12-16 13:45:41 jdbc[4]: exception +org.h2.jdbc.JdbcSQLException: Неизвестный тип данных: "NOT" +Unknown data type: "NOT"; SQL statement: +CREATE TABLE IF NOT EXISTS player( INTEGER NOT NULL PRIMARY KEY, VARCHAR(20), BIGINT, VARCHAR(20)) [50004-190] + at org.h2.message.DbException.getJdbcSQLException(DbException.java:345) + at org.h2.message.DbException.get(DbException.java:179) + at org.h2.message.DbException.get(DbException.java:155) + at org.h2.command.Parser.parseColumnWithType(Parser.java:4009) + at org.h2.command.Parser.parseColumnForTable(Parser.java:3872) + at org.h2.command.Parser.parseCreateTable(Parser.java:5808) + at org.h2.command.Parser.parseCreate(Parser.java:4167) + at org.h2.command.Parser.parsePrepared(Parser.java:349) + at org.h2.command.Parser.parse(Parser.java:304) + at org.h2.command.Parser.parse(Parser.java:276) + at org.h2.command.Parser.prepareCommand(Parser.java:241) + at org.h2.engine.Session.prepareLocal(Session.java:460) + at org.h2.engine.Session.prepareCommand(Session.java:402) + at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1188) + at org.h2.jdbc.JdbcStatement.executeUpdateInternal(JdbcStatement.java:126) + at org.h2.jdbc.JdbcStatement.executeUpdate(JdbcStatement.java:115) + at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseService.createTable(DatabaseService.java:237) + at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseServiceTest.createTableTest(DatabaseServiceTest.java:44) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:497) + at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) + at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) + at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) + at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) + at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) + at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) + at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) + at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) + at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) + at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) + at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) + at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) + at org.junit.runners.ParentRunner.run(ParentRunner.java:363) + at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37) + at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62) + at org.junit.runner.JUnitCore.run(JUnitCore.java:137) + at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78) + at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212) + at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:497) + at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140) +2015-12-16 13:56:25 jdbc[3]: exception +org.h2.jdbc.JdbcSQLException: Объект уже закрыт +The object is already closed [90007-190] +2015-12-16 14:51:35 jdbc[3]: exception +org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" уже существует +Table "PLAYER" already exists; SQL statement: +CREATE TABLE PLAYER(id INTEGER NOT NULL PRIMARY KEY, last_name VARCHAR(20), salary BIGINT, club VARCHAR(20)) [42101-190] +2015-12-16 15:25:52 jdbc[4]: exception +org.h2.jdbc.JdbcSQLException: Синтаксическая ошибка в выражении SQL "INSERT INTO PLAYER VALUES (?, ?, ?, ? [*]"; ожидалось "[, ::, *, /, %, +, -, ||, ~, !~, NOT, LIKE, REGEXP, IS, IN, BETWEEN, AND, OR, ,, )" +Syntax error in SQL statement "INSERT INTO PLAYER VALUES (?, ?, ?, ? [*]"; expected "[, ::, *, /, %, +, -, ||, ~, !~, NOT, LIKE, REGEXP, IS, IN, BETWEEN, AND, OR, ,, )"; SQL statement: +INSERT INTO player VALUES (?, ?, ?, ? [42001-190] +2015-12-16 17:15:47 jdbc[4]: exception +org.h2.jdbc.JdbcSQLException: Синтаксическая ошибка в выражении SQL "UPDATE PLAYER SET ID=?, LAST_NAME=?, SALARY=?, CLUB=? WHEREID[*]=? " +Syntax error in SQL statement "UPDATE PLAYER SET ID=?, LAST_NAME=?, SALARY=?, CLUB=? WHEREID[*]=? "; SQL statement: +UPDATE player SET id=?, last_name=?, salary=?, club=? WHEREid=? [42000-190] +2015-12-16 17:16:05 jdbc[4]: exception +org.h2.jdbc.JdbcSQLException: Синтаксическая ошибка в выражении SQL "UPDATE PLAYER SET ID=?, LAST_NAME=?, SALARY=?, CLUB=? WHEREID[*]=? " +Syntax error in SQL statement "UPDATE PLAYER SET ID=?, LAST_NAME=?, SALARY=?, CLUB=? WHEREID[*]=? "; SQL statement: +UPDATE player SET id=?, last_name=?, salary=?, club=? WHEREid=? [42000-190] +2015-12-16 17:19:42 jdbc[5]: exception +org.h2.jdbc.JdbcSQLException: Таблица "PLAYERWHERE" не найдена +Table "PLAYERWHERE" not found; SQL statement: +SELECT * FROM playerWHERE id=? [42102-190] +2015-12-16 17:42:00 jdbc[27]: exception +org.h2.jdbc.JdbcSQLException: Недопустимое значение "5" для параметра "parameterIndex" +Invalid value "5" for parameter "parameterIndex" [90008-190] + at org.h2.message.DbException.getJdbcSQLException(DbException.java:345) + at org.h2.message.DbException.get(DbException.java:179) + at org.h2.message.DbException.getInvalidValueException(DbException.java:228) + at org.h2.jdbc.JdbcPreparedStatement.setParameter(JdbcPreparedStatement.java:1382) + at org.h2.jdbc.JdbcPreparedStatement.setObject(JdbcPreparedStatement.java:460) + at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseService.delete(DatabaseService.java:213) + at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseServiceTest.deleteTest(DatabaseServiceTest.java:157) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:497) + at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) + at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) + at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) + at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) + at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) + at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) + at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) + at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) + at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) + at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) + at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) + at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) + at org.junit.runners.ParentRunner.run(ParentRunner.java:363) + at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37) + at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62) + at org.junit.runner.JUnitCore.run(JUnitCore.java:137) + at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78) + at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212) + at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:497) + at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140) +2015-12-16 18:14:37 jdbc[4]: exception +org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" не найдена +Table "PLAYER" not found; SQL statement: +SELECT * FROM player [42102-190] +2015-12-16 18:15:36 jdbc[4]: exception +org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" не найдена +Table "PLAYER" not found; SQL statement: +SELECT * FROM player [42102-190] +2015-12-16 18:16:31 jdbc[4]: exception +org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" не найдена +Table "PLAYER" not found; SQL statement: +SELECT * FROM PLAYER [42102-190] +2015-12-16 18:17:40 jdbc[4]: exception +org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" не найдена +Table "PLAYER" not found; SQL statement: +SELECT * FROM PLAYER [42102-190] +2015-12-16 18:21:18 jdbc[3]: exception +org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" не найдена +Table "PLAYER" not found; SQL statement: +SELECT * FROM PLAYER [42102-190] +2015-12-16 18:22:05 jdbc[3]: exception +org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" не найдена +Table "PLAYER" not found; SQL statement: +SELECT * FROM PLAYER [42102-190] +2015-12-16 18:23:10 jdbc[3]: exception +org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" не найдена +Table "PLAYER" not found; SQL statement: +SELECT * FROM PLAYER [42102-190] +2015-12-16 18:41:50 jdbc[7]: null +org.h2.message.DbException: Незакрытое приложением соединение уничтожено сборщиком мусора +The connection was not closed by the application and is garbage collected [90018-190] + at org.h2.message.DbException.get(DbException.java:179) + at org.h2.message.DbException.get(DbException.java:155) + at org.h2.message.DbException.get(DbException.java:144) + at org.h2.jdbc.JdbcConnection.closeOld(JdbcConnection.java:173) + at org.h2.jdbc.JdbcConnection.(JdbcConnection.java:118) + at org.h2.jdbc.JdbcConnection.(JdbcConnection.java:91) + at org.h2.Driver.connect(Driver.java:72) + at java.sql.DriverManager.getConnection(DriverManager.java:664) + at java.sql.DriverManager.getConnection(DriverManager.java:270) + at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseService.(DatabaseService.java:62) + at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseServiceTest.insertTest(DatabaseServiceTest.java:102) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:497) + at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) + at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) + at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) + at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) + at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) + at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) + at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) + at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) + at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) + at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) + at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) + at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) + at org.junit.runners.ParentRunner.run(ParentRunner.java:363) + at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37) + at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62) + at org.junit.runner.JUnitCore.run(JUnitCore.java:137) + at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78) + at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212) + at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:497) + at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140) +Caused by: org.h2.jdbc.JdbcSQLException: Незакрытое приложением соединение уничтожено сборщиком мусора +The connection was not closed by the application and is garbage collected [90018-190] + at org.h2.message.DbException.getJdbcSQLException(DbException.java:345) + ... 39 more +2015-12-16 18:44:06 jdbc[9]: exception +org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" уже существует +Table "PLAYER" already exists; SQL statement: +CREATE TABLE player(id INTEGER NOT NULL PRIMARY KEY, last_name VARCHAR(20), salary BIGINT, club VARCHAR(20)) [42101-190] +2015-12-16 18:44:51 jdbc[14]: exception +org.h2.jdbc.JdbcSQLException: Синтаксическая ошибка в выражении SQL "CREATE TABLE IF NOT EXISTSPLAYER[*](ID INTEGER NOT NULL PRIMARY KEY, LAST_NAME VARCHAR(20), SALARY BIGINT, CLUB VARCHAR(20)) "; ожидалось "EXISTS" +Syntax error in SQL statement "CREATE TABLE IF NOT EXISTSPLAYER[*](ID INTEGER NOT NULL PRIMARY KEY, LAST_NAME VARCHAR(20), SALARY BIGINT, CLUB VARCHAR(20)) "; expected "EXISTS"; SQL statement: +CREATE TABLE IF NOT EXISTSplayer(id INTEGER NOT NULL PRIMARY KEY, last_name VARCHAR(20), salary BIGINT, club VARCHAR(20)) [42001-190] +2015-12-16 18:44:51 jdbc[17]: exception +org.h2.jdbc.JdbcSQLException: Синтаксическая ошибка в выражении SQL "CREATE TABLE IF NOT EXISTSPLAYER[*](ID INTEGER NOT NULL PRIMARY KEY, LAST_NAME VARCHAR(20), SALARY BIGINT, CLUB VARCHAR(20)) "; ожидалось "EXISTS" +Syntax error in SQL statement "CREATE TABLE IF NOT EXISTSPLAYER[*](ID INTEGER NOT NULL PRIMARY KEY, LAST_NAME VARCHAR(20), SALARY BIGINT, CLUB VARCHAR(20)) "; expected "EXISTS"; SQL statement: +CREATE TABLE IF NOT EXISTSplayer(id INTEGER NOT NULL PRIMARY KEY, last_name VARCHAR(20), salary BIGINT, club VARCHAR(20)) [42001-190] +2015-12-16 18:44:51 jdbc[20]: exception +org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" не найдена +Table "PLAYER" not found; SQL statement: +DELETE FROM player WHERE id=? [42102-190] +2015-12-16 18:45:12 jdbc[4]: exception +org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" не найдена +Table "PLAYER" not found; SQL statement: +SELECT * FROM player WHERE id=? [42102-190] +2015-12-16 18:45:12 jdbc[7]: exception +org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" не найдена +Table "PLAYER" not found; SQL statement: +UPDATE player SET id=?, last_name=?, salary=?, club=? WHERE id=? [42102-190] +2015-12-16 18:45:12 jdbc[14]: exception +org.h2.jdbc.JdbcSQLException: Синтаксическая ошибка в выражении SQL "CREATE TABLE IF NOT EXISTSPLAYER[*](ID INTEGER NOT NULL PRIMARY KEY, LAST_NAME VARCHAR(20), SALARY BIGINT, CLUB VARCHAR(20)) "; ожидалось "EXISTS" +Syntax error in SQL statement "CREATE TABLE IF NOT EXISTSPLAYER[*](ID INTEGER NOT NULL PRIMARY KEY, LAST_NAME VARCHAR(20), SALARY BIGINT, CLUB VARCHAR(20)) "; expected "EXISTS"; SQL statement: +CREATE TABLE IF NOT EXISTSplayer(id INTEGER NOT NULL PRIMARY KEY, last_name VARCHAR(20), salary BIGINT, club VARCHAR(20)) [42001-190] +2015-12-16 18:45:12 jdbc[17]: exception +org.h2.jdbc.JdbcSQLException: Синтаксическая ошибка в выражении SQL "CREATE TABLE IF NOT EXISTSPLAYER[*](ID INTEGER NOT NULL PRIMARY KEY, LAST_NAME VARCHAR(20), SALARY BIGINT, CLUB VARCHAR(20)) "; ожидалось "EXISTS" +Syntax error in SQL statement "CREATE TABLE IF NOT EXISTSPLAYER[*](ID INTEGER NOT NULL PRIMARY KEY, LAST_NAME VARCHAR(20), SALARY BIGINT, CLUB VARCHAR(20)) "; expected "EXISTS"; SQL statement: +CREATE TABLE IF NOT EXISTSplayer(id INTEGER NOT NULL PRIMARY KEY, last_name VARCHAR(20), salary BIGINT, club VARCHAR(20)) [42001-190] +2015-12-16 18:45:12 jdbc[20]: exception +org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" не найдена +Table "PLAYER" not found; SQL statement: +DELETE FROM player WHERE id=? [42102-190] +2015-12-16 18:45:25 jdbc[4]: exception +org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" не найдена +Table "PLAYER" not found; SQL statement: +SELECT * FROM player WHERE id=? [42102-190] +2015-12-16 18:45:25 jdbc[7]: exception +org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" не найдена +Table "PLAYER" not found; SQL statement: +UPDATE player SET id=?, last_name=?, salary=?, club=? WHERE id=? [42102-190] +2015-12-16 18:46:22 jdbc[7]: null +org.h2.message.DbException: Незакрытое приложением соединение уничтожено сборщиком мусора +The connection was not closed by the application and is garbage collected [90018-190] + at org.h2.message.DbException.get(DbException.java:179) + at org.h2.message.DbException.get(DbException.java:155) + at org.h2.message.DbException.get(DbException.java:144) + at org.h2.jdbc.JdbcConnection.closeOld(JdbcConnection.java:173) + at org.h2.jdbc.JdbcConnection.(JdbcConnection.java:118) + at org.h2.jdbc.JdbcConnection.(JdbcConnection.java:91) + at org.h2.Driver.connect(Driver.java:72) + at java.sql.DriverManager.getConnection(DriverManager.java:664) + at java.sql.DriverManager.getConnection(DriverManager.java:270) + at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseService.(DatabaseService.java:62) + at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseServiceTest.insertTest(DatabaseServiceTest.java:102) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:497) + at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) + at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) + at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) + at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) + at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) + at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) + at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) + at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) + at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) + at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) + at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) + at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) + at org.junit.runners.ParentRunner.run(ParentRunner.java:363) + at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37) + at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62) + at org.junit.runner.JUnitCore.run(JUnitCore.java:137) + at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78) + at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212) + at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68) + at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) + at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) + at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) + at java.lang.reflect.Method.invoke(Method.java:497) + at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140) +Caused by: org.h2.jdbc.JdbcSQLException: Незакрытое приложением соединение уничтожено сборщиком мусора +The connection was not closed by the application and is garbage collected [90018-190] + at org.h2.message.DbException.getJdbcSQLException(DbException.java:345) + ... 39 more diff --git a/projects/simon23rus/pom.xml b/projects/simon23rus/pom.xml index abbd771..d243e87 100644 --- a/projects/simon23rus/pom.xml +++ b/projects/simon23rus/pom.xml @@ -54,7 +54,16 @@ - + + com.h2database + h2 + 1.4.190 + + + com.google.guava + guava + 19.0 + org.powermock powermock-module-junit4 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..6715135 --- /dev/null +++ b/projects/simon23rus/src/test/java/ru/mipt/diht/students/simon23rus/DatabaseService/DatabaseServiceTest.java @@ -0,0 +1,208 @@ +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<>(); + 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))); + } +} From 08fda647eb90d7ae892698c8796a7fc1ce374e7a Mon Sep 17 00:00:00 2001 From: simon23rus Date: Wed, 16 Dec 2015 20:03:16 +0300 Subject: [PATCH 12/13] Update dbTask.trace.db --- projects/simon23rus/dbTask.trace.db | 484 +--------------------------- 1 file changed, 1 insertion(+), 483 deletions(-) diff --git a/projects/simon23rus/dbTask.trace.db b/projects/simon23rus/dbTask.trace.db index bfaee0c..8b13789 100644 --- a/projects/simon23rus/dbTask.trace.db +++ b/projects/simon23rus/dbTask.trace.db @@ -1,483 +1 @@ -2015-12-16 13:38:00 jdbc[4]: exception -org.h2.jdbc.JdbcSQLException: Синтаксическая ошибка в выражении SQL "CREATE TABLE IF NOT EXISTS NULL[*]( INTEGERNOT NULL PRIMARY KEY, VARCHAR(20), BIGINT, VARCHAR(20)) "; ожидалось "identifier" -Syntax error in SQL statement "CREATE TABLE IF NOT EXISTS NULL[*]( INTEGERNOT NULL PRIMARY KEY, VARCHAR(20), BIGINT, VARCHAR(20)) "; expected "identifier"; SQL statement: -CREATE TABLE IF NOT EXISTS null( INTEGERNOT NULL PRIMARY KEY, VARCHAR(20), BIGINT, VARCHAR(20)) [42001-190] -2015-12-16 13:38:16 jdbc[4]: exception -org.h2.jdbc.JdbcSQLException: Синтаксическая ошибка в выражении SQL "CREATE TABLE IF NOT EXISTS NULL[*]( INTEGERNOT NULL PRIMARY KEY, VARCHAR(20), BIGINT, VARCHAR(20)) "; ожидалось "identifier" -Syntax error in SQL statement "CREATE TABLE IF NOT EXISTS NULL[*]( INTEGERNOT NULL PRIMARY KEY, VARCHAR(20), BIGINT, VARCHAR(20)) "; expected "identifier"; SQL statement: -CREATE TABLE IF NOT EXISTS null( INTEGERNOT NULL PRIMARY KEY, VARCHAR(20), BIGINT, VARCHAR(20)) [42001-190] -2015-12-16 13:40:28 jdbc[4]: exception -org.h2.jdbc.JdbcSQLException: Неизвестный тип данных: "(" -Unknown data type: "("; SQL statement: -CREATE TABLE IF NOT EXISTS player( INTEGERNOT NULL PRIMARY KEY, VARCHAR(20), BIGINT, VARCHAR(20)) [50004-190] - at org.h2.message.DbException.getJdbcSQLException(DbException.java:345) - at org.h2.message.DbException.get(DbException.java:179) - at org.h2.message.DbException.get(DbException.java:155) - at org.h2.command.Parser.parseColumnWithType(Parser.java:4009) - at org.h2.command.Parser.parseColumnForTable(Parser.java:3872) - at org.h2.command.Parser.parseCreateTable(Parser.java:5808) - at org.h2.command.Parser.parseCreate(Parser.java:4167) - at org.h2.command.Parser.parsePrepared(Parser.java:349) - at org.h2.command.Parser.parse(Parser.java:304) - at org.h2.command.Parser.parse(Parser.java:276) - at org.h2.command.Parser.prepareCommand(Parser.java:241) - at org.h2.engine.Session.prepareLocal(Session.java:460) - at org.h2.engine.Session.prepareCommand(Session.java:402) - at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1188) - at org.h2.jdbc.JdbcStatement.executeUpdateInternal(JdbcStatement.java:126) - at org.h2.jdbc.JdbcStatement.executeUpdate(JdbcStatement.java:115) - at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseService.createTable(DatabaseService.java:235) - at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseServiceTest.createTableTest(DatabaseServiceTest.java:44) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) - at java.lang.reflect.Method.invoke(Method.java:497) - at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) - at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) - at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) - at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) - at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) - at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) - at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) - at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) - at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) - at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) - at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) - at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) - at org.junit.runners.ParentRunner.run(ParentRunner.java:363) - at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37) - at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62) - at org.junit.runner.JUnitCore.run(JUnitCore.java:137) - at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78) - at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212) - at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) - at java.lang.reflect.Method.invoke(Method.java:497) - at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140) -2015-12-16 13:41:29 jdbc[4]: exception -org.h2.jdbc.JdbcSQLException: Неизвестный тип данных: "NOT" -Unknown data type: "NOT"; SQL statement: -CREATE TABLE IF NOT EXISTS player( INTEGER NOT NULL PRIMARY KEY, VARCHAR(20), BIGINT, VARCHAR(20)) [50004-190] - at org.h2.message.DbException.getJdbcSQLException(DbException.java:345) - at org.h2.message.DbException.get(DbException.java:179) - at org.h2.message.DbException.get(DbException.java:155) - at org.h2.command.Parser.parseColumnWithType(Parser.java:4009) - at org.h2.command.Parser.parseColumnForTable(Parser.java:3872) - at org.h2.command.Parser.parseCreateTable(Parser.java:5808) - at org.h2.command.Parser.parseCreate(Parser.java:4167) - at org.h2.command.Parser.parsePrepared(Parser.java:349) - at org.h2.command.Parser.parse(Parser.java:304) - at org.h2.command.Parser.parse(Parser.java:276) - at org.h2.command.Parser.prepareCommand(Parser.java:241) - at org.h2.engine.Session.prepareLocal(Session.java:460) - at org.h2.engine.Session.prepareCommand(Session.java:402) - at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1188) - at org.h2.jdbc.JdbcStatement.executeUpdateInternal(JdbcStatement.java:126) - at org.h2.jdbc.JdbcStatement.executeUpdate(JdbcStatement.java:115) - at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseService.createTable(DatabaseService.java:235) - at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseServiceTest.createTableTest(DatabaseServiceTest.java:44) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) - at java.lang.reflect.Method.invoke(Method.java:497) - at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) - at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) - at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) - at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) - at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) - at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) - at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) - at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) - at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) - at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) - at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) - at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) - at org.junit.runners.ParentRunner.run(ParentRunner.java:363) - at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37) - at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62) - at org.junit.runner.JUnitCore.run(JUnitCore.java:137) - at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78) - at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212) - at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) - at java.lang.reflect.Method.invoke(Method.java:497) - at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140) -2015-12-16 13:42:57 jdbc[4]: exception -org.h2.jdbc.JdbcSQLException: Неизвестный тип данных: "NOT" -Unknown data type: "NOT"; SQL statement: -CREATE TABLE IF NOT EXISTS player( INTEGER NOT NULL PRIMARY KEY, VARCHAR(20), BIGINT, VARCHAR(20)) [50004-190] - at org.h2.message.DbException.getJdbcSQLException(DbException.java:345) - at org.h2.message.DbException.get(DbException.java:179) - at org.h2.message.DbException.get(DbException.java:155) - at org.h2.command.Parser.parseColumnWithType(Parser.java:4009) - at org.h2.command.Parser.parseColumnForTable(Parser.java:3872) - at org.h2.command.Parser.parseCreateTable(Parser.java:5808) - at org.h2.command.Parser.parseCreate(Parser.java:4167) - at org.h2.command.Parser.parsePrepared(Parser.java:349) - at org.h2.command.Parser.parse(Parser.java:304) - at org.h2.command.Parser.parse(Parser.java:276) - at org.h2.command.Parser.prepareCommand(Parser.java:241) - at org.h2.engine.Session.prepareLocal(Session.java:460) - at org.h2.engine.Session.prepareCommand(Session.java:402) - at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1188) - at org.h2.jdbc.JdbcStatement.executeUpdateInternal(JdbcStatement.java:126) - at org.h2.jdbc.JdbcStatement.executeUpdate(JdbcStatement.java:115) - at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseService.createTable(DatabaseService.java:236) - at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseServiceTest.createTableTest(DatabaseServiceTest.java:44) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) - at java.lang.reflect.Method.invoke(Method.java:497) - at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) - at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) - at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) - at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) - at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) - at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) - at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) - at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) - at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) - at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) - at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) - at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) - at org.junit.runners.ParentRunner.run(ParentRunner.java:363) - at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37) - at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62) - at org.junit.runner.JUnitCore.run(JUnitCore.java:137) - at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78) - at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212) - at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) - at java.lang.reflect.Method.invoke(Method.java:497) - at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140) -2015-12-16 13:44:41 jdbc[4]: exception -org.h2.jdbc.JdbcSQLException: Неизвестный тип данных: "NOT" -Unknown data type: "NOT"; SQL statement: -CREATE TABLE IF NOT EXISTS player( INTEGER NOT NULL PRIMARY KEY, VARCHAR(20), BIGINT, VARCHAR(20)) [50004-190] - at org.h2.message.DbException.getJdbcSQLException(DbException.java:345) - at org.h2.message.DbException.get(DbException.java:179) - at org.h2.message.DbException.get(DbException.java:155) - at org.h2.command.Parser.parseColumnWithType(Parser.java:4009) - at org.h2.command.Parser.parseColumnForTable(Parser.java:3872) - at org.h2.command.Parser.parseCreateTable(Parser.java:5808) - at org.h2.command.Parser.parseCreate(Parser.java:4167) - at org.h2.command.Parser.parsePrepared(Parser.java:349) - at org.h2.command.Parser.parse(Parser.java:304) - at org.h2.command.Parser.parse(Parser.java:276) - at org.h2.command.Parser.prepareCommand(Parser.java:241) - at org.h2.engine.Session.prepareLocal(Session.java:460) - at org.h2.engine.Session.prepareCommand(Session.java:402) - at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1188) - at org.h2.jdbc.JdbcStatement.executeUpdateInternal(JdbcStatement.java:126) - at org.h2.jdbc.JdbcStatement.executeUpdate(JdbcStatement.java:115) - at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseService.createTable(DatabaseService.java:236) - at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseServiceTest.createTableTest(DatabaseServiceTest.java:44) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) - at java.lang.reflect.Method.invoke(Method.java:497) - at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) - at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) - at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) - at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) - at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) - at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) - at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) - at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) - at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) - at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) - at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) - at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) - at org.junit.runners.ParentRunner.run(ParentRunner.java:363) - at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37) - at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62) - at org.junit.runner.JUnitCore.run(JUnitCore.java:137) - at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78) - at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212) - at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) - at java.lang.reflect.Method.invoke(Method.java:497) - at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140) -2015-12-16 13:45:41 jdbc[4]: exception -org.h2.jdbc.JdbcSQLException: Неизвестный тип данных: "NOT" -Unknown data type: "NOT"; SQL statement: -CREATE TABLE IF NOT EXISTS player( INTEGER NOT NULL PRIMARY KEY, VARCHAR(20), BIGINT, VARCHAR(20)) [50004-190] - at org.h2.message.DbException.getJdbcSQLException(DbException.java:345) - at org.h2.message.DbException.get(DbException.java:179) - at org.h2.message.DbException.get(DbException.java:155) - at org.h2.command.Parser.parseColumnWithType(Parser.java:4009) - at org.h2.command.Parser.parseColumnForTable(Parser.java:3872) - at org.h2.command.Parser.parseCreateTable(Parser.java:5808) - at org.h2.command.Parser.parseCreate(Parser.java:4167) - at org.h2.command.Parser.parsePrepared(Parser.java:349) - at org.h2.command.Parser.parse(Parser.java:304) - at org.h2.command.Parser.parse(Parser.java:276) - at org.h2.command.Parser.prepareCommand(Parser.java:241) - at org.h2.engine.Session.prepareLocal(Session.java:460) - at org.h2.engine.Session.prepareCommand(Session.java:402) - at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1188) - at org.h2.jdbc.JdbcStatement.executeUpdateInternal(JdbcStatement.java:126) - at org.h2.jdbc.JdbcStatement.executeUpdate(JdbcStatement.java:115) - at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseService.createTable(DatabaseService.java:237) - at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseServiceTest.createTableTest(DatabaseServiceTest.java:44) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) - at java.lang.reflect.Method.invoke(Method.java:497) - at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) - at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) - at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) - at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) - at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) - at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) - at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) - at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) - at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) - at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) - at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) - at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) - at org.junit.runners.ParentRunner.run(ParentRunner.java:363) - at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37) - at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62) - at org.junit.runner.JUnitCore.run(JUnitCore.java:137) - at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78) - at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212) - at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) - at java.lang.reflect.Method.invoke(Method.java:497) - at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140) -2015-12-16 13:56:25 jdbc[3]: exception -org.h2.jdbc.JdbcSQLException: Объект уже закрыт -The object is already closed [90007-190] -2015-12-16 14:51:35 jdbc[3]: exception -org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" уже существует -Table "PLAYER" already exists; SQL statement: -CREATE TABLE PLAYER(id INTEGER NOT NULL PRIMARY KEY, last_name VARCHAR(20), salary BIGINT, club VARCHAR(20)) [42101-190] -2015-12-16 15:25:52 jdbc[4]: exception -org.h2.jdbc.JdbcSQLException: Синтаксическая ошибка в выражении SQL "INSERT INTO PLAYER VALUES (?, ?, ?, ? [*]"; ожидалось "[, ::, *, /, %, +, -, ||, ~, !~, NOT, LIKE, REGEXP, IS, IN, BETWEEN, AND, OR, ,, )" -Syntax error in SQL statement "INSERT INTO PLAYER VALUES (?, ?, ?, ? [*]"; expected "[, ::, *, /, %, +, -, ||, ~, !~, NOT, LIKE, REGEXP, IS, IN, BETWEEN, AND, OR, ,, )"; SQL statement: -INSERT INTO player VALUES (?, ?, ?, ? [42001-190] -2015-12-16 17:15:47 jdbc[4]: exception -org.h2.jdbc.JdbcSQLException: Синтаксическая ошибка в выражении SQL "UPDATE PLAYER SET ID=?, LAST_NAME=?, SALARY=?, CLUB=? WHEREID[*]=? " -Syntax error in SQL statement "UPDATE PLAYER SET ID=?, LAST_NAME=?, SALARY=?, CLUB=? WHEREID[*]=? "; SQL statement: -UPDATE player SET id=?, last_name=?, salary=?, club=? WHEREid=? [42000-190] -2015-12-16 17:16:05 jdbc[4]: exception -org.h2.jdbc.JdbcSQLException: Синтаксическая ошибка в выражении SQL "UPDATE PLAYER SET ID=?, LAST_NAME=?, SALARY=?, CLUB=? WHEREID[*]=? " -Syntax error in SQL statement "UPDATE PLAYER SET ID=?, LAST_NAME=?, SALARY=?, CLUB=? WHEREID[*]=? "; SQL statement: -UPDATE player SET id=?, last_name=?, salary=?, club=? WHEREid=? [42000-190] -2015-12-16 17:19:42 jdbc[5]: exception -org.h2.jdbc.JdbcSQLException: Таблица "PLAYERWHERE" не найдена -Table "PLAYERWHERE" not found; SQL statement: -SELECT * FROM playerWHERE id=? [42102-190] -2015-12-16 17:42:00 jdbc[27]: exception -org.h2.jdbc.JdbcSQLException: Недопустимое значение "5" для параметра "parameterIndex" -Invalid value "5" for parameter "parameterIndex" [90008-190] - at org.h2.message.DbException.getJdbcSQLException(DbException.java:345) - at org.h2.message.DbException.get(DbException.java:179) - at org.h2.message.DbException.getInvalidValueException(DbException.java:228) - at org.h2.jdbc.JdbcPreparedStatement.setParameter(JdbcPreparedStatement.java:1382) - at org.h2.jdbc.JdbcPreparedStatement.setObject(JdbcPreparedStatement.java:460) - at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseService.delete(DatabaseService.java:213) - at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseServiceTest.deleteTest(DatabaseServiceTest.java:157) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) - at java.lang.reflect.Method.invoke(Method.java:497) - at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) - at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) - at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) - at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) - at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) - at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) - at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) - at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) - at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) - at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) - at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) - at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) - at org.junit.runners.ParentRunner.run(ParentRunner.java:363) - at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37) - at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62) - at org.junit.runner.JUnitCore.run(JUnitCore.java:137) - at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78) - at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212) - at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) - at java.lang.reflect.Method.invoke(Method.java:497) - at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140) -2015-12-16 18:14:37 jdbc[4]: exception -org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" не найдена -Table "PLAYER" not found; SQL statement: -SELECT * FROM player [42102-190] -2015-12-16 18:15:36 jdbc[4]: exception -org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" не найдена -Table "PLAYER" not found; SQL statement: -SELECT * FROM player [42102-190] -2015-12-16 18:16:31 jdbc[4]: exception -org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" не найдена -Table "PLAYER" not found; SQL statement: -SELECT * FROM PLAYER [42102-190] -2015-12-16 18:17:40 jdbc[4]: exception -org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" не найдена -Table "PLAYER" not found; SQL statement: -SELECT * FROM PLAYER [42102-190] -2015-12-16 18:21:18 jdbc[3]: exception -org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" не найдена -Table "PLAYER" not found; SQL statement: -SELECT * FROM PLAYER [42102-190] -2015-12-16 18:22:05 jdbc[3]: exception -org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" не найдена -Table "PLAYER" not found; SQL statement: -SELECT * FROM PLAYER [42102-190] -2015-12-16 18:23:10 jdbc[3]: exception -org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" не найдена -Table "PLAYER" not found; SQL statement: -SELECT * FROM PLAYER [42102-190] -2015-12-16 18:41:50 jdbc[7]: null -org.h2.message.DbException: Незакрытое приложением соединение уничтожено сборщиком мусора -The connection was not closed by the application and is garbage collected [90018-190] - at org.h2.message.DbException.get(DbException.java:179) - at org.h2.message.DbException.get(DbException.java:155) - at org.h2.message.DbException.get(DbException.java:144) - at org.h2.jdbc.JdbcConnection.closeOld(JdbcConnection.java:173) - at org.h2.jdbc.JdbcConnection.(JdbcConnection.java:118) - at org.h2.jdbc.JdbcConnection.(JdbcConnection.java:91) - at org.h2.Driver.connect(Driver.java:72) - at java.sql.DriverManager.getConnection(DriverManager.java:664) - at java.sql.DriverManager.getConnection(DriverManager.java:270) - at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseService.(DatabaseService.java:62) - at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseServiceTest.insertTest(DatabaseServiceTest.java:102) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) - at java.lang.reflect.Method.invoke(Method.java:497) - at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) - at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) - at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) - at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) - at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) - at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) - at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) - at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) - at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) - at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) - at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) - at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) - at org.junit.runners.ParentRunner.run(ParentRunner.java:363) - at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37) - at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62) - at org.junit.runner.JUnitCore.run(JUnitCore.java:137) - at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78) - at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212) - at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) - at java.lang.reflect.Method.invoke(Method.java:497) - at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140) -Caused by: org.h2.jdbc.JdbcSQLException: Незакрытое приложением соединение уничтожено сборщиком мусора -The connection was not closed by the application and is garbage collected [90018-190] - at org.h2.message.DbException.getJdbcSQLException(DbException.java:345) - ... 39 more -2015-12-16 18:44:06 jdbc[9]: exception -org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" уже существует -Table "PLAYER" already exists; SQL statement: -CREATE TABLE player(id INTEGER NOT NULL PRIMARY KEY, last_name VARCHAR(20), salary BIGINT, club VARCHAR(20)) [42101-190] -2015-12-16 18:44:51 jdbc[14]: exception -org.h2.jdbc.JdbcSQLException: Синтаксическая ошибка в выражении SQL "CREATE TABLE IF NOT EXISTSPLAYER[*](ID INTEGER NOT NULL PRIMARY KEY, LAST_NAME VARCHAR(20), SALARY BIGINT, CLUB VARCHAR(20)) "; ожидалось "EXISTS" -Syntax error in SQL statement "CREATE TABLE IF NOT EXISTSPLAYER[*](ID INTEGER NOT NULL PRIMARY KEY, LAST_NAME VARCHAR(20), SALARY BIGINT, CLUB VARCHAR(20)) "; expected "EXISTS"; SQL statement: -CREATE TABLE IF NOT EXISTSplayer(id INTEGER NOT NULL PRIMARY KEY, last_name VARCHAR(20), salary BIGINT, club VARCHAR(20)) [42001-190] -2015-12-16 18:44:51 jdbc[17]: exception -org.h2.jdbc.JdbcSQLException: Синтаксическая ошибка в выражении SQL "CREATE TABLE IF NOT EXISTSPLAYER[*](ID INTEGER NOT NULL PRIMARY KEY, LAST_NAME VARCHAR(20), SALARY BIGINT, CLUB VARCHAR(20)) "; ожидалось "EXISTS" -Syntax error in SQL statement "CREATE TABLE IF NOT EXISTSPLAYER[*](ID INTEGER NOT NULL PRIMARY KEY, LAST_NAME VARCHAR(20), SALARY BIGINT, CLUB VARCHAR(20)) "; expected "EXISTS"; SQL statement: -CREATE TABLE IF NOT EXISTSplayer(id INTEGER NOT NULL PRIMARY KEY, last_name VARCHAR(20), salary BIGINT, club VARCHAR(20)) [42001-190] -2015-12-16 18:44:51 jdbc[20]: exception -org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" не найдена -Table "PLAYER" not found; SQL statement: -DELETE FROM player WHERE id=? [42102-190] -2015-12-16 18:45:12 jdbc[4]: exception -org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" не найдена -Table "PLAYER" not found; SQL statement: -SELECT * FROM player WHERE id=? [42102-190] -2015-12-16 18:45:12 jdbc[7]: exception -org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" не найдена -Table "PLAYER" not found; SQL statement: -UPDATE player SET id=?, last_name=?, salary=?, club=? WHERE id=? [42102-190] -2015-12-16 18:45:12 jdbc[14]: exception -org.h2.jdbc.JdbcSQLException: Синтаксическая ошибка в выражении SQL "CREATE TABLE IF NOT EXISTSPLAYER[*](ID INTEGER NOT NULL PRIMARY KEY, LAST_NAME VARCHAR(20), SALARY BIGINT, CLUB VARCHAR(20)) "; ожидалось "EXISTS" -Syntax error in SQL statement "CREATE TABLE IF NOT EXISTSPLAYER[*](ID INTEGER NOT NULL PRIMARY KEY, LAST_NAME VARCHAR(20), SALARY BIGINT, CLUB VARCHAR(20)) "; expected "EXISTS"; SQL statement: -CREATE TABLE IF NOT EXISTSplayer(id INTEGER NOT NULL PRIMARY KEY, last_name VARCHAR(20), salary BIGINT, club VARCHAR(20)) [42001-190] -2015-12-16 18:45:12 jdbc[17]: exception -org.h2.jdbc.JdbcSQLException: Синтаксическая ошибка в выражении SQL "CREATE TABLE IF NOT EXISTSPLAYER[*](ID INTEGER NOT NULL PRIMARY KEY, LAST_NAME VARCHAR(20), SALARY BIGINT, CLUB VARCHAR(20)) "; ожидалось "EXISTS" -Syntax error in SQL statement "CREATE TABLE IF NOT EXISTSPLAYER[*](ID INTEGER NOT NULL PRIMARY KEY, LAST_NAME VARCHAR(20), SALARY BIGINT, CLUB VARCHAR(20)) "; expected "EXISTS"; SQL statement: -CREATE TABLE IF NOT EXISTSplayer(id INTEGER NOT NULL PRIMARY KEY, last_name VARCHAR(20), salary BIGINT, club VARCHAR(20)) [42001-190] -2015-12-16 18:45:12 jdbc[20]: exception -org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" не найдена -Table "PLAYER" not found; SQL statement: -DELETE FROM player WHERE id=? [42102-190] -2015-12-16 18:45:25 jdbc[4]: exception -org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" не найдена -Table "PLAYER" not found; SQL statement: -SELECT * FROM player WHERE id=? [42102-190] -2015-12-16 18:45:25 jdbc[7]: exception -org.h2.jdbc.JdbcSQLException: Таблица "PLAYER" не найдена -Table "PLAYER" not found; SQL statement: -UPDATE player SET id=?, last_name=?, salary=?, club=? WHERE id=? [42102-190] -2015-12-16 18:46:22 jdbc[7]: null -org.h2.message.DbException: Незакрытое приложением соединение уничтожено сборщиком мусора -The connection was not closed by the application and is garbage collected [90018-190] - at org.h2.message.DbException.get(DbException.java:179) - at org.h2.message.DbException.get(DbException.java:155) - at org.h2.message.DbException.get(DbException.java:144) - at org.h2.jdbc.JdbcConnection.closeOld(JdbcConnection.java:173) - at org.h2.jdbc.JdbcConnection.(JdbcConnection.java:118) - at org.h2.jdbc.JdbcConnection.(JdbcConnection.java:91) - at org.h2.Driver.connect(Driver.java:72) - at java.sql.DriverManager.getConnection(DriverManager.java:664) - at java.sql.DriverManager.getConnection(DriverManager.java:270) - at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseService.(DatabaseService.java:62) - at ru.mipt.diht.students.simon23rus.DatabaseService.DatabaseServiceTest.insertTest(DatabaseServiceTest.java:102) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) - at java.lang.reflect.Method.invoke(Method.java:497) - at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) - at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) - at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) - at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) - at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) - at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) - at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) - at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) - at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) - at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) - at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) - at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) - at org.junit.runners.ParentRunner.run(ParentRunner.java:363) - at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37) - at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62) - at org.junit.runner.JUnitCore.run(JUnitCore.java:137) - at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78) - at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212) - at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68) - at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) - at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) - at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) - at java.lang.reflect.Method.invoke(Method.java:497) - at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140) -Caused by: org.h2.jdbc.JdbcSQLException: Незакрытое приложением соединение уничтожено сборщиком мусора -The connection was not closed by the application and is garbage collected [90018-190] - at org.h2.message.DbException.getJdbcSQLException(DbException.java:345) - ... 39 more + From 53f5d11c99340eab6433d89712b6990a6ac3c311 Mon Sep 17 00:00:00 2001 From: Semyon Fedotov Date: Fri, 18 Dec 2015 20:24:42 +0300 Subject: [PATCH 13/13] final --- projects/simon23rus/dbTask.mv.db | Bin 28672 -> 36864 bytes .../simon23rus/CQL/data/CollectionQuery.java | 22 ++--- .../simon23rus/CQL/impl/FromStmt.java | 24 +++-- .../students/simon23rus/CQL/impl/Tuple.java | 2 +- .../simon23rus/Threads/BlockingQueue.java | 90 +++++++++++++++--- .../Threads/BlockingQueueRunner.java | 2 +- .../TwitterStream/GeoCodeConverter.java | 7 +- .../TwitterStream/TimeTransformer.java | 18 +--- .../TwitterStream/TwitterPrinter.java | 3 +- .../TwitterStream/TwitterStreamer.java | 7 +- .../simon23rus/CQL/impl/FromStmtTest.java | 28 +++++- .../DatabaseService/DatabaseServiceTest.java | 18 ++-- .../simon23rus/Threads/BlockingQueueTest.java | 81 ++++++++++++++++ .../TwitterStream/GeoCodeConverterTest.java | 2 + .../TwitterStream/TwitterPrinterTest.java | 11 +++ 15 files changed, 241 insertions(+), 74 deletions(-) diff --git a/projects/simon23rus/dbTask.mv.db b/projects/simon23rus/dbTask.mv.db index befdb81a6cff607768d245633c2154956e0b0596..7215bfd61bfb2443f47967fa0a6283ac00e3b7e4 100644 GIT binary patch literal 36864 zcmeHQOKjW7875^j-Z;({2HIPTGTuD9s=$XNl0pxWCD~RiD_%(s;5Mao*T zo86OvK5jh}z3rhWdMH|8Q7raQ^q5001=?Wy0J`U(D9~GbD0Yt>a%M=GqSv-$*+TLA zU=By*@Skt^(D!{mM{7APX}7!1E??GL@8g`RC`!_Ky5HH&*?Q91!>EtloSIP)%3$3z z^klQU_YC!OYVrW@^;+GIw_UT1`_5Cmm&@pemPu>+ya0cI03ZMe00MvjAOHve0)PM@ z00;mAfB+yc1qiHh-p`l7|EFM7AOt`F5C8-K0YCr{00aO5KmZT`1ONd*;CvAXOn#mO z(8e9&>OVuza~Yc~UXX>7?BEyuoSuA+c5pA3PVRNP{ha1FBuhY1GOnU0`>kg~e_Gc4a@zl&x#G2xv41GC@l{xoMF&^#KC;_5rCjqrX?N`n^gJlnaPw<^ zJ>7_>x0rQsQ0VO~D`jtpDHe+fB7PE`E_x=n84Ki2BHHI5lt(uS^c&2b+ow zHpSwj?XWoL3hTxd@3xTA=t7_K*D^L;rLpAL;lJwlg$2gai+EpD(Gas@TFi*5s3$VE zsENvg=1`zDL-khZjYl&SC-}s~rgpw}MraKX00aO5KmZT`1ONd*01!BT1cvx`Ts}Q= zjf{=m>^N*Xe&2a^{4^tGIwM6s|96h^z;uNCxKSSH5x-`7fc&K64|>X4!vDpeiNBqZ z1XYvPrHZscnEws=_Tze~As1?;e53Sad8=G0%BrOhO+a3{uF-0Ft6r+fi-ZdEEt|AR`t-gr{YZItcOV#*JzK|PJGTqI50 zl5bt#A-yEg#q@x5xF{DMR_l#goqPdum!jc3ETV&!D?e(r+erHPkFUH_#ov>+ zyL-EGq1AuyJk^|;zx!&=H%XU2{fi)wrTBwa^P!sak+>twf03HQWgRNwoFMBsAnOEo z$rELrScQu!o8!njZ05V`@nb)sonA zi)u-1#WFoDiLHQ^#BbfO1Oxy9KmZT`1OS0aATY$ggKxI!@O^rOO~Y=w<|&Eu88&15 zAGwVGrw94J>GS`+z*<$BFy@pZkpQ?fb<4 zZwLZeidOYnz!+yX6HkR}oG~JU@k37z6L>~| zMGe_O8yu-wG9v`b2+*3gt>JL42xRb#0A#T+qHcT)f1*JIrz7{`c{&OjJ{^&+W{hKl zumUU)3&M(|1jKSj!^Z;glmHY_#n5m{0MadzTM%MFE)qMuNKk-<&BD+kVZ>lTgE%%d z2SrnJ_y`;qgw3)eki%l&LLld}vDp#y1`#BRLd#O^{r``t|6h_;q*d_$YunT1|9=?q z|4W|#zvB7-tHIUqI-!00QZ$?k^#A`#-{v5F_Wb|ku>bFb{y%cKWaIJz=7r{IL>v?d z7ss*nSm9z+wjO8(j-g?FfV>C7MN~cHqCt#sF{-9`To5i7E-<@;Wh3HAEEJZn;RODF z^bHq#Si>R8rjZHz?oD*+`TwYSdd-F&G|+4^Q8{&3vxxvsU(cBEyCkUT`~Sb3LbU{q zsg@x2E(w*T*t;Zjh5G+=1Qbw9f_pa<00BS%5C8-K0YG2^2r&OYo_s3BUT+5 zRVd<*E;7f(kgR=l+L3byI9y=<|DUOvb4dOF!=EAOL|G^Hv>0F3;j<%#kF}#}QjGsU>hFEeyX0Y|~c$p8QV literal 28672 zcmeI4&u<$=6vua+Y}2?6$Omp9ZPMmPTi4wm{w)qTw%fRIoYZ!r=76H{?l`sL*ug(S zS|Jn(kPs3F#I1)4A%w(@6XIA24#1(RI2Cb0{R`j(7X-6Av+M2Jp>9lEgPsrG-PzsQ zx8Io^`}5|#U5YFIQnjw_#8tX1RPNxoEJ>1IyVb7k#A9W@*1)KR^|&085ei{78d3e_ zdSe&0;024p~PyiGF1wa8%02BZPKmkwy6aWQ4fs<8$P4eq32te^yagEIC z@1nhU$XFc2LnX;y!w0Q+*uRIiaWfwDH|q6PT!{oplz=3KbV>EMD!U|VK+$omggPMs zx;V(kh#q*v{dB|2DQYkjjtHlPNx>_e;e6vW%c**MyNa5^*B^PVT}>|f#?NKeDsQy0 z@bLEuT5x_jk9I1piYEN={WvX}%`Uc^z^Y%Z5VwThUi?qf&ke5QbEct^PZ z?ZnE}q_|PnYn2_}_`-6gR>92{5`O)7lGb_QdZCRP_>OS@?pa!LF|&f3&5CgN@I_j1 z>3R;|-bD@TBywNV{C6DBbKLxE9EbCC`P+lZ7X%`FAk1+dWh~B3a;MGa3B-`KQnFSw z^GMnJR?KhJ{0^Gmp;JaZA^AO?wJ)-RJZSq?EBknbG_D+#{Kop4*|MzNC9~Zln6-P5 zwR@PgdpK&gyDmlTb}y+hP4l;F?WPeX;_e3M9m|XoGb6~lnPrC42;=Ic^HC%0&KGiZ zzOdHa`BWq;M;cMuXHsa)hLFn!mGtwD6sq$Pu%)mb0ZWRAX@umILRS%rbshojr5YlS zMtu+0iVak2BCSQDWtwNr(soU+XY1Q^qlHRU9FWeKd#d%)3fi;R^SJzqSxyg9SxC-? z6?;?SI9~8Iuob!b@irCUmGA zGdAeJLkcx}j~0=XlN~9cc2EEm00lq+PyiGF1wa8%U~mPx_}h-B*E{j_vaae{SjU6V zbnkP$?D}OFADRfJJjwqS2ipAKg9@jn%s@jo4S82{5f z!2g5)7C{Z504M+ofC8WZC;$q80w=FP7k}IQ@5rZ@%ORvivD_y(Kf_^+|B>XHm^Jy| zm;*hC9|=G7kGFI3lYn1Y?Z6L`p23ptLka)$_xMl81Wr~2NstAF%=}M_b2kg=qL|F5 z6UFq_;(8{V66KggVgkgODTNk`>xFb)%v=?7t3@$=GgBxQ#F-hfkjNIr`FU|EQCKpT ziPTCaM5Q_c50j4C9$r@9grJNiOJPmp_oq) zORNeyC8S=*g%?Pb^5Ll)IsB%$ zS#Ru!$x7??zZj=6H+FYI;C!BG+2@&2e4cZHt$kr_Bj@D;->>JaYvp@2e(sNmMIN6DwUb$WWZ26yX_7oD)TqgZcGc`~rZ z8B4+!!F4VIt) zC;$q80-yjWa1sj8zmX39w*J|YBKv)Mv2s`<@6!u*GxDG%*8IPFe%R#y4!T9rh-_Z~MchWkd%xxES#WM7Q-eB2u=S8iwj+iT!A>5tI z5X3=McVtwU2^RL#9ks(cV$2LHd+6w}4rYX%)}gx7I=XX;NN!0)KGKMo71lA73>W*} zk;VT*$Y`-IS{e%fo4F(tAB-UXpGYnV?e&mLVh?7p0t$cvpa3WU3V;G9tpJ-w>hQPy zZ%^y+zpMo#S_ls|o!*nhE&g{0MLXjEkDUMSBlx-JHTx~3{Qt}IiT@uW|G!Q7|FRGe zt^og!8vlRh;{VGA{|5~IzhaLK(_?>9{y${=f7mtuzvAHk4((g~--!t5hyOci9YcX$ zE2HAS`C5lwt`PQS6MJMk#%moc{vSd{i~WnB4~75DT#||RN09$dB$tHF`9m&=J($4? oC;$q80-yjW01BM60*wDV{B8f+!w&w(;h+}5YQN;%|8d^G0T_0cz5oCK 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 index a52b256..5606fc3 100644 --- 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 @@ -15,17 +15,17 @@ 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 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 { 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 index 5b7bab7..218f8f4 100644 --- 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 @@ -1,7 +1,6 @@ package ru.mipt.diht.students.simon23rus.CQL.impl; -import java.util.ArrayList; -import java.util.List; +import java.util.*; import java.util.function.BiPredicate; import java.util.function.Function; import java.util.stream.Collectors; @@ -53,11 +52,11 @@ public JoinClause join(Iterable iterable) { public class JoinClause { - private List firstElements = new ArrayList<>(); + private List firstElements = new ArrayList<>(); private List secondElements = new ArrayList<>(); - private List> joinedElements = new ArrayList<>(); + private List> joinedElements = new ArrayList<>(); - public JoinClause(List firstElements, Iterable secondElements) { + public JoinClause(List firstElements, Iterable secondElements) { this.firstElements .addAll(firstElements.stream() .collect(Collectors.toList())); @@ -66,7 +65,7 @@ public JoinClause(List firstElements, Iterable secondElements) { } } - public FromStmt> on(BiPredicate condition) { + public FromStmt> on(BiPredicate condition) { firstElements.forEach(first -> secondElements.forEach(second -> { if (condition.test(first, second)) { @@ -76,10 +75,17 @@ public FromStmt> on(BiPredicate condition) { return new FromStmt<>(joinedElements); } - public > FromStmt> on( - Function leftKey, + public > FromStmt> on( + Function leftKey, Function rightKey) { - throw new UnsupportedOperationException(); + 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/Tuple.java b/projects/simon23rus/src/main/java/ru/mipt/diht/students/simon23rus/CQL/impl/Tuple.java index 2f0ffab..dbc54a3 100644 --- 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 @@ -23,6 +23,6 @@ public String toString() { return "Tuple{" + "first=" + first + ", second=" + second - + "}\n"; + + "}"; } } 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 index b3eaf93..22ff33b 100644 --- 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 @@ -4,6 +4,8 @@ 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; @@ -38,28 +40,52 @@ void printQueue() { //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 { - insertLocker.lock(); - for(int i = 0; i < toAdd.size(); ++i) { + long currentTime = System.currentTimeMillis(); + if (footLocker.tryLock(timeout, TimeUnit.MILLISECONDS)) { try { - footLocker.lock(); - while (myBlockingQueue.size() == elementsBound) { - nonFull.await(); + while (myBlockingQueue.size() + toAdd.size() > elementsBound) { + timeout -= System.currentTimeMillis() - currentTime; + currentTime = System.currentTimeMillis(); + if (nonFull.await(timeout, TimeUnit.MILLISECONDS) == false) { + throw new TimeoutException(); + } } - myBlockingQueue.add(toAdd.get(i)); - nonEmpty.signalAll(); - } catch (InterruptedException e) { - + 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"); } - finally { - insertLocker.unlock(); - } - } + return; + } //vzyat iz nachala List take(int numberOfElements) { @@ -73,7 +99,7 @@ List take(int numberOfElements) { nonEmpty.await(); } takenElements.add(myBlockingQueue.poll()); - nonFull.signalAll(); + nonFull.signal(); } catch (InterruptedException e) { } finally { @@ -86,4 +112,40 @@ List take(int numberOfElements) { 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 index d6df977..7a7bcbc 100644 --- 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 @@ -7,7 +7,7 @@ * Created by semenfedotov on 13.12.15. */ public class BlockingQueueRunner { - public static void main(String[] args) { + 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); 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 index 83397b9..c7879b3 100644 --- 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 @@ -36,8 +36,7 @@ public static GeoLocation getCoordinates(String place) throws IOException, Inter JSONException { //if (place != "Moscow") System.out.println(place); if (place.equals("nearby")) { -// place = webSource(); - place = "Долгопрудный"; + place = webSource(); } URL getTheLL = new URL("https://maps.googleapis.com/maps/api/geocode/json?address=" + place + "&apikey=" + "AIzaSyCSLjuyawVt4lZAlb8t0EwuxKQWvRCaqsY"); @@ -56,10 +55,9 @@ public static GeoLocation getCoordinates(String place) throws IOException, Inter System.out.println(parseDouble(location.getString("lng"))); return new GeoLocation(parseDouble(location.getString("lat")), parseDouble(location.getString("lng"))); } else { - System.out.println("bu"); + return new GeoLocation((double) -5, (double) -5); } } - return new GeoLocation((double) 0, (double) 0); } @@ -77,7 +75,6 @@ public static boolean near(GeoLocation first, GeoLocation second, double radius) 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; - //System.out.println(distance); return distance < radius; } } 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 index 60e9b78..af13f96 100644 --- 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 @@ -104,23 +104,7 @@ public static boolean isItYesterdayTweet(Date tweetDate) { isItYesterday = false; return false; } -// System.out.println(result + "STOL'KO"); -// -// String currentHour = new SimpleDateFormat("HH").format(currentDate1); -// String currentMinute = new SimpleDateFormat("mm").format(currentDate1); -// String currentSecond = new SimpleDateFormat("ss").format(currentDate1); -// -// int todaySeconds = Integer.valueOf(currentSecond) + Integer.valueOf(currentMinute) * SECONDS_IN_MINUTE + Integer.valueOf(currentHour) * SECONDS_IN_HOUR; -// System.out.println(todaySeconds); -// if(delta < SECONDS_IN_DAY + todaySeconds && delta > todaySeconds) { -// 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 index 3212358..ef511f1 100644 --- 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 @@ -25,7 +25,8 @@ public static String printStringWithFormat(Date currentTime, Status tweet, boole tweetToShow += ":" + (char)27 + "[33;4m" + " ретвитнул "; tweetToShow += (char)27 + "[31;1m@" + tweet.getRetweetedStatus().getUser().getScreenName(); tweetToShow += (char)27 + "[0m" + ":"; - tweetToShow += tweet.getText().substring(5 + tweet.getRetweetedStatus().getUser().getScreenName().length()); + tweetToShow += tweet.getText(); +// tweetToShow += tweet.getText().substring(5 + tweet.getRetweetedStatus().getUser().getScreenName().length()); } else { tweetToShow += (char)27 + "[0m" + ":" + tweet.getText(); 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 index d104b7c..2351cbe 100644 --- 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 @@ -84,6 +84,8 @@ public static void main(String[] args) throws TwitterException, IOException, Int 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; @@ -96,17 +98,16 @@ public static void main(String[] args) throws TwitterException, IOException, Int tweetLocation = new GeoLocation(tweet.getGeoLocation().getLatitude(), tweet.getGeoLocation().getLongitude()); } else { - tweetLocation = myOwnConverter.getCoordinates("nearby"); + continue; } if(queryLocation == null) { - System.out.println("bububuqueryloc"); + 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); -// System.out.println(tweet.getPlace()); ++counter; if (counter == jct.tweetsByQuery) { return; 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 index 6c79edc..a93701b 100644 --- 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 @@ -7,12 +7,16 @@ 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 { @@ -39,7 +43,7 @@ public void setUp() throws Exception { @Test public void testFrom() throws Exception { - FromStmt fromStmt = FromStmt.from(toTest); + 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)); @@ -48,8 +52,8 @@ public void testFrom() throws Exception { @Test public void testSelect() throws Exception { - SelectStmt select = FromStmt - .from(toTest) + SelectStmt select = + from(toTest) .select(CollectionQuery.Student.class, CollectionQuery.Student::age); assertEquals(-1, select.getMaxRawsNeeded()); assertEquals(CollectionQuery.Student.class, select.getToReturn()); @@ -68,9 +72,25 @@ public void testSelect() throws Exception { } } + @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 = FromStmt.from(toTest) + SelectStmt select = from(toTest) .selectDistinct(CollectionQuery.Student.class, CollectionQuery.Student::getName, CollectionQuery.Student::getGroup); assertEquals(-1,select.getMaxRawsNeeded()); 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 index 6715135..8c9c74a 100644 --- 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 @@ -177,15 +177,17 @@ public void queryAllTest() throws SQLException, ClassNotFoundException, IllegalA Statement selectZvezdochka = myFourthConnection.createStatement(); System.out.println("We R Here"); ResultSet selectResult = selectZvezdochka.executeQuery("SELECT * FROM player"); + List answer = new ArrayList<>(); - while (selectResult.next()) { - answer.add((new Player( - selectResult.getString(1), - selectResult.getString(2), - selectResult.getString(3), - selectResult.getString(4)) - )); - } + 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")); 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 index c26332f..73b8f75 100644 --- 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 @@ -98,4 +98,85 @@ public void hardUsageTest() throws InterruptedException { 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 index d12b542..b198182 100644 --- 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 @@ -25,6 +25,7 @@ public void getCoordinatesTest() throws InterruptedException, JSONException, IOE 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}); @@ -39,6 +40,7 @@ public void getCoordinatesTest() throws InterruptedException, JSONException, IOE 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 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 index ef5c3b0..efb89d1 100644 --- 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 @@ -47,15 +47,26 @@ public void makeBlueTest() { 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)); }