Commit 9af3974e authored by PEDRO SANDIN MUÑOZ DE ARENILLAS's avatar PEDRO SANDIN MUÑOZ DE ARENILLAS
Browse files

Update Proyecto_Computacion/src/cdist/TwitterProducer.java

parent 09b57d17
package cdist;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.channels.ServerSocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import twitter4j.FilterQuery;
import twitter4j.StallWarning;
import twitter4j.Status;
import twitter4j.StatusDeletionNotice;
import twitter4j.StatusListener;
import twitter4j.TwitterStream;
import twitter4j.TwitterStreamFactory;
import twitter4j.conf.ConfigurationBuilder;
import com.vdurmont.emoji.*;
import com.monkeylearn.*;
import org.json.simple.JSONObject;
import java.io.File;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
public class TwitterProducer {
//Claves obtenidas de la API de Twitter
public static final String _consumerKey = "XXXXXXXXXXXXXXX";
public static final String _consumerSecret = "XXXXXXXXXXXXXXX";
public static final String _accessToken = "XXXXXXXXXXXXXXX";
public static final String _accessTokenSecret = "XXXXXXXXXXXXXXX";
private static final boolean EXTENDED_TWITTER_MODE = true;
//Variables para contabilizar el tipo de Tweets
static int total = 0;
static int positivo = 0;
static int negativo = 0;
static int neutro = 0;
static File f = null;
static PrintWriter writer = null;
public class Handler {
public AsynchronousSocketChannel client;
public ByteBuffer out = ByteBuffer.allocate(1024);
public ByteBuffer in = ByteBuffer.allocate(1024);
}
public static void main(String[] args) {
TwitterProducer tp = new TwitterProducer();
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setOAuthConsumerKey(_consumerKey).setOAuthConsumerSecret(_consumerSecret)
.setOAuthAccessToken(_accessToken).setOAuthAccessTokenSecret(_accessTokenSecret);
AsynchronousServerSocketChannel server;
AsynchronousSocketChannel client = null;
Handler h = tp.new Handler();
try {
server = AsynchronousServerSocketChannel.open();
server.bind(new InetSocketAddress("127.0.0.1", 9999));
server.accept(h, new CompletionHandler<AsynchronousSocketChannel, Handler>() {
@Override
public void completed(AsynchronousSocketChannel result, Handler handler) {
// prepare for future connections
if (server.isOpen())
server.accept(null, this);
if (result != null && result.isOpen()) {
handler.client = result;
}
}
@Override
public void failed(Throwable exc, Handler attachment) {
// TODO Auto-generated method stub
}
});
} catch (IOException e) {
}
TwitterStream twitterStream = new TwitterStreamFactory(configurationBuilder.build()).getInstance();
twitterStream.addListener(new StatusListener() {
//cuando llega un nuevo tweet
public void onStatus(Status status) {
System.out.println("TW: " + status.getText());
String tweet = status.getText();
//Limpiar tweet
String cleanTweet = tweet.replace("\n", "").replace("\r", "");
cleanTweet = EmojiParser.removeAllEmojis(cleanTweet);
cleanTweet = EmojiParser.parseToAliases(cleanTweet);
try {
//Obtener de cuenta MonkeyLearn el propio api key
String apiKey_monkey = "XXXXXXXXXXXXXXX";
MonkeyLearn monkey = new MonkeyLearn(apiKey_monkey);
String modelId = "XXXXXXXXXXXXXXX";
MonkeyLearnResponse res;
String[] tweets = {cleanTweet};
//Crear clasicador de sentimientos
res = monkey.classifiers.classify(modelId, tweets, false);
String sentimiento = res.arrayResult.toString();
if(sentimiento.contains("Negative")){
negativo++;
total++;
System.out.println(" || Tweet Negativo || ");
}
else if(sentimiento.contains("Positive")){
positivo++;
total++;
System.out.println(" || Tweet Positivo || ");
}
else{
neutro++;
total++;
System.out.println("|| Tweet Neutro || ");
}
try {
//Generar las filas del archivo .csv para despu�s explotarlo en Power BI
writer = new PrintWriter("Garzon.csv");
writer.println("Sentimiento, Cantidad de tweets, Porcentaje, Total");
writer.println("Positivo, " + positivo + ", " + (positivo*100.0/total) + "% , " + total);
writer.println("Negativo, " + negativo + ", " + (negativo*100.0/total) + "% , " + total);
writer.println("Neutro, " + neutro + ", " + (neutro*100.0/total) + "% , " + total);
writer.flush();
writer.close();
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
}
}
catch(MonkeyLearnException ex) {
ex.printStackTrace();
}
if (h != null) {
if (h.client != null) {
h.out.clear();
h.out.put(tweet.getBytes(StandardCharsets.UTF_8));
h.out.flip();
h.client.write(h.out);
}
}
}
@Override
public void onException(Exception arg0) {
System.out.println("Exception on twitter");
}
@Override
public void onDeletionNotice(StatusDeletionNotice arg0) {
System.out.println("Exception on twitter");
}
@Override
public void onScrubGeo(long arg0, long arg1) {
System.out.println("onScrubGeo");
}
@Override
public void onStallWarning(StallWarning arg0) {
System.out.println("EonStallWarning");
}
@Override
public void onTrackLimitationNotice(int arg0) {
System.out.println("EonTrackLimitationNotice");
}
});
FilterQuery tweetFilterQuery = new FilterQuery();
tweetFilterQuery.track(new String[] { "Garzon", "Garz�n","garzon","garz�n", "ganaderia","ganader�a", "macrogranjas"});
twitterStream.filter(tweetFilterQuery);
}
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment