Added maven facet

This commit is contained in:
Klemek
2019-06-09 17:27:00 +02:00
parent 458cc56f0c
commit c034fadddf
8 changed files with 657 additions and 554 deletions
Binary file not shown.
+106
View File
@@ -0,0 +1,106 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
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>com.github.klemek</groupId>
<artifactId>primedate</artifactId>
<version>1.0</version>
<name>PrimeDate</name>
<packaging>jar</packaging>
<prerequisites>
<maven>3.0.0</maven>
</prerequisites>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.twitter4j</groupId>
<artifactId>twitter4j-core</artifactId>
<version>4.0.7</version>
</dependency>
<!-- Test Dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<outputDirectory>${project.build.directory}/classes</outputDirectory>
<sourceDirectory>src/main/java</sourceDirectory>
<testSourceDirectory>src/test/java</testSourceDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/resources</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</testResource>
</testResources>
<plugins>
<!-- Compilation -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>unpack-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/classes</outputDirectory>
<includeScope>runtime</includeScope>
</configuration>
</execution>
</executions>
</plugin>
<!-- JAR -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<archive>
<manifest>
<mainClass>fr.klemek.englishparser.Launch</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<!-- Unit tests -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.0</version>
</plugin>
</plugins>
</build>
</project>
-3
View File
@@ -1,3 +0,0 @@
Manifest-Version: 1.0
Main-Class: fr.klemek.primedate.MainProcess
@@ -1,157 +1,157 @@
package fr.klemek.primedate; package fr.klemek.primedate;
import java.text.NumberFormat; import java.text.NumberFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Calendar; import java.util.Calendar;
import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.ThreadLocalRandom;
import java.util.Locale; import java.util.Locale;
import java.util.Timer; import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
/** /**
* Main process to be launched * Main process to be launched
* *
* @author Kleme * @author Kleme
*/ */
public abstract class MainProcess { public abstract class MainProcess {
private final static String VERSION = "v1.5"; private final static String VERSION = "v1.5";
private final static SimpleDateFormat DATE_TO_NUM = new SimpleDateFormat("yyyyMMddHHmm"); private final static SimpleDateFormat DATE_TO_NUM = new SimpleDateFormat("yyyyMMddHHmm");
private final static String[] GREETINGS_SENTENCES = new String[] { "Hi", "Hello there", "Good %s", "What's up?", private final static String[] GREETINGS_SENTENCES = new String[] { "Hi", "Hello there", "Good %s", "What's up?",
"Greetings", "How are you?", "Hey", "How are you doing?", "How's life?", "Long time no see", "Greetings", "How are you?", "Hey", "How are you doing?", "How's life?", "Long time no see",
"It's been a while", "How do you do?", "Yo", "Howdy", "Sup?", "Whazzup?", "Yoooooo", "Bonjour", "Hola", "It's been a while", "How do you do?", "Yo", "Howdy", "Sup?", "Whazzup?", "Yoooooo", "Bonjour", "Hola",
"Hallo", "Salam", "Aloha", "Hey", "Heyy", "Heyy", "Heyyy", "Heyyyy", "Heyyyyy" }; "Hallo", "Salam", "Aloha", "Hey", "Heyy", "Heyy", "Heyyy", "Heyyyy", "Heyyyyy" };
private final static String[] DATE_SENTENCES = new String[] { "The date is %1$s and it's %2$s", private final static String[] DATE_SENTENCES = new String[] { "The date is %1$s and it's %2$s",
"We are %1$s and it's already %2$s", "It's already %2$s today", "Today is %1$s and it's %2$s", "We are %1$s and it's already %2$s", "It's already %2$s today", "Today is %1$s and it's %2$s",
"It's %2$s and today's %1$s", "It's %2$s on %1$s", "Already %2$s on %1$s" }; "It's %2$s and today's %1$s", "It's %2$s on %1$s", "Already %2$s on %1$s" };
private final static String[] PRIME_SENTENCES = new String[] { "%s is a prime number", private final static String[] PRIME_SENTENCES = new String[] { "%s is a prime number",
"%s cannot be divided by another number", "nobody can divide %s", "%s is prime", "%s is prime as fuck", "%s cannot be divided by another number", "nobody can divide %s", "%s is prime", "%s is prime as fuck",
"%s is prime as hell", "%s is prime as shit", "%s sure is prime", "%s is pretty prime", "%s is prime as hell", "%s is prime as shit", "%s sure is prime", "%s is pretty prime",
"you can trust %s to be prime", "%s is like other primes" }; "you can trust %s to be prime", "%s is like other primes" };
private final static String[] END_SENTENCES = new String[] { "", "Pretty cool, huh?", "It blows your mind!", private final static String[] END_SENTENCES = new String[] { "", "Pretty cool, huh?", "It blows your mind!",
"You can forget it now.", "You wasted 20 seconds of your time.", "That's cool!", "Isn't it cool?", "You can forget it now.", "You wasted 20 seconds of your time.", "That's cool!", "Isn't it cool?",
"You should stop reading these tweets...", "That's a good password.", "Maybe not.", "Why ? ...", "You should stop reading these tweets...", "That's a good password.", "Maybe not.", "Why ? ...",
"Pls help stuck in prime factory", "Why do you read these ?", "Can someone check ?", "Really ?", "Cool.", "Pls help stuck in prime factory", "Why do you read these ?", "Can someone check ?", "Really ?", "Cool.",
"You can use it.", "Google it.", "How do I stop this?", "Send STOP to not receive this anymore.", "Yes.", "You can use it.", "Google it.", "How do I stop this?", "Send STOP to not receive this anymore.", "Yes.",
"It's true.", "Move on.", "That's no FAKE news!", "Soooo hard to calculate by hand!", "It is also my IQ.", "It's true.", "Move on.", "That's no FAKE news!", "Soooo hard to calculate by hand!", "It is also my IQ.",
"Add 1 and it doesn't work anymore.", "I'm a bot, I know that stuff.", "Awesome!", "Add 1 and it doesn't work anymore.", "I'm a bot, I know that stuff.", "Awesome!",
"Next one should be better!", "Let's calculate its factorial now...", "There's a phone number in it.", "Next one should be better!", "Let's calculate its factorial now...", "There's a phone number in it.",
"Don't do this at home, kids.", "Highest one so far!", "Next one will blow your mind!", "Don't do this at home, kids.", "Highest one so far!", "Next one will blow your mind!",
"That's the exact number of bacteria in your body.", "Don't believe me? Fine.", "That's the exact number of bacteria in your body.", "Don't believe me? Fine.",
"Funniest thing of the day.", "See you next time!", "Bye!", "See ya!", "See you later!" }; "Funniest thing of the day.", "See you next time!", "Bye!", "See ya!", "See you later!" };
private final static char[] SENTENCE_ENDS = new char[] { '.', '!', ',' }; private final static char[] SENTENCE_ENDS = new char[] { '.', '!', ',' };
private static void checkTime(Calendar currentTime, boolean fake) { private static void checkTime(Calendar currentTime, boolean fake) {
try { try {
long currentTimeValue = Long.parseLong(DATE_TO_NUM.format(currentTime.getTime())); long currentTimeValue = Long.parseLong(DATE_TO_NUM.format(currentTime.getTime()));
if (PrimeCalculator.isPrime(currentTimeValue)) { if (PrimeCalculator.isPrime(currentTimeValue)) {
String msg; String msg;
do { do {
msg = constructSentence(currentTime, currentTimeValue); msg = constructSentence(currentTime, currentTimeValue);
} while (msg.length() > 280); } while (msg.length() > 280);
if (fake) if (fake)
System.out.println(msg); System.out.println(msg);
else else
TwitterClient.tweet(msg); TwitterClient.tweet(msg);
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
private static String constructSentence(Calendar time, long timeValue) { private static String constructSentence(Calendar time, long timeValue) {
final int hour = time.get(Calendar.HOUR_OF_DAY); final int hour = time.get(Calendar.HOUR_OF_DAY);
final String dayPeriod = hour >= 5 && hour <= 12 ? "morning" : (hour <= 18 ? "afternoon" : "evening"); final String dayPeriod = hour >= 5 && hour <= 12 ? "morning" : (hour <= 18 ? "afternoon" : "evening");
final PrettyDate time2 = new PrettyDate(time); final PrettyDate time2 = new PrettyDate(time);
final int r1 = ThreadLocalRandom.current().nextInt(0, GREETINGS_SENTENCES.length); final int r1 = ThreadLocalRandom.current().nextInt(0, GREETINGS_SENTENCES.length);
final int r2 = ThreadLocalRandom.current().nextInt(0, SENTENCE_ENDS.length); final int r2 = ThreadLocalRandom.current().nextInt(0, SENTENCE_ENDS.length);
final int r3 = ThreadLocalRandom.current().nextInt(0, DATE_SENTENCES.length); final int r3 = ThreadLocalRandom.current().nextInt(0, DATE_SENTENCES.length);
final int r4 = ThreadLocalRandom.current().nextInt(0, SENTENCE_ENDS.length); final int r4 = ThreadLocalRandom.current().nextInt(0, SENTENCE_ENDS.length);
final int r5 = ThreadLocalRandom.current().nextInt(0, PRIME_SENTENCES.length); final int r5 = ThreadLocalRandom.current().nextInt(0, PRIME_SENTENCES.length);
final int r6 = ThreadLocalRandom.current().nextInt(0, SENTENCE_ENDS.length); final int r6 = ThreadLocalRandom.current().nextInt(0, SENTENCE_ENDS.length);
final int r7 = ThreadLocalRandom.current().nextInt(0, END_SENTENCES.length); final int r7 = ThreadLocalRandom.current().nextInt(0, END_SENTENCES.length);
// GREETINGS // GREETINGS
String greetings = String.format(GREETINGS_SENTENCES[r1], dayPeriod); String greetings = String.format(GREETINGS_SENTENCES[r1], dayPeriod);
if (!greetings.endsWith("?")) if (!greetings.endsWith("?"))
greetings += SENTENCE_ENDS[r2]; greetings += SENTENCE_ENDS[r2];
// DATE // DATE
String date = String.format(DATE_SENTENCES[r3], time2.getPrettyDate(), time2.getPrettyTime()); String date = String.format(DATE_SENTENCES[r3], time2.getPrettyDate(), time2.getPrettyTime());
if (greetings.endsWith(",")) if (greetings.endsWith(","))
date = date.substring(0, 1).toLowerCase() + date.substring(1); date = date.substring(0, 1).toLowerCase() + date.substring(1);
date += SENTENCE_ENDS[r4]; date += SENTENCE_ENDS[r4];
if (date.endsWith(",")) if (date.endsWith(","))
date = date.substring(0, date.length() - 1) + " and"; date = date.substring(0, date.length() - 1) + " and";
// PRIME // PRIME
String prime = String.format(PRIME_SENTENCES[r5], NumberFormat.getNumberInstance().format(timeValue)); String prime = String.format(PRIME_SENTENCES[r5], NumberFormat.getNumberInstance().format(timeValue));
if (date.endsWith("d")) if (date.endsWith("d"))
prime = prime.substring(0, 1).toLowerCase() + prime.substring(1); prime = prime.substring(0, 1).toLowerCase() + prime.substring(1);
if (END_SENTENCES[r7].length() == 0 && SENTENCE_ENDS[r6] == ',') if (END_SENTENCES[r7].length() == 0 && SENTENCE_ENDS[r6] == ',')
prime += "."; prime += ".";
else else
prime += SENTENCE_ENDS[r6]; prime += SENTENCE_ENDS[r6];
// END // END
String end = END_SENTENCES[r7]; String end = END_SENTENCES[r7];
if (prime.endsWith(",")) if (prime.endsWith(","))
end = end.substring(0, 1).toLowerCase() + end.substring(1); end = end.substring(0, 1).toLowerCase() + end.substring(1);
return greetings + " " + date + " " + prime + " " + end; return greetings + " " + date + " " + prime + " " + end;
} }
public static void main(String[] args) { public static void main(String[] args) {
Locale.setDefault(Locale.ENGLISH); Locale.setDefault(Locale.ENGLISH);
final int max_random = GREETINGS_SENTENCES.length * DATE_SENTENCES.length * PRIME_SENTENCES.length final int max_random = GREETINGS_SENTENCES.length * DATE_SENTENCES.length * PRIME_SENTENCES.length
* END_SENTENCES.length; * END_SENTENCES.length;
System.out.println(String.format("PrimeDate %s%n%s%n%s+ sentences available randomly", VERSION, System.out.println(String.format("PrimeDate %s%n%s%n%s+ sentences available randomly", VERSION,
Calendar.getInstance().getTime(), NumberFormat.getInstance().format(max_random))); Calendar.getInstance().getTime(), NumberFormat.getInstance().format(max_random)));
if (args.length < 1) { if (args.length < 1) {
System.out.println("Argument 1 must be a file containing customer keys"); System.out.println("Argument 1 must be a file containing customer keys");
System.exit(0); System.exit(0);
} }
if (TwitterClient.setUpTwitter(args[0])) { if (TwitterClient.setUpTwitter(args[0])) {
PrimeCalculator.computeList(); PrimeCalculator.computeList();
Timer timer = new Timer(); Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() { timer.scheduleAtFixedRate(new TimerTask() {
@Override @Override
public void run() { public void run() {
Calendar currentTime = Calendar.getInstance(); Calendar currentTime = Calendar.getInstance();
currentTime.add(Calendar.MILLISECOND, currentTime.add(Calendar.MILLISECOND,
-currentTime.getTimeZone().getOffset(currentTime.getTimeInMillis())); -currentTime.getTimeZone().getOffset(currentTime.getTimeInMillis()));
checkTime(currentTime, false); checkTime(currentTime, false);
} }
}, 0, 1 * 60 * 1000); }, 0, 1 * 60 * 1000);
/* /*
* Calendar time = Calendar.getInstance(); while (true) { checkTime(time, true); * Calendar time = Calendar.getInstance(); while (true) { checkTime(time, true);
* time.add(Calendar.MINUTE, 1); } * time.add(Calendar.MINUTE, 1); }
*/ */
} }
} }
} }
@@ -1,42 +1,42 @@
package fr.klemek.primedate; package fr.klemek.primedate;
import java.util.Calendar; import java.util.Calendar;
public class PrettyDate { public class PrettyDate {
private Calendar cal; private Calendar cal;
public PrettyDate() { public PrettyDate() {
cal = Calendar.getInstance(); cal = Calendar.getInstance();
} }
public PrettyDate(Calendar cal) { public PrettyDate(Calendar cal) {
this.cal = cal; this.cal = cal;
} }
private String getPrettyDayOfMonth() { private String getPrettyDayOfMonth() {
final int n = cal.get(Calendar.DAY_OF_MONTH); final int n = cal.get(Calendar.DAY_OF_MONTH);
if (n >= 11 && n <= 13) { if (n >= 11 && n <= 13) {
return n+"th"; return n+"th";
} }
switch (n % 10) { switch (n % 10) {
case 1: case 1:
return n + "st"; return n + "st";
case 2: case 2:
return n + "nd"; return n + "nd";
case 3: case 3:
return n + "rd"; return n + "rd";
default: default:
return n + "th"; return n + "th";
} }
} }
public String getPrettyDate() { public String getPrettyDate() {
return String.format("%1$tB the %2$s, %1$tY", cal.getTime(), getPrettyDayOfMonth()); return String.format("%1$tB the %2$s, %1$tY", cal.getTime(), getPrettyDayOfMonth());
} }
public String getPrettyTime() { public String getPrettyTime() {
return String.format("%1$tH:%1$tM GMT", cal.getTime()); return String.format("%1$tH:%1$tM GMT", cal.getTime());
} }
} }
@@ -1,129 +1,129 @@
package fr.klemek.primedate; package fr.klemek.primedate;
import java.util.Arrays; import java.util.Arrays;
/** /**
* Calculate and check prime numbers * Calculate and check prime numbers
* *
* @author Kleme * @author Kleme
*/ */
public abstract class PrimeCalculator { public abstract class PrimeCalculator {
// http://compoasso.free.fr/primelistweb/page/prime/eratosthene_en.php // http://compoasso.free.fr/primelistweb/page/prime/eratosthene_en.php
private static final long MAX = 1000000L; // 1 000 000 private static final long MAX = 1000000L; // 1 000 000
private static final long SQRT_MAX = (long) Math.sqrt(MAX) + 1; private static final long SQRT_MAX = (long) Math.sqrt(MAX) + 1;
private static final int MEMORY_SIZE = (int) (MAX >> 4); private static final int MEMORY_SIZE = (int) (MAX >> 4);
private static final int BLOCK_MAX = (int) (1 << 4); private static final int BLOCK_MAX = (int) (1 << 4);
private static boolean computed = false; private static boolean computed = false;
private static byte[] primes = new byte[MEMORY_SIZE]; private static byte[] primes = new byte[MEMORY_SIZE];
/** /**
* Get stored bit for number i * Get stored bit for number i
* *
* @param i * @param i
* @return * @return
*/ */
private static boolean getBit(long i) { private static boolean getBit(long i) {
byte block = primes[(int) (i >> 4)]; byte block = primes[(int) (i >> 4)];
byte mask = (byte) (1 << ((i >> 1) & 7)); byte mask = (byte) (1 << ((i >> 1) & 7));
return ((block & mask) != 0); return ((block & mask) != 0);
} }
/** /**
* Set stored bit for number i * Set stored bit for number i
* *
* @param i * @param i
*/ */
private static void setBit(long i) { private static void setBit(long i) {
int index = (int) (i >> 4); int index = (int) (i >> 4);
byte block = primes[index]; byte block = primes[index];
byte mask = (byte) (1 << ((i >> 1) & 7)); byte mask = (byte) (1 << ((i >> 1) & 7));
primes[index] = (byte) (block | mask); primes[index] = (byte) (block | mask);
} }
/** /**
* Computes first million numbers, (takes ~25 ms) * Computes first million numbers, (takes ~25 ms)
*/ */
public static void computeList() { public static void computeList() {
Arrays.fill(primes, (byte) 0); Arrays.fill(primes, (byte) 0);
long t0 = System.currentTimeMillis(); long t0 = System.currentTimeMillis();
for (long i = 3; i < SQRT_MAX; i += 2) for (long i = 3; i < SQRT_MAX; i += 2)
if (!getBit(i)) { if (!getBit(i)) {
long j = (i * i); long j = (i * i);
while (j < MAX) { while (j < MAX) {
setBit(j); setBit(j);
j += (2 * i); j += (2 * i);
} }
} }
computed = true; computed = true;
System.out.println( System.out.println(
String.format("Calculated %d KB of primes in %d ms", MEMORY_SIZE / 1000, System.currentTimeMillis() - t0)); String.format("Calculated %d KB of primes in %d ms", MEMORY_SIZE / 1000, System.currentTimeMillis() - t0));
} }
/** /**
* Next prime stored * Next prime stored
* *
* @param p * @param p
* @return * @return
*/ */
private static int nextPrime(int p) { private static int nextPrime(int p) {
p++; p++;
while (getBit(p)) while (getBit(p))
p++; p++;
return p; return p;
} }
/** /**
* Check if a number is prime by calculating its block * Check if a number is prime by calculating its block
* *
* @param number * @param number
* @return * @return
*/ */
private static boolean isPrimeByBlock(long number) { private static boolean isPrimeByBlock(long number) {
long start = number - number % BLOCK_MAX; long start = number - number % BLOCK_MAX;
long end = start + BLOCK_MAX; long end = start + BLOCK_MAX;
long endSqrt = (long) Math.sqrt(end) + 1; long endSqrt = (long) Math.sqrt(end) + 1;
byte block = 0; byte block = 0;
int p = 2; int p = 2;
while (p < endSqrt) { while (p < endSqrt) {
p = nextPrime(p); p = nextPrime(p);
long j = p - (start % p); long j = p - (start % p);
j += ((j & 1) == 0 ? p : 0); j += ((j & 1) == 0 ? p : 0);
long p2 = p * 2; long p2 = p * 2;
while (j < BLOCK_MAX) { while (j < BLOCK_MAX) {
block |= (1 << ((j >> 1) & 7)); block |= (1 << ((j >> 1) & 7));
j += p2; j += p2;
} }
} }
byte mask = (byte) (1 << ((number >> 1) & 7)); byte mask = (byte) (1 << ((number >> 1) & 7));
return !((block & mask) != 0); return !((block & mask) != 0);
} }
/** /**
* Check if a number is prime (max 1 000 000 000 000) * Check if a number is prime (max 1 000 000 000 000)
* *
* @param number * @param number
* @return * @return
* @throws Exception * @throws Exception
*/ */
public static boolean isPrime(long number) throws Exception { public static boolean isPrime(long number) throws Exception {
if (number <= 0 || Math.sqrt(number) > MAX) if (number <= 0 || Math.sqrt(number) > MAX)
throw new Exception("Number out of range"); throw new Exception("Number out of range");
if (number <= 2) if (number <= 2)
return true; return true;
if ((number & 1) == 0) if ((number & 1) == 0)
return false; return false;
if (!computed) if (!computed)
computeList(); computeList();
if (number < MAX) if (number < MAX)
return !getBit(number); return !getBit(number);
return isPrimeByBlock(number); return isPrimeByBlock(number);
} }
} }
@@ -1,179 +1,179 @@
package fr.klemek.primedate; package fr.klemek.primedate;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import java.util.ArrayList; import java.util.ArrayList;
import twitter4j.Twitter; import twitter4j.Twitter;
import twitter4j.TwitterException; import twitter4j.TwitterException;
import twitter4j.TwitterFactory; import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken; import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken; import twitter4j.auth.RequestToken;
import twitter4j.conf.ConfigurationBuilder; import twitter4j.conf.ConfigurationBuilder;
/** /**
* Contains the useful functions to connect to twitter * Contains the useful functions to connect to twitter
* @author Kleme * @author Kleme
*/ */
public abstract class TwitterClient { public abstract class TwitterClient {
//http://twitter4j.org/en/code-examples.html //http://twitter4j.org/en/code-examples.html
private final static String ACCESS_TOKEN_FILE = "access_token.txt"; private final static String ACCESS_TOKEN_FILE = "access_token.txt";
private static Twitter twitter; private static Twitter twitter;
/** /**
* Load keys and tokens to connect to the correct twitter account * Load keys and tokens to connect to the correct twitter account
* @param keyFile the file containing the customer keys * @param keyFile the file containing the customer keys
* @return * @return
*/ */
public static boolean setUpTwitter(String keyFile) { public static boolean setUpTwitter(String keyFile) {
try { try {
File consumer_file = new File(keyFile); File consumer_file = new File(keyFile);
if(!consumer_file.exists()) { if(!consumer_file.exists()) {
System.out.println("Invalid consumer key file"); System.out.println("Invalid consumer key file");
return false; return false;
} }
String[] consumer_key = loadConsumerKey(keyFile); String[] consumer_key = loadConsumerKey(keyFile);
if(consumer_key.length < 2) { if(consumer_key.length < 2) {
System.out.println("Invalid consumer key file"); System.out.println("Invalid consumer key file");
return false; return false;
} }
File token_file = new File(ACCESS_TOKEN_FILE); File token_file = new File(ACCESS_TOKEN_FILE);
if(!token_file.exists()) { if(!token_file.exists()) {
twitter = TwitterFactory.getSingleton(); twitter = TwitterFactory.getSingleton();
twitter.setOAuthConsumer(consumer_key[0], consumer_key[1]); twitter.setOAuthConsumer(consumer_key[0], consumer_key[1]);
RequestToken requestToken = twitter.getOAuthRequestToken(); RequestToken requestToken = twitter.getOAuthRequestToken();
AccessToken accessToken = null; AccessToken accessToken = null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (null == accessToken) { while (null == accessToken) {
System.out.println("Open the following URL and grant access to your account:"); System.out.println("Open the following URL and grant access to your account:");
System.out.println(requestToken.getAuthorizationURL()); System.out.println(requestToken.getAuthorizationURL());
System.out.print("Enter the PIN(if available) or just hit enter.[PIN]:"); System.out.print("Enter the PIN(if available) or just hit enter.[PIN]:");
String pin; String pin;
pin = br.readLine(); pin = br.readLine();
if (pin.length() > 0) { if (pin.length() > 0) {
accessToken = twitter.getOAuthAccessToken(requestToken, pin); accessToken = twitter.getOAuthAccessToken(requestToken, pin);
} else { } else {
accessToken = twitter.getOAuthAccessToken(); accessToken = twitter.getOAuthAccessToken();
} }
} }
// persist to the accessToken for future reference. // persist to the accessToken for future reference.
storeAccessToken(accessToken); storeAccessToken(accessToken);
}else { }else {
/*TwitterFactory factory = new TwitterFactory(); /*TwitterFactory factory = new TwitterFactory();
twitter = factory.getInstance(); twitter = factory.getInstance();
twitter.setOAuthConsumer(consumer_key[0], consumer_key[1]); twitter.setOAuthConsumer(consumer_key[0], consumer_key[1]);
twitter.setOAuthAccessToken(accessToken);*/ twitter.setOAuthAccessToken(accessToken);*/
AccessToken accessToken = loadAccessToken(); AccessToken accessToken = loadAccessToken();
ConfigurationBuilder cb = new ConfigurationBuilder(); ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true) cb.setDebugEnabled(true)
.setOAuthConsumerKey(consumer_key[0]) .setOAuthConsumerKey(consumer_key[0])
.setOAuthConsumerSecret(consumer_key[1]) .setOAuthConsumerSecret(consumer_key[1])
.setOAuthAccessToken(accessToken.getToken()) .setOAuthAccessToken(accessToken.getToken())
.setOAuthAccessTokenSecret(accessToken.getTokenSecret()); .setOAuthAccessTokenSecret(accessToken.getTokenSecret());
TwitterFactory tf = new TwitterFactory(cb.build()); TwitterFactory tf = new TwitterFactory(cb.build());
twitter = tf.getInstance(); twitter = tf.getInstance();
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
return false; return false;
} catch (TwitterException te) { } catch (TwitterException te) {
if (401 == te.getStatusCode()) { if (401 == te.getStatusCode()) {
System.out.println("Unable to get the access token."); System.out.println("Unable to get the access token.");
} else { } else {
te.printStackTrace(); te.printStackTrace();
} }
return false; return false;
} }
System.out.println("Successfuly connected to twitter"); System.out.println("Successfuly connected to twitter");
return true; return true;
} }
/** /**
* Store the access tokens into the constant file * Store the access tokens into the constant file
* @param accessToken * @param accessToken
* @throws IOException * @throws IOException
*/ */
private static void storeAccessToken(AccessToken accessToken) throws IOException { private static void storeAccessToken(AccessToken accessToken) throws IOException {
BufferedWriter bw = null; BufferedWriter bw = null;
try { try {
File file = new File(ACCESS_TOKEN_FILE); File file = new File(ACCESS_TOKEN_FILE);
file.createNewFile(); file.createNewFile();
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))); bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
bw.write(accessToken.getToken()); bw.write(accessToken.getToken());
bw.newLine(); bw.newLine();
bw.write(accessToken.getTokenSecret()); bw.write(accessToken.getTokenSecret());
}finally { }finally {
bw.close(); bw.close();
} }
} }
/** /**
* Load the access tokens from the constant file * Load the access tokens from the constant file
* @return * @return
* @throws IOException * @throws IOException
*/ */
private static AccessToken loadAccessToken() throws IOException { private static AccessToken loadAccessToken() throws IOException {
BufferedReader br = null; BufferedReader br = null;
try { try {
File file = new File(ACCESS_TOKEN_FILE); File file = new File(ACCESS_TOKEN_FILE);
br = new BufferedReader(new InputStreamReader(new FileInputStream(file))); br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String token = br.readLine(); String token = br.readLine();
String tokenSecret = br.readLine(); String tokenSecret = br.readLine();
return new AccessToken(token, tokenSecret); return new AccessToken(token, tokenSecret);
}finally { }finally {
br.close(); br.close();
} }
} }
/** /**
* Load the consumer keys from the given file * Load the consumer keys from the given file
* @param file_name * @param file_name
* @return * @return
* @throws IOException * @throws IOException
*/ */
private static String[] loadConsumerKey(String file_name) throws IOException{ private static String[] loadConsumerKey(String file_name) throws IOException{
BufferedReader br = null; BufferedReader br = null;
try { try {
ArrayList<String> file_lines = new ArrayList<>(); ArrayList<String> file_lines = new ArrayList<>();
File file = new File(file_name); File file = new File(file_name);
br = new BufferedReader(new InputStreamReader(new FileInputStream(file))); br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line; String line;
while((line = br.readLine()) != null) { while((line = br.readLine()) != null) {
file_lines.add(line); file_lines.add(line);
} }
return file_lines.toArray(new String[0]); return file_lines.toArray(new String[0]);
}finally { }finally {
br.close(); br.close();
} }
} }
/** /**
* Update the status of the twitter account * Update the status of the twitter account
* @param msg * @param msg
*/ */
public static void tweet(String msg) { public static void tweet(String msg) {
try { try {
twitter.updateStatus(msg); twitter.updateStatus(msg);
System.out.println("Tweeted : "+msg); System.out.println("Tweeted : "+msg);
} catch (TwitterException e) { } catch (TwitterException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
@@ -1,44 +1,44 @@
package fr.klemek.primedate; package fr.klemek.primedate;
import static org.junit.Assert.*; import static org.junit.Assert.*;
import org.junit.Test; import org.junit.Test;
public class PrimeCalculatorTests { public class PrimeCalculatorTests {
public void testNumber(boolean expected, long number) throws Exception { public void testNumber(boolean expected, long number) throws Exception {
if(expected) if(expected)
assertTrue(number+" should be prime", PrimeCalculator.isPrime(number)); assertTrue(number+" should be prime", PrimeCalculator.isPrime(number));
else else
assertFalse(number+" should not be prime", PrimeCalculator.isPrime(number)); assertFalse(number+" should not be prime", PrimeCalculator.isPrime(number));
} }
@Test @Test
public void testIsPrimeSmall() throws Exception { public void testIsPrimeSmall() throws Exception {
testNumber(true, 1); testNumber(true, 1);
testNumber(true, 2); testNumber(true, 2);
testNumber(true, 3); testNumber(true, 3);
testNumber(false, 4); testNumber(false, 4);
testNumber(true, 5); testNumber(true, 5);
testNumber(false, 6); testNumber(false, 6);
testNumber(true, 7); testNumber(true, 7);
testNumber(false, 9); testNumber(false, 9);
} }
@Test @Test
public void testIsPrimeNormal() throws Exception { public void testIsPrimeNormal() throws Exception {
testNumber(true, 8011); testNumber(true, 8011);
testNumber(true, 8941); testNumber(true, 8941);
testNumber(false, 8943); testNumber(false, 8943);
testNumber(true, 9283); testNumber(true, 9283);
} }
@Test @Test
public void testIsPrimeBig() throws Exception { public void testIsPrimeBig() throws Exception {
testNumber(true, 201802181381L); testNumber(true, 201802181381L);
testNumber(false, 201802181383L); testNumber(false, 201802181383L);
testNumber(false, 201802181307L); testNumber(false, 201802181307L);
testNumber(false, 201802181409L); testNumber(false, 201802181409L);
testNumber(true, 201802181411L); testNumber(true, 201802181411L);
} }
} }