/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package design_patterns.observer;
import beans.Author;
import design_patterns.facade.RestClient;
import design_patterns.strategy.Product;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Observable;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import ui.Login;
/**
*
* @author root
*/
public class EventSource extends Observable implements Runnable {
private String username;
private char[] password;
private ArrayList newproducts;
public Login login_window;
private ArrayList checkServer(){
String data = new RestClient().apacheHttpClientGet(Login.url+"api/reservation/product/?format=json", this.getUsername(), this.getPassword());
if( data!=null) {
try {
this.newproducts = new ArrayList();
JSONObject jsonObject = (JSONObject) new JSONParser().parse(data);
for (Object c : (JSONArray) jsonObject.get("objects")){
jsonObject = (JSONObject) c;
Matcher makeMatch = Pattern.compile("\\d+").matcher((String)jsonObject.get("author"));
makeMatch.find();
String inputInt = makeMatch.group();
// Author author = (Author) this.getAuthors_map().get(Integer.parseInt(inputInt));
Author author=null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date=null;
try {
date = sdf.parse((String) jsonObject.get("pub_date"));
} catch (java.text.ParseException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
Product product = new Product(Integer.parseInt((String)jsonObject.get("id")),author,(String) jsonObject.get("name"),(String) jsonObject.get("genre"),date);
this.newproducts.add(product);
}
} catch (ParseException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
}
return this.newproducts;
}
public void run() {
try {
while (true) {
checkServer();
String response;
if(this.login_window.getProducts().size()!=this.newproducts.size()){
response="There is a product update";
this.login_window.setProducts(this.newproducts);
}
else{
response="No product updates";
}
setChanged();
notifyObservers(response);
Thread.sleep(10000);
}
} catch (InterruptedException ex) {
Logger.getLogger(EventSource.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* @return the username
*/
public String getUsername() {
return username;
}
/**
* @param username the username to set
*/
public void setUsername(String username) {
this.username = username;
}
/**
* @return the password
*/
public char[] getPassword() {
return password;
}
/**
* @param password the password to set
*/
public void setPassword(char[] password) {
this.password = password;
}
public void updateProducts(Login login_window) {
this.login_window = login_window;
}
}