package placeholder.website.queue.http;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.NoSuchElementException;
import placeholder.http.HttpMethod;
import placeholder.http.HttpRequest;
import placeholder.website.WebsiteResult;
import placeholder.website.queue.AbstractWebsiteResultQueue;
import placeholder.website.queue.WebsiteResultQueueFlushException;
/**
* @author Heiko Bornholdt
*/
public class HttpWebsiteResultQueue extends AbstractWebsiteResultQueue {
public HttpWebsiteResultQueue(PrintStream out) {
super(out);
}
synchronized public boolean flush() throws WebsiteResultQueueFlushException {
this.out.print("Flush WebsiteResultQueue...");
boolean result = this.__fill();
this.out.println("finished!");
return result;
}
@Override
protected boolean __fill() throws WebsiteResultQueueFlushException {
HashMap<String, String> postFields = new HashMap<String, String>();
try {
WebsiteResult result;
while ((result = this.queue.removeFirst()) != null) {
// http status
postFields.put("websites[" + result.getWebsite() + "][httpStatus]", new Integer(result.getHTTPStatus()).toString());
// check time
postFields.put("websites[" + result.getWebsite() + "][checkTime]", new Integer(result.getCheckTime()).toString());
// websites
String[] websites = result.getWebsites();
for (int i = 0; i < websites.length; i++) {
postFields.put("websites[" + result.getWebsite() + "][websites][" + i + "]", websites[i]);
}
// services
String[] services = result.getServices();
for (int i = 0; i < services.length; i++) {
postFields.put("websites[" + result.getWebsite() + "][services][" + i + "]", services[i]);
}
}
} catch (NoSuchElementException e) {
// do nothing
}
// request
try {
HttpRequest request = new HttpRequest("http://62.75.144.112/~heiko/placeholder/set.php", HttpMethod.POST);
request.addPostFields(postFields);
request.send();
if (request.getConnection().getResponseCode() != 200) {
throw new HttpWebsiteResultQueueFlushException("Error while sending website results to server.", request, request.getConnection().getResponseMessage(), request.getConnection().getResponseCode());
}
} catch (Exception e) {
throw new WebsiteResultQueueFlushException(e);
}
return !postFields.isEmpty();
}
}