org.deeplearning4j.ui.WebReporter Maven / Gradle / Ivy
package org.deeplearning4j.ui;
import lombok.NonNull;
import org.nd4j.linalg.primitives.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.concurrent.LinkedBlockingQueue;
/**
* This is simple wrapper for sending state updates generated by IterationListeners.
* Basic idea is simple: network processing should be handled in background, without slowing caller thread
*
* @author [email protected]
*/
public class WebReporter {
private static final WebReporter INSTANCE = new WebReporter();
protected LinkedBlockingQueue> queue = new LinkedBlockingQueue<>();
private static final Logger log = LoggerFactory.getLogger(WebReporter.class);
private WebReporter() {
ReporterThread thread = new ReporterThread(queue);
thread.start();
throw new RuntimeException("Not implemented");
}
public static WebReporter getInstance() {
return INSTANCE;
}
/**
* This method queues UI report for sending
*
* @param target
* @param entity
*/
public void queueReport(WebTarget target, Entity entity) {
queue.add(Pair.makePair(target, entity));
}
/**
* This method immediately sends UI report to specified target using POST request
*
* @param target
* @param entity
*/
public void postReport(WebTarget target, Entity entity) {
Response resp = target.request(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).post(entity);
log.debug("{}", resp);
}
private class ReporterThread extends Thread implements Runnable {
private LinkedBlockingQueue> queue;
public ReporterThread(@NonNull LinkedBlockingQueue> queue) {
this.queue = queue;
this.setName("DL4j Ui WebReporter thread");
this.setDaemon(true);
}
@Override
public void run() {
while (true) {
try {
Pair pair = queue.take();
postReport(pair.getFirst(), pair.getSecond());
} catch (Exception e) {
log.error("Exception caught but ignored: " + e.getMessage());
e.printStackTrace();
} finally {
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
}
}
}
}