Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Максим Гришкин, 494, ModuleTests #197

Open
wants to merge 11 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,4 @@ workbench.xmi
.settings
.checkstyle
twitter4j.properties
riskingh/twitter4j.properties
7 changes: 4 additions & 3 deletions pom.xml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>ru.fizteh.fivt.students</groupId>
Expand All @@ -19,7 +19,7 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<modules>
<modules>
<module>egiby</module>
<module>akormushin</module>
<!--Add you module here-->
Expand All @@ -46,6 +46,7 @@
<module>ladyae</module>
<module>nikitarykov</module>
<module>duha666</module>
<module>riskingh</module>
</modules>

<dependencies>
Expand Down
45 changes: 45 additions & 0 deletions riskingh/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>ru.fizteh.fivt.students</groupId>
<artifactId>parent</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>ru.fizteh.fivt.students</groupId>
<artifactId>riskingh</artifactId>
<version>1.0-SNAPSHOT</version>
<name>riskingh</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.twitter4j</groupId>
<artifactId>twitter4j-core</artifactId>
<version>[4.0,)</version>
</dependency>
<dependency>
<groupId>org.twitter4j</groupId>
<artifactId>twitter4j-stream</artifactId>
<version>4.0.4</version>
</dependency>
<dependency>
<groupId>com.beust</groupId>
<artifactId>jcommander</artifactId>
<version>1.48</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20151123</version>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package ru.fizteh.fivt.students.riskingh.TwitterStream;

/**
* Created by max on 18/12/15.
*/

import twitter4j.*;

import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Properties;

public class GeoUtils {
public static GeoLocation getLocationByPlace(String placeString) throws IOException,
URISyntaxException, org.json.JSONException {
Properties properties = new Properties();
try (InputStream inputStream = GeoLocation.class.getResourceAsStream("/googleMaps.properties")) {
properties.load(inputStream);
}
String googleMapsKey = properties.getProperty("google");
String urlString = "https://maps.googleapis.com/maps/api/geocode/json?key="
+ googleMapsKey + "&address=" + URLEncoder.encode(placeString, "UTF-8");
URL url = new URL(urlString);
org.json.JSONObject jsonObject = JSONReader.readJSONFromUrl(url.toString());
jsonObject = jsonObject.getJSONArray("results").getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location");
return new GeoLocation(jsonObject.getDouble("lat"), jsonObject.getDouble("lng"));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package ru.fizteh.fivt.students.riskingh.TwitterStream;

/**
* Created by max on 18/12/15.
*/

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;

import org.json.JSONException;
import org.json.JSONObject;

public class JSONReader {

private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}

public static JSONObject readJSONFromUrl(String url) throws IOException, JSONException {
try (InputStream is = new URL(url).openStream()) {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
return new JSONObject(jsonText);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package ru.fizteh.fivt.students.riskingh.TwitterStream;

/**
* Created by max on 18/12/15.
*/
import com.beust.jcommander.*;

public class Settings {

private static final int DEFAULT_TWEET_LIMIT = 10;

@Parameter(names = {"-q", "--query"}, description = "Query or keywords for stream")
private String query = "";

@Parameter(names = {"-p", "--place"}, description = "Location")
private String place = "nearby";

@Parameter(names = {"-s", "--stream"}, description = "Stream")
private boolean stream = false;

@Parameter(names = {"--hideRetweets"}, description = "Hide retweets")
private boolean hideRetweets = false;

@Parameter(names = {"-l", "--limit"}, description = "Tweets limit")
private Integer limit = DEFAULT_TWEET_LIMIT;

@Parameter(names = {"-h", "--help"}, description = "Show this help")
private boolean printHelp = false;

public String getQuery() {
return query;
}

public String getPlace() {
return place;
}

public boolean stream() {
return stream;
}

public boolean hideRetweets() {
return hideRetweets;
}

public Integer getLimitNumber() {
return limit;
}

public boolean printHelp() {
return printHelp;
}
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package ru.fizteh.fivt.students.riskingh.TwitterStream;

/**
* Created by max on 18/12/15.
*/

import twitter4j.*;
import twitter4j.TwitterStream;

import java.util.List;

public class StatusPrinter {
public static final int SEARCH_DISTANCE_IN_KM = 5;
public static final int MILLISECONDS_IN_SECOND = 1000;

public static void printStatus(Status status) {
System.out.print("[" + TimeUtils.formatTime(status.getCreatedAt()) + "]");
System.out.print("@" + status.getUser().getScreenName() + ": ");
if (status.isRetweet()) {
System.out.print("ретвитнул ");
System.out.print(status.getRetweetedStatus().getUser().getScreenName() + ":");
System.out.print(status.getRetweetedStatus().getText());
} else {
System.out.print(status.getText());
int retweetsCount = status.getRetweetCount();
if (retweetsCount > 0) {
System.out.print("(" + retweetsCount + " ретвитов)");
}
}
System.out.println();
}

public static void print(Settings settings, GeoLocation location) throws TwitterException {
Twitter twitter = new TwitterFactory().getInstance();
Query query = new Query(settings.getQuery()).geoCode(location, SEARCH_DISTANCE_IN_KM, "km");
query.setCount(settings.getLimitNumber());
QueryResult queryResult = twitter.search(query);
List<Status> statuses = queryResult.getTweets();
statuses.stream().
filter(status -> !settings.hideRetweets() || !status.isRetweet()).
forEach(ru.fizteh.fivt.students.riskingh.TwitterStream.StatusPrinter::printStatus);
}

public static void stream(Settings settings, GeoLocation location) throws TwitterException {
TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
twitterStream.addListener(new StatusAdapter() {
@Override
public void onStatus(Status status) {
if (settings.hideRetweets() && status.isRetweet()) {
return;
}
printStatus(status);
try {
Thread.sleep(MILLISECONDS_IN_SECOND);
} catch (Exception e) {
System.err.print("ERROR!");
}
}
});
FilterQuery filterQuery = new FilterQuery();
double[][] locations = {
{location.getLongitude() - SEARCH_DISTANCE_IN_KM, location.getLatitude() - SEARCH_DISTANCE_IN_KM},
{location.getLongitude() + SEARCH_DISTANCE_IN_KM, location.getLatitude() + SEARCH_DISTANCE_IN_KM}
};
filterQuery.track(settings.getQuery()).locations(locations);
twitterStream.filter(filterQuery);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package ru.fizteh.fivt.students.riskingh.TwitterStream;

/**
* Created by max on 18/12/15.
*/

import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class TimeUtils {
public static String formatTime(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);

Calendar today = Calendar.getInstance();

Calendar yesterday = Calendar.getInstance();
yesterday.add(Calendar.DAY_OF_YEAR, -1);

Date current = new Date();
long difference = current.getTime() - date.getTime();

long differenceInMinutes = TimeUnit.MILLISECONDS.toMinutes(difference);
long differenceInHours = TimeUnit.MILLISECONDS.toHours(difference);
long differenceInDays = TimeUnit.MILLISECONDS.toDays(difference);

if (differenceInMinutes < 2) {
return "только что";
} else if (differenceInHours < 1) {
return Long.toString(differenceInMinutes) + " минут назад";
} else if (calendar.get(Calendar.YEAR) == today.get(Calendar.YEAR)
&& calendar.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) {
return Long.toString(differenceInHours) + " часов назад";
} else if (calendar.get(Calendar.YEAR) == yesterday.get(Calendar.YEAR)
&& calendar.get(Calendar.DAY_OF_YEAR) == yesterday.get(Calendar.DAY_OF_YEAR)) {
return "вчера";
} else {
return Long.toString(differenceInDays) + " дней назад";
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package ru.fizteh.fivt.students.riskingh.TwitterStream;

/**
* Created by max on 18/12/15.
*/

import com.beust.jcommander.JCommander;
import twitter4j.GeoLocation;
import twitter4j.TwitterException;

public class TwitterStream {
public static void main(String[] args) throws TwitterException {
Settings settings = new Settings();
try {
JCommander jcommander = new JCommander(settings, args);
if (settings.printHelp()) {
jcommander.usage();
return;
}
} catch (Exception e) {
JCommander jcommander = new JCommander(settings);
jcommander.usage();
return;
}

System.out.print("Твиты по запросу " + settings.getQuery() + " для " + settings.getPlace() + ":");
System.out.println();
try {
GeoLocation location = GeoUtils.getLocationByPlace(settings.getPlace());
if (settings.stream()) {
StatusPrinter.stream(settings, location);
} else {
StatusPrinter.print(settings, location);
}
} catch (Exception e) {
System.err.print("ERROR: " + e.toString());
e.printStackTrace();
}
}
}
1 change: 1 addition & 0 deletions riskingh/src/main/resources/googleMaps.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
google=AIzaSyDaqLm20LUsl5pwFWF92UZnHxTKL9OSqUg
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package ru.fizteh.fivt.students.riskingh.TwitterStream;

import org.junit.Assert;
import org.junit.Test;
import twitter4j.GeoLocation;

import static ru.fizteh.fivt.students.riskingh.TwitterStream.GeoUtils.getLocationByPlace;

/**
* Created by max on 19/12/15.
*/

public class GeoUtilsTest {
@Test
public void testGetLocationByPlace() throws Exception {
String city1 = "Moscow, Russia";
String city2 = "Kostroma, Russia";

GeoLocation geo1 = getLocationByPlace(city1);
GeoLocation geo2 = getLocationByPlace(city2);

Assert.assertEquals(geo1.getLatitude(), 55.755826, 1E-3);
Assert.assertEquals(geo1.getLongitude(), 37.6173, 1E-3);

Assert.assertEquals(geo2.getLatitude(), 57.77748, 1E-3);
Assert.assertEquals(geo2.getLongitude(), 40.96989, 1E-3);
}
}
Loading