Java "theatre"

         
package nova;
import java.io.*;
import java.lang.reflect.Field;
import java.math.BigInteger;
import java.net.ConnectException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpTimeoutException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystemException;
import java.time.DayOfWeek;
import java.time.Month;
import java.time.format.TextStyle;
import java.util.*;
import java.util.function.BiFunction;
/**
* Warranty & Liability
* To the extent permitted by applicable law and unless explicitly
* otherwise agreed upon, XLOG Technologies AG makes no warranties
* regarding the provided information. XLOG Technologies AG assumes
* no liability that any problems might be solved with the information
* provided by XLOG Technologies AG.
*
* Rights & License
* All industrial property rights regarding the information - copyright
* and patent rights in particular - are the sole property of XLOG
* Technologies AG. If the company was not the originator of some
* excerpts, XLOG Technologies AG has at least obtained the right to
* reproduce, change and translate the information.
*
* Reproduction is restricted to the whole unaltered document. Reproduction
* of the information is only allowed for non-commercial uses. Selling,
* giving away or letting of the execution of the library is prohibited.
* The library can be distributed as part of your applications and libraries
* for execution provided this comment remains unchanged.
*
* Restrictions
* Only to be distributed with programs that add significant and primary
* functionality to the library. Not to be distributed with additional
* software intended to replace any components of the library.
*
* Trademarks
* Jekejeke is a registered trademark of XLOG Technologies AG.
*/
public final class theatre {
/**************************************************************/
/* Core API */
/**************************************************************/
/**
* Initialize the Novacore Prolog system subset.
*
* @param args The program args.
* @throws IOException Shit happens.
* @throws URISyntaxException Shith appens.
*/
public static void core(String[] args) throws IOException, URISyntaxException {
special.set_args(args);
special.boot();
runtime.boot();
eval.boot();
boot();
Bootload.boot9();
Bootload.boot11();
Bootload.boot2();
Bootload.boot4();
Bootload.boot8();
Bootload.boot10();
Streams.boot5();
Streams.boot6();
Streams.boot7();
String[] classpath = findRoots(runtime.class.getClassLoader());
special.set_classpath(classpath);
String bootbase = (classpath.length > 0 ? classpath[0] : "");
runtime.set_bootbase(bootbase);
}
private static final String MARKER = "root_marker.properties";
/**
* Find the roots.
*
* @param loader The loader.
* @return The roots.
* @throws IOException Shit happens.
*/
public static String[] findRoots(ClassLoader loader)
throws IOException, URISyntaxException {
ArrayList list = new ArrayList();
Enumeration it = loader.getResources(MARKER);
while (it.hasMoreElements()) {
String path = it.nextElement().toString();
path = path.substring(0, path.length() - MARKER.length());
list.add(minifyURI(path));
}
String[] res = new String[list.size()];
list.toArray(res);
return res;
}
public static String minifyURI(String adr) throws URISyntaxException {
URI uri = new URI(adr);
if ("file".equals(uri.getScheme()))
return new File(uri).toString() + File.separatorChar;
return adr;
}
/**************************************************************/
/* Main API */
/**************************************************************/
/**
* Post a message to the Prolog interpreter.
*
* @param message The message.
*/
public static void post(Object message) {
Machine.Engine en = Machine.determine_engine(Machine.CTX_MAIN);
en.signal = message;
en.abort.run();
}
/**
* Run a Prolog term once. The goal is run with auto-yield
* disabled and promises are not accepted.
*
* @param goal The Prolog term.
* @return boolean True or false.
*/
public static Object perform(Object goal) {
return Machine.launch(goal, Machine.CTX_MAIN, Machine.VOID_ARGS);
}
/**
* Run a Prolog term once. The goal is run with auto-yield
* enabled and promises are accepted.
*
* @param goal The Prolog term.
* @return boolean True or false.
*/
public static boolean perform_async(Object goal) {
return Machine.launch_async(goal, Machine.CTX_MAIN, Machine.VOID_ARGS);
}
/**************************************************************/
/* Register API */
/**************************************************************/
/**
* The flag indicates a non-void dispatch foreign function.
*/
public static int FFI_FUNC = 0x00000100;
/**
* Add a Java function to the knowledge base. The given
* function is invoked with rather slow argument spreading.
* Also the function is wrapped and registered as a special,
* therefore not eligible to neck optimization.
*
* @param functor The functor.
* @param arity The arity.
* @param func The Java function.
* @param flags The flags.
*/
public static void register(String functor, int arity, Handler.Builtin func, int flags) {
Store.Provable res;
if ((flags & FFI_FUNC) != 0) {
res = special.make_check((args) -> invoke_func(func, args));
} else {
res = special.make_check((args) -> invoke(func, args));
}
Store.set(functor, arity, res);
}
private static boolean invoke(Handler.Builtin func, Object[] args) {
Object[] temp = new Object[args.length];
for (int i = 0; i < temp.length; i++)
temp[i] = Machine.exec_build(args[i]);
func.run(temp);
return true;
}
private static boolean invoke_func(Handler.Builtin func, Object[] args) {
Object[] temp = new Object[args.length - 1];
for (int i = 0; i < temp.length; i++)
temp[i] = Machine.exec_build(args[i]);
Object res = func.run(temp);
return Machine.exec_unify(args[args.length - 1], res);
}
/*****************************************************************/
/* os_obj_new/1 and os_obj_current/3 */
/*****************************************************************/
/**
* os_obj_new(O):
* The predicate succeeds in O with a new Java object.
*/
private static boolean test_os_obj_new(Object[] args) {
Map res = new HashMap();
return Machine.exec_unify(args[0], res);
}
/**
* os_obj_current(O, K, V):
* The predicate succeeds in V with the value of the key K in the Java object O.
*/
private static boolean test_os_obj_current(Object[] args) {
Object obj = Machine.exec_build(args[0]);
Object key = Machine.exec_build(args[1]);
special.check_atom(key);
Object res;
if (obj instanceof Map) {
res = ((Map) obj).getOrDefault(key, Store.UNDEF_OBJ);
} else {
try {
Field field = obj.getClass().getField((String)key);
res = field.get(obj);
} catch (NullPointerException | NoSuchFieldException |
IllegalAccessException e) {
res = Store.UNDEF_OBJ;
}
}
if (res == Store.UNDEF_OBJ)
return false;
return Machine.exec_unify(args[2], res);
}
/*****************************************************************/
/* os_obj_set/3, os_obj_reset/2 and os_obj_keys/2 */
/*****************************************************************/
/**
* os_obj_set(O, K, V):
* The predicate sets the value of the key K in the Java object O to V.
*/
private static boolean test_os_obj_set(Object[] args) {
Object obj = Machine.exec_build(args[0]);
Object key = Machine.exec_build(args[1]);
special.check_atom(key);
Object value = Machine.exec_build(args[2]);
if (obj instanceof Map) {
((Map) obj).put(key, value);
} else {
try {
Field field = obj.getClass().getField((String)key);
field.set(obj, value);
} catch (NullPointerException | NoSuchFieldException |
IllegalAccessException e) {
throw Machine.make_error(new Store.Compound("permission_error",
new Object[]{"modify", "field", key}));
}
}
return true;
}
/**
* os_obj_reset(O, K):
* The predicate removes the key K from the Java object O.
*/
private static boolean test_os_obj_reset(Object[] args) {
Object obj = Machine.exec_build(args[0]);
Object key = Machine.exec_build(args[1]);
special.check_atom(key);
if (obj instanceof Map) {
((Map) obj).remove(key);
} else {
throw Machine.make_error(new Store.Compound("permission_error",
new Object[]{"modify", "field", key}));
}
return true;
}
/**
* os_obj_keys(O, L):
* The predicate succeeds in L with the keys of the Java object O.
*/
private static boolean test_os_obj_keys(Object[] args) {
Object obj = Machine.exec_build(args[0]);
if (obj instanceof Map) {
obj = ((Map) obj).keySet();
} else {
Field[] fields = obj.getClass().getFields();
obj = new FieldNames(fields);
}
obj = set_to_list((Collection)obj);
return Machine.exec_unify(args[1], obj);
}
private static class FieldNames extends AbstractList<Object> {
private final Field[] fields;
public FieldNames(Field[] fields) {
this.fields = fields;
}
public Object get(int index) {
return fields[index].getName();
}
public int size() {
return fields.length;
}
}
/**
* Convert a native set into a Prolog list.
*
* @param temp The native set.
*/
public static Object set_to_list(Collection temp) {
Store.Structure back = null;
Object res = null;
if (temp != null) {
Iterator it = temp.iterator();
while (it.hasNext()) {
Object value = it.next();
Store.Structure peek = new Store.Compound(".",
new Object[]{value, Store.UNDEF_OBJ});
if (back == null) {
res = peek;
} else {
back.args[1] = peek;
}
back = peek;
}
}
if (back == null) {
res = "[]";
} else {
back.args[1] = "[]";
}
return res;
}
/******************************************************************/
/* os_float_value/2 and os_atom_offset/3 */
/******************************************************************/
/**
* os_float_value(P, H):
* If P is instantiated, then the predicate succeeds in H with the
* Java float of P, otherwise in P with the Prolog float of H.
*/
private static boolean test_os_float_value(Object[] args) {
Object alpha = Machine.exec_deref(args[0]);
if (Store.is_variable(alpha) || Machine.is_pending(alpha)) {
Object beta = Machine.exec_build(args[1]);
special.check_number(beta);
Object res = (Machine.is_special(beta) ? beta :
special.norm_float(special.narrow_float((Number) beta)));
return Machine.exec_unify(alpha, res);
} else {
alpha = Machine.exec_build(alpha);
special.check_number(alpha);
Object res = (Machine.is_special(alpha) ? alpha :
Double.valueOf(special.narrow_float((Number) alpha)));
return Machine.exec_unify(args[1], res);
}
}
/**
* os_atom_offset(A, P, H):
* If P is instantiated, then the predicate succeeds in H with
* the Java offset of P into atom A, otherwise in P with the
* Prolog offset of H into the atom A. If the corresponding
* offset exceeds the given atom A the predicate fails.
*/
private static boolean test_os_atom_offset(Object[] args) {
Object alpha = Machine.exec_build(args[0]);
special.check_atom(alpha);
Object beta = Machine.exec_deref(args[1]);
if (Store.is_variable(beta) || Machine.is_pending(beta)) {
Object gamma = Machine.exec_build(args[2]);
special.check_integer(gamma);
if (Machine.is_bigint(alpha))
return false;
int at = ((Integer)gamma).intValue();
if (at < 0 || at > ((String)alpha).length())
return false;
int res = ((String)alpha).codePointCount(0, at);
return Machine.exec_unify(beta, Integer.valueOf(res));
} else {
beta = Machine.exec_build(beta);
special.check_integer(beta);
if (Machine.is_bigint(beta))
return false;
int at = ((Integer)beta).intValue();
int res = eval.atom_offset((String)alpha, 0, at);
if (res < 0)
return false;
return Machine.exec_unify(args[2], Integer.valueOf(res));
}
}
/**
* Parse a date time string.
*
* @param res The date time as a string.
* @param pat The pattern.
* @param utc The UTC calendar flag.
* @return The date time in UTC milliseconds.
*/
public static long sys_time_parse(String res, String pat, int utc) {
int year = 1900; int month = 1; int day = 1;
int hour = 0; int minute = 0; int second = 0;
int j = 0;
for (int i = 0; i < pat.length(); i++) {
char ch = pat.charAt(i);
if (ch == '%') {
i++;
int k;
switch (pat.charAt(i)) {
case '%':
if (j < res.length() && res.charAt(j) == '%') {
j++;
} else {
throw new NumberFormatException("illegal date");
}
break;
case 'a':
k = scan_alphanum(res, j);
int weekday = parse_weekday(res.substring(j, k),
(utc != 0 ? Locale.US : Locale.getDefault()));
j = k;
break;
case 'b':
k = scan_alphanum(res, j);
month = parse_month(res.substring(j, k),
(utc != 0 ? Locale.US : Locale.getDefault()));
j = k;
break;
case 'd':
k = scan_integer(res, j);
day = Integer.parseInt(res.substring(j, k));
j = k;
break;
case 'm':
k = scan_integer(res, j);
month = Integer.parseInt(res.substring(j, k));
j = k;
break;
case 'Y':
k = scan_integer(res, j);
year = Integer.parseInt(res.substring(j, k));
j = k;
break;
case 'H':
k = scan_integer(res, j);
hour = Integer.parseInt(res.substring(j, k));
j = k;
break;
case 'M':
k = scan_integer(res, j);
minute = Integer.parseInt(res.substring(j, k));
j = k;
break;
case 'S':
k = scan_integer(res, j);
second = Integer.parseInt(res.substring(j, k));
j = k;
break;
default:
throw new IllegalArgumentException("illegal format");
}
} else {
if (j < res.length() && res.charAt(j) == ch) {
j++;
} else {
throw new NumberFormatException("illegal date");
}
}
}
Calendar cal;
if (utc != 0) {
cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
} else {
cal = Calendar.getInstance();
}
cal.set(year, month - 1, day, hour, minute, second);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTimeInMillis();
}
/**
* Scan alphanum.
*
* @param res The text.
* @param j The old position.
* @return The new position.
*/
private static int scan_alphanum(String res, int j) {
while (j < res.length() && Character.isLetterOrDigit(res.charAt(j)))
j++;
return j;
}
/**
* Parse a week day.
*
* @param str The text.
* @param locale The locale to use, not null
* @return The index.
*/
private static int parse_weekday(String str, Locale locale) {
str = str.toLowerCase();
for (int i = 1; i < 8; i++) {
DayOfWeek wday = DayOfWeek.of(i);
String val = wday.getDisplayName(TextStyle.SHORT_STANDALONE, locale);
val = val.toLowerCase();
if (str.equals(val))
return i;
}
throw new NumberFormatException("illegal date");
}
/**
* Parse a month.
*
* @param str The text.
* @param locale The locale to use, not null
* @return The index.
*/
private static int parse_month(String str, Locale locale) {
str = str.toLowerCase();
for (int i = 1; i < 13; i++) {
Month mon = Month.of(i);
String val = mon.getDisplayName(TextStyle.SHORT_STANDALONE, locale);
val = val.toLowerCase();
if (str.equals(val))
return i;
}
throw new NumberFormatException("illegal date");
}
/**
* Scan integer.
*
* @param res The text.
* @param j The old position.
* @return The new position.
*/
private static int scan_integer(String res, int j) {
while (j < res.length() && Character.isDigit(res.charAt(j)))
j++;
return j;
}
/******************************************************************/
/* os_get_gestalt/1 and os_get_host/1 */
/******************************************************************/
/**
* os_get_gestalt(M): Internal only
* The built-in succeeds in M with a gestalt properties map.
*/
private static boolean test_os_get_gestalt(Object[] args) {
Map gestalt = new HashMap();
String val = System.getenv("TERM_SCHEME");
gestalt.put("sys_color", (val != null ? val : "normal"));
Locale loc = Locale.getDefault();
gestalt.put("sys_locale", loc.toString());
Object res = special.objects_list(special.main_args, 0, special.main_args.length);
gestalt.put("argv", res);
return Machine.exec_unify(args[0], gestalt);
}
/**
* os_get_host(M): internal only
* The built-in succeeds in W with a host properties map.
*/
private static boolean test_os_get_host(Object[] args) {
Map res = new HashMap();
res.put("system_url", runtime.bootbase);
res.put("foreign_ext", special.NAT_EXT);
res.put("host_info", System.getProperty("java.vendor")+
", Java "+System.getProperty("java.version"));
res.put("mach_info", System.getProperty("os.arch")+
", "+System.getProperty("os.name"));
return Machine.exec_unify(args[0], res);
}
/******************************************************************/
/* os_get_workdir/1 and os_set_workdir/1 */
/******************************************************************/
/**
* os_get_workdir(D): internal only
* The built-in succeeds in D with the working directory.
*/
private static boolean test_os_get_workdir(Object[] args) {
Object name = runtime.codebase;
return Machine.exec_unify(args[0], name);
}
/**
* os_set_workdir(D): internal only
* The built-in succeeds. As a side effect it changes the working directory to D.
*/
private static boolean test_os_set_workdir(Object[] args) {
Object obj = Machine.exec_build(args[0]);
special.check_atom(obj);
String name = (String)obj;
File file = runtime.findWrite(runtime.codebase, name);
try {
if (!file.exists())
throw new FileNotFoundException();
if (!file.isDirectory())
throw new FileSystemException(null);
runtime.set_codebase(file.getPath() + File.separatorChar);
return true;
} catch (IOException err) {
throw Machine.make_error(map_file_error(err, name));
}
}
/****************************************************************/
/* os_open_promise/4 */
/****************************************************************/
/**
* os_open_promise(P, L, S, Q):
* The predicate succeeds in Q with a promise for open input S
* on path P and option list L.
*/
private static boolean test_os_open_promise(Object[] args) {
Object obj = Machine.exec_build(args[0]);
special.check_atom(obj);
String name = (String) obj;
Map opts = (Map) Machine.exec_build(args[1]);
runtime.Source stream = new runtime.Source();
if (!Machine.exec_unify(args[2], stream))
return false;
return Machine.exec_unify(args[3],
open_file_promise(Machine.engine, stream, name, opts));
}
public static Charset get_encoding(Map opts) {
if (opts.get("encoding") != null) {
String encoding = opts.get("encoding").toString();
return Charset.forName(encoding);
} else {
return StandardCharsets.UTF_8;
}
}
private static Handler.Promise open_file_promise(Machine.Engine en,
runtime.Source stream, String name, Map opts) {
return new Handler.Promise(() -> {
File file = runtime.findWrite(runtime.codebase, name);
try {
InputStream ins = new FileInputStream(file);
stream.data = new InputStreamReader(ins, get_encoding(opts));
stream.receive = (BiFunction<Machine.Engine, runtime.Source, Handler.Promise>)
runtime::file_read_promise;
stream.release = (BiFunction<Machine.Engine, runtime.Source, Handler.Promise>)
runtime::file_close_promise;
stream.flags |= runtime.MASK_SRC_AREAD;
} catch (IOException err) {
err = (file.isFile() ? new IOException() :
(file.exists() ? new FileSystemException(null) : err));
en.signal = map_file_error(err, name);
}
});
}
private static Object map_file_error(IOException err, String name) {
if (err instanceof FileNotFoundException) {
return new Store.Compound("existence_error",
new Object[]{"source_sink", name});
} else if (err instanceof FileSystemException) {
return new Store.Compound("permission_error",
new Object[]{"open", "source_sink", name});
} else {
return new Store.Compound("resource_error",
new Object[]{"io_error"});
}
}
/*******************************************************************/
/* os_prop_promise/3 */
/*******************************************************************/
/**
* os_prop_promise(F, M, Q):
* The predicate succeeds in Q with with a promise for the
* properties M of the file F. Barks if path F doesn't exist
* or io exception while resolving.
*/
private static boolean test_os_prop_promise(Object[] args) {
Object obj = Machine.exec_build(args[0]);
special.check_atom(obj);
String name = (String) obj;
Map res = new LinkedHashMap();
if (!Machine.exec_unify(args[1], res))
return false;
return Machine.exec_unify(args[2],
prop_file_promise(Machine.engine, name, res));
}
private static Handler.Promise prop_file_promise(Machine.Engine en,
String name, Map res) {
return new Handler.Promise(() -> {
File file = runtime.findWrite(runtime.codebase, name);
if (file.exists()) {
String ftype = (file.isFile() ? "regular" :
(file.isDirectory() ? "directory" : "other"));
res.put("type", ftype);
res.put("absolute_path", (ftype.equals("directory") ?
file.getPath() + File.separatorChar : file.getPath()));
res.put("last_modified", special.norm_smallint(
file.lastModified()));
res.put("can_write", (file.canWrite() ? "true" : "false"));
} else {
/* */
}
});
}
/**************************************************************/
/* os_open_sync/4 */
/**************************************************************/
/**
* os_open_sync(P, M, L, S):
* The predicate succeeds. As a side effect the stream S is
* opened on the path P with the mode M and the option list L.
*/
private static boolean test_os_open_sync(Object[] args) {
Object obj = Machine.exec_build(args[0]);
special.check_atom(obj);
String name = (String) obj;
Object mode = Machine.exec_build(args[1]);
special.check_atom(mode);
Map opts = (Map) Machine.exec_build(args[2]);
Object stream;
if ("read".equals(mode)) {
throw Machine.make_error(new Store.Compound("resource_error",
new Object[]{"not_supported"}));
} else if ("write".equals(mode)) {
stream = open_write(name, false, opts);
} else if ("append".equals(mode)) {
stream = open_write(name, true, opts);
} else {
throw Machine.make_error(new Store.Compound("domain_error",
new Object[]{"io_mode", mode}));
}
return Machine.exec_unify(args[3], stream);
}
public static Object open_write(String name, boolean append, Map opts) {
File file = runtime.findWrite(runtime.codebase, name);
try {
OutputStream outs = new FileOutputStream(file, append);
runtime.Sink dst = new runtime.Sink();
dst.buf = new StringBuilder();
dst.data = new OutputStreamWriter(outs, get_encoding(opts));
dst.send = theatre::file_write;
dst.release = theatre::file_close;
dst.notify = theatre::file_flush;
return dst;
} catch (IOException err) {
err = (file.isFile() ? new IOException() :
(file.exists() ? new FileSystemException(null) : err));
throw Machine.make_error(map_file_error(err, name));
}
}
public static Object file_write(Object data, String buf) {
try {
int len = buf.length();
int pos = 0;
char[] cbuf = null;
while (len > 0) {
int span = Math.min(len, 8192);
if (cbuf == null)
cbuf = new char[span];
buf.getChars(pos, span, cbuf, 0);
((Writer) data).write(cbuf, 0, span);
pos += span;
len -= span;
}
return data;
} catch (IOException err) {
throw Machine.make_error(runtime.map_stream_error(err));
}
}
public static void file_flush(Object data) {
try {
((Flushable) data).flush();
} catch (IOException err) {
throw Machine.make_error(runtime.map_stream_error(err));
}
}
public static void file_close(Object data) {
try {
((Closeable) data).close();
} catch (IOException err) {
throw Machine.make_error(runtime.map_stream_error(err));
}
}
/*******************************************************************/
/* os_cntrl_sync/2 */
/*******************************************************************/
/**
* os_cntrl_sync(F, P):
* The predicate assigns the property P to the file F.
*/
private static boolean test_os_cntrl_sync(Object[] args) {
Object obj = Machine.exec_build(args[0]);
special.check_atom(obj);
String name = (String)obj;
File file = runtime.findWrite(runtime.codebase, name);
Object prop = Machine.exec_build(args[1]);
if (!file.exists())
throw Machine.make_error(new Store.Compound("existence_error",
new Object[]{"source_sink", name}));
if (Store.is_structure(prop) &&
"last_modified".equals(((Store.Structure) prop).functor) &&
((Store.Structure) prop).args.length == 1) {
Object val = Store.deref(((Store.Structure) prop).args[0]);
special.check_integer(val);
if (eval.integer_signum((Number) val) < 0)
throw Machine.make_error(new Store.Compound("domain_error",
new Object[]{"not_less_than_zero", val}));
if (!is_long((Number) val))
throw Machine.make_error(new Store.Compound("representation_error",
new Object[]{"long", val}));
if (!file.setLastModified(((Number) val).longValue())) {
throw Machine.make_error(new Store.Compound("resource_error",
new Object[]{"io_exception"}));
}
} else if (Store.is_structure(prop) &&
"can_write".equals(((Store.Structure) prop).functor) &&
((Store.Structure) prop).args.length == 1) {
Object val = Store.deref(((Store.Structure) prop).args[0]);
special.check_atom(val);
if (!"true".equals(val) && !"false".equals(val))
throw Machine.make_error(new Store.Compound("domain_error",
new Object[]{"boolean", val}));
if (!file.setWritable("true".equals(val))) {
throw Machine.make_error(new Store.Compound("resource_error",
new Object[]{"io_exception"}));
}
} else {
Store.check_nonvar(prop);
prop = Store.copy_term(prop);
throw Machine.make_error(new Store.Compound("domain_error",
new Object[]{"file_property", prop}));
}
return true;
}
private static final BigInteger MIN_LONG = BigInteger.valueOf(Long.MIN_VALUE);
private static final BigInteger MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE);
public static boolean is_long(Number num) {
if (num instanceof Integer) {
return true;
} else {
return MIN_LONG.compareTo((BigInteger) num) <= 0 &&
((BigInteger) num).compareTo(MAX_LONG) <= 0;
}
}
/******************************************************************/
/* os_http_open_promise/4 */
/******************************************************************/
private static HttpClient client = null;
public static HttpClient getHttpClient() {
if (client == null)
client = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
return client;
}
/**
* os_http_open_promise(P, L, S, Q):
* The predicate succeeds in Q with a promise for open input S
* on path P and option list L.
*/
private static boolean test_os_http_open_promise(Object[] args) {
Object obj = Machine.exec_build(args[0]);
special.check_atom(obj);
String url = (String) obj;
Map opts = (Map) Machine.exec_build(args[1]);
runtime.Source stream = new runtime.Source();
if (!Machine.exec_unify(args[2], stream))
return false;
return Machine.exec_unify(args[3],
open_http_promise(Machine.engine, stream, url, opts));
}
private static Handler.Promise open_http_promise(Machine.Engine en,
runtime.Source stream, String url, Map opts) {
return new Handler.Promise(() -> {
Thread self = Thread.currentThread();
en.abort = self::interrupt;
try {
String method;
HttpRequest.BodyPublisher body;
if (opts.get("method") != null) {
method = opts.get("method").toString();
} else if (opts.get("body") != null) {
method = "POST";
} else {
method = "GET";
}
if (opts.get("body") != null) {
Map opts2 = (Map) opts.get("body");
body = HttpRequest.BodyPublishers.ofString(
opts2.get("text").toString(),
get_encoding(opts2));
} else {
body = HttpRequest.BodyPublishers.noBody();
}
HttpRequest.Builder builder = HttpRequest.newBuilder().method(method, body);
if (opts.get("headers") != null) {
Map headers = (Map) opts.get("headers");
Iterator it = headers.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
builder = builder.header((String)entry.getKey(), entry.getValue().toString());
}
}
HttpClient client = getHttpClient();
HttpResponse<InputStream> response;
try {
response = client.send(builder.uri(URI.create(url)).build(),
HttpResponse.BodyHandlers.ofInputStream());
} catch (IOException err) {
en.signal = map_net_error(err, url);
return;
}
if (200 <= response.statusCode() && response.statusCode() <= 399) {
opts.put("uri", response.uri().toString());
opts.put("status", Integer.valueOf(response.statusCode()));
Map res = new HashMap();
Map<String, List<String>> map = response.headers().map();
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
res.put(entry.getKey(), ((List) entry.getValue()).get(0));
}
opts.put("fields", res);
InputStream ins = response.body();
stream.data = new InputStreamReader(ins, get_encoding(opts));
stream.receive = (BiFunction<Machine.Engine, runtime.Source, Handler.Promise>)
runtime::file_read_promise;
stream.release = (BiFunction<Machine.Engine, runtime.Source, Handler.Promise>)
runtime::file_close_promise;
stream.flags |= runtime.MASK_SRC_AREAD;
} else {
en.signal = map_http_result(response.statusCode(), url);
}
} catch (InterruptedException x) {
/* */
} finally {
en.abort = () -> {};
}
});
}
public static Object map_net_error(IOException err, String url) {
if (err instanceof ConnectException) {
return new Store.Compound("existence_error",
new Object[]{"host", url});
} else if (err instanceof HttpTimeoutException) {
return new Store.Compound("resource_error",
new Object[]{"connect_failed"});
} else {
return new Store.Compound("resource_error",
new Object[]{"remote_error"});
}
}
public static Object map_http_result(int res, String url) {
switch (res) {
case 403: // Forbidden
return new Store.Compound("permission_error",
new Object[]{"open", "source_sink", url});
case 404: // Not Found
return new Store.Compound("existence_error",
new Object[]{"source_sink", url});
case 405: // Method Not Allowed
return new Store.Compound("resource_error",
new Object[]{"illegal_method"});
case 500: // Internal Server Error
return new Store.Compound("resource_error",
new Object[]{"internal_error"});
case 503: // Service Unavailable
return new Store.Compound("resource_error",
new Object[]{"service_unavailable"});
default:
return new Store.Compound("resource_error",
new Object[]{"io_exception"});
}
}
/*******************************************************************/
/* os_http_prop_promise/3 */
/*******************************************************************/
private static final String HTTP_TIME = "%a, %d %b %Y %H:%M:%S GMT";
/**
* os_http_prop_promise(F, M, Q):
* The predicate succeeds in Q with with a promise for the
* properties M of the file F. Barks if path F doesn't exist
* or io exception while resolving.
*/
private static boolean test_os_http_prop_promise(Object[] args) {
Object obj = Machine.exec_build(args[0]);
special.check_atom(obj);
String url = (String) obj;
Map res = new HashMap();
if (!Machine.exec_unify(args[1], res))
return false;
return Machine.exec_unify(args[2],
prop_http_promise(Machine.engine, url, res));
}
public static Handler.Promise prop_http_promise(Machine.Engine en, String url, Map res) {
return new Handler.Promise(() -> {
Thread self = Thread.currentThread();
en.abort = self::interrupt;
try {
HttpRequest.BodyPublisher body = HttpRequest.BodyPublishers.noBody();
String method = "HEAD";
HttpRequest.Builder builder = HttpRequest.newBuilder().method(method, body);
HttpClient client = getHttpClient();
HttpResponse<Void> response;
try {
response = client.send(builder.uri(URI.create(url)).build(),
HttpResponse.BodyHandlers.discarding());
} catch (IOException err) {
en.signal = map_net_error(err, url);
return;
}
if (200 <= response.statusCode() && response.statusCode() <= 399) {
Optional<String> val = response.headers().firstValue("last-modified");
long mtime = (val.isPresent() ? theatre.sys_time_parse(
val.get(), HTTP_TIME, 1) : -1);
res.put("last_modified", special.norm_smallint(mtime));
res.put("absolute_path", response.uri().toString());
res.put("type", "regular");
res.put("can_write", "false");
} else {
if (response.statusCode() != 404)
en.signal = map_http_result(response.statusCode(), url);
}
} catch (InterruptedException x) {
/* */
} finally {
en.abort = () -> {};
}
});
}
/******************************************************************/
/* os_http_open_sync/4 and os_http_cntrl_sync/2 */
/******************************************************************/
/**
* os_http_open_sync(P, M, L, S):
* The predicate succeeds. As a side effect the stream S is
* opened on the path P with the mode M and the option list L.
*/
private static boolean test_os_http_open_sync(Object[] args) {
Object obj = Machine.exec_build(args[0]);
special.check_atom(obj);
String url = (String) obj;
throw Machine.make_error(new Store.Compound("permission_error",
new Object[]{"access", "source_sink", url}));
}
/**
* os_http_cntrl_sync(F, P):
* The predicate assigns the property P to the file F.
*/
private static boolean test_os_http_cntrl_sync(Object[] args) {
Object obj = Machine.exec_build(args[0]);
special.check_atom(obj);
String url = (String) obj;
throw Machine.make_error(new Store.Compound("permission_error",
new Object[]{"access", "source_sink", url}));
}
/******************************************************************/
/* Theatre Init */
/******************************************************************/
public static void boot() {
// system specials, host
Store.set("os_obj_new", 1, special.make_check(theatre::test_os_obj_new));
Store.set("os_obj_current", 3, special.make_check(theatre::test_os_obj_current));
Store.set("os_obj_set", 3, special.make_check(theatre::test_os_obj_set));
Store.set("os_obj_reset", 2, special.make_check(theatre::test_os_obj_reset));
Store.set("os_obj_keys", 2, special.make_check(theatre::test_os_obj_keys));
// system specials, types
Store.set("os_float_value", 2, special.make_check(theatre::test_os_float_value));
Store.set("os_atom_offset", 3, special.make_check(theatre::test_os_atom_offset));
// stream specials, gestalt
Store.set("os_get_gestalt", 1, special.make_check(theatre::test_os_get_gestalt));
Store.set("os_get_host", 1, special.make_check(theatre::test_os_get_host));
Store.set("os_get_workdir", 1, special.make_check(theatre::test_os_get_workdir));
Store.set("os_set_workdir", 1, special.make_check(theatre::test_os_set_workdir));
// stream specials, file
Store.set("os_open_promise", 4, special.make_check(theatre::test_os_open_promise));
Store.set("os_prop_promise", 3, special.make_check(theatre::test_os_prop_promise));
Store.set("os_open_sync", 4, special.make_check(theatre::test_os_open_sync));
Store.set("os_cntrl_sync", 2, special.make_check(theatre::test_os_cntrl_sync));
// stream specials, net
Store.set("os_http_open_promise", 4, special.make_check(theatre::test_os_http_open_promise));
Store.set("os_http_prop_promise", 3, special.make_check(theatre::test_os_http_prop_promise));
Store.set("os_http_open_sync", 4, special.make_check(theatre::test_os_http_open_sync));
Store.set("os_http_cntrl_sync", 2, special.make_check(theatre::test_os_http_cntrl_sync));
}
}