Skip to content

Commit

Permalink
webservice: refactoring: generalize Callback
Browse files Browse the repository at this point in the history
A callback is something that pushes notifications, but which not
necessarily does this by posting messages to a HTTP server.
  • Loading branch information
bertfrees committed Jan 20, 2023
1 parent ceafbe1 commit 75903c8
Show file tree
Hide file tree
Showing 5 changed files with 150 additions and 157 deletions.
Original file line number Diff line number Diff line change
@@ -1,34 +1,30 @@
package org.daisy.pipeline.webservice;

import java.net.URI;
import java.math.BigDecimal;
import java.util.List;

import org.daisy.pipeline.clients.Client;
import org.daisy.common.messaging.Message;
import org.daisy.pipeline.job.Job;
import org.daisy.pipeline.job.Job.Status;

public abstract class Callback {

public class Callback {
public enum CallbackType {STATUS, MESSAGES}

private final URI href;
private final CallbackType type;
private final Job job;
private int frequency = 1;
private final Client client;

public Callback(Job job, Client client, URI href, CallbackType type, int frequency) {
this.href = href;
public Callback(Job job, CallbackType type, int frequency) {
this.type = type;
this.job = job;
this.client = client;
this.frequency = frequency;
}

public Job getJob() {
return job;
}

public URI getHref() {
return href;
}

public CallbackType getType() {
return type;
}
Expand All @@ -37,12 +33,8 @@ public int getFrequency() {
return frequency;
}

public Client getClient() {
return client;
}
public abstract boolean postMessages(List<Message> messages, int newerThan, BigDecimal progress);

public abstract boolean postStatusUpdate(Status status);

@Override
public String toString() {
return "Callback [href='" + href+ "'; client=" + client + "]";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@
import org.daisy.pipeline.script.XProcOptionMetadata;
import org.daisy.pipeline.script.XProcScript;
import org.daisy.pipeline.script.XProcScriptService;
import org.daisy.pipeline.webservice.Callback;
import org.daisy.pipeline.webservice.Callback.CallbackType;
import org.daisy.pipeline.webservice.CallbackHandler;
import org.daisy.pipeline.webservice.xml.JobXmlWriter;
Expand Down Expand Up @@ -399,27 +398,21 @@ private Optional<Job> createJob(Document doc, ZipFile zip)
NodeList callbacks = doc.getElementsByTagNameNS(Validator.NS_DAISY,"callback");
for (int i = 0; i<callbacks.getLength(); i++) {
Element elm = (Element)callbacks.item(i);
String href = elm.getAttribute("href");
CallbackType type = CallbackType.valueOf(elm.getAttribute("type").toUpperCase());
String frequency = elm.getAttribute("frequency");
Callback callback = null;
int freq = 0;
if (frequency.length() > 0) {
freq = Integer.parseInt(frequency);
}

try {
callback = new Callback(newJob.get(), this.getClient(), new URI(href), type, freq);
} catch (URISyntaxException e) {
logger.warn("Cannot create callback: " + e.getMessage());
}

if (callback != null) {
CallbackHandler pushNotifier = webservice().getCallbackHandler();
if (pushNotifier == null) {
URI href = new URI(elm.getAttribute("href"));
CallbackHandler handler = webservice().getCallbackHandler();
if (handler == null) {
throw new RuntimeException("No push notifier");
}
pushNotifier.addCallback(callback);
handler.addCallback(new PosterCallback(newJob.get(), type, freq, href, getClient()));
} catch (URISyntaxException e) {
logger.warn("Cannot create callback: " + e.getMessage());
}
}
return newJob;
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
package org.daisy.pipeline.webservice.impl;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URI;
import java.util.List;
import java.util.stream.Collectors;

import org.daisy.common.messaging.Message;
import org.daisy.pipeline.clients.Client;
import org.daisy.pipeline.job.Job;
import org.daisy.pipeline.job.Job.Status;
import org.daisy.pipeline.webservice.Authenticator;
import org.daisy.pipeline.webservice.Callback;
import org.daisy.pipeline.webservice.xml.JobXmlWriter;
import org.daisy.pipeline.webservice.xml.XmlUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.w3c.dom.Document;

/**
* Callback that posts notification messages to a HTTP server.
*/
public class PosterCallback extends Callback {

private final URI url;
private final Client client;
private static Logger logger = LoggerFactory.getLogger(PosterCallback.class.getName());

public PosterCallback(Job job, CallbackType type, int frequency, URI url, Client client) {
super(job, type, frequency);
this.url = url;
this.client = client;
}

public boolean postMessages(List<Message> messages, int newerThan, BigDecimal progress) {
logger.debug("Posting messages to " + url);
JobXmlWriter writer = new JobXmlWriter(getJob());
writer.withMessages(messages, newerThan);
writer.withProgress(progress);
Document doc = writer.getXmlDocument();
return postXml(doc, url, client);
}

public boolean postStatusUpdate(Status status) {
logger.debug("Posting status '" + status + "' to " + url);
JobXmlWriter writer = new JobXmlWriter(getJob());
writer.overwriteStatus(status);
Document doc = writer.getXmlDocument();
return postXml(doc, url, client);
}

private static boolean postXml(Document doc, URI url, Client client) {
URI requestUri = url;
if (client != null) {
requestUri = Authenticator.createUriWithCredentials(url.toString(), client);
}

// from http://code.geek.sh/2009/10/simple-post-in-java/
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) requestUri.toURL().openConnection();
} catch (IOException e) {
logger.error(e.getMessage());
return false;
}

connection.setDoInput (true);
connection.setDoOutput (true);
connection.setUseCaches (false);

try {
connection.setRequestMethod("POST");
} catch (ProtocolException e) {
logger.error(e.getMessage());
return false;
}

try {
connection.connect();
} catch (IOException e) {
logger.error(e.getMessage());
return false;
}

DataOutputStream output = null;

try {
output = new DataOutputStream(connection.getOutputStream());
} catch (IOException e) {
logger.error(e.getMessage());
return false;
}

// Send the request data.
try {
logger.debug("Posting XML: "+XmlUtils.nodeToString(doc));
output.writeBytes(XmlUtils.nodeToString(doc));
output.flush();
output.close();
} catch (IOException e) {
logger.error(e.getMessage());
return false;
}

// Get response data. We're not doing anything with it but if we don't retrieve it, the callback doesn't appear to work.
try {
logger.debug("Got response: " + connection.getResponseMessage() + " (" + connection.getResponseCode() + ")");
try {
DataInputStream input = new DataInputStream(connection.getInputStream());
try {
logger.debug((new BufferedReader(new InputStreamReader(input))).lines().collect(Collectors.joining("\n")));
} finally { input.close(); }
} catch (Exception e) {
}
return true;
} catch (IOException e) {
logger.warn("No response");
logger.debug("No response", e);
return false;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,6 @@ public PushNotifier() {

@Activate
public void init() {
logger = LoggerFactory.getLogger(Poster.class.getName());
logger.debug("Activating push notifier");
jobManager = jobManagerFactory.createFor(clientStorage.defaultClient());
callbacks = new HashMap<>();
Expand Down Expand Up @@ -245,7 +244,7 @@ private void postStatus() {
if (callbacks != null) {
for (Callback callback : callbacks) {
if (callback.getType() == CallbackType.STATUS) {
Poster.postStatusUpdate(job, holder.status, callback);
callback.postStatusUpdate(holder.status);
}
}
}
Expand Down Expand Up @@ -288,7 +287,7 @@ private synchronized void postMessages() {
}
for (Callback callback : callbacks) {
if (callback.getType() == CallbackType.MESSAGES) {
Poster.postMessages(job, messages, newerThan, progress, callback);
callback.postMessages(messages, newerThan, progress);
}
}
}
Expand Down

0 comments on commit 75903c8

Please sign in to comment.