index int64 | repo_id string | file_path string | content string |
|---|---|---|---|
0 | java-sources/ai/swim/swim-java/3.10.0/swim | java-sources/ai/swim/swim-java/3.10.0/swim/java/JavaAgentFactory.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.java;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import swim.api.Lane;
import swim.api.SwimContext;
import swim.api.SwimLane;
import swim.api.SwimResident;
import swim.api.SwimTransient;
import swim.api.agent.AbstractAgentRoute;
import swim.api.agent.Agent;
import swim.api.agent.AgentContext;
import swim.api.agent.AgentException;
import swim.api.http.HttpLane;
import swim.api.lane.CommandLane;
import swim.api.lane.DemandLane;
import swim.api.lane.DemandMapLane;
import swim.api.lane.JoinMapLane;
import swim.api.lane.JoinValueLane;
import swim.api.lane.ListLane;
import swim.api.lane.MapLane;
import swim.api.lane.SpatialLane;
import swim.api.lane.SupplyLane;
import swim.api.lane.ValueLane;
import swim.runtime.http.HttpLaneView;
import swim.runtime.lane.CommandLaneView;
import swim.runtime.lane.DemandLaneView;
import swim.runtime.lane.DemandMapLaneView;
import swim.runtime.lane.JoinMapLaneView;
import swim.runtime.lane.JoinValueLaneView;
import swim.runtime.lane.ListLaneView;
import swim.runtime.lane.MapLaneView;
import swim.runtime.lane.SpatialLaneView;
import swim.runtime.lane.SupplyLaneView;
import swim.runtime.lane.ValueLaneView;
import swim.structure.Form;
import swim.uri.Uri;
public class JavaAgentFactory<A extends Agent> extends AbstractAgentRoute<A> {
protected final JavaAgentDef agentDef;
protected final Class<? extends A> agentClass;
protected final Constructor<? extends A> constructor;
protected JavaAgentFactory(JavaAgentDef agentDef, Class<? extends A> agentClass,
Constructor<? extends A> constructor) {
this.agentDef = agentDef;
this.agentClass = agentClass;
this.constructor = constructor;
}
public JavaAgentFactory(JavaAgentDef agentDef, Class<? extends A> agentClass) {
this(agentDef, agentClass, reflectConstructor(agentClass));
}
public JavaAgentFactory(Class<? extends A> agentClass) {
this(null, agentClass, reflectConstructor(agentClass));
}
public final JavaAgentDef agentDef() {
return this.agentDef;
}
public final Class<? extends A> agentClass() {
return this.agentClass;
}
@Override
public A createAgent(AgentContext agentContext) {
final A agent = constructAgent(agentContext);
reflectLaneFields(this.agentClass, agentContext, agent);
return agent;
}
protected A constructAgent(AgentContext agentContext) {
final Constructor<? extends A> constructor = this.constructor;
final int parameterCount = constructor.getParameterCount();
if (parameterCount == 0) {
return constructAgentWithNoArgs(agentContext, constructor);
} else if (parameterCount == 1) {
return constructAgentWithContext(agentContext, constructor);
} else {
throw new AgentException(constructor.toString());
}
}
A constructAgentWithNoArgs(AgentContext agentContext, Constructor<? extends A> constructor) {
SwimContext.setAgentContext(agentContext);
try {
constructor.setAccessible(true);
return constructor.newInstance();
} catch (ReflectiveOperationException cause) {
throw new AgentException(cause);
} finally {
SwimContext.clear();
}
}
A constructAgentWithContext(AgentContext agentContext, Constructor<? extends A> constructor) {
SwimContext.setAgentContext(agentContext);
try {
constructor.setAccessible(true);
return constructor.newInstance(agentContext);
} catch (ReflectiveOperationException cause) {
throw new AgentException(cause);
} finally {
SwimContext.clear();
}
}
static <A extends Agent> Constructor<? extends A> reflectConstructor(Class<? extends A> agentClass) {
try {
return agentClass.getDeclaredConstructor(AgentContext.class);
} catch (NoSuchMethodException error) {
try {
return agentClass.getDeclaredConstructor();
} catch (NoSuchMethodException cause) {
throw new AgentException(cause);
}
}
}
static void reflectLaneFields(Class<?> agentClass, AgentContext agentContext, Agent agent) {
if (agentClass != null) {
reflectLaneFields(agentClass.getSuperclass(), agentContext, agent);
final Field[] fields = agentClass.getDeclaredFields();
for (Field field : fields) {
if (Lane.class.isAssignableFrom(field.getType())) {
reflectLaneField(field, agentContext, agent);
}
}
}
}
static void reflectLaneField(Field field, AgentContext agentContext, Agent agent) {
final SwimLane swimLane = field.getAnnotation(SwimLane.class);
if (swimLane != null) {
final Lane lane = reflectLaneType(agent, field, field.getGenericType());
final Uri laneUri = Uri.parse(swimLane.value());
agentContext.openLane(laneUri, lane);
}
}
static Lane reflectLaneType(Agent agent, Field field, Type type) {
if (type instanceof ParameterizedType) {
return reflectParameterizedLaneType(agent, field, (ParameterizedType) type);
}
return reflectOtherLaneType(agent, field, type);
}
static Lane reflectParameterizedLaneType(Agent agent, Field field, ParameterizedType type) {
final Type rawType = type.getRawType();
if (rawType instanceof Class<?>) {
return reflectLaneTypeArguments(agent, field, (Class<?>) rawType, type.getActualTypeArguments());
}
return reflectOtherLaneType(agent, field, type);
}
static Lane reflectLaneTypeArguments(Agent agent, Field field, Class<?> type, Type[] arguments) {
if (CommandLane.class.equals(type)) {
return reflectCommandLaneType(agent, field, type, arguments);
} else if (DemandLane.class.equals(type)) {
return reflectDemandLaneType(agent, field, type, arguments);
} else if (DemandMapLane.class.equals(type)) {
return reflectDemandMapLaneType(agent, field, type, arguments);
} else if (JoinMapLane.class.equals(type)) {
return reflectJoinMapLaneType(agent, field, type, arguments);
} else if (JoinValueLane.class.equals(type)) {
return reflectJoinValueLaneType(agent, field, type, arguments);
} else if (ListLane.class.equals(type)) {
return reflectListLaneType(agent, field, type, arguments);
} else if (MapLane.class.equals(type)) {
return reflectMapLaneType(agent, field, type, arguments);
} else if (SpatialLane.class.equals(type)) {
return reflectSpatialLaneType(agent, field, type, arguments);
} else if (SupplyLane.class.equals(type)) {
return reflectSupplyLaneType(agent, field, type, arguments);
} else if (ValueLane.class.equals(type)) {
return reflectValueLaneType(agent, field, type, arguments);
} else if (HttpLane.class.equals(type)) {
return reflectHttpLaneType(agent, field, type, arguments);
}
return reflectOtherLaneType(agent, field, type);
}
@SuppressWarnings("unchecked")
static Lane reflectCommandLaneType(Agent agent, Field field, Class<?> type, Type[] arguments) {
try {
field.setAccessible(true);
Object object = field.get(agent);
if (object == null) {
object = agent.agentContext().commandLane();
field.set(agent, object);
}
if (object instanceof CommandLaneView<?>) {
final CommandLaneView<Object> lane = (CommandLaneView<Object>) object;
Form<Object> valueForm = lane.valueForm();
final Type valueType = arguments[0];
if (valueForm == null && valueType instanceof Class<?>) {
valueForm = Form.forClass((Class<?>) valueType);
lane.setValueForm(valueForm);
}
return lane;
}
return reflectOtherLaneType(agent, field, type);
} catch (IllegalAccessException cause) {
throw new AgentException(cause);
}
}
@SuppressWarnings("unchecked")
static Lane reflectDemandLaneType(Agent agent, Field field, Class<?> type, Type[] arguments) {
try {
field.setAccessible(true);
Object object = field.get(agent);
if (object == null) {
object = agent.agentContext().demandLane();
field.set(agent, object);
}
if (object instanceof DemandLaneView<?>) {
final DemandLaneView<Object> lane = (DemandLaneView<Object>) object;
Form<Object> valueForm = lane.valueForm();
final Type valueType = arguments[0];
if (valueForm == null && valueType instanceof Class<?>) {
valueForm = Form.forClass((Class<?>) valueType);
lane.setValueForm(valueForm);
}
return lane;
}
return reflectOtherLaneType(agent, field, type);
} catch (IllegalAccessException cause) {
throw new AgentException(cause);
}
}
@SuppressWarnings("unchecked")
static Lane reflectDemandMapLaneType(Agent agent, Field field, Class<?> type, Type[] arguments) {
try {
field.setAccessible(true);
Object object = field.get(agent);
if (object == null) {
object = agent.agentContext().demandMapLane();
field.set(agent, object);
}
if (object instanceof DemandMapLaneView<?, ?>) {
final DemandMapLaneView<Object, Object> lane = (DemandMapLaneView<Object, Object>) object;
Form<Object> keyForm = lane.keyForm();
final Type keyType = arguments[0];
if (keyForm == null && keyType instanceof Class<?>) {
keyForm = Form.forClass((Class<?>) keyType);
lane.setKeyForm(keyForm);
}
Form<Object> valueForm = lane.valueForm();
final Type valueType = arguments[1];
if (valueForm == null && valueType instanceof Class<?>) {
valueForm = Form.forClass((Class<?>) valueType);
lane.setValueForm(valueForm);
}
return lane;
}
return reflectOtherLaneType(agent, field, type);
} catch (IllegalAccessException cause) {
throw new AgentException(cause);
}
}
@SuppressWarnings("unchecked")
static Lane reflectJoinMapLaneType(Agent agent, Field field, Class<?> type, Type[] arguments) {
try {
field.setAccessible(true);
Object object = field.get(agent);
if (object == null) {
object = agent.agentContext().joinMapLane();
field.set(agent, object);
}
if (object instanceof JoinMapLaneView<?, ?, ?>) {
final JoinMapLaneView<Object, Object, Object> lane = (JoinMapLaneView<Object, Object, Object>) object;
Form<Object> linkForm = lane.linkForm();
final Type linkType = arguments[0];
if (linkForm == null && linkType instanceof Class<?>) {
linkForm = Form.forClass((Class<?>) linkType);
lane.setLinkForm(linkForm);
}
Form<Object> keyForm = lane.keyForm();
final Type keyType = arguments[1];
if (keyForm == null && keyType instanceof Class<?>) {
keyForm = Form.forClass((Class<?>) keyType);
lane.setKeyForm(keyForm);
}
Form<Object> valueForm = lane.valueForm();
final Type valueType = arguments[2];
if (valueForm == null && valueType instanceof Class<?>) {
valueForm = Form.forClass((Class<?>) valueType);
lane.setValueForm(valueForm);
}
final SwimResident swimResident = field.getAnnotation(SwimResident.class);
if (swimResident != null) {
lane.isResident(swimResident.value());
}
final SwimTransient swimTransient = field.getAnnotation(SwimTransient.class);
if (swimTransient != null) {
lane.isTransient(swimTransient.value());
}
return lane;
}
return reflectOtherLaneType(agent, field, type);
} catch (IllegalAccessException cause) {
throw new AgentException(cause);
}
}
@SuppressWarnings("unchecked")
static Lane reflectJoinValueLaneType(Agent agent, Field field, Class<?> type, Type[] arguments) {
try {
field.setAccessible(true);
Object object = field.get(agent);
if (object == null) {
object = agent.agentContext().joinValueLane();
field.set(agent, object);
}
if (object instanceof JoinValueLaneView<?, ?>) {
final JoinValueLaneView<Object, Object> lane = (JoinValueLaneView<Object, Object>) object;
Form<Object> keyForm = lane.keyForm();
final Type keyType = arguments[0];
if (keyForm == null && keyType instanceof Class<?>) {
keyForm = Form.forClass((Class<?>) keyType);
lane.setKeyForm(keyForm);
}
Form<Object> valueForm = lane.valueForm();
final Type valueType = arguments[1];
if (valueForm == null && valueType instanceof Class<?>) {
valueForm = Form.forClass((Class<?>) valueType);
lane.setValueForm(valueForm);
}
final SwimResident swimResident = field.getAnnotation(SwimResident.class);
if (swimResident != null) {
lane.isResident(swimResident.value());
}
final SwimTransient swimTransient = field.getAnnotation(SwimTransient.class);
if (swimTransient != null) {
lane.isTransient(swimTransient.value());
}
return lane;
}
return reflectOtherLaneType(agent, field, type);
} catch (IllegalAccessException cause) {
throw new AgentException(cause);
}
}
@SuppressWarnings("unchecked")
static Lane reflectListLaneType(Agent agent, Field field, Class<?> type, Type[] arguments) {
try {
field.setAccessible(true);
Object object = field.get(agent);
if (object == null) {
object = agent.agentContext().listLane();
field.set(agent, object);
}
if (object instanceof ListLaneView<?>) {
final ListLaneView<Object> lane = (ListLaneView<Object>) object;
Form<Object> valueForm = lane.valueForm();
final Type valueType = arguments[0];
if (valueForm == null && valueType instanceof Class<?>) {
valueForm = Form.forClass((Class<?>) valueType);
lane.setValueForm(valueForm);
}
final SwimResident swimResident = field.getAnnotation(SwimResident.class);
if (swimResident != null) {
lane.isResident(swimResident.value());
}
final SwimTransient swimTransient = field.getAnnotation(SwimTransient.class);
if (swimTransient != null) {
lane.isTransient(swimTransient.value());
}
return lane;
}
return reflectOtherLaneType(agent, field, type);
} catch (IllegalAccessException cause) {
throw new AgentException(cause);
}
}
@SuppressWarnings("unchecked")
static Lane reflectMapLaneType(Agent agent, Field field, Class<?> type, Type[] arguments) {
try {
field.setAccessible(true);
Object object = field.get(agent);
if (object == null) {
object = agent.agentContext().mapLane();
field.set(agent, object);
}
if (object instanceof MapLaneView<?, ?>) {
final MapLaneView<Object, Object> lane = (MapLaneView<Object, Object>) object;
Form<Object> keyForm = lane.keyForm();
final Type keyType = arguments[0];
if (keyForm == null && keyType instanceof Class<?>) {
keyForm = Form.forClass((Class<?>) keyType);
lane.setKeyForm(keyForm);
}
Form<Object> valueForm = lane.valueForm();
final Type valueType = arguments[1];
if (valueForm == null && valueType instanceof Class<?>) {
valueForm = Form.forClass((Class<?>) valueType);
lane.setValueForm(valueForm);
}
final SwimResident swimResident = field.getAnnotation(SwimResident.class);
if (swimResident != null) {
lane.isResident(swimResident.value());
}
final SwimTransient swimTransient = field.getAnnotation(SwimTransient.class);
if (swimTransient != null) {
lane.isTransient(swimTransient.value());
}
return lane;
}
return reflectOtherLaneType(agent, field, type);
} catch (IllegalAccessException cause) {
throw new AgentException(cause);
}
}
@SuppressWarnings("unchecked")
static Lane reflectSpatialLaneType(Agent agent, Field field, Class<?> type, Type[] arguments) {
try {
field.setAccessible(true);
Object object = field.get(agent);
if (object == null) {
object = agent.agentContext().geospatialLane();
field.set(agent, object);
}
if (object instanceof SpatialLaneView<?, ?, ?>) {
final SpatialLaneView<Object, ?, Object> lane = (SpatialLaneView<Object, ?, Object>) object;
Form<Object> keyForm = lane.keyForm();
final Type keyType = arguments[0];
if (keyForm == null && keyType instanceof Class<?>) {
keyForm = Form.forClass((Class<?>) keyType);
lane.setKeyForm(keyForm);
}
Form<Object> valueForm = lane.valueForm();
final Type valueType = arguments[2];
if (valueForm == null && valueType instanceof Class<?>) {
valueForm = Form.forClass((Class<?>) valueType);
lane.setValueForm(valueForm);
}
final SwimResident swimResident = field.getAnnotation(SwimResident.class);
if (swimResident != null) {
lane.isResident(swimResident.value());
}
final SwimTransient swimTransient = field.getAnnotation(SwimTransient.class);
if (swimTransient != null) {
lane.isTransient(swimTransient.value());
}
return lane;
}
return reflectOtherLaneType(agent, field, type);
} catch (IllegalAccessException cause) {
throw new AgentException(cause);
}
}
@SuppressWarnings("unchecked")
static Lane reflectSupplyLaneType(Agent agent, Field field, Class<?> type, Type[] arguments) {
try {
field.setAccessible(true);
Object object = field.get(agent);
if (object == null) {
object = agent.agentContext().supplyLane();
field.set(agent, object);
}
if (object instanceof SupplyLaneView<?>) {
final SupplyLaneView<Object> lane = (SupplyLaneView<Object>) object;
Form<Object> valueForm = lane.valueForm();
final Type valueType = arguments[0];
if (valueForm == null && valueType instanceof Class<?>) {
valueForm = Form.forClass((Class<?>) valueType);
lane.setValueForm(valueForm);
}
return lane;
}
return reflectOtherLaneType(agent, field, type);
} catch (IllegalAccessException cause) {
throw new AgentException(cause);
}
}
@SuppressWarnings("unchecked")
static Lane reflectValueLaneType(Agent agent, Field field, Class<?> type, Type[] arguments) {
try {
field.setAccessible(true);
Object object = field.get(agent);
if (object == null) {
object = agent.agentContext().valueLane();
field.set(agent, object);
}
if (object instanceof ValueLaneView<?>) {
final ValueLaneView<Object> lane = (ValueLaneView<Object>) object;
Form<Object> valueForm = lane.valueForm();
final Type valueType = arguments[0];
if (valueForm == null && valueType instanceof Class<?>) {
valueForm = Form.forClass((Class<?>) valueType);
lane.setValueForm(valueForm);
}
final SwimResident swimResident = field.getAnnotation(SwimResident.class);
if (swimResident != null) {
lane.isResident(swimResident.value());
}
final SwimTransient swimTransient = field.getAnnotation(SwimTransient.class);
if (swimTransient != null) {
lane.isTransient(swimTransient.value());
}
return lane;
}
return reflectOtherLaneType(agent, field, type);
} catch (IllegalAccessException cause) {
throw new AgentException(cause);
}
}
@SuppressWarnings("unchecked")
static Lane reflectHttpLaneType(Agent agent, Field field, Class<?> type, Type[] arguments) {
try {
field.setAccessible(true);
Object object = field.get(agent);
if (object == null) {
object = agent.agentContext().httpLane();
field.set(agent, object);
}
if (object instanceof HttpLaneView<?>) {
final HttpLaneView<Object> lane = (HttpLaneView<Object>) object;
// TODO: infer request decoder
return lane;
}
return reflectOtherLaneType(agent, field, type);
} catch (IllegalAccessException cause) {
throw new AgentException(cause);
}
}
static Lane reflectOtherLaneType(Agent agent, Field field, Type type) {
try {
field.setAccessible(true);
final Object object = field.get(agent);
if (object instanceof Lane) {
return (Lane) object;
} else {
throw new AgentException("unknown lane type: " + type);
}
} catch (IllegalAccessException cause) {
throw new AgentException(cause);
}
}
}
|
0 | java-sources/ai/swim/swim-java/3.10.0/swim | java-sources/ai/swim/swim-java/3.10.0/swim/java/JavaKernel.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.java;
import swim.api.agent.Agent;
import swim.api.agent.AgentDef;
import swim.api.agent.AgentException;
import swim.api.agent.AgentFactory;
import swim.api.agent.AgentRoute;
import swim.api.plane.Plane;
import swim.api.plane.PlaneDef;
import swim.api.plane.PlaneException;
import swim.api.plane.PlaneFactory;
import swim.kernel.KernelContext;
import swim.kernel.KernelProxy;
import swim.structure.Item;
import swim.structure.Value;
import swim.uri.Uri;
public class JavaKernel extends KernelProxy {
final double kernelPriority;
public JavaKernel(double kernelPriority) {
this.kernelPriority = kernelPriority;
}
public JavaKernel() {
this(KERNEL_PRIORITY);
}
@Override
public final double kernelPriority() {
return this.kernelPriority;
}
@Override
public PlaneDef definePlane(Item planeConfig) {
final PlaneDef planeDef = defineJavaPlane(planeConfig);
return planeDef != null ? planeDef : super.definePlane(planeConfig);
}
public JavaPlaneDef defineJavaPlane(Item planeConfig) {
final Value value = planeConfig.toValue();
final Value header = value.getAttr("plane");
if (header.isDefined()) {
final String planeClassName = header.get("class").stringValue(null);
if (planeClassName != null) {
final String planeName = planeConfig.key().stringValue(planeClassName);
return new JavaPlaneDef(planeName, planeClassName);
}
}
return null;
}
@Override
public PlaneFactory<?> createPlaneFactory(PlaneDef planeDef, ClassLoader classLoader) {
if (planeDef instanceof JavaPlaneDef) {
return createJavaPlaneFactory((JavaPlaneDef) planeDef, classLoader);
} else {
return super.createPlaneFactory(planeDef, classLoader);
}
}
public JavaPlaneFactory<?> createJavaPlaneFactory(JavaPlaneDef planeDef, ClassLoader classLoader) {
final String planeClassName = planeDef.className;
final Class<? extends Plane> planeClass = loadPlaneClass(planeClassName, classLoader);
final KernelContext kernel = kernelWrapper().unwrapKernel(KernelContext.class);
return new JavaPlaneFactory<Plane>(kernel, planeDef, planeClass);
}
@SuppressWarnings("unchecked")
protected Class<? extends Plane> loadPlaneClass(String planeClassName, ClassLoader classLoader) {
if (classLoader == null) {
classLoader = getClass().getClassLoader();
}
try {
return (Class<? extends Plane>) Class.forName(planeClassName, true, classLoader);
} catch (ClassNotFoundException cause) {
throw new PlaneException(cause);
}
}
@Override
public <P extends Plane> PlaneFactory<P> createPlaneFactory(Class<? extends P> planeClass) {
PlaneFactory<P> planeFactory = super.createPlaneFactory(planeClass);
if (planeFactory == null) {
final KernelContext kernel = kernelWrapper().unwrapKernel(KernelContext.class);
planeFactory = new JavaPlaneFactory<P>(kernel, null, planeClass);
}
return planeFactory;
}
@Override
public AgentDef defineAgent(Item agentConfig) {
final AgentDef agentDef = defineJavaAgent(agentConfig);
return agentDef != null ? agentDef : super.defineAgent(agentConfig);
}
public JavaAgentDef defineJavaAgent(Item agentConfig) {
final Value value = agentConfig.toValue();
final Value header = value.getAttr("agent");
if (header.isDefined()) {
final String agentClassName = header.get("class").stringValue(null);
if (agentClassName != null) {
final String agentName = agentConfig.key().stringValue(agentClassName);
final Value props = value.get("props");
return new JavaAgentDef(agentName, agentClassName, props);
}
}
return null;
}
@Override
public AgentFactory<?> createAgentFactory(AgentDef agentDef, ClassLoader classLoader) {
if (agentDef instanceof JavaAgentDef) {
return createJavaAgentFactory((JavaAgentDef) agentDef, classLoader);
} else {
return super.createAgentFactory(agentDef, classLoader);
}
}
@Override
public AgentFactory<?> createAgentFactory(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, AgentDef agentDef) {
if (agentDef instanceof JavaAgentDef) {
return createJavaAgentFactory((JavaAgentDef) agentDef, null);
} else {
return super.createAgentFactory(edgeName, meshUri, partKey, hostUri, nodeUri, agentDef);
}
}
public JavaAgentFactory<?> createJavaAgentFactory(JavaAgentDef agentDef, ClassLoader classLoader) {
final String agentClassName = agentDef.className;
final Class<? extends Agent> agentClass = loadAgentClass(agentClassName, classLoader);
return new JavaAgentFactory<Agent>(agentDef, agentClass);
}
@SuppressWarnings("unchecked")
protected Class<? extends Agent> loadAgentClass(String agentClassName, ClassLoader classLoader) {
if (classLoader == null) {
classLoader = getClass().getClassLoader();
}
try {
return (Class<? extends Agent>) Class.forName(agentClassName, true, classLoader);
} catch (ClassNotFoundException cause) {
throw new AgentException(cause);
}
}
@Override
public <A extends Agent> AgentFactory<A> createAgentFactory(Class<? extends A> agentClass) {
AgentFactory<A> agentFactory = super.createAgentFactory(agentClass);
if (agentFactory == null) {
agentFactory = new JavaAgentFactory<A>(agentClass);
}
return agentFactory;
}
@Override
public <A extends Agent> AgentFactory<A> createAgentFactory(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri,
Class<? extends A> agentClass) {
AgentFactory<A> agentFactory = super.createAgentFactory(edgeName, meshUri, partKey, hostUri, nodeUri, agentClass);
if (agentFactory == null) {
agentFactory = new JavaAgentFactory<A>(agentClass);
}
return agentFactory;
}
@Override
public <A extends Agent> AgentRoute<A> createAgentRoute(String edgeName, Class<? extends A> agentClass) {
AgentRoute<A> agentRoute = super.createAgentRoute(edgeName, agentClass);
if (agentRoute == null) {
agentRoute = new JavaAgentFactory<A>(agentClass);
}
return agentRoute;
}
private static final double KERNEL_PRIORITY = 1.5;
public static JavaKernel fromValue(Value moduleConfig) {
final Value header = moduleConfig.getAttr("kernel");
final String kernelClassName = header.get("class").stringValue(null);
if (kernelClassName == null || JavaKernel.class.getName().equals(kernelClassName)) {
final double kernelPriority = header.get("priority").doubleValue(KERNEL_PRIORITY);
return new JavaKernel(kernelPriority);
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-java/3.10.0/swim | java-sources/ai/swim/swim-java/3.10.0/swim/java/JavaPlaneDef.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.java;
import swim.api.plane.PlaneDef;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.util.Murmur3;
public class JavaPlaneDef implements PlaneDef, Debug {
final String planeName;
final String className;
public JavaPlaneDef(String planeName, String className) {
this.planeName = planeName;
this.className = className;
}
@Override
public final String planeName() {
return this.planeName;
}
public JavaPlaneDef planeName(String planeName) {
return copy(planeName, this.className);
}
public final String className() {
return this.className;
}
public JavaPlaneDef className(String className) {
return copy(this.planeName, className);
}
protected JavaPlaneDef copy(String planeName, String className) {
return new JavaPlaneDef(planeName, className);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof JavaPlaneDef) {
final JavaPlaneDef that = (JavaPlaneDef) other;
return (this.planeName == null ? that.planeName == null : this.planeName.equals(that.planeName))
&& (this.className == null ? that.className == null : this.className.equals(that.className));
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(JavaPlaneDef.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(hashSeed,
Murmur3.hash(this.planeName)), Murmur3.hash(this.className)));
}
@Override
public void debug(Output<?> output) {
output = output.write("JavaPlaneDef").write('.').write("from").write('(')
.debug(this.planeName).write(", ").debug(this.className).write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
public static JavaPlaneDef from(String planeName, String className) {
return new JavaPlaneDef(planeName, className);
}
public static JavaPlaneDef fromClassName(String className) {
return new JavaPlaneDef(className, className);
}
}
|
0 | java-sources/ai/swim/swim-java/3.10.0/swim | java-sources/ai/swim/swim-java/3.10.0/swim/java/JavaPlaneFactory.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.java;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import swim.api.SwimAgent;
import swim.api.SwimContext;
import swim.api.SwimRoute;
import swim.api.agent.Agent;
import swim.api.agent.AgentRoute;
import swim.api.plane.Plane;
import swim.api.plane.PlaneContext;
import swim.api.plane.PlaneException;
import swim.api.plane.PlaneFactory;
import swim.kernel.KernelContext;
import swim.uri.UriPattern;
public class JavaPlaneFactory<P extends Plane> implements PlaneFactory<P> {
protected final KernelContext kernel;
protected final JavaPlaneDef planeDef;
protected final Class<? extends P> planeClass;
public JavaPlaneFactory(KernelContext kernel, JavaPlaneDef planeDef, Class<? extends P> planeClass) {
this.kernel = kernel;
this.planeDef = planeDef;
this.planeClass = planeClass;
}
public final KernelContext kernel() {
return this.kernel;
}
public final JavaPlaneDef planeDef() {
return this.planeDef;
}
public final Class<? extends P> planeClass() {
return this.planeClass;
}
@Override
public P createPlane(PlaneContext planeContext) {
final P plane = constructPlane(planeContext);
reflectAgentRouteFields(planeContext, this.planeClass, plane);
return plane;
}
protected P constructPlane(PlaneContext planeContext) {
try {
return constructPlaneWithContext(planeContext, this.planeClass.getDeclaredConstructor(PlaneContext.class));
} catch (NoSuchMethodException error) {
try {
return constructPlaneWithNoArgs(planeContext, this.planeClass.getDeclaredConstructor());
} catch (NoSuchMethodException cause) {
throw new PlaneException(cause);
}
}
}
P constructPlaneWithContext(PlaneContext planeContext, Constructor<? extends P> constructor) {
SwimContext.setPlaneContext(planeContext);
try {
constructor.setAccessible(true);
return constructor.newInstance(planeContext);
} catch (ReflectiveOperationException cause) {
throw new PlaneException(cause);
} finally {
SwimContext.clear();
}
}
P constructPlaneWithNoArgs(PlaneContext planeContext, Constructor<? extends P> constructor) {
SwimContext.setPlaneContext(planeContext);
try {
constructor.setAccessible(true);
return constructor.newInstance();
} catch (ReflectiveOperationException cause) {
throw new PlaneException(cause);
} finally {
SwimContext.clear();
}
}
protected void reflectAgentRouteFields(PlaneContext planeContext, Class<?> planeClass, P plane) {
if (planeClass != null) {
reflectAgentRouteFields(planeContext, planeClass.getSuperclass(), plane);
final Field[] fields = planeClass.getDeclaredFields();
for (Field field : fields) {
if (AgentRoute.class.isAssignableFrom(field.getType())) {
reflectAgentRouteField(planeContext, plane, field);
}
}
}
}
protected void reflectAgentRouteField(PlaneContext planeContext, P plane, Field field) {
final SwimAgent swimAgent = field.getAnnotation(SwimAgent.class);
final SwimRoute swimRoute = field.getAnnotation(SwimRoute.class);
if (swimAgent != null || swimRoute != null) {
reflectAgentRouteFieldType(planeContext, plane, field, field.getGenericType());
}
}
void reflectAgentRouteFieldType(PlaneContext planeContext, P plane, Field field, Type type) {
if (type instanceof ParameterizedType) {
reflectAgentRouteFieldTypeParameters(planeContext, plane, field, (ParameterizedType) type);
} else {
reflectOtherAgentRouteFieldType(planeContext, plane, field, type);
}
}
void reflectAgentRouteFieldTypeParameters(PlaneContext planeContext, P plane, Field field, ParameterizedType type) {
final Type rawType = type.getRawType();
if (rawType instanceof Class<?>) {
reflectAgentRouteFieldTypeArguments(planeContext, plane, field, (Class<?>) rawType, type.getActualTypeArguments());
} else {
reflectOtherAgentRouteFieldType(planeContext, plane, field, type);
}
}
void reflectAgentRouteFieldTypeArguments(PlaneContext planeContext, P plane, Field field, Class<?> type, Type[] arguments) {
if (AgentRoute.class.equals(type)) {
reflectBaseAgentRouteFieldTypeArgumemnts(planeContext, plane, field, type, arguments);
} else {
reflectOtherAgentRouteFieldType(planeContext, plane, field, type);
}
}
@SuppressWarnings("unchecked")
void reflectBaseAgentRouteFieldTypeArgumemnts(PlaneContext planeContext, P plane, Field field, Class<?> type, Type[] arguments) {
final Type agentType = arguments[0];
if (agentType instanceof Class<?>) {
reflectBaseAgentRouteFieldReifiedType(planeContext, plane, field, type, (Class<? extends Agent>) agentType);
} else {
reflectOtherAgentRouteFieldType(planeContext, plane, field, type);
}
}
void reflectBaseAgentRouteFieldReifiedType(PlaneContext planeContext, P plane, Field field, Class<?> type, Class<? extends Agent> agentClass) {
try {
field.setAccessible(true);
Object object = field.get(plane);
if (object == null) {
object = planeContext.createAgentRoute(agentClass);
field.set(plane, object);
}
if (object instanceof AgentRoute<?>) {
final AgentRoute<?> agentRoute = (AgentRoute<?>) object;
String routeName = null;
SwimAgent swimAgent = field.getAnnotation(SwimAgent.class);
if (swimAgent == null) {
swimAgent = agentClass.getAnnotation(SwimAgent.class);
}
if (swimAgent != null) {
routeName = swimAgent.value();
}
if (routeName == null || routeName.length() == 0) {
routeName = field.getName();
}
UriPattern pattern = null;
SwimRoute swimRoute = field.getAnnotation(SwimRoute.class);
if (swimRoute == null) {
swimRoute = agentClass.getAnnotation(SwimRoute.class);
}
if (swimRoute != null) {
pattern = UriPattern.parse(swimRoute.value());
}
if (pattern != null) {
planeContext.addAgentRoute(routeName, pattern, agentRoute);
} else {
throw new PlaneException("No URI pattern for route: " + routeName);
}
} else {
reflectOtherAgentRouteFieldType(planeContext, plane, field, type);
}
} catch (IllegalAccessException cause) {
throw new PlaneException(cause);
}
}
void reflectOtherAgentRouteFieldType(PlaneContext planeContext, P plane, Field field, Type type) {
try {
field.setAccessible(true);
final Object object = field.get(plane);
if (object instanceof AgentRoute<?>) {
final AgentRoute<?> agentRoute = (AgentRoute<?>) object;
String routeName = null;
final SwimAgent swimAgent = field.getAnnotation(SwimAgent.class);
if (swimAgent != null) {
routeName = swimAgent.value();
}
if (routeName == null || routeName.length() == 0) {
routeName = field.getName();
}
UriPattern pattern = null;
final SwimRoute swimRoute = field.getAnnotation(SwimRoute.class);
if (swimRoute != null) {
pattern = UriPattern.parse(swimRoute.value());
}
if (pattern != null) {
planeContext.addAgentRoute(routeName, pattern, agentRoute);
} else {
throw new PlaneException("No URI pattern for route: " + routeName);
}
} else {
throw new PlaneException("unknown agent route type: " + type);
}
} catch (IllegalAccessException cause) {
throw new PlaneException(cause);
}
}
}
|
0 | java-sources/ai/swim/swim-java/3.10.0/swim | java-sources/ai/swim/swim-java/3.10.0/swim/java/package-info.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* Java kernel runtime.
*/
package swim.java;
|
0 | java-sources/ai/swim/swim-js | java-sources/ai/swim/swim-js/3.10.0/module-info.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* JavaScript kernel runtime.
*/
open module swim.js {
requires swim.json;
requires transitive swim.kernel;
requires swim.dynamic.java;
requires swim.dynamic.structure;
requires swim.dynamic.observable;
requires swim.dynamic.api;
requires transitive swim.vm.js;
exports swim.js;
provides swim.kernel.Kernel with swim.js.JsKernel;
}
|
0 | java-sources/ai/swim/swim-js/3.10.0/swim | java-sources/ai/swim/swim-js/3.10.0/swim/js/JsAgent.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.js;
import swim.api.agent.Agent;
import swim.api.agent.AgentContext;
import swim.dynamic.GuestWrapper;
import swim.vm.js.JsBridge;
import swim.vm.js.JsModule;
public class JsAgent implements Agent, GuestWrapper {
protected final AgentContext agentContext;
protected final JsBridge bridge;
protected final JsModule module;
protected final Object guest;
public JsAgent(AgentContext agentContext, JsBridge bridge,
JsModule module, Object guest) {
this.agentContext = agentContext;
this.bridge = bridge;
this.module = module;
this.guest = guest;
}
@Override
public final AgentContext agentContext() {
return this.agentContext;
}
public final JsBridge bridge() {
return this.bridge;
}
public final JsModule module() {
return this.module;
}
@Override
public final Object unwrap() {
return this.guest;
}
@Override
public void willOpen() {
if (this.bridge.guestCanInvokeMember(this.guest, "willOpen")) {
this.bridge.guestInvokeMember(this.guest, "willOpen");
}
}
@Override
public void didOpen() {
if (this.bridge.guestCanInvokeMember(this.guest, "didOpen")) {
this.bridge.guestInvokeMember(this.guest, "didOpen");
}
}
@Override
public void willLoad() {
if (this.bridge.guestCanInvokeMember(this.guest, "willLoad")) {
this.bridge.guestInvokeMember(this.guest, "willLoad");
}
}
@Override
public void didLoad() {
if (this.bridge.guestCanInvokeMember(this.guest, "didLoad")) {
this.bridge.guestInvokeMember(this.guest, "didLoad");
}
}
@Override
public void willStart() {
if (this.bridge.guestCanInvokeMember(this.guest, "willStart")) {
this.bridge.guestInvokeMember(this.guest, "willStart");
}
}
@Override
public void didStart() {
if (this.bridge.guestCanInvokeMember(this.guest, "didStart")) {
this.bridge.guestInvokeMember(this.guest, "didStart");
}
}
@Override
public void willStop() {
if (this.bridge.guestCanInvokeMember(this.guest, "willStop")) {
this.bridge.guestInvokeMember(this.guest, "willStop");
}
}
@Override
public void didStop() {
if (this.bridge.guestCanInvokeMember(this.guest, "didStop")) {
this.bridge.guestInvokeMember(this.guest, "didStop");
}
}
@Override
public void willUnload() {
if (this.bridge.guestCanInvokeMember(this.guest, "willUnload")) {
this.bridge.guestInvokeMember(this.guest, "willUnload");
}
}
@Override
public void didUnload() {
if (this.bridge.guestCanInvokeMember(this.guest, "didUnload")) {
this.bridge.guestInvokeMember(this.guest, "didUnload");
}
}
@Override
public void willClose() {
if (this.bridge.guestCanInvokeMember(this.guest, "willClose")) {
this.bridge.guestInvokeMember(this.guest, "willClose");
}
}
@Override
public void didClose() {
if (this.bridge.guestCanInvokeMember(this.guest, "didClose")) {
this.bridge.guestInvokeMember(this.guest, "didClose");
}
}
@Override
public void didFail(Throwable error) {
if (this.bridge.guestCanInvokeMember(this.guest, "didFail")) {
this.bridge.guestInvokeMember(this.guest, "didFail", error);
} else {
error.printStackTrace();
}
}
}
|
0 | java-sources/ai/swim/swim-js/3.10.0/swim | java-sources/ai/swim/swim-js/3.10.0/swim/js/JsAgentDef.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.js;
import swim.api.agent.AgentDef;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.structure.Value;
import swim.uri.UriPath;
import swim.util.Murmur3;
public class JsAgentDef implements AgentDef, Debug {
final String agentName;
final UriPath modulePath;
final Value props;
public JsAgentDef(String agentName, UriPath modulePath, Value props) {
this.agentName = agentName;
this.modulePath = modulePath;
this.props = props;
}
@Override
public final String agentName() {
return this.agentName;
}
public JsAgentDef agentName(String agentName) {
return copy(agentName, this.modulePath, this.props);
}
public final UriPath modulePath() {
return this.modulePath;
}
public JsAgentDef modulePath(UriPath modulePath) {
return copy(this.agentName, modulePath, this.props);
}
@Override
public final Value props() {
return this.props;
}
public JsAgentDef props(Value props) {
return copy(this.agentName, this.modulePath, props);
}
protected JsAgentDef copy(String agentName, UriPath modulePath, Value props) {
return new JsAgentDef(agentName, modulePath, props);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof JsAgentDef) {
final JsAgentDef that = (JsAgentDef) other;
return (this.agentName == null ? that.agentName == null : this.agentName.equals(that.agentName))
&& (this.modulePath == null ? that.modulePath == null : this.modulePath.equals(that.modulePath))
&& this.props.equals(that.props);
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(JsAgentDef.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed,
Murmur3.hash(this.agentName)), Murmur3.hash(this.modulePath)), this.props.hashCode()));
}
@Override
public void debug(Output<?> output) {
output = output.write("JsAgentDef").write('.').write("from").write('(')
.debug(this.agentName).write(", ").debug(this.modulePath).write(')');
if (this.props.isDefined()) {
output = output.write('.').write("props").write('(').debug(this.props).write(')');
}
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
public static JsAgentDef from(String agentName, UriPath modulePath) {
return new JsAgentDef(agentName, modulePath, Value.absent());
}
public static JsAgentDef from(String agentName, String modulePath) {
return new JsAgentDef(agentName, UriPath.parse(modulePath), Value.absent());
}
public static JsAgentDef fromModulePath(UriPath modulePath) {
return new JsAgentDef(modulePath.toString(), modulePath, Value.absent());
}
public static JsAgentDef fromModulePath(String modulePath) {
return new JsAgentDef(modulePath, UriPath.parse(modulePath), Value.absent());
}
}
|
0 | java-sources/ai/swim/swim-js/3.10.0/swim | java-sources/ai/swim/swim-js/3.10.0/swim/js/JsAgentFactory.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.js;
import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Value;
import swim.api.agent.AbstractAgentRoute;
import swim.api.agent.AgentContext;
import swim.uri.UriPath;
import swim.vm.js.JsBridge;
import swim.vm.js.JsModule;
import swim.vm.js.JsModuleSystem;
public class JsAgentFactory extends AbstractAgentRoute<JsAgent> {
protected final JsKernel jsKernel;
protected final UriPath basePath;
protected final JsAgentDef agentDef;
public JsAgentFactory(JsKernel jsKernel, UriPath basePath, JsAgentDef agentDef) {
this.jsKernel = jsKernel;
this.basePath = basePath;
this.agentDef = agentDef;
}
public final JsKernel jsKernel() {
return this.jsKernel;
}
public final UriPath basePath() {
return this.basePath;
}
public final JsAgentDef agentDef() {
return this.agentDef;
}
protected Context createAgentJsContext(AgentContext agentContext) {
return Context.newBuilder("js")
.engine(this.jsKernel.jsEngine())
// TODO: .in(...)
// TODO: .out(...)
// TODO: .err(...)
// TODO: .logHandler(...)
// TODO: .fileSystem(...)
// TODO: .processHandler(...)
// TODO: .serverTransport(...)
.build();
}
protected JsBridge createAgentJsBridge(AgentContext agentContext, Context jsContext) {
return new JsBridge(this.jsKernel.jsRuntime(), jsContext);
}
protected JsModuleSystem createAgentModuleSystem(AgentContext agentContext, Context jsContext, JsBridge jsBridge) {
return new JsModuleSystem(jsContext, jsBridge);
}
protected JsModule requireAgentModule(AgentContext agentContext, JsModuleSystem moduleSystem) {
return moduleSystem.requireModule(basePath(), this.agentDef.modulePath());
}
protected Value createGuestAgent(AgentContext agentContext, JsBridge jsBridge, JsModule agentModule) {
final Object guestAgentContext = jsBridge.hostToGuest(agentContext);
final Value agentExports = agentModule.moduleExports();
final Value guestAgent;
if (agentExports.canInstantiate()) {
guestAgent = agentExports.newInstance(guestAgentContext);
} else {
guestAgent = agentExports;
if (guestAgent.hasMembers()) {
guestAgent.putMember("context", guestAgentContext);
}
}
return guestAgent;
}
@Override
public JsAgent createAgent(AgentContext agentContext) {
final Context jsContext = createAgentJsContext(agentContext);
final JsBridge jsBridge = createAgentJsBridge(agentContext, jsContext);
final JsModuleSystem moduleSystem = createAgentModuleSystem(agentContext, jsContext, jsBridge);
final JsModule module = requireAgentModule(agentContext, moduleSystem);
final Value guest = createGuestAgent(agentContext, jsBridge, module);
return new JsAgent(agentContext, jsBridge, module, guest);
}
}
|
0 | java-sources/ai/swim/swim-js/3.10.0/swim | java-sources/ai/swim/swim-js/3.10.0/swim/js/JsKernel.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.js;
import java.io.File;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import org.graalvm.polyglot.Engine;
import swim.api.agent.AgentDef;
import swim.api.agent.AgentFactory;
import swim.api.plane.PlaneDef;
import swim.api.plane.PlaneFactory;
import swim.dynamic.api.SwimApi;
import swim.dynamic.java.JavaBase;
import swim.dynamic.observable.SwimObservable;
import swim.dynamic.structure.SwimStructure;
import swim.kernel.KernelProxy;
import swim.structure.Item;
import swim.structure.Value;
import swim.uri.Uri;
import swim.uri.UriPath;
import swim.vm.js.JsCachedModuleResolver;
import swim.vm.js.JsHostRuntime;
import swim.vm.js.JsModuleResolver;
import swim.vm.js.JsNodeModuleResolver;
import swim.vm.js.JsRuntime;
public class JsKernel extends KernelProxy {
final double kernelPriority;
volatile Engine jsEngine;
volatile JsRuntime jsRuntime;
volatile UriPath rootPath;
public JsKernel(double kernelPriority) {
this.kernelPriority = kernelPriority;
}
public JsKernel() {
this(KERNEL_PRIORITY);
}
@Override
public final double kernelPriority() {
return this.kernelPriority;
}
protected Engine createJsEngine() {
// TODO: configure from moduleConfig
return Engine.newBuilder()
.build();
}
protected JsModuleResolver createJsModuleResolver() {
// TODO: configure module resolution strategy
JsModuleResolver moduleResolver = new JsNodeModuleResolver(rootPath());
// TODO: configure source cache
moduleResolver = new JsCachedModuleResolver(moduleResolver);
return moduleResolver;
}
protected JsRuntime createJsRuntime() {
final JsModuleResolver moduleResolver = createJsModuleResolver();
final JsHostRuntime runtime = new JsHostRuntime(moduleResolver);
runtime.addHostLibrary(JavaBase.LIBRARY);
runtime.addHostLibrary(SwimStructure.LIBRARY);
runtime.addHostModule("@swim/structure", SwimStructure.LIBRARY);
runtime.addHostLibrary(SwimObservable.LIBRARY);
runtime.addHostModule("@swim/observable", SwimObservable.LIBRARY);
runtime.addHostLibrary(SwimApi.LIBRARY);
runtime.addHostModule("@swim/api", SwimApi.LIBRARY);
return runtime;
}
protected UriPath createRootPath() {
return UriPath.parse(new File("").getAbsolutePath().replace('\\', '/'));
}
public final Engine jsEngine() {
Engine jsEngine;
Engine newJsEngine = null;
do {
final Engine oldJsEngine = this.jsEngine;
if (oldJsEngine != null) {
jsEngine = oldJsEngine;
if (newJsEngine != null) {
// Lost creation race.
newJsEngine.close();
newJsEngine = null;
}
} else {
if (newJsEngine == null) {
newJsEngine = createJsEngine();
}
if (JS_ENGINE.compareAndSet(this, oldJsEngine, newJsEngine)) {
jsEngine = newJsEngine;
} else {
continue;
}
}
break;
} while (true);
return jsEngine;
}
public final JsRuntime jsRuntime() {
JsRuntime jsRuntime;
JsRuntime newJsRuntime = null;
do {
final JsRuntime oldJsRuntime = this.jsRuntime;
if (oldJsRuntime != null) {
jsRuntime = oldJsRuntime;
if (newJsRuntime != null) {
// Lost creation race.
newJsRuntime = null;
}
} else {
if (newJsRuntime == null) {
newJsRuntime = createJsRuntime();
}
if (JS_RUNTIME.compareAndSet(this, oldJsRuntime, newJsRuntime)) {
jsRuntime = newJsRuntime;
} else {
continue;
}
}
break;
} while (true);
return jsRuntime;
}
public final UriPath rootPath() {
UriPath rootPath;
UriPath newRootPath = null;
do {
final UriPath oldRootPath = this.rootPath;
if (oldRootPath != null) {
rootPath = oldRootPath;
if (newRootPath != null) {
// Lost creation race.
newRootPath = null;
}
} else {
if (newRootPath == null) {
newRootPath = createRootPath();
}
if (ROOT_PATH.compareAndSet(this, oldRootPath, newRootPath)) {
rootPath = newRootPath;
} else {
continue;
}
}
break;
} while (true);
return rootPath;
}
public void setRootPath(UriPath rootPath) {
ROOT_PATH.set(this, rootPath);
}
@Override
public PlaneDef definePlane(Item planeConfig) {
final PlaneDef planeDef = defineJsPlane(planeConfig);
return planeDef != null ? planeDef : super.definePlane(planeConfig);
}
public JsPlaneDef defineJsPlane(Item planeConfig) {
final Value value = planeConfig.toValue();
final Value header = value.getAttr("plane");
if (header.isDefined()) {
final UriPath planeModulePath = header.get("js").cast(UriPath.pathForm());
if (planeModulePath != null) {
final String planeName = planeConfig.key().stringValue(planeModulePath.toString());
return new JsPlaneDef(planeName, planeModulePath);
}
}
return null;
}
@Override
public PlaneFactory<?> createPlaneFactory(PlaneDef planeDef, ClassLoader classLoader) {
if (planeDef instanceof JsPlaneDef) {
return createJsPlaneFactory((JsPlaneDef) planeDef);
} else {
return super.createPlaneFactory(planeDef, classLoader);
}
}
public JsPlaneFactory createJsPlaneFactory(JsPlaneDef planeDef) {
return new JsPlaneFactory(this, rootPath(), planeDef);
}
@Override
public AgentDef defineAgent(Item agentConfig) {
final AgentDef agentDef = defineJsAgent(agentConfig);
return agentDef != null ? agentDef : super.defineAgent(agentConfig);
}
public JsAgentDef defineJsAgent(Item agentConfig) {
final Value value = agentConfig.toValue();
final Value header = value.getAttr("agent");
if (header.isDefined()) {
final UriPath agentModulePath = header.get("js").cast(UriPath.pathForm());
if (agentModulePath != null) {
final String agentName = agentConfig.key().stringValue(agentModulePath.toString());
final Value props = value.get("props");
return new JsAgentDef(agentName, agentModulePath, props);
}
}
return null;
}
@Override
public AgentFactory<?> createAgentFactory(AgentDef agentDef, ClassLoader classLoader) {
if (agentDef instanceof JsAgentDef) {
return createJsAgentFactory((JsAgentDef) agentDef);
} else {
return super.createAgentFactory(agentDef, classLoader);
}
}
@Override
public AgentFactory<?> createAgentFactory(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, AgentDef agentDef) {
if (agentDef instanceof JsAgentDef) {
return createJsAgentFactory((JsAgentDef) agentDef);
} else {
return super.createAgentFactory(edgeName, meshUri, partKey, hostUri, nodeUri, agentDef);
}
}
public JsAgentFactory createJsAgentFactory(JsAgentDef agentDef) {
return new JsAgentFactory(this, rootPath(), agentDef);
}
private static final double KERNEL_PRIORITY = 1.75;
public static JsKernel fromValue(Value moduleConfig) {
final Value header = moduleConfig.getAttr("kernel");
final String kernelClassName = header.get("class").stringValue(null);
if (kernelClassName == null || JsKernel.class.getName().equals(kernelClassName)) {
final double kernelPriority = header.get("priority").doubleValue(KERNEL_PRIORITY);
return new JsKernel(kernelPriority);
}
return null;
}
static final AtomicReferenceFieldUpdater<JsKernel, Engine> JS_ENGINE =
AtomicReferenceFieldUpdater.newUpdater(JsKernel.class, Engine.class, "jsEngine");
static final AtomicReferenceFieldUpdater<JsKernel, JsRuntime> JS_RUNTIME =
AtomicReferenceFieldUpdater.newUpdater(JsKernel.class, JsRuntime.class, "jsRuntime");
static final AtomicReferenceFieldUpdater<JsKernel, UriPath> ROOT_PATH =
AtomicReferenceFieldUpdater.newUpdater(JsKernel.class, UriPath.class, "rootPath");
}
|
0 | java-sources/ai/swim/swim-js/3.10.0/swim | java-sources/ai/swim/swim-js/3.10.0/swim/js/JsPlane.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.js;
import swim.api.plane.Plane;
import swim.api.plane.PlaneContext;
import swim.dynamic.GuestWrapper;
import swim.vm.js.JsBridge;
import swim.vm.js.JsModule;
public class JsPlane implements Plane, GuestWrapper {
protected final PlaneContext planeContext;
protected final JsBridge bridge;
protected final JsModule module;
protected final Object guest;
public JsPlane(PlaneContext planeContext, JsBridge bridge,
JsModule module, Object guest) {
this.planeContext = planeContext;
this.bridge = bridge;
this.module = module;
this.guest = guest;
}
@Override
public final PlaneContext planeContext() {
return this.planeContext;
}
public final JsBridge bridge() {
return this.bridge;
}
public final JsModule module() {
return this.module;
}
@Override
public final Object unwrap() {
return this.guest;
}
@Override
public void willStart() {
if (this.bridge.guestCanInvokeMember(this.guest, "willStart")) {
this.bridge.guestInvokeMember(this.guest, "willStart");
}
}
@Override
public void didStart() {
if (this.bridge.guestCanInvokeMember(this.guest, "didStart")) {
this.bridge.guestInvokeMember(this.guest, "didStart");
}
}
@Override
public void willStop() {
if (this.bridge.guestCanInvokeMember(this.guest, "willStop")) {
this.bridge.guestInvokeMember(this.guest, "willStop");
}
}
@Override
public void didStop() {
if (this.bridge.guestCanInvokeMember(this.guest, "didStop")) {
this.bridge.guestInvokeMember(this.guest, "didStop");
}
}
@Override
public void willClose() {
if (this.bridge.guestCanInvokeMember(this.guest, "willClose")) {
this.bridge.guestInvokeMember(this.guest, "willClose");
}
}
@Override
public void didClose() {
if (this.bridge.guestCanInvokeMember(this.guest, "didClose")) {
this.bridge.guestInvokeMember(this.guest, "didClose");
}
}
@Override
public void didFail(Throwable error) {
if (this.bridge.guestCanInvokeMember(this.guest, "didFail")) {
this.bridge.guestInvokeMember(this.guest, "didFail", error);
} else {
error.printStackTrace();
}
}
}
|
0 | java-sources/ai/swim/swim-js/3.10.0/swim | java-sources/ai/swim/swim-js/3.10.0/swim/js/JsPlaneDef.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.js;
import swim.api.plane.PlaneDef;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.uri.UriPath;
import swim.util.Murmur3;
public class JsPlaneDef implements PlaneDef, Debug {
final String planeName;
final UriPath modulePath;
public JsPlaneDef(String planeName, UriPath modulePath) {
this.planeName = planeName;
this.modulePath = modulePath;
}
@Override
public final String planeName() {
return this.planeName;
}
public JsPlaneDef planeName(String planeName) {
return copy(planeName, this.modulePath);
}
public final UriPath modulePath() {
return this.modulePath;
}
public JsPlaneDef modulePath(UriPath modulePath) {
return copy(this.planeName, modulePath);
}
protected JsPlaneDef copy(String planeName, UriPath modulePath) {
return new JsPlaneDef(planeName, modulePath);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof JsPlaneDef) {
final JsPlaneDef that = (JsPlaneDef) other;
return (this.planeName == null ? that.planeName == null : this.planeName.equals(that.planeName))
&& (this.modulePath == null ? that.modulePath == null : this.modulePath.equals(that.modulePath));
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(JsPlaneDef.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(hashSeed,
Murmur3.hash(this.planeName)), Murmur3.hash(this.modulePath)));
}
@Override
public void debug(Output<?> output) {
output = output.write("JsPlaneDef").write('.').write("from").write('(')
.debug(this.planeName).write(", ").debug(this.modulePath).write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
public static JsPlaneDef from(String planeName, UriPath modulePath) {
return new JsPlaneDef(planeName, modulePath);
}
public static JsPlaneDef from(String planeName, String modulePath) {
return new JsPlaneDef(planeName, UriPath.parse(modulePath));
}
public static JsPlaneDef fromModulePath(UriPath modulePath) {
return new JsPlaneDef(modulePath.toString(), modulePath);
}
public static JsPlaneDef fromModulePath(String modulePath) {
return new JsPlaneDef(modulePath, UriPath.parse(modulePath));
}
}
|
0 | java-sources/ai/swim/swim-js/3.10.0/swim | java-sources/ai/swim/swim-js/3.10.0/swim/js/JsPlaneFactory.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.js;
import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Value;
import swim.api.plane.PlaneContext;
import swim.api.plane.PlaneFactory;
import swim.uri.UriPath;
import swim.vm.js.JsBridge;
import swim.vm.js.JsModule;
import swim.vm.js.JsModuleSystem;
public class JsPlaneFactory implements PlaneFactory<JsPlane> {
protected final JsKernel jsKernel;
protected final UriPath basePath;
protected final JsPlaneDef planeDef;
public JsPlaneFactory(JsKernel jsKernel, UriPath basePath, JsPlaneDef planeDef) {
this.jsKernel = jsKernel;
this.basePath = basePath;
this.planeDef = planeDef;
}
public final JsKernel jsKernel() {
return this.jsKernel;
}
public final UriPath basePath() {
return this.basePath;
}
public final JsPlaneDef planeDef() {
return this.planeDef;
}
protected Context createPlaneJsContext(PlaneContext planeContext) {
return Context.newBuilder("js")
.engine(this.jsKernel.jsEngine())
// TODO: .in(...)
// TODO: .out(...)
// TODO: .err(...)
// TODO: .logHandler(...)
// TODO: .fileSystem(...)
// TODO: .processHandler(...)
// TODO: .serverTransport(...)
.build();
}
protected JsBridge createPlaneJsBridge(PlaneContext planeContext, Context jsContext) {
return new JsBridge(this.jsKernel.jsRuntime(), jsContext);
}
protected JsModuleSystem createPlaneModuleSystem(PlaneContext planeContext, Context jsContext, JsBridge jsBridge) {
return new JsModuleSystem(jsContext, jsBridge);
}
protected JsModule requirePlaneModule(PlaneContext planeContext, JsModuleSystem moduleSystem) {
return moduleSystem.requireModule(basePath(), this.planeDef.modulePath());
}
protected Value createGuestPlane(PlaneContext planeContext, JsBridge jsBridge, JsModule planeModule) {
final Object guestPlaneContext = jsBridge.hostToGuest(planeContext);
final Value planeExports = planeModule.moduleExports();
final Value guestPlane;
if (planeExports.canInstantiate()) {
guestPlane = planeExports.newInstance(guestPlaneContext);
} else {
guestPlane = planeExports;
if (guestPlane.hasMembers()) {
guestPlane.putMember("context", guestPlaneContext);
}
}
return guestPlane;
}
@Override
public JsPlane createPlane(PlaneContext planeContext) {
final Context jsContext = createPlaneJsContext(planeContext);
final JsBridge jsBridge = createPlaneJsBridge(planeContext, jsContext);
final JsModuleSystem moduleSystem = createPlaneModuleSystem(planeContext, jsContext, jsBridge);
final JsModule module = requirePlaneModule(planeContext, moduleSystem);
final Value guest = createGuestPlane(planeContext, jsBridge, module);
return new JsPlane(planeContext, jsBridge, module, guest);
}
}
|
0 | java-sources/ai/swim/swim-js/3.10.0/swim | java-sources/ai/swim/swim-js/3.10.0/swim/js/package-info.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* JavaScript kernel runtime.
*/
package swim.js;
|
0 | java-sources/ai/swim/swim-json | java-sources/ai/swim/swim-json/3.10.0/module-info.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* JavaScript Object Notation (JSON) codec.
*/
module swim.json {
requires swim.util;
requires transitive swim.codec;
requires transitive swim.structure;
exports swim.json;
}
|
0 | java-sources/ai/swim/swim-json/3.10.0/swim | java-sources/ai/swim/swim-json/3.10.0/swim/json/ArrayParser.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.json;
import swim.codec.Diagnostic;
import swim.codec.Input;
import swim.codec.Parser;
import swim.util.Builder;
final class ArrayParser<I, V> extends Parser<V> {
final JsonParser<I, V> json;
final Builder<I, V> builder;
final Parser<V> valueParser;
final int step;
ArrayParser(JsonParser<I, V> json, Builder<I, V> builder, Parser<V> valueParser, int step) {
this.json = json;
this.builder = builder;
this.valueParser = valueParser;
this.step = step;
}
ArrayParser(JsonParser<I, V> json) {
this(json, null, null, 1);
}
@Override
public Parser<V> feed(Input input) {
return parse(input, this.json, this.builder, this.valueParser, this.step);
}
static <I, V> Parser<V> parse(Input input, JsonParser<I, V> json, Builder<I, V> builder,
Parser<V> valueParser, int step) {
int c = 0;
if (step == 1) {
while (input.isCont()) {
c = input.head();
if (Json.isWhitespace(c)) {
input = input.step();
} else {
break;
}
}
if (input.isCont()) {
if (c == '[') {
input = input.step();
step = 2;
} else {
return error(Diagnostic.expected('[', input));
}
} else if (input.isDone()) {
return error(Diagnostic.expected('[', input));
}
}
if (step == 2) {
while (input.isCont()) {
c = input.head();
if (Json.isWhitespace(c)) {
input = input.step();
} else {
break;
}
}
if (input.isCont()) {
if (builder == null) {
builder = json.arrayBuilder();
}
if (c == ']') {
input = input.step();
return done(builder.bind());
} else {
step = 3;
}
} else if (input.isDone()) {
return error(Diagnostic.expected(']', input));
}
}
while (step >= 3 && !input.isEmpty()) {
if (step == 3) {
if (valueParser == null) {
valueParser = json.parseValue(input);
}
while (valueParser.isCont() && !input.isEmpty()) {
valueParser = valueParser.feed(input);
}
if (valueParser.isDone()) {
builder.add(json.item(valueParser.bind()));
valueParser = null;
step = 4;
} else if (valueParser.isError()) {
return valueParser;
} else {
break;
}
}
if (step == 4) {
while (input.isCont()) {
c = input.head();
if (Json.isWhitespace(c)) {
input = input.step();
} else {
break;
}
}
if (input.isCont()) {
if (c == ',') {
input = input.step();
step = 3;
} else if (c == ']') {
input = input.step();
return done(builder.bind());
} else {
return error(Diagnostic.expected("',' or ']'", input));
}
} else if (input.isDone()) {
return error(Diagnostic.expected(']', input));
} else {
break;
}
}
}
if (input.isError()) {
return error(input.trap());
}
return new ArrayParser<I, V>(json, builder, valueParser, step);
}
static <I, V> Parser<V> parse(Input input, JsonParser<I, V> json) {
return parse(input, json, null, null, 1);
}
}
|
0 | java-sources/ai/swim/swim-json/3.10.0/swim | java-sources/ai/swim/swim-json/3.10.0/swim/json/ArrayWriter.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.json;
import java.util.Iterator;
import swim.codec.Output;
import swim.codec.Writer;
import swim.codec.WriterException;
final class ArrayWriter<I, V> extends Writer<Object, Object> {
final JsonWriter<I, V> json;
final Iterator<I> items;
final Writer<?, ?> part;
final int index;
final int step;
ArrayWriter(JsonWriter<I, V> json, Iterator<I> items, Writer<?, ?> part, int index, int step) {
this.json = json;
this.items = items;
this.part = part;
this.index = index;
this.step = step;
}
@Override
public Writer<Object, Object> pull(Output<?> output) {
return write(output, this.json, this.items, this.part, this.index, this.step);
}
static <I, V> Writer<Object, Object> write(Output<?> output, JsonWriter<I, V> json, Iterator<I> items,
Writer<?, ?> part, int index, int step) {
if (step == 1 && output.isCont()) {
output = output.write('[');
step = 2;
}
do {
if (step == 2) {
if (part == null) {
if (items.hasNext()) {
part = json.writeValue(items.next(), output, index);
} else {
step = 4;
break;
}
} else {
part = part.pull(output);
}
if (part.isDone()) {
part = null;
index += 1;
if (items.hasNext()) {
step = 3;
} else {
step = 4;
break;
}
} else if (part.isError()) {
return part.asError();
} else {
break;
}
}
if (step == 3 && output.isCont()) {
output = output.write(',');
step = 2;
continue;
}
} while (step == 2);
if (step == 4 && output.isCont()) {
output = output.write(']');
return done();
}
if (output.isDone()) {
return error(new WriterException("truncated"));
} else if (output.isError()) {
return error(output.trap());
}
return new ArrayWriter<I, V>(json, items, part, index, step);
}
static <I, V> Writer<Object, Object> write(Output<?> output, JsonWriter<I, V> json, Iterator<I> items) {
return write(output, json, items, null, 0, 1);
}
}
|
0 | java-sources/ai/swim/swim-json/3.10.0/swim | java-sources/ai/swim/swim-json/3.10.0/swim/json/DataWriter.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.json;
import java.nio.ByteBuffer;
import swim.codec.Base64;
import swim.codec.Output;
import swim.codec.Writer;
import swim.codec.WriterException;
final class DataWriter extends Writer<Object, Object> {
final ByteBuffer buffer;
final Writer<?, ?> part;
final int step;
DataWriter(ByteBuffer buffer, Writer<?, ?> part, int step) {
this.buffer = buffer;
this.part = part;
this.step = step;
}
@Override
public Writer<Object, Object> pull(Output<?> output) {
return write(output, this.buffer, this.part, this.step);
}
static Writer<Object, Object> write(Output<?> output, ByteBuffer buffer,
Writer<?, ?> part, int step) {
if (step == 1 && output.isCont()) {
output = output.write('"');
step = 2;
}
if (step == 2) {
if (part == null) {
part = Base64.standard().writeByteBuffer(buffer, output);
} else {
part = part.pull(output);
}
if (part.isDone()) {
part = null;
step = 3;
} else if (part.isError()) {
return part.asError();
}
}
if (step == 3 && output.isCont()) {
output = output.write('"');
return done();
}
if (output.isDone()) {
return error(new WriterException("truncated"));
} else if (output.isError()) {
return error(output.trap());
}
return new DataWriter(buffer, part, step);
}
static Writer<Object, Object> write(Output<?> output, ByteBuffer buffer) {
return write(output, buffer, null, 1);
}
}
|
0 | java-sources/ai/swim/swim-json/3.10.0/swim | java-sources/ai/swim/swim-json/3.10.0/swim/json/FieldWriter.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.json;
import swim.codec.Output;
import swim.codec.Writer;
import swim.codec.WriterException;
final class FieldWriter<I, V> extends Writer<Object, Object> {
final JsonWriter<I, V> json;
final V key;
final V value;
final Writer<?, ?> part;
final int step;
FieldWriter(JsonWriter<I, V> json, V key, V value, Writer<?, ?> part, int step) {
this.json = json;
this.key = key;
this.value = value;
this.part = part;
this.step = step;
}
@Override
public Writer<Object, Object> pull(Output<?> output) {
return write(output, this.json, this.key, this.value, this.part, this.step);
}
static <I, V> Writer<Object, Object> write(Output<?> output, JsonWriter<I, V> json,
V key, V value, Writer<?, ?> part, int step) {
if (step == 1) {
if (part == null) {
part = json.writeValue(key, output);
} else {
part = part.pull(output);
}
if (part.isDone()) {
part = null;
step = 2;
} else if (part.isError()) {
return part.asError();
}
}
if (step == 2 && output.isCont()) {
output = output.write(':');
step = 3;
}
if (step == 3) {
if (part == null) {
part = json.writeValue(value, output);
} else {
part = part.pull(output);
}
if (part.isDone()) {
return done();
} else if (part.isError()) {
return part.asError();
}
}
if (output.isDone()) {
return error(new WriterException("truncated"));
} else if (output.isError()) {
return error(output.trap());
}
return new FieldWriter<I, V>(json, key, value, part, step);
}
static <I, V> Writer<Object, Object> write(Output<?> output, JsonWriter<I, V> json,
V key, V value) {
return write(output, json, key, value, null, 1);
}
}
|
0 | java-sources/ai/swim/swim-json/3.10.0/swim | java-sources/ai/swim/swim-json/3.10.0/swim/json/IdentParser.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.json;
import swim.codec.Diagnostic;
import swim.codec.Input;
import swim.codec.Output;
import swim.codec.Parser;
final class IdentParser<I, V> extends Parser<V> {
final JsonParser<I, V> json;
final Output<V> output;
final int step;
IdentParser(JsonParser<I, V> json, Output<V> output, int step) {
this.json = json;
this.output = output;
this.step = step;
}
@Override
public Parser<V> feed(Input input) {
return parse(input, this.json, this.output, this.step);
}
static <I, V> Parser<V> parse(Input input, JsonParser<I, V> json, Output<V> output, int step) {
int c = 0;
if (step == 1) {
if (input.isCont()) {
c = input.head();
if (Json.isIdentStartChar(c)) {
input = input.step();
if (output == null) {
output = json.textOutput();
}
output = output.write(c);
step = 2;
} else {
return error(Diagnostic.expected("identifier", input));
}
} else if (input.isDone()) {
return error(Diagnostic.expected("identifier", input));
}
}
if (step == 2) {
while (input.isCont()) {
c = input.head();
if (Json.isIdentChar(c)) {
input = input.step();
output = output.write(c);
} else {
break;
}
}
if (!input.isEmpty()) {
return done(json.ident(output.bind()));
}
}
if (input.isError()) {
return error(input.trap());
}
return new IdentParser<I, V>(json, output, step);
}
static <I, V> Parser<V> parse(Input input, JsonParser<I, V> json, Output<V> output) {
return parse(input, json, output, 1);
}
static <I, V> Parser<V> parse(Input input, JsonParser<I, V> json) {
return parse(input, json, null, 1);
}
}
|
0 | java-sources/ai/swim/swim-json/3.10.0/swim | java-sources/ai/swim/swim-json/3.10.0/swim/json/Json.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.json;
import swim.codec.Decoder;
import swim.codec.Encoder;
import swim.codec.Output;
import swim.codec.Parser;
import swim.codec.Unicode;
import swim.codec.Utf8;
import swim.codec.Writer;
import swim.structure.Data;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Value;
/**
* Factory for constructing JSON parsers and writers.
*/
public final class Json {
private Json() {
// stub
}
static boolean isSpace(int c) {
return c == 0x20 || c == 0x9;
}
static boolean isNewline(int c) {
return c == 0xa || c == 0xd;
}
static boolean isWhitespace(int c) {
return isSpace(c) || isNewline(c);
}
static boolean isIdentStartChar(int c) {
return c >= 'A' && c <= 'Z'
|| c == '_'
|| c >= 'a' && c <= 'z'
|| c >= 0xc0 && c <= 0xd6
|| c >= 0xd8 && c <= 0xf6
|| c >= 0xf8 && c <= 0x2ff
|| c >= 0x370 && c <= 0x37d
|| c >= 0x37f && c <= 0x1fff
|| c >= 0x200c && c <= 0x200d
|| c >= 0x2070 && c <= 0x218f
|| c >= 0x2c00 && c <= 0x2fef
|| c >= 0x3001 && c <= 0xd7ff
|| c >= 0xf900 && c <= 0xfdcf
|| c >= 0xfdf0 && c <= 0xfffd
|| c >= 0x10000 && c <= 0xeffff;
}
static boolean isIdentChar(int c) {
return c == '-'
|| c >= '0' && c <= '9'
|| c >= 'A' && c <= 'Z'
|| c == '_'
|| c >= 'a' && c <= 'z'
|| c == 0xb7
|| c >= 0xc0 && c <= 0xd6
|| c >= 0xd8 && c <= 0xf6
|| c >= 0xf8 && c <= 0x37d
|| c >= 0x37f && c <= 0x1fff
|| c >= 0x200c && c <= 0x200d
|| c >= 0x203f && c <= 0x2040
|| c >= 0x2070 && c <= 0x218f
|| c >= 0x2c00 && c <= 0x2fef
|| c >= 0x3001 && c <= 0xd7ff
|| c >= 0xf900 && c <= 0xfdcf
|| c >= 0xfdf0 && c <= 0xfffd
|| c >= 0x10000 && c <= 0xeffff;
}
private static JsonParser<Item, Value> structureParser;
private static JsonWriter<Item, Value> structureWriter;
public static JsonParser<Item, Value> structureParser() {
if (structureParser == null) {
structureParser = new JsonStructureParser();
}
return structureParser;
}
public static JsonWriter<Item, Value> structureWriter() {
if (structureWriter == null) {
structureWriter = new JsonStructureWriter();
}
return structureWriter;
}
public static Value parse(String json) {
return structureParser().parseValueString(json);
}
public static Parser<Value> parser() {
return structureParser().valueParser();
}
public static Writer<?, ?> write(Item item, Output<?> output) {
return structureWriter().writeItem(item, output);
}
public static String toString(Item item) {
final Output<String> output = Unicode.stringOutput();
write(item, output);
return output.bind();
}
public static Data toData(Item item) {
final Output<Data> output = Utf8.encodedOutput(Data.output());
write(item, output);
return output.bind();
}
public static <T> Parser<T> formParser(Form<T> form) {
return new JsonFormParser<T>(structureParser(), form);
}
public static <T> Decoder<T> formDecoder(Form<T> form) {
return Utf8.decodedParser(formParser(form));
}
public static <T> Writer<T, T> formWriter(Form<T> form) {
return new JsonFormWriter<T>(structureWriter(), form);
}
public static <T> Encoder<T, T> formEncoder(Form<T> form) {
return Utf8.encodedWriter(formWriter(form));
}
}
|
0 | java-sources/ai/swim/swim-json/3.10.0/swim | java-sources/ai/swim/swim-json/3.10.0/swim/json/JsonFormParser.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.json;
import swim.codec.Input;
import swim.codec.Parser;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Value;
final class JsonFormParser<T> extends Parser<T> {
final JsonParser<Item, Value> json;
final Form<T> form;
final Parser<Value> parser;
JsonFormParser(JsonParser<Item, Value> json, Form<T> form, Parser<Value> parser) {
this.json = json;
this.form = form;
this.parser = parser;
}
JsonFormParser(JsonParser<Item, Value> json, Form<T> form) {
this(json, form, null);
}
@Override
public Parser<T> feed(Input input) {
return parse(input, this.json, this.form, this.parser);
}
static <T> Parser<T> parse(Input input, JsonParser<Item, Value> json,
Form<T> form, Parser<Value> parser) {
if (parser == null) {
parser = json.parseValue(input);
} else {
parser = parser.feed(input);
}
if (parser.isDone()) {
final Value value = parser.bind();
return done(form.cast(value));
} else if (parser.isError()) {
return parser.asError();
}
return new JsonFormParser<T>(json, form, parser);
}
static <T> Parser<T> parse(Input input, JsonParser<Item, Value> json, Form<T> form) {
return parse(input, json, form, null);
}
}
|
0 | java-sources/ai/swim/swim-json/3.10.0/swim | java-sources/ai/swim/swim-json/3.10.0/swim/json/JsonFormWriter.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.json;
import swim.codec.Output;
import swim.codec.Writer;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Value;
final class JsonFormWriter<T> extends Writer<T, T> {
final JsonWriter<Item, Value> json;
final Form<T> form;
final T object;
final Writer<?, ?> part;
JsonFormWriter(JsonWriter<Item, Value> json, Form<T> form, T object, Writer<?, ?> part) {
this.json = json;
this.form = form;
this.object = object;
this.part = part;
}
JsonFormWriter(JsonWriter<Item, Value> json, Form<T> form) {
this(json, form, null, null);
}
@Override
public Writer<T, T> feed(T object) {
return new JsonFormWriter<T>(json, form, object, null);
}
@Override
public Writer<T, T> pull(Output<?> output) {
return write(output, this.json, this.form, this.object, this.part);
}
static <T> Writer<T, T> write(Output<?> output, JsonWriter<Item, Value> json,
Form<T> form, T object, Writer<?, ?> part) {
if (output == null) {
return done();
}
if (part == null) {
final Value value = form.mold(object).toValue();
part = json.writeValue(value, output);
} else {
part = part.pull(output);
}
if (part.isDone()) {
return done(object);
} else if (part.isError()) {
return part.asError();
}
return new JsonFormWriter<T>(json, form, object, part);
}
static <T> Writer<T, T> write(Output<T> output, JsonWriter<Item, Value> json,
Form<T> form, T object) {
return write(output, json, form, object, null);
}
}
|
0 | java-sources/ai/swim/swim-json/3.10.0/swim | java-sources/ai/swim/swim-json/3.10.0/swim/json/JsonParser.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.json;
import java.math.BigInteger;
import swim.codec.Diagnostic;
import swim.codec.Input;
import swim.codec.Output;
import swim.codec.Parser;
import swim.codec.Unicode;
import swim.util.Builder;
/**
* Factory for constructing JSON parsers and parse trees.
*/
public abstract class JsonParser<I, V> {
public abstract I item(V value);
public abstract V value(I item);
public abstract I field(V key, V value);
public abstract Builder<I, V> objectBuilder();
public abstract Builder<I, V> arrayBuilder();
public abstract Output<V> textOutput();
public abstract V ident(V value);
public abstract V num(int value);
public abstract V num(long value);
public abstract V num(float value);
public abstract V num(double value);
public abstract V num(BigInteger value);
public abstract V num(String value);
public abstract V uint32(int value);
public abstract V uint64(long value);
public abstract V bool(boolean value);
public Parser<V> parseValue(Input input) {
return ValueParser.parse(input, this);
}
public Parser<V> parseObject(Input input) {
return ObjectParser.parse(input, this);
}
public Parser<V> parseArray(Input input) {
return ArrayParser.parse(input, this);
}
public Parser<V> parseIdent(Input input) {
return IdentParser.parse(input, this);
}
public Parser<V> parseString(Input input) {
return StringParser.parse(input, this);
}
public Parser<V> parseNumber(Input input) {
return NumberParser.parse(input, this);
}
public Parser<V> valueParser() {
return new ValueParser<I, V>(this);
}
public Parser<V> objectParser() {
return new ObjectParser<I, V>(this);
}
public Parser<V> arrayParser() {
return new ArrayParser<I, V>(this);
}
public V parseValueString(String string) {
Input input = Unicode.stringInput(string);
while (input.isCont() && Json.isWhitespace(input.head())) {
input = input.step();
}
Parser<V> parser = parseValue(input);
if (parser.isDone()) {
while (input.isCont() && Json.isWhitespace(input.head())) {
input = input.step();
}
}
if (input.isCont() && !parser.isError()) {
parser = Parser.error(Diagnostic.unexpected(input));
} else if (input.isError()) {
parser = Parser.error(input.trap());
}
return parser.bind();
}
public V parseObjectString(String string) {
Input input = Unicode.stringInput(string);
while (input.isCont() && Json.isWhitespace(input.head())) {
input = input.step();
}
Parser<V> parser = parseObject(input);
if (parser.isDone()) {
while (input.isCont() && Json.isWhitespace(input.head())) {
input = input.step();
}
}
if (input.isCont() && !parser.isError()) {
parser = Parser.error(Diagnostic.unexpected(input));
} else if (input.isError()) {
parser = Parser.error(input.trap());
}
return parser.bind();
}
}
|
0 | java-sources/ai/swim/swim-json/3.10.0/swim | java-sources/ai/swim/swim-json/3.10.0/swim/json/JsonStructureParser.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.json;
import java.math.BigInteger;
import swim.codec.Output;
import swim.structure.Attr;
import swim.structure.Bool;
import swim.structure.Item;
import swim.structure.Num;
import swim.structure.Record;
import swim.structure.Slot;
import swim.structure.Text;
import swim.structure.Value;
import swim.util.Builder;
public class JsonStructureParser extends JsonParser<Item, Value> {
@Override
public Item item(Value value) {
return value;
}
@Override
public Value value(Item item) {
return item.toValue();
}
@Override
public Item field(Value key, Value value) {
if (key instanceof Text) {
final String name = key.stringValue();
if (name.length() > 1 && name.charAt(0) == '@') {
return Attr.of(Text.from(name.substring(1)), value);
}
}
return Slot.of(key, value);
}
@SuppressWarnings("unchecked")
@Override
public Builder<Item, Value> objectBuilder() {
return (Builder<Item, Value>) (Builder<?, ?>) Record.create();
}
@SuppressWarnings("unchecked")
@Override
public Builder<Item, Value> arrayBuilder() {
return (Builder<Item, Value>) (Builder<?, ?>) Record.create();
}
@SuppressWarnings("unchecked")
@Override
public Output<Value> textOutput() {
return (Output<Value>) (Output<?>) Text.output();
}
@Override
public Value ident(Value value) {
if (value instanceof Text) {
final String string = value.stringValue();
if ("true".equals(string)) {
return Bool.from(true);
} else if ("false".equals(string)) {
return Bool.from(false);
} else if ("null".equals(string)) {
return Value.extant();
}
}
return value;
}
@Override
public Value num(int value) {
return Num.from(value);
}
@Override
public Value num(long value) {
if ((int) value == value) {
return Num.from((int) value);
} else {
return Num.from(value);
}
}
@Override
public Value num(float value) {
return Num.from(value);
}
@Override
public Value num(double value) {
if ((float) value == value) {
return Num.from((float) value);
} else {
return Num.from(value);
}
}
@Override
public Value num(BigInteger value) {
return Num.from(value);
}
@Override
public Value num(String value) {
return Num.from(value);
}
@Override
public Value uint32(int value) {
return Num.uint32(value);
}
@Override
public Value uint64(long value) {
return Num.uint64(value);
}
@Override
public Value bool(boolean value) {
return Bool.from(value);
}
}
|
0 | java-sources/ai/swim/swim-json/3.10.0/swim | java-sources/ai/swim/swim-json/3.10.0/swim/json/JsonStructureWriter.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.json;
import java.util.Iterator;
import swim.codec.Output;
import swim.codec.Writer;
import swim.codec.WriterException;
import swim.structure.Absent;
import swim.structure.Attr;
import swim.structure.Bool;
import swim.structure.Data;
import swim.structure.Extant;
import swim.structure.Field;
import swim.structure.Item;
import swim.structure.Num;
import swim.structure.Record;
import swim.structure.Slot;
import swim.structure.Text;
import swim.structure.Value;
public class JsonStructureWriter extends JsonWriter<Item, Value> {
@Override
public Iterator<Item> items(Item item) {
return item.iterator();
}
@Override
public Item item(Value value) {
return value;
}
@Override
public Value key(Item item) {
return item.key();
}
@Override
public Value value(Item item) {
return item.toValue();
}
@Override
public Writer<?, ?> writeItem(Item item, Output<?> output) {
if (item instanceof Field) {
if (item instanceof Attr) {
final Attr that = (Attr) item;
return writeField(Text.from('@' + that.key().stringValue()), that.value(), output);
} else if (item instanceof Slot) {
final Slot that = (Slot) item;
if (that.key() instanceof Text) {
return writeField(that.key(), that.value(), output);
} else {
return writeValue(Record.of(Slot.of("$key", that.key()), Slot.of("$value", that.value())), output);
}
}
} else if (item instanceof Value) {
return writeValue((Value) item, output);
}
return Writer.error(new WriterException("No JSON serialization for " + item));
}
@Override
public Writer<?, ?> writeField(Item item, Output<?> output, int index) {
if (item instanceof Field) {
if (item instanceof Attr) {
final Attr that = (Attr) item;
return writeField(Text.from('@' + that.key().stringValue()), that.value(), output);
} else if (item instanceof Slot) {
final Slot that = (Slot) item;
if (that.key() instanceof Text) {
return writeField(that.key(), that.value(), output);
} else {
return writeField(Text.from("$" + index),
Record.of(Slot.of("$key", that.key()), Slot.of("$value", that.value())),
output);
}
}
} else if (item instanceof Value) {
return writeItem(Slot.of(Text.from("$" + index), (Value) item), output);
}
return Writer.error(new WriterException("No JSON serialization for " + item));
}
@Override
public Writer<?, ?> writeValue(Item item, Output<?> output, int index) {
if (item instanceof Field) {
return writeValue(item.toValue(), output);
} else if (item instanceof Value) {
return writeValue((Value) item, output);
}
return Writer.error(new WriterException("No JSON serialization for " + item));
}
@Override
public Writer<?, ?> writeValue(Value value, Output<?> output) {
if (value instanceof Record) {
final Record that = (Record) value;
if (that.isArray()) {
return writeArray(that, output);
} else {
return writeObject(that, output);
}
} else if (value instanceof Data) {
final Data that = (Data) value;
return writeData(that.asByteBuffer(), output);
} else if (value instanceof Text) {
final Text that = (Text) value;
return writeText(that.stringValue(), output);
} else if (value instanceof Num) {
final Num that = (Num) value;
if (that.isUint32()) {
return writeUint32(that.intValue(), output);
} else if (that.isUint64()) {
return writeUint64(that.longValue(), output);
} else if (that.isValidInt()) {
return writeNum(that.intValue(), output);
} else if (that.isValidLong()) {
return writeNum(that.longValue(), output);
} else if (that.isValidFloat()) {
return writeNum(that.floatValue(), output);
} else if (that.isValidDouble()) {
return writeNum(that.doubleValue(), output);
} else if (that.isValidInteger()) {
return writeNum(that.integerValue(), output);
}
} else if (value instanceof Bool) {
final Bool that = (Bool) value;
return writeBool(that.booleanValue(), output);
} else if (value instanceof Extant) {
return writeNull(output);
} else if (value instanceof Absent) {
return writeUndefined(output);
}
return Writer.error(new WriterException("No JSON serialization for " + value));
}
}
|
0 | java-sources/ai/swim/swim-json/3.10.0/swim | java-sources/ai/swim/swim-json/3.10.0/swim/json/JsonWriter.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.json;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.util.Iterator;
import swim.codec.Base10;
import swim.codec.Base16;
import swim.codec.Output;
import swim.codec.Unicode;
import swim.codec.Writer;
/**
* Factory for constructing JSON writers.
*/
public abstract class JsonWriter<I, V> {
public abstract Iterator<I> items(I item);
public abstract I item(V value);
public abstract V key(I item);
public abstract V value(I item);
public abstract Writer<?, ?> writeItem(I item, Output<?> output);
public abstract Writer<?, ?> writeField(I item, Output<?> output, int index);
public abstract Writer<?, ?> writeValue(I item, Output<?> output, int index);
public abstract Writer<?, ?> writeValue(V value, Output<?> output);
public Writer<?, ?> writeField(V key, V value, Output<?> output) {
return FieldWriter.write(output, this, key, value);
}
public Writer<?, ?> writeArray(I item, Output<?> output) {
return ArrayWriter.write(output, this, items(item));
}
public Writer<?, ?> writeObject(I item, Output<?> output) {
return ObjectWriter.write(output, this, items(item));
}
public Writer<?, ?> writeData(ByteBuffer value, Output<?> output) {
if (value != null) {
return DataWriter.write(output, value);
} else {
return Unicode.writeString("\"\"", output);
}
}
public Writer<?, ?> writeText(String value, Output<?> output) {
return StringWriter.write(output, value);
}
public Writer<?, ?> writeNum(int value, Output<?> output) {
return Base10.writeInt(value, output);
}
public Writer<?, ?> writeNum(long value, Output<?> output) {
return Base10.writeLong(value, output);
}
public Writer<?, ?> writeNum(float value, Output<?> output) {
return Base10.writeFloat(value, output);
}
public Writer<?, ?> writeNum(double value, Output<?> output) {
return Base10.writeDouble(value, output);
}
public Writer<?, ?> writeNum(BigInteger value, Output<?> output) {
return Unicode.writeString(value, output);
}
public Writer<?, ?> writeUint32(int value, Output<?> output) {
return Base16.lowercase().writeIntLiteral(value, output, 8);
}
public Writer<?, ?> writeUint64(long value, Output<?> output) {
return Base16.lowercase().writeLongLiteral(value, output, 16);
}
public Writer<?, ?> writeBool(boolean value, Output<?> output) {
return Unicode.writeString(value ? "true" : "false", output);
}
public Writer<?, ?> writeNull(Output<?> output) {
return Unicode.writeString("null", output);
}
public Writer<?, ?> writeUndefined(Output<?> output) {
return Unicode.writeString("undefined", output);
}
}
|
0 | java-sources/ai/swim/swim-json/3.10.0/swim | java-sources/ai/swim/swim-json/3.10.0/swim/json/NumberParser.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.json;
import java.math.BigInteger;
import swim.codec.Base16;
import swim.codec.Diagnostic;
import swim.codec.Input;
import swim.codec.Parser;
final class NumberParser<I, V> extends Parser<V> {
final JsonParser<I, V> json;
final int sign;
final long value;
final int mode;
final int step;
NumberParser(JsonParser<I, V> json, int sign, long value, int mode, int step) {
this.json = json;
this.sign = sign;
this.value = value;
this.mode = mode;
this.step = step;
}
@Override
public Parser<V> feed(Input input) {
return parse(input, this.json, this.sign, this.value, this.mode, this.step);
}
static <I, V> Parser<V> parse(Input input, JsonParser<I, V> json, int sign,
long value, int mode, int step) {
int c = 0;
if (step == 1) {
while (input.isCont()) {
c = input.head();
if (Json.isWhitespace(c)) {
input = input.step();
} else {
break;
}
}
if (input.isCont()) {
if (c == '-') {
input = input.step();
sign = -1;
}
step = 2;
} else if (input.isDone()) {
return error(Diagnostic.expected("number", input));
}
}
if (step == 2) {
if (input.isCont()) {
c = input.head();
if (c == '0') {
input = input.step();
step = 4;
} else if (c >= '1' && c <= '9') {
input = input.step();
value = sign * (c - '0');
step = 3;
} else {
return error(Diagnostic.expected("digit", input));
}
} else if (input.isDone()) {
return error(Diagnostic.expected("digit", input));
}
}
if (step == 3) {
while (input.isCont()) {
c = input.head();
if (c >= '0' && c <= '9') {
final long newValue = 10 * value + sign * (c - '0');
if (value >> 63 == newValue >> 63) {
value = newValue;
input = input.step();
} else {
return BigIntegerParser.parse(input, json, sign, BigInteger.valueOf(value));
}
} else {
break;
}
}
if (input.isCont()) {
step = 4;
} else if (input.isDone()) {
return done(json.num(value));
}
}
if (step == 4) {
if (input.isCont()) {
c = input.head();
if (mode > 0 && c == '.' || mode > 1 && (c == 'E' || c == 'e')) {
return DecimalParser.parse(input, json, sign, value, mode);
} else if (c == 'x' && sign > 0 && value == 0L) {
input = input.step();
return HexadecimalParser.parse(input, json);
} else {
return done(json.num(value));
}
} else if (input.isDone()) {
return done(json.num(value));
}
}
if (input.isError()) {
return error(input.trap());
}
return new NumberParser<I, V>(json, sign, value, mode, step);
}
static <I, V> Parser<V> parse(Input input, JsonParser<I, V> json) {
return parse(input, json, 1, 0L, 2, 1);
}
static <I, V> Parser<V> parseDecimal(Input input, JsonParser<I, V> json) {
return parse(input, json, 1, 0L, 1, 1);
}
static <I, V> Parser<V> parseInteger(Input input, JsonParser<I, V> json) {
return parse(input, json, 1, 0L, 0, 1);
}
}
final class BigIntegerParser<I, V> extends Parser<V> {
final JsonParser<I, V> json;
final int sign;
final BigInteger value;
BigIntegerParser(JsonParser<I, V> json, int sign, BigInteger value) {
this.json = json;
this.sign = sign;
this.value = value;
}
@Override
public Parser<V> feed(Input input) {
return parse(input, this.json, this.sign, this.value);
}
static <I, V> Parser<V> parse(Input input, JsonParser<I, V> json, int sign, BigInteger value) {
while (input.isCont()) {
final int c = input.head();
if (c >= '0' && c <= '9') {
input = input.step();
value = BigInteger.TEN.multiply(value).add(BigInteger.valueOf(sign * (c - '0')));
} else {
break;
}
}
if (!input.isEmpty()) {
return done(json.num(value));
}
return new BigIntegerParser<I, V>(json, sign, value);
}
}
final class DecimalParser<I, V> extends Parser<V> {
final JsonParser<I, V> json;
final StringBuilder builder;
final int mode;
final int step;
DecimalParser(JsonParser<I, V> json, StringBuilder builder, int mode, int step) {
this.json = json;
this.builder = builder;
this.mode = mode;
this.step = step;
}
@Override
public Parser<V> feed(Input input) {
return parse(input, this.json, this.builder, this.mode, this.step);
}
static <I, V> Parser<V> parse(Input input, JsonParser<I, V> json, StringBuilder builder,
int mode, int step) {
int c = 0;
if (step == 1) {
if (input.isCont()) {
c = input.head();
if (c == '.') {
input = input.step();
builder.appendCodePoint(c);
step = 2;
} else if (mode > 1 && (c == 'E' || c == 'e')) {
input = input.step();
builder.appendCodePoint(c);
step = 5;
} else {
return error(Diagnostic.expected("decimal or exponent", input));
}
} else if (input.isDone()) {
return error(Diagnostic.expected("decimal or exponent", input));
}
}
if (step == 2) {
if (input.isCont()) {
c = input.head();
if (c >= '0' && c <= '9') {
input = input.step();
builder.appendCodePoint(c);
step = 3;
} else {
return error(Diagnostic.expected("digit", input));
}
} else if (input.isDone()) {
return error(Diagnostic.expected("digit", input));
}
}
if (step == 3) {
while (input.isCont()) {
c = input.head();
if (c >= '0' && c <= '9') {
input = input.step();
builder.appendCodePoint(c);
} else {
break;
}
}
if (input.isCont()) {
if (mode > 1) {
step = 4;
} else {
return done(json.num(builder.toString()));
}
} else if (input.isDone()) {
return done(json.num(builder.toString()));
}
}
if (step == 4) {
c = input.head();
if (c == 'E' || c == 'e') {
input = input.step();
builder.appendCodePoint(c);
step = 5;
} else {
return done(json.num(builder.toString()));
}
}
if (step == 5) {
if (input.isCont()) {
c = input.head();
if (c == '+' || c == '-') {
input = input.step();
builder.appendCodePoint(c);
}
step = 6;
} else if (input.isDone()) {
return error(Diagnostic.unexpected(input));
}
}
if (step == 6) {
if (input.isCont()) {
c = input.head();
if (c >= '0' && c <= '9') {
input = input.step();
builder.appendCodePoint(c);
step = 7;
} else {
return error(Diagnostic.expected("digit", input));
}
} else if (input.isDone()) {
return error(Diagnostic.expected("digit", input));
}
}
if (step == 7) {
while (input.isCont()) {
c = input.head();
if (c >= '0' && c <= '9') {
input = input.step();
builder.appendCodePoint(c);
} else {
break;
}
}
if (!input.isEmpty()) {
return done(json.num(builder.toString()));
}
}
if (input.isError()) {
return error(input.trap());
}
return new DecimalParser<I, V>(json, builder, mode, step);
}
static <I, V> Parser<V> parse(Input input, JsonParser<I, V> json, int sign,
long value, int mode) {
final StringBuilder builder = new StringBuilder();
if (sign < 0 && value == 0L) {
builder.append('-').append('0');
} else {
builder.append(value);
}
return parse(input, json, builder, mode, 1);
}
}
final class HexadecimalParser<I, V> extends Parser<V> {
final JsonParser<I, V> json;
final long value;
final int size;
HexadecimalParser(JsonParser<I, V> json, long value, int size) {
this.json = json;
this.value = value;
this.size = size;
}
@Override
public Parser<V> feed(Input input) {
return parse(input, this.json, this.value, this.size);
}
static <I, V> Parser<V> parse(Input input, JsonParser<I, V> json, long value, int size) {
int c = 0;
while (input.isCont()) {
c = input.head();
if (Base16.isDigit(c)) {
input = input.step();
value = (value << 4) | Base16.decodeDigit(c);
size += 1;
} else {
break;
}
}
if (!input.isEmpty()) {
if (size > 0) {
if (size <= 8) {
return done(json.uint32((int) value));
} else {
return done(json.uint64(value));
}
} else {
return error(Diagnostic.expected("hex digit", input));
}
}
if (input.isError()) {
return error(input.trap());
}
return new HexadecimalParser<I, V>(json, value, size);
}
static <I, V> Parser<V> parse(Input input, JsonParser<I, V> json) {
return parse(input, json, 0L, 0);
}
}
|
0 | java-sources/ai/swim/swim-json/3.10.0/swim | java-sources/ai/swim/swim-json/3.10.0/swim/json/ObjectParser.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.json;
import swim.codec.Diagnostic;
import swim.codec.Input;
import swim.codec.Parser;
import swim.util.Builder;
final class ObjectParser<I, V> extends Parser<V> {
final JsonParser<I, V> json;
final Builder<I, V> builder;
final Parser<V> keyParser;
final Parser<V> valueParser;
final int step;
ObjectParser(JsonParser<I, V> json, Builder<I, V> builder, Parser<V> keyParser,
Parser<V> valueParser, int step) {
this.json = json;
this.builder = builder;
this.keyParser = keyParser;
this.valueParser = valueParser;
this.step = step;
}
ObjectParser(JsonParser<I, V> json) {
this(json, null, null, null, 1);
}
@Override
public Parser<V> feed(Input input) {
return parse(input, this.json, this.builder, this.keyParser, this.valueParser, this.step);
}
static <I, V> Parser<V> parse(Input input, JsonParser<I, V> json, Builder<I, V> builder,
Parser<V> keyParser, Parser<V> valueParser, int step) {
int c = 0;
if (step == 1) {
while (input.isCont()) {
c = input.head();
if (Json.isWhitespace(c)) {
input = input.step();
} else {
break;
}
}
if (input.isCont()) {
if (c == '{') {
input = input.step();
step = 2;
} else {
return error(Diagnostic.expected('{', input));
}
} else if (input.isDone()) {
return error(Diagnostic.expected('{', input));
}
}
if (step == 2) {
while (input.isCont()) {
c = input.head();
if (Json.isWhitespace(c)) {
input = input.step();
} else {
break;
}
}
if (input.isCont()) {
if (builder == null) {
builder = json.objectBuilder();
}
if (c == '}') {
input = input.step();
return done(builder.bind());
} else {
step = 3;
}
} else if (input.isDone()) {
return error(Diagnostic.expected('}', input));
}
}
while (step >= 3 && !input.isEmpty()) {
if (step == 3) {
if (keyParser == null) {
keyParser = json.parseString(input);
}
while (keyParser.isCont() && !input.isEmpty()) {
keyParser = keyParser.feed(input);
}
if (keyParser.isDone()) {
step = 4;
} else if (keyParser.isError()) {
return keyParser;
} else {
break;
}
}
if (step == 4) {
while (input.isCont()) {
c = input.head();
if (Json.isWhitespace(c)) {
input = input.step();
} else {
break;
}
}
if (input.isCont()) {
if (c == ':') {
input = input.step();
step = 5;
} else {
return error(Diagnostic.expected(':', input));
}
} else if (input.isDone()) {
return error(Diagnostic.expected(':', input));
} else {
break;
}
}
if (step == 5) {
while (input.isCont() && Json.isWhitespace(input.head())) {
input = input.step();
}
if (input.isCont()) {
step = 6;
} else if (input.isDone()) {
return error(Diagnostic.expected("value", input));
} else {
break;
}
}
if (step == 6) {
if (valueParser == null) {
valueParser = json.parseValue(input);
}
while (valueParser.isCont() && !input.isEmpty()) {
valueParser = valueParser.feed(input);
}
if (valueParser.isDone()) {
builder.add(json.field(keyParser.bind(), valueParser.bind()));
keyParser = null;
valueParser = null;
step = 7;
} else if (valueParser.isError()) {
return valueParser;
} else {
break;
}
}
if (step == 7) {
while (input.isCont()) {
c = input.head();
if (Json.isWhitespace(c)) {
input = input.step();
} else {
break;
}
}
if (input.isCont()) {
if (c == ',') {
input = input.step();
step = 3;
} else if (c == '}') {
input = input.step();
return done(builder.bind());
} else {
return error(Diagnostic.expected("',' or '}'", input));
}
} else if (input.isDone()) {
return error(Diagnostic.expected('}', input));
} else {
break;
}
}
}
if (input.isError()) {
return error(input.trap());
}
return new ObjectParser<I, V>(json, builder, keyParser, valueParser, step);
}
static <I, V> Parser<V> parse(Input input, JsonParser<I, V> json) {
return parse(input, json, null, null, null, 1);
}
}
|
0 | java-sources/ai/swim/swim-json/3.10.0/swim | java-sources/ai/swim/swim-json/3.10.0/swim/json/ObjectWriter.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.json;
import java.util.Iterator;
import swim.codec.Output;
import swim.codec.Writer;
import swim.codec.WriterException;
final class ObjectWriter<I, V> extends Writer<Object, Object> {
final JsonWriter<I, V> json;
final Iterator<I> items;
final Writer<?, ?> part;
final int index;
final int step;
ObjectWriter(JsonWriter<I, V> json, Iterator<I> items, Writer<?, ?> part, int index, int step) {
this.json = json;
this.items = items;
this.part = part;
this.index = index;
this.step = step;
}
@Override
public Writer<Object, Object> pull(Output<?> output) {
return write(output, this.json, this.items, this.part, this.index, this.step);
}
static <I, V> Writer<Object, Object> write(Output<?> output, JsonWriter<I, V> json, Iterator<I> items,
Writer<?, ?> part, int index, int step) {
if (step == 1 && output.isCont()) {
output = output.write('{');
step = 3;
}
do {
if (step == 3) {
if (part == null) {
if (items.hasNext()) {
part = json.writeField(items.next(), output, index);
} else {
step = 5;
break;
}
} else {
part = part.pull(output);
}
if (part.isDone()) {
part = null;
index += 1;
if (items.hasNext()) {
step = 4;
} else {
step = 5;
break;
}
} else if (part.isError()) {
return part.asError();
} else {
break;
}
}
if (step == 4 && output.isCont()) {
output = output.write(',');
step = 3;
continue;
}
} while (step == 3);
if (step == 5 && output.isCont()) {
output = output.write('}');
return done();
}
if (output.isDone()) {
return error(new WriterException("truncated"));
} else if (output.isError()) {
return error(output.trap());
}
return new ObjectWriter<I, V>(json, items, part, index, step);
}
static <I, V> Writer<Object, Object> write(Output<?> output, JsonWriter<I, V> json, Iterator<I> items) {
return write(output, json, items, null, 0, 1);
}
}
|
0 | java-sources/ai/swim/swim-json/3.10.0/swim | java-sources/ai/swim/swim-json/3.10.0/swim/json/StringParser.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.json;
import swim.codec.Base16;
import swim.codec.Diagnostic;
import swim.codec.Input;
import swim.codec.Output;
import swim.codec.Parser;
final class StringParser<I, V> extends Parser<V> {
final JsonParser<I, V> json;
final Output<V> output;
final int quote;
final int code;
final int step;
StringParser(JsonParser<I, V> json, Output<V> output, int quote, int code, int step) {
this.json = json;
this.output = output;
this.quote = quote;
this.code = code;
this.step = step;
}
@Override
public Parser<V> feed(Input input) {
return parse(input, this.json, this.output, this.quote, this.code, this.step);
}
static <I, V> Parser<V> parse(Input input, JsonParser<I, V> json, Output<V> output,
int quote, int code, int step) {
int c = 0;
if (step == 1) {
while (input.isCont()) {
c = input.head();
if (Json.isWhitespace(c)) {
input = input.step();
} else {
break;
}
}
if (input.isCont()) {
if ((c == '"' || c == '\'') && (quote == c || quote == 0)) {
input = input.step();
if (output == null) {
output = json.textOutput();
}
quote = c;
step = 2;
} else {
return error(Diagnostic.expected("string", input));
}
} else if (input.isDone()) {
return error(Diagnostic.expected("string", input));
}
}
string: do {
if (step == 2) {
while (input.isCont()) {
c = input.head();
if (c >= 0x20 && c != quote && c != '\\') {
input = input.step();
output = output.write(c);
} else {
break;
}
}
if (input.isCont()) {
if (c == quote) {
input = input.step();
return done(output.bind());
} else if (c == '\\') {
input = input.step();
step = 3;
} else {
return error(Diagnostic.expected(quote, input));
}
} else if (input.isDone()) {
return error(Diagnostic.expected(quote, input));
}
}
if (step == 3) {
if (input.isCont()) {
c = input.head();
if (c == '"' || c == '$' || c == '\'' || c == '/' || c == '@' || c == '[' || c == '\\' || c == ']' || c == '{' || c == '}') {
input = input.step();
output = output.write(c);
step = 2;
continue;
} else if (c == 'b') {
input = input.step();
output = output.write('\b');
step = 2;
continue;
} else if (c == 'f') {
input = input.step();
output = output.write('\f');
step = 2;
continue;
} else if (c == 'n') {
input = input.step();
output = output.write('\n');
step = 2;
continue;
} else if (c == 'r') {
input = input.step();
output = output.write('\r');
step = 2;
continue;
} else if (c == 't') {
input = input.step();
output = output.write('\t');
step = 2;
continue;
} else if (c == 'u') {
input = input.step();
step = 4;
} else {
return error(Diagnostic.expected("escape character", input));
}
} else if (input.isDone()) {
return error(Diagnostic.expected("escape character", input));
}
}
if (step >= 4) {
do {
if (input.isCont()) {
c = input.head();
if (Base16.isDigit(c)) {
input = input.step();
code = 16 * code + Base16.decodeDigit(c);
if (step <= 6) {
step += 1;
continue;
} else {
output = output.write(code);
code = 0;
step = 2;
continue string;
}
} else {
return error(Diagnostic.expected("hex digit", input));
}
} else if (input.isDone()) {
return error(Diagnostic.expected("hex digit", input));
}
break;
} while (true);
}
break;
} while (true);
if (input.isError()) {
return error(input.trap());
}
return new StringParser<I, V>(json, output, quote, code, step);
}
static <I, V> Parser<V> parse(Input input, JsonParser<I, V> json) {
return parse(input, json, null, 0, 0, 1);
}
static <I, V> Parser<V> parse(Input input, JsonParser<I, V> json, Output<V> output) {
return parse(input, json, output, 0, 0, 1);
}
}
|
0 | java-sources/ai/swim/swim-json/3.10.0/swim | java-sources/ai/swim/swim-json/3.10.0/swim/json/StringWriter.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.json;
import swim.codec.Base16;
import swim.codec.Output;
import swim.codec.Utf8;
import swim.codec.Writer;
import swim.codec.WriterException;
final class StringWriter extends Writer<Object, Object> {
final String string;
final int index;
final int escape;
final int step;
StringWriter(String string, int index, int escape, int step) {
this.string = string;
this.index = index;
this.escape = escape;
this.step = step;
}
@Override
public Writer<Object, Object> pull(Output<?> output) {
return write(output, this.string, this.index, this.escape, this.step);
}
static int sizeOf(String string) {
int size = 0;
size += 1; // '"';
for (int i = 0, n = string.length(); i < n; i = string.offsetByCodePoints(i, 1)) {
final int c = string.codePointAt(i);
if (c == '"' || c == '\\' || c == '\b' || c == '\f' || c == '\n' || c == '\r' || c == '\t') {
size += 2;
} else if (c < 0x20) {
size += 6;
} else {
size += Utf8.sizeOf(c);
}
}
size += 1; // '"';
return size;
}
static Writer<Object, Object> write(Output<?> output, String string,
int index, int escape, int step) {
if (step == 1 && output.isCont()) {
output = output.write('"');
step = 2;
}
final int length = string.length();
while (step >= 2 && step <= 8 && output.isCont()) {
if (step == 2) {
if (index < length) {
final int c = string.codePointAt(index);
index = string.offsetByCodePoints(index, 1);
if (c == '"' || c == '\\') {
output = output.write('\\');
escape = c;
step = 3;
} else if (c == '\b') {
output = output.write('\\');
escape = 'b';
step = 3;
} else if (c == '\f') {
output = output.write('\\');
escape = 'f';
step = 3;
} else if (c == '\n') {
output = output.write('\\');
escape = 'n';
step = 3;
} else if (c == '\r') {
output = output.write('\\');
escape = 'r';
step = 3;
} else if (c == '\t') {
output = output.write('\\');
escape = 't';
step = 3;
} else if (c < 0x20) {
output = output.write('\\');
escape = c;
step = 4;
} else {
output = output.write(c);
}
} else {
step = 9;
break;
}
} else if (step == 3) {
output = output.write(escape);
escape = 0;
step = 2;
} else if (step == 4) {
output = output.write('u');
step = 5;
} else if (step == 5) {
output = output.write(Base16.uppercase().encodeDigit((escape >>> 12) & 0xf));
step = 6;
} else if (step == 6) {
output = output.write(Base16.uppercase().encodeDigit((escape >>> 8) & 0xf));
step = 7;
} else if (step == 7) {
output = output.write(Base16.uppercase().encodeDigit((escape >>> 4) & 0xf));
step = 8;
} else if (step == 8) {
output = output.write(Base16.uppercase().encodeDigit(escape & 0xf));
escape = 0;
step = 2;
}
}
if (step == 9 && output.isCont()) {
output = output.write('"');
return done();
}
if (output.isDone()) {
return error(new WriterException("truncated"));
} else if (output.isError()) {
return error(output.trap());
}
return new StringWriter(string, index, escape, step);
}
static Writer<Object, Object> write(Output<?> output, String string) {
return write(output, string, 0, 0, 1);
}
}
|
0 | java-sources/ai/swim/swim-json/3.10.0/swim | java-sources/ai/swim/swim-json/3.10.0/swim/json/ValueParser.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.json;
import swim.codec.Diagnostic;
import swim.codec.Input;
import swim.codec.Parser;
final class ValueParser<I, V> extends Parser<V> {
final JsonParser<I, V> json;
ValueParser(JsonParser<I, V> json) {
this.json = json;
}
@Override
public Parser<V> feed(Input input) {
return parse(input, this.json);
}
static <I, V> Parser<V> parse(Input input, JsonParser<I, V> json) {
int c = 0;
while (input.isCont()) {
c = input.head();
if (Json.isWhitespace(c)) {
input = input.step();
} else {
break;
}
}
if (input.isCont()) {
if (c == '{') {
return json.parseObject(input);
} else if (c == '[') {
return json.parseArray(input);
} else if (Json.isIdentStartChar(c)) {
return json.parseIdent(input);
} else if (c == '"' || c == '\'') {
return json.parseString(input);
} else if (c == '-' || c >= '0' && c <= '9') {
return json.parseNumber(input);
} else {
return error(Diagnostic.expected("value", input));
}
} else if (input.isDone()) {
return error(Diagnostic.expected("value", input));
} else if (input.isError()) {
return error(input.trap());
}
return new ValueParser<I, V>(json);
}
}
|
0 | java-sources/ai/swim/swim-json/3.10.0/swim | java-sources/ai/swim/swim-json/3.10.0/swim/json/package-info.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* JavaScript Object Notation (JSON) codec.
*/
package swim.json;
|
0 | java-sources/ai/swim/swim-kernel | java-sources/ai/swim/swim-kernel/3.10.0/module-info.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* Swim kernel runtime.
*/
module swim.kernel {
requires swim.recon;
requires transitive swim.io;
requires transitive swim.api;
requires transitive swim.runtime;
exports swim.kernel;
provides swim.kernel.Kernel with swim.kernel.BootKernel;
}
|
0 | java-sources/ai/swim/swim-kernel/3.10.0/swim | java-sources/ai/swim/swim-kernel/3.10.0/swim/kernel/BootKernel.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.kernel;
import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import swim.concurrent.Clock;
import swim.concurrent.ClockDef;
import swim.concurrent.MainStage;
import swim.concurrent.Schedule;
import swim.concurrent.ScheduleDef;
import swim.concurrent.SideStage;
import swim.concurrent.Stage;
import swim.concurrent.StageClock;
import swim.concurrent.StageDef;
import swim.concurrent.Theater;
import swim.concurrent.TheaterDef;
import swim.io.IpService;
import swim.io.IpServiceRef;
import swim.io.IpSettings;
import swim.io.IpSocket;
import swim.io.IpSocketRef;
import swim.io.IpStation;
import swim.io.Station;
import swim.io.TransportSettings;
import swim.math.R2Shape;
import swim.runtime.EdgeBinding;
import swim.runtime.HostBinding;
import swim.runtime.HostDef;
import swim.runtime.LaneBinding;
import swim.runtime.LaneDef;
import swim.runtime.MeshBinding;
import swim.runtime.MeshDef;
import swim.runtime.PartBinding;
import swim.runtime.PartDef;
import swim.runtime.http.RestLaneModel;
import swim.runtime.lane.CommandLaneModel;
import swim.runtime.lane.ListLaneModel;
import swim.runtime.lane.MapLaneModel;
import swim.runtime.lane.SpatialLaneModel;
import swim.runtime.lane.SupplyLaneModel;
import swim.runtime.lane.ValueLaneModel;
import swim.runtime.router.EdgeTable;
import swim.runtime.router.HostTable;
import swim.runtime.router.MeshTable;
import swim.runtime.router.PartTable;
import swim.spatial.GeoProjection;
import swim.structure.Item;
import swim.structure.Value;
import swim.uri.Uri;
public class BootKernel extends KernelProxy implements IpStation {
final double kernelPriority;
final Value moduleConfig;
KernelShutdownHook shutdownHook;
volatile Stage stage;
volatile Station station;
public BootKernel(double kernelPriority, Value moduleConfig) {
this.kernelPriority = kernelPriority;
this.moduleConfig = moduleConfig;
}
public BootKernel(double kernelPriority) {
this(kernelPriority, Value.absent());
}
public BootKernel() {
this(KERNEL_PRIORITY, Value.absent());
}
@Override
public final double kernelPriority() {
return this.kernelPriority;
}
protected Stage createStage() {
final KernelContext kernel = kernelWrapper().unwrapKernel(KernelContext.class);
StageDef stageDef = null;
for (Item item : this.moduleConfig) {
final StageDef newStageDef = kernel.defineStage(item);
if (newStageDef != null) {
stageDef = newStageDef;
continue;
}
}
Stage stage = stageDef != null ? kernel.createStage(stageDef) : null;
if (stage == null) {
stage = new Theater("SwimKernel");
}
if (stage != null) {
stage = kernel.injectStage(stage);
}
return stage;
}
protected Station createStation() {
final KernelContext kernel = kernelWrapper().unwrapKernel(KernelContext.class);
TransportSettings transportSettings = null;
for (Item item : this.moduleConfig) {
final TransportSettings newTransportSettings = TransportSettings.form().cast(item);
if (newTransportSettings != null) {
transportSettings = newTransportSettings;
continue;
}
}
Stage stage = kernel.stage();
if (stage instanceof MainStage) {
stage = new SideStage(stage); // isolate stage lifecycle
}
return new Station(stage, transportSettings);
}
@Override
public final Stage stage() {
Stage stage;
Stage newStage = null;
do {
stage = super.stage();
if (stage == null) {
final Stage oldStage = this.stage;
if (oldStage != null) {
stage = oldStage;
if (newStage != null) {
// Lost creation race.
if (newStage instanceof MainStage) {
((MainStage) newStage).stop();
}
newStage = null;
}
} else {
if (newStage == null) {
newStage = createStage();
if (newStage instanceof MainStage) {
((MainStage) newStage).start();
}
}
if (STAGE.compareAndSet(this, oldStage, newStage)) {
stage = newStage;
} else {
continue;
}
}
}
break;
} while (true);
return stage;
}
@Override
public final Station station() {
Station station;
Station newStation = null;
do {
station = super.station();
if (station == null) {
final Station oldStation = this.station;
if (oldStation != null) {
station = oldStation;
if (newStation != null) {
// Lost creation race.
newStation.stop();
newStation = null;
}
} else {
if (newStation == null) {
newStation = createStation();
newStation.start();
}
if (STATION.compareAndSet(this, oldStation, newStation)) {
station = newStation;
} else {
continue;
}
}
}
break;
} while (true);
return station;
}
@Override
public ScheduleDef defineSchedule(Item scheduleConfig) {
final ScheduleDef scheduleDef = ScheduleDef.form().cast(scheduleConfig);
return scheduleDef != null ? scheduleDef : super.defineSchedule(scheduleConfig);
}
@Override
public Schedule createSchedule(ScheduleDef scheduleDef, Stage stage) {
if (scheduleDef instanceof ClockDef) {
return createClock((ClockDef) scheduleDef, stage);
} else {
return super.createSchedule(scheduleDef, stage);
}
}
public Clock createClock(ClockDef clockDef, Stage stage) {
if (stage != null) {
return new StageClock(stage, clockDef);
} else {
return new Clock(clockDef);
}
}
@Override
public StageDef defineStage(Item stageConfig) {
final StageDef stageDef = StageDef.form().cast(stageConfig);
return stageDef != null ? stageDef : super.defineStage(stageConfig);
}
@Override
public Stage createStage(StageDef stageDef) {
if (stageDef instanceof TheaterDef) {
return createTheater((TheaterDef) stageDef);
} else {
return super.createStage(stageDef);
}
}
public Theater createTheater(TheaterDef theaterDef) {
return new Theater(theaterDef);
}
@Override
public Stage openStoreStage(String storeName) {
Stage stage = super.openStoreStage(storeName);
if (stage == null) {
stage = stage();
if (stage instanceof MainStage) {
stage = new SideStage(stage); // isolate stage lifecycle
}
}
return stage;
}
@Override
public IpSettings ipSettings() {
IpSettings ipSettings = super.ipSettings();
if (ipSettings == null) {
ipSettings = IpSettings.standard();
}
return ipSettings;
}
@Override
public IpServiceRef bindTcp(InetSocketAddress localAddress, IpService service, IpSettings ipSettings) {
return IpStation.super.bindTcp(localAddress, service, ipSettings);
}
@Override
public IpServiceRef bindTls(InetSocketAddress localAddress, IpService service, IpSettings ipSettings) {
return IpStation.super.bindTls(localAddress, service, ipSettings);
}
@Override
public IpSocketRef connectTcp(InetSocketAddress remoteAddress, IpSocket socket, IpSettings ipSettings) {
return IpStation.super.connectTcp(remoteAddress, socket, ipSettings);
}
@Override
public IpSocketRef connectTls(InetSocketAddress remoteAddress, IpSocket socket, IpSettings ipSettings) {
return IpStation.super.connectTls(remoteAddress, socket, ipSettings);
}
@Override
public EdgeBinding createEdge(String edgeName) {
EdgeBinding edge = super.createEdge(edgeName);
if (edge == null) {
edge = new EdgeTable();
}
return edge;
}
@Override
public Stage openEdgeStage(String edgeName) {
Stage stage = super.openEdgeStage(edgeName);
if (stage == null) {
stage = stage();
if (stage instanceof MainStage) {
stage = new SideStage(stage); // isolate stage lifecycle
}
}
return stage;
}
@Override
public MeshBinding createMesh(String edgeName, MeshDef meshDef) {
MeshBinding mesh = super.createMesh(edgeName, meshDef);
if (mesh == null) {
mesh = new MeshTable();
}
return mesh;
}
@Override
public MeshBinding createMesh(String edgeName, Uri meshUri) {
MeshBinding mesh = super.createMesh(edgeName, meshUri);
if (mesh == null) {
mesh = new MeshTable();
}
return mesh;
}
@Override
public PartBinding createPart(String edgeName, Uri meshUri, PartDef partDef) {
PartBinding part = super.createPart(edgeName, meshUri, partDef);
if (part == null) {
part = new PartTable(partDef.predicate());
}
return part;
}
@Override
public PartBinding createPart(String edgeName, Uri meshUri, Value partKey) {
PartBinding part = super.createPart(edgeName, meshUri, partKey);
if (part == null) {
part = new PartTable();
}
return part;
}
@Override
public HostBinding createHost(String edgeName, Uri meshUri, Value partKey, HostDef hostDef) {
HostBinding host = super.createHost(edgeName, meshUri, partKey, hostDef);
if (host == null) {
host = new HostTable();
}
return host;
}
@Override
public HostBinding createHost(String edgeName, Uri meshUri, Value partKey, Uri hostUri) {
HostBinding host = super.createHost(edgeName, meshUri, partKey, hostUri);
if (host == null) {
host = new HostTable();
}
return host;
}
@Override
public LaneBinding createLane(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, LaneDef laneDef) {
LaneBinding lane = super.createLane(edgeName, meshUri, partKey, hostUri, nodeUri, laneDef);
if (lane == null) {
final String laneType = laneDef.laneType();
if ("command".equals(laneType)) {
lane = createCommandLane(edgeName, meshUri, partKey, hostUri, nodeUri, laneDef);
} else if ("list".equals(laneType)) {
lane = createListLane(edgeName, meshUri, partKey, hostUri, nodeUri, laneDef);
} else if ("map".equals(laneType)) {
lane = createMapLane(edgeName, meshUri, partKey, hostUri, nodeUri, laneDef);
} else if ("geospatial".equals(laneType)) {
lane = createGeospatialLane(edgeName, meshUri, partKey, hostUri, nodeUri, laneDef);
} else if ("supply".equals(laneType)) {
lane = createSupplyLane(edgeName, meshUri, partKey, hostUri, nodeUri, laneDef);
} else if ("value".equals(laneType)) {
lane = createValueLane(edgeName, meshUri, partKey, hostUri, nodeUri, laneDef);
} else if ("http".equals(laneType)) {
lane = createHttpLane(edgeName, meshUri, partKey, hostUri, nodeUri, laneDef);
}
}
return lane;
}
public LaneBinding createCommandLane(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, LaneDef laneDef) {
return new CommandLaneModel();
}
public LaneBinding createListLane(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, LaneDef laneDef) {
return new ListLaneModel();
}
public LaneBinding createMapLane(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, LaneDef laneDef) {
return new MapLaneModel();
}
public LaneBinding createGeospatialLane(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, LaneDef laneDef) {
return new SpatialLaneModel<R2Shape>(GeoProjection.wgs84Form());
}
public LaneBinding createSupplyLane(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, LaneDef laneDef) {
return new SupplyLaneModel();
}
public LaneBinding createValueLane(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, LaneDef laneDef) {
return new ValueLaneModel();
}
public LaneBinding createHttpLane(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, LaneDef laneDef) {
return new RestLaneModel();
}
@Override
public void willStart() {
this.shutdownHook = new KernelShutdownHook(kernelWrapper());
Runtime.getRuntime().addShutdownHook(this.shutdownHook);
}
@Override
public void didStop() {
final Station station = STATION.getAndSet(this, null);
if (station != null) {
station.stop();
}
final Stage stage = STAGE.getAndSet(this, null);
if (stage instanceof MainStage) {
((MainStage) stage).stop();
}
final KernelShutdownHook shutdownHook = this.shutdownHook;
if (Thread.currentThread() != shutdownHook) {
Runtime.getRuntime().removeShutdownHook(shutdownHook);
}
this.shutdownHook = null;
}
@Override
public void run() {
start();
final KernelContext kernelContext = this.kernelContext;
if (kernelContext != null) {
kernelContext.run();
} else {
final KernelShutdownHook shutdownHook = this.shutdownHook;
if (shutdownHook != null) {
while (shutdownHook.isAlive()) {
try {
shutdownHook.join();
} catch (InterruptedException swallow) {
// nop
}
}
}
}
}
private static final double KERNEL_PRIORITY = Double.NEGATIVE_INFINITY;
public static BootKernel fromValue(Value moduleConfig) {
final Value header = moduleConfig.getAttr("kernel");
final String kernelClassName = header.get("class").stringValue(null);
if (kernelClassName == null || BootKernel.class.getName().equals(kernelClassName)) {
final double kernelPriority = header.get("priority").doubleValue(KERNEL_PRIORITY);
return new BootKernel(kernelPriority, moduleConfig);
}
return null;
}
static final AtomicReferenceFieldUpdater<BootKernel, Stage> STAGE =
AtomicReferenceFieldUpdater.newUpdater(BootKernel.class, Stage.class, "stage");
static final AtomicReferenceFieldUpdater<BootKernel, Station> STATION =
AtomicReferenceFieldUpdater.newUpdater(BootKernel.class, Station.class, "station");
}
|
0 | java-sources/ai/swim/swim-kernel/3.10.0/swim | java-sources/ai/swim/swim-kernel/3.10.0/swim/kernel/Kernel.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.kernel;
import swim.api.agent.Agent;
import swim.api.agent.AgentDef;
import swim.api.agent.AgentFactory;
import swim.api.plane.Plane;
import swim.api.plane.PlaneDef;
import swim.api.plane.PlaneFactory;
import swim.api.service.Service;
import swim.api.service.ServiceDef;
import swim.api.service.ServiceFactory;
import swim.api.space.Space;
import swim.api.space.SpaceDef;
import swim.structure.Item;
public interface Kernel {
/**
* Returns the relative priority of this {@code Kernel} implementation.
* Kernel implementations with greater priority inject into kernel stacks
* before implementations with lower priority.
*/
double kernelPriority();
/**
* Returns a {@code Kernel} implementation with the combined capabilities
* of this {@code Kernel} implementation and the given {@code kernel}
* implementation.
*/
Kernel injectKernel(Kernel kernel);
<T> T unwrapKernel(Class<T> kernelClass);
ServiceDef defineService(Item serviceConfig);
ServiceFactory<?> createServiceFactory(ServiceDef serviceDef, ClassLoader classLoader);
<S extends Service> S openService(String serviceName, ServiceFactory<S> serviceFactory);
default Service openService(ServiceDef serviceDef, ClassLoader classLoader) {
final String serviceName = serviceDef.serviceName();
Service service = getService(serviceName);
if (service == null) {
final ServiceFactory<?> serviceFactory = createServiceFactory(serviceDef, classLoader);
if (serviceFactory != null) {
service = openService(serviceName, serviceFactory);
}
}
return service;
}
default Service openService(ServiceDef serviceDef) {
return openService(serviceDef, null);
}
Service getService(String serviceName);
SpaceDef defineSpace(Item spaceConfig);
Space openSpace(SpaceDef spaceDef);
Space getSpace(String spaceName);
PlaneDef definePlane(Item planeConfig);
PlaneFactory<?> createPlaneFactory(PlaneDef planeDef, ClassLoader classLoader);
<P extends Plane> PlaneFactory<P> createPlaneFactory(Class<? extends P> planeClass);
AgentDef defineAgent(Item agentConfig);
AgentFactory<?> createAgentFactory(AgentDef agentDef, ClassLoader classLoader);
<A extends Agent> AgentFactory<A> createAgentFactory(Class<? extends A> agentClass);
boolean isStarted();
void start();
void stop();
void run();
}
|
0 | java-sources/ai/swim/swim-kernel/3.10.0/swim | java-sources/ai/swim/swim-kernel/3.10.0/swim/kernel/KernelBinding.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.kernel;
public interface KernelBinding extends Kernel {
KernelBinding kernelWrapper();
KernelContext kernelContext();
void setKernelContext(KernelContext context);
}
|
0 | java-sources/ai/swim/swim-kernel/3.10.0/swim | java-sources/ai/swim/swim-kernel/3.10.0/swim/kernel/KernelContext.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.kernel;
import java.net.InetSocketAddress;
import swim.api.agent.Agent;
import swim.api.agent.AgentDef;
import swim.api.agent.AgentFactory;
import swim.api.agent.AgentRoute;
import swim.api.auth.Authenticator;
import swim.api.auth.AuthenticatorDef;
import swim.api.plane.Plane;
import swim.api.plane.PlaneDef;
import swim.api.plane.PlaneFactory;
import swim.api.policy.Policy;
import swim.api.service.Service;
import swim.api.service.ServiceDef;
import swim.api.service.ServiceFactory;
import swim.api.space.Space;
import swim.api.space.SpaceDef;
import swim.collections.FingerTrieSeq;
import swim.concurrent.Schedule;
import swim.concurrent.ScheduleDef;
import swim.concurrent.Stage;
import swim.concurrent.StageDef;
import swim.io.IpInterface;
import swim.io.IpService;
import swim.io.IpServiceRef;
import swim.io.IpSettings;
import swim.io.IpSocket;
import swim.io.IpSocketRef;
import swim.io.Station;
import swim.runtime.EdgeBinding;
import swim.runtime.HostBinding;
import swim.runtime.HostDef;
import swim.runtime.LaneBinding;
import swim.runtime.LaneDef;
import swim.runtime.LogDef;
import swim.runtime.MeshBinding;
import swim.runtime.MeshDef;
import swim.runtime.NodeBinding;
import swim.runtime.NodeDef;
import swim.runtime.PartBinding;
import swim.runtime.PartDef;
import swim.runtime.PolicyDef;
import swim.store.StoreBinding;
import swim.store.StoreDef;
import swim.structure.Item;
import swim.structure.Value;
import swim.uri.Uri;
import swim.util.Log;
public interface KernelContext extends Kernel, IpInterface, Log {
KernelBinding kernelWrapper();
KernelBinding kernelBinding();
void setKernelBinding(KernelBinding kernelBinding);
FingerTrieSeq<Kernel> modules();
Stage stage();
Station station();
LogDef defineLog(Item logConfig);
Log createLog(LogDef logDef);
Log injectLog(Log log);
PolicyDef definePolicy(Item policyConfig);
Policy createPolicy(PolicyDef policyDef);
Policy injectPolicy(Policy policy);
ScheduleDef defineSchedule(Item scheduleConfig);
Schedule createSchedule(ScheduleDef scheduleDef, Stage stage);
Schedule injectSchedule(Schedule schedule);
StageDef defineStage(Item stageConfig);
Stage createStage(StageDef stageDef);
Stage injectStage(Stage stage);
StoreDef defineStore(Item storeConfig);
StoreBinding createStore(StoreDef storeDef, ClassLoader classLoader);
StoreBinding injectStore(StoreBinding store);
Log openStoreLog(String storeName);
Stage openStoreStage(String storeName);
AuthenticatorDef defineAuthenticator(Item authenticatorConfig);
Authenticator createAuthenticator(AuthenticatorDef authenticatorDef, ClassLoader classLoader);
Authenticator injectAuthenticator(Authenticator authenticator);
Log openAuthenticatorLog(String authenticatorName);
Stage openAuthenticatorStage(String authenticatorName);
@Override
IpSettings ipSettings();
@Override
IpServiceRef bindTcp(InetSocketAddress localAddress, IpService service, IpSettings ipSettings);
@Override
IpServiceRef bindTls(InetSocketAddress localAddress, IpService service, IpSettings ipSettings);
@Override
IpSocketRef connectTcp(InetSocketAddress remoteAddress, IpSocket socket, IpSettings ipSettings);
@Override
IpSocketRef connectTls(InetSocketAddress remoteAddress, IpSocket socket, IpSettings ipSettings);
@Override
Service getService(String serviceName);
@Override
ServiceDef defineService(Item serviceConfig);
@Override
ServiceFactory<?> createServiceFactory(ServiceDef serviceDef, ClassLoader classLoader);
@Override
<S extends Service> S openService(String serviceName, ServiceFactory<S> serviceFactory);
Service injectService(Service service);
Log openServiceLog(String serviceName);
Policy openServicePolicy(String serviceName);
Stage openServiceStage(String serviceName);
@Override
Space getSpace(String spaceName);
@Override
SpaceDef defineSpace(Item spaceConfig);
@Override
Space openSpace(SpaceDef spaceDef);
@Override
PlaneDef definePlane(Item planeConfig);
@Override
PlaneFactory<?> createPlaneFactory(PlaneDef planeDef, ClassLoader classLoader);
@Override
<P extends Plane> PlaneFactory<P> createPlaneFactory(Class<? extends P> planeClass);
Plane injectPlane(Plane plane);
@Override
AgentDef defineAgent(Item agentConfig);
@Override
AgentFactory<?> createAgentFactory(AgentDef agentDef, ClassLoader classLoader);
AgentFactory<?> createAgentFactory(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, AgentDef agentDef);
<A extends Agent> AgentFactory<A> createAgentFactory(Class<? extends A> agentClass);
<A extends Agent> AgentFactory<A> createAgentFactory(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri,
Class<? extends A> agentClass);
<A extends Agent> AgentRoute<A> createAgentRoute(String edgeName, Class<? extends A> agentClass);
void openAgents(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, NodeBinding node);
EdgeBinding createEdge(String edgeName);
EdgeBinding injectEdge(String edgeName, EdgeBinding edge);
Log openEdgeLog(String edgeName);
Policy openEdgePolicy(String edgeName);
Stage openEdgeStage(String edgeName);
StoreBinding openEdgeStore(String edgeName);
MeshDef defineMesh(Item meshConfig);
MeshDef getMeshDef(String edgeName, Uri meshUri);
MeshBinding createMesh(String edgeName, MeshDef meshDef);
MeshBinding createMesh(String edgeName, Uri meshUri);
MeshBinding injectMesh(String edgeName, Uri meshUri, MeshBinding mesh);
Log openMeshLog(String edgeName, Uri meshUri);
Policy openMeshPolicy(String edgeName, Uri meshUri);
Stage openMeshStage(String edgeName, Uri meshUri);
StoreBinding openMeshStore(String edgeName, Uri meshUri);
PartDef definePart(Item partConfig);
PartDef getPartDef(String edgeName, Uri meshUri, Value partKey);
PartBinding createPart(String edgeName, Uri meshUri, PartDef partDef);
PartBinding createPart(String edgeName, Uri meshUri, Value partKey);
PartBinding injectPart(String edgeName, Uri meshUri, Value partKey, PartBinding part);
Log openPartLog(String edgeName, Uri meshUri, Value partKey);
Policy openPartPolicy(String edgeName, Uri meshUri, Value partKey);
Stage openPartStage(String edgeName, Uri meshUri, Value partKey);
StoreBinding openPartStore(String edgeName, Uri meshUri, Value partKey);
HostDef defineHost(Item hostConfig);
HostDef getHostDef(String edgeName, Uri meshUri, Value partKey, Uri hostUri);
HostBinding createHost(String edgeName, Uri meshUri, Value partKey, HostDef hostDef);
HostBinding createHost(String edgeName, Uri meshUri, Value partKey, Uri hostUri);
HostBinding injectHost(String edgeName, Uri meshUri, Value partKey, Uri hostUri, HostBinding host);
Log openHostLog(String edgeName, Uri meshUri, Value partKey, Uri hostUri);
Policy openHostPolicy(String edgeName, Uri meshUri, Value partKey, Uri hostUri);
Stage openHostStage(String edgeName, Uri meshUri, Value partKey, Uri hostUri);
StoreBinding openHostStore(String edgeName, Uri meshUri, Value partKey, Uri hostUri);
NodeDef defineNode(Item nodeConfig);
NodeDef getNodeDef(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri);
NodeBinding createNode(String edgeName, Uri meshUri, Value partKey, Uri hostUri, NodeDef nodeDef);
NodeBinding createNode(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri);
NodeBinding injectNode(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, NodeBinding node);
Log openNodeLog(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri);
Policy openNodePolicy(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri);
Stage openNodeStage(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri);
StoreBinding openNodeStore(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri);
LaneDef defineLane(Item laneConfig);
LaneDef getLaneDef(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, Uri laneUri);
LaneBinding createLane(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, LaneDef laneDef);
LaneBinding createLane(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, Uri laneUri);
LaneBinding injectLane(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, Uri laneUri, LaneBinding lane);
void openLanes(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, NodeBinding node);
Log openLaneLog(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, Uri laneUri);
Policy openLanePolicy(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, Uri laneUri);
Stage openLaneStage(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, Uri laneUri);
StoreBinding openLaneStore(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, Uri laneUri);
}
|
0 | java-sources/ai/swim/swim-kernel/3.10.0/swim | java-sources/ai/swim/swim-kernel/3.10.0/swim/kernel/KernelException.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.kernel;
public class KernelException extends RuntimeException {
private static final long serialVersionUID = 1L;
public KernelException(String message, Throwable cause) {
super(message, cause);
}
public KernelException(String message) {
super(message);
}
public KernelException(Throwable cause) {
super(cause);
}
public KernelException() {
super();
}
}
|
0 | java-sources/ai/swim/swim-kernel/3.10.0/swim | java-sources/ai/swim/swim-kernel/3.10.0/swim/kernel/KernelLoader.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.kernel;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import swim.codec.Utf8;
import swim.recon.Recon;
import swim.structure.Item;
import swim.structure.Value;
public final class KernelLoader {
private KernelLoader() {
// static
}
public static Kernel loadKernel() {
return loadKernel(KernelLoader.class.getClassLoader());
}
public static Kernel loadKernel(ClassLoader classLoader) {
try {
Value kernelConfig = loadConfig(classLoader);
if (kernelConfig == null) {
kernelConfig = Value.absent();
}
return loadKernelStack(classLoader, kernelConfig);
} catch (IOException cause) {
throw new KernelException(cause);
}
}
public static Kernel loadKernelStack(ClassLoader classLoader, Value kernelConfig) {
Kernel kernelStack = null;
for (int i = 0, n = kernelConfig.length(); i < n; i += 1) {
final Item moduleConfig = kernelConfig.getItem(i);
final Kernel kernelModule = loadKernelModule(classLoader, moduleConfig.toValue());
if (kernelModule != null) {
kernelStack = kernelStack == null ? kernelModule : kernelStack.injectKernel(kernelModule);
}
}
return kernelStack;
}
@SuppressWarnings("unchecked")
public static Kernel loadKernelModule(ClassLoader classLoader, Value moduleConfig) {
Kernel kernel = null;
final Value header = moduleConfig.getAttr("kernel");
final String kernelClassName = header.get("class").stringValue(null);
if (kernelClassName != null) {
try {
final Class<? extends Kernel> kernelClass = (Class<? extends Kernel>) Class.forName(kernelClassName, true, classLoader);
try {
final Method kernelFromValueMethod = kernelClass.getMethod("fromValue", Value.class);
if ((kernelFromValueMethod.getModifiers() & Modifier.STATIC) != 0) {
kernelFromValueMethod.setAccessible(true);
kernel = (Kernel) kernelFromValueMethod.invoke(null, moduleConfig);
}
} catch (NoSuchMethodException swallow) {
// continue
}
if (kernel == null) {
final Constructor<? extends Kernel> kernelConstructor = kernelClass.getConstructor();
kernelConstructor.setAccessible(true);
kernel = kernelConstructor.newInstance();
}
} catch (ReflectiveOperationException cause) {
if (!header.get("optional").booleanValue(false)) {
throw new KernelException("failed to load required kernel class: " + kernelClassName, cause);
}
}
}
return kernel;
}
public static Value loadConfig() throws IOException {
return loadConfig(KernelLoader.class.getClassLoader());
}
public static Value loadConfig(ClassLoader classLoader) throws IOException {
Value configValue = loadConfigFile();
if (configValue == null) {
configValue = loadConfigResource(classLoader);
}
return configValue;
}
public static Value loadConfigFile() throws IOException {
Value configValue = null;
String configPath = System.getProperty("swim.config.file");
if (configPath == null) {
configPath = System.getProperty("swim.config");
}
if (configPath != null) {
final File configFile = new File(configPath);
if (configFile.exists()) {
configValue = loadConfigFile(configFile);
}
}
return configValue;
}
public static Value loadConfigFile(File configFile) throws IOException {
Value configValue = null;
FileInputStream configInput = null;
try {
configInput = new FileInputStream(configFile);
if (configInput != null) {
configValue = parseConfigValue(configInput);
}
} finally {
try {
if (configInput != null) {
configInput.close();
}
} catch (IOException swallow) {
}
}
return configValue;
}
public static Value loadConfigResource(ClassLoader classLoader) throws IOException {
Value configValue = null;
String configResource = System.getProperty("swim.config.resource");
if (configResource == null) {
configResource = System.getProperty("swim.config");
}
if (configResource != null) {
configValue = loadConfigResource(classLoader, configResource);
}
return configValue;
}
public static Value loadConfigResource(ClassLoader classLoader, String configResource) throws IOException {
Value configValue = null;
InputStream configInput = null;
try {
configInput = classLoader.getResourceAsStream(configResource);
if (configInput != null) {
configValue = parseConfigValue(configInput);
}
} finally {
try {
if (configInput != null) {
configInput.close();
}
} catch (IOException swallow) {
}
}
return configValue;
}
public static Value parseConfigValue(InputStream configInput) throws IOException {
return Utf8.read(Recon.structureParser().blockParser(), configInput);
}
}
|
0 | java-sources/ai/swim/swim-kernel/3.10.0/swim | java-sources/ai/swim/swim-kernel/3.10.0/swim/kernel/KernelProxy.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.kernel;
import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import swim.api.agent.Agent;
import swim.api.agent.AgentDef;
import swim.api.agent.AgentFactory;
import swim.api.agent.AgentRoute;
import swim.api.auth.Authenticator;
import swim.api.auth.AuthenticatorDef;
import swim.api.plane.Plane;
import swim.api.plane.PlaneDef;
import swim.api.plane.PlaneFactory;
import swim.api.policy.Policy;
import swim.api.service.Service;
import swim.api.service.ServiceDef;
import swim.api.service.ServiceFactory;
import swim.api.space.Space;
import swim.api.space.SpaceDef;
import swim.collections.FingerTrieSeq;
import swim.concurrent.Schedule;
import swim.concurrent.ScheduleDef;
import swim.concurrent.Stage;
import swim.concurrent.StageDef;
import swim.io.IpService;
import swim.io.IpServiceRef;
import swim.io.IpSettings;
import swim.io.IpSocket;
import swim.io.IpSocketRef;
import swim.io.Station;
import swim.runtime.EdgeBinding;
import swim.runtime.HostBinding;
import swim.runtime.HostDef;
import swim.runtime.LaneBinding;
import swim.runtime.LaneDef;
import swim.runtime.LogDef;
import swim.runtime.MeshBinding;
import swim.runtime.MeshDef;
import swim.runtime.NodeBinding;
import swim.runtime.NodeDef;
import swim.runtime.PartBinding;
import swim.runtime.PartDef;
import swim.runtime.PolicyDef;
import swim.store.StoreBinding;
import swim.store.StoreDef;
import swim.structure.Item;
import swim.structure.Value;
import swim.uri.Uri;
import swim.util.Log;
public abstract class KernelProxy implements KernelBinding, KernelContext {
protected KernelBinding kernelBinding;
protected KernelContext kernelContext;
protected volatile int status;
@Override
public final KernelBinding kernelWrapper() {
final KernelBinding kernelBinding = this.kernelBinding;
return kernelBinding != null ? kernelBinding.kernelWrapper() : this;
}
@Override
public final KernelBinding kernelBinding() {
return this.kernelBinding;
}
@Override
public void setKernelBinding(KernelBinding kernelBinding) {
this.kernelBinding = kernelBinding;
}
@Override
public final KernelContext kernelContext() {
return this.kernelContext;
}
@Override
public void setKernelContext(KernelContext kernelContext) {
this.kernelContext = kernelContext;
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrapKernel(Class<T> kernelClass) {
if (kernelClass.isAssignableFrom(getClass())) {
return (T) this;
} else {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.unwrapKernel(kernelClass) : null;
}
}
@Override
public abstract double kernelPriority();
@Override
public Kernel injectKernel(Kernel kernel) {
if (kernelPriority() < kernel.kernelPriority()) {
setKernelBinding((KernelBinding) kernel);
((KernelBinding) kernel).setKernelContext(this);
return kernel;
} else {
final KernelContext kernelContext = this.kernelContext;
if (kernelContext == null) {
((KernelContext) kernel).setKernelBinding(this);
setKernelContext((KernelContext) kernel);
} else {
kernel = kernelContext.injectKernel(kernel);
((KernelContext) kernel).setKernelBinding(this);
setKernelContext((KernelContext) kernel);
}
return this;
}
}
@Override
public FingerTrieSeq<Kernel> modules() {
final KernelContext kernelContext = this.kernelContext;
FingerTrieSeq<Kernel> modules = kernelContext != null ? kernelContext.modules() : FingerTrieSeq.empty();
modules = modules.prepended(this);
return modules;
}
@Override
public final boolean isStarted() {
return (this.status & STARTED) != 0;
}
@Override
public Stage stage() {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.stage() : null;
}
@Override
public Station station() {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.station() : null;
}
@Override
public LogDef defineLog(Item logConfig) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.defineLog(logConfig) : null;
}
@Override
public Log createLog(LogDef logDef) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.createLog(logDef) : null;
}
@Override
public Log injectLog(Log log) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.injectLog(log) : log;
}
@Override
public PolicyDef definePolicy(Item policyConfig) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.definePolicy(policyConfig) : null;
}
@Override
public Policy createPolicy(PolicyDef policyDef) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.createPolicy(policyDef) : null;
}
@Override
public Policy injectPolicy(Policy policy) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.injectPolicy(policy) : policy;
}
@Override
public ScheduleDef defineSchedule(Item scheduleConfig) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.defineSchedule(scheduleConfig) : null;
}
@Override
public Schedule createSchedule(ScheduleDef scheduleDef, Stage stage) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.createSchedule(scheduleDef, stage) : null;
}
@Override
public Schedule injectSchedule(Schedule schedule) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.injectSchedule(schedule) : schedule;
}
@Override
public StageDef defineStage(Item stageConfig) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.defineStage(stageConfig) : null;
}
@Override
public Stage createStage(StageDef stageDef) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.createStage(stageDef) : null;
}
@Override
public Stage injectStage(Stage stage) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.injectStage(stage) : stage;
}
@Override
public StoreDef defineStore(Item storeConfig) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.defineStore(storeConfig) : null;
}
@Override
public StoreBinding createStore(StoreDef storeDef, ClassLoader classLoader) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.createStore(storeDef, classLoader) : null;
}
@Override
public StoreBinding injectStore(StoreBinding store) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.injectStore(store) : store;
}
@Override
public Log openStoreLog(String storeName) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openStoreLog(storeName) : null;
}
@Override
public Stage openStoreStage(String storeName) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openStoreStage(storeName) : null;
}
@Override
public AuthenticatorDef defineAuthenticator(Item authenticatorConfig) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.defineAuthenticator(authenticatorConfig) : null;
}
@Override
public Authenticator createAuthenticator(AuthenticatorDef authenticatorDef, ClassLoader classLoader) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.createAuthenticator(authenticatorDef, classLoader) : null;
}
@Override
public Authenticator injectAuthenticator(Authenticator authenticator) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.injectAuthenticator(authenticator) : authenticator;
}
@Override
public Log openAuthenticatorLog(String authenticatorName) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openAuthenticatorLog(authenticatorName) : null;
}
@Override
public Stage openAuthenticatorStage(String authenticatorName) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openAuthenticatorStage(authenticatorName) : null;
}
@Override
public IpSettings ipSettings() {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.ipSettings() : null;
}
@Override
public IpServiceRef bindTcp(InetSocketAddress localAddress, IpService service, IpSettings ipSettings) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.bindTcp(localAddress, service, ipSettings) : null;
}
@Override
public IpServiceRef bindTls(InetSocketAddress localAddress, IpService service, IpSettings ipSettings) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.bindTls(localAddress, service, ipSettings) : null;
}
@Override
public IpSocketRef connectTcp(InetSocketAddress remoteAddress, IpSocket socket, IpSettings ipSettings) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.connectTcp(remoteAddress, socket, ipSettings) : null;
}
@Override
public IpSocketRef connectTls(InetSocketAddress remoteAddress, IpSocket socket, IpSettings ipSettings) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.connectTls(remoteAddress, socket, ipSettings) : null;
}
@Override
public Service getService(String serviceName) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.getService(serviceName) : null;
}
@Override
public ServiceDef defineService(Item serviceConfig) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.defineService(serviceConfig) : null;
}
@Override
public ServiceFactory<?> createServiceFactory(ServiceDef serviceDef, ClassLoader classLoader) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.createServiceFactory(serviceDef, classLoader) : null;
}
@Override
public Service injectService(Service service) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.injectService(service) : service;
}
@Override
public <S extends Service> S openService(String serviceName, ServiceFactory<S> serviceFactory) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openService(serviceName, serviceFactory) : null;
}
@Override
public Log openServiceLog(String serviceName) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openServiceLog(serviceName) : null;
}
@Override
public Policy openServicePolicy(String policyName) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openServicePolicy(policyName) : null;
}
@Override
public Stage openServiceStage(String serviceName) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openServiceStage(serviceName) : null;
}
@Override
public Space getSpace(String spaceName) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.getSpace(spaceName) : null;
}
@Override
public SpaceDef defineSpace(Item spaceConfig) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.defineSpace(spaceConfig) : null;
}
@Override
public Space openSpace(SpaceDef spaceDef) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openSpace(spaceDef) : null;
}
@Override
public PlaneDef definePlane(Item planeConfig) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.definePlane(planeConfig) : null;
}
@Override
public PlaneFactory<?> createPlaneFactory(PlaneDef planeDef, ClassLoader classLoader) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.createPlaneFactory(planeDef, classLoader) : null;
}
@Override
public <P extends Plane> PlaneFactory<P> createPlaneFactory(Class<? extends P> planeClass) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.createPlaneFactory(planeClass) : null;
}
@Override
public Plane injectPlane(Plane plane) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.injectPlane(plane) : plane;
}
@Override
public AgentDef defineAgent(Item agentConfig) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.defineAgent(agentConfig) : null;
}
@Override
public AgentFactory<?> createAgentFactory(AgentDef agentDef, ClassLoader classLoader) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.createAgentFactory(agentDef, classLoader) : null;
}
@Override
public AgentFactory<?> createAgentFactory(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, AgentDef agentDef) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.createAgentFactory(edgeName, meshUri, partKey, hostUri, nodeUri, agentDef) : null;
}
@Override
public <A extends Agent> AgentFactory<A> createAgentFactory(Class<? extends A> agentClass) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.createAgentFactory(agentClass) : null;
}
@Override
public <A extends Agent> AgentFactory<A> createAgentFactory(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri,
Class<? extends A> agentClass) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.createAgentFactory(edgeName, meshUri, partKey, hostUri, nodeUri, agentClass) : null;
}
@Override
public <A extends Agent> AgentRoute<A> createAgentRoute(String edgeName, Class<? extends A> agentClass) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.createAgentRoute(edgeName, agentClass) : null;
}
@Override
public void openAgents(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, NodeBinding node) {
final KernelContext kernelContext = this.kernelContext;
if (kernelContext != null) {
kernelContext.openAgents(edgeName, meshUri, partKey, hostUri, nodeUri, node);
}
}
@Override
public EdgeBinding createEdge(String edgeName) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.createEdge(edgeName) : null;
}
@Override
public EdgeBinding injectEdge(String edgeName, EdgeBinding edge) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.injectEdge(edgeName, edge) : edge;
}
@Override
public Log openEdgeLog(String edgeName) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openEdgeLog(edgeName) : null;
}
@Override
public Policy openEdgePolicy(String edgeName) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openEdgePolicy(edgeName) : null;
}
@Override
public Stage openEdgeStage(String edgeName) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openEdgeStage(edgeName) : null;
}
@Override
public StoreBinding openEdgeStore(String edgeName) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openEdgeStore(edgeName) : null;
}
@Override
public MeshDef defineMesh(Item meshConfig) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.defineMesh(meshConfig) : null;
}
@Override
public MeshDef getMeshDef(String edgeName, Uri meshUri) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.getMeshDef(edgeName, meshUri) : null;
}
@Override
public MeshBinding createMesh(String edgeName, MeshDef meshDef) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.createMesh(edgeName, meshDef) : null;
}
@Override
public MeshBinding createMesh(String edgeName, Uri meshUri) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.createMesh(edgeName, meshUri) : null;
}
@Override
public MeshBinding injectMesh(String edgeName, Uri meshUri, MeshBinding mesh) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.injectMesh(edgeName, meshUri, mesh) : mesh;
}
@Override
public Log openMeshLog(String edgeName, Uri meshUri) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openMeshLog(edgeName, meshUri) : null;
}
@Override
public Policy openMeshPolicy(String edgeName, Uri meshUri) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openMeshPolicy(edgeName, meshUri) : null;
}
@Override
public Stage openMeshStage(String edgeName, Uri meshUri) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openMeshStage(edgeName, meshUri) : null;
}
@Override
public StoreBinding openMeshStore(String edgeName, Uri meshUri) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openMeshStore(edgeName, meshUri) : null;
}
@Override
public PartDef definePart(Item partConfig) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.definePart(partConfig) : null;
}
@Override
public PartDef getPartDef(String edgeName, Uri meshUri, Value partKey) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.getPartDef(edgeName, meshUri, partKey) : null;
}
@Override
public PartBinding createPart(String edgeName, Uri meshUri, PartDef partDef) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.createPart(edgeName, meshUri, partDef) : null;
}
@Override
public PartBinding createPart(String edgeName, Uri meshUri, Value partKey) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.createPart(edgeName, meshUri, partKey) : null;
}
@Override
public PartBinding injectPart(String edgeName, Uri meshUri, Value partKey, PartBinding part) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.injectPart(edgeName, meshUri, partKey, part) : part;
}
@Override
public Log openPartLog(String edgeName, Uri meshUri, Value partKey) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openPartLog(edgeName, meshUri, partKey) : null;
}
@Override
public Policy openPartPolicy(String edgeName, Uri meshUri, Value partKey) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openPartPolicy(edgeName, meshUri, partKey) : null;
}
@Override
public Stage openPartStage(String edgeName, Uri meshUri, Value partKey) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openPartStage(edgeName, meshUri, partKey) : null;
}
@Override
public StoreBinding openPartStore(String edgeName, Uri meshUri, Value partKey) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openPartStore(edgeName, meshUri, partKey) : null;
}
@Override
public HostDef defineHost(Item hostConfig) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.defineHost(hostConfig) : null;
}
@Override
public HostDef getHostDef(String edgeName, Uri meshUri, Value partKey, Uri hostUri) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.getHostDef(edgeName, meshUri, partKey, hostUri) : null;
}
@Override
public HostBinding createHost(String edgeName, Uri meshUri, Value partKey, HostDef hostDef) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.createHost(edgeName, meshUri, partKey, hostDef) : null;
}
@Override
public HostBinding createHost(String edgeName, Uri meshUri, Value partKey, Uri hostUri) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.createHost(edgeName, meshUri, partKey, hostUri) : null;
}
@Override
public HostBinding injectHost(String edgeName, Uri meshUri, Value partKey, Uri hostUri, HostBinding host) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.injectHost(edgeName, meshUri, partKey, hostUri, host) : host;
}
@Override
public Log openHostLog(String edgeName, Uri meshUri, Value partKey, Uri hostUri) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openHostLog(edgeName, meshUri, partKey, hostUri) : null;
}
@Override
public Policy openHostPolicy(String edgeName, Uri meshUri, Value partKey, Uri hostUri) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openHostPolicy(edgeName, meshUri, partKey, hostUri) : null;
}
@Override
public Stage openHostStage(String edgeName, Uri meshUri, Value partKey, Uri hostUri) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openHostStage(edgeName, meshUri, partKey, hostUri) : null;
}
@Override
public StoreBinding openHostStore(String edgeName, Uri meshUri, Value partKey, Uri hostUri) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openHostStore(edgeName, meshUri, partKey, hostUri) : null;
}
@Override
public NodeDef defineNode(Item nodeConfig) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.defineNode(nodeConfig) : null;
}
@Override
public NodeDef getNodeDef(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.getNodeDef(edgeName, meshUri, partKey, hostUri, nodeUri) : null;
}
@Override
public NodeBinding createNode(String edgeName, Uri meshUri, Value partKey, Uri hostUri, NodeDef nodeDef) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.createNode(edgeName, meshUri, partKey, hostUri, nodeDef) : null;
}
@Override
public NodeBinding createNode(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.createNode(edgeName, meshUri, partKey, hostUri, nodeUri) : null;
}
@Override
public NodeBinding injectNode(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, NodeBinding node) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.injectNode(edgeName, meshUri, partKey, hostUri, nodeUri, node) : node;
}
@Override
public Log openNodeLog(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openNodeLog(edgeName, meshUri, partKey, hostUri, nodeUri) : null;
}
@Override
public Policy openNodePolicy(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openNodePolicy(edgeName, meshUri, partKey, hostUri, nodeUri) : null;
}
@Override
public Stage openNodeStage(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openNodeStage(edgeName, meshUri, partKey, hostUri, nodeUri) : null;
}
@Override
public StoreBinding openNodeStore(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openNodeStore(edgeName, meshUri, partKey, hostUri, nodeUri) : null;
}
@Override
public LaneDef defineLane(Item laneConfig) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.defineLane(laneConfig) : null;
}
@Override
public LaneDef getLaneDef(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, Uri laneUri) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.getLaneDef(edgeName, meshUri, partKey, hostUri, nodeUri, laneUri) : null;
}
@Override
public LaneBinding createLane(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, LaneDef laneDef) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.createLane(edgeName, meshUri, partKey, hostUri, nodeUri, laneDef) : null;
}
@Override
public LaneBinding createLane(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, Uri laneUri) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.createLane(edgeName, meshUri, partKey, hostUri, nodeUri, laneUri) : null;
}
@Override
public LaneBinding injectLane(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, Uri laneUri, LaneBinding lane) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.injectLane(edgeName, meshUri, partKey, hostUri, nodeUri, laneUri, lane) : lane;
}
@Override
public void openLanes(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, NodeBinding node) {
final KernelContext kernelContext = this.kernelContext;
if (kernelContext != null) {
kernelContext.openLanes(edgeName, meshUri, partKey, hostUri, nodeUri, node);
}
}
@Override
public Log openLaneLog(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, Uri laneUri) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openLaneLog(edgeName, meshUri, partKey, hostUri, nodeUri, laneUri) : null;
}
@Override
public Policy openLanePolicy(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, Uri laneUri) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openLanePolicy(edgeName, meshUri, partKey, hostUri, nodeUri, laneUri) : null;
}
@Override
public Stage openLaneStage(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, Uri laneUri) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openLaneStage(edgeName, meshUri, partKey, hostUri, nodeUri, laneUri) : null;
}
@Override
public StoreBinding openLaneStore(String edgeName, Uri meshUri, Value partKey, Uri hostUri, Uri nodeUri, Uri laneUri) {
final KernelContext kernelContext = this.kernelContext;
return kernelContext != null ? kernelContext.openLaneStore(edgeName, meshUri, partKey, hostUri, nodeUri, laneUri) : null;
}
@Override
public void trace(Object message) {
final KernelContext kernelContext = this.kernelContext;
if (kernelContext != null) {
kernelContext.trace(message);
}
}
@Override
public void debug(Object message) {
final KernelContext kernelContext = this.kernelContext;
if (kernelContext != null) {
kernelContext.debug(message);
}
}
@Override
public void info(Object message) {
final KernelContext kernelContext = this.kernelContext;
if (kernelContext != null) {
kernelContext.info(message);
}
}
@Override
public void warn(Object message) {
final KernelContext kernelContext = this.kernelContext;
if (kernelContext != null) {
kernelContext.warn(message);
}
}
@Override
public void error(Object message) {
final KernelContext kernelContext = this.kernelContext;
if (kernelContext != null) {
kernelContext.error(message);
}
}
@Override
public void start() {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
newStatus = oldStatus | STARTED;
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
if ((oldStatus & STARTED) == 0) {
willStart();
}
final KernelContext kernelContext = this.kernelContext;
if (kernelContext != null) {
kernelContext.start();
}
if ((oldStatus & STARTED) == 0) {
didStart();
}
}
@Override
public void stop() {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
newStatus = oldStatus & ~STARTED;
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
if ((oldStatus & STARTED) != 0) {
willStop();
}
final KernelContext kernelContext = this.kernelContext;
if (kernelContext != null) {
kernelContext.stop();
}
if ((oldStatus & STARTED) != 0) {
didStop();
}
}
@Override
public void run() {
start();
final KernelContext kernelContext = this.kernelContext;
if (kernelContext != null) {
kernelContext.run();
}
}
protected void willStart() {
// hook
}
protected void didStart() {
// hook
}
protected void willStop() {
// hook
}
protected void didStop() {
// hook
}
protected static final int STARTED = 0x01;
protected static final AtomicIntegerFieldUpdater<KernelProxy> STATUS =
AtomicIntegerFieldUpdater.newUpdater(KernelProxy.class, "status");
}
|
0 | java-sources/ai/swim/swim-kernel/3.10.0/swim | java-sources/ai/swim/swim-kernel/3.10.0/swim/kernel/KernelShutdownHook.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.kernel;
public final class KernelShutdownHook extends Thread {
final Kernel kernel;
KernelShutdownHook(Kernel kernel) {
this.kernel = kernel;
}
public Kernel kernel() {
return this.kernel;
}
@Override
public void run() {
this.kernel.stop();
}
}
|
0 | java-sources/ai/swim/swim-kernel/3.10.0/swim | java-sources/ai/swim/swim-kernel/3.10.0/swim/kernel/package-info.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* Swim kernel runtime.
*/
package swim.kernel;
|
0 | java-sources/ai/swim/swim-linker | java-sources/ai/swim/swim-linker/3.9.3/module-info.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* Runtime configuration interfaces.
*/
module swim.linker {
requires transitive swim.api;
requires transitive swim.util;
requires transitive swim.io.warp;
requires transitive swim.security;
requires transitive swim.store;
exports swim.linker;
}
|
0 | java-sources/ai/swim/swim-linker/3.9.3/swim | java-sources/ai/swim/swim-linker/3.9.3/swim/linker/AgentTypeDef.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.linker;
import swim.api.agent.AgentTypeContext;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Record;
import swim.structure.Value;
import swim.uri.UriPattern;
import swim.util.Murmur3;
public final class AgentTypeDef implements AgentTypeContext, Debug {
final String name;
final UriPattern route;
String className;
public AgentTypeDef(String name, UriPattern route, String className) {
this.name = name;
this.route = route;
this.className = className;
}
@Override
public String name() {
return this.name;
}
public AgentTypeDef name(String name) {
return new AgentTypeDef(name, this.route, this.className);
}
@Override
public UriPattern route() {
return this.route;
}
public AgentTypeDef route(UriPattern route) {
return new AgentTypeDef(this.name, route, this.className);
}
public String className() {
return this.className;
}
public AgentTypeDef className(String className) {
return new AgentTypeDef(this.name, this.route, className);
}
public Value toValue() {
return form().mold(this).toValue();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof AgentTypeDef) {
final AgentTypeDef that = (AgentTypeDef) other;
return (this.name == null ? that.name == null : this.name.equals(that.name))
&& (this.route == null ? that.route == null : this.route.equals(that.route))
&& (this.className == null ? that.className == null : this.className.equals(that.className));
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(AgentTypeDef.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed,
Murmur3.hash(this.name)), Murmur3.hash(this.route)), Murmur3.hash(this.className)));
}
@Override
public void debug(Output<?> output) {
output = output.write("AgentTypeDef").write('.').write("of").write('(').debug(this.name).write(')');
if (this.route != null) {
output = output.write('.').write("route").write('(').debug(this.route).write(')');
}
if (this.className != null) {
output = output.write('.').write("className").write('(').debug(this.className).write(')');
}
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static Form<AgentTypeDef> form;
public static AgentTypeDef of(String name) {
return new AgentTypeDef(name, null, null);
}
@Kind
public static Form<AgentTypeDef> form() {
if (form == null) {
form = new AgentTypeForm();
}
return form;
}
}
final class AgentTypeForm extends Form<AgentTypeDef> {
@Override
public String tag() {
return "agent";
}
@Override
public Class<?> type() {
return AgentTypeDef.class;
}
@Override
public Item mold(AgentTypeDef agentType) {
if (agentType != null) {
final Record record = Record.create(3)
.attr(tag(), agentType.name)
.slot("route", agentType.route.toUri().toString());
if (agentType.className != null) {
record.slot("class", agentType.className);
}
return record;
} else {
return Item.extant();
}
}
@Override
public AgentTypeDef cast(Item value) {
final String name = value.getAttr(tag()).stringValue(null);
if (name != null) {
final UriPattern route = value.get("route").cast(UriPattern.form());
final String className = value.get("class").cast(Form.forString());
return new AgentTypeDef(name, route, className);
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-linker/3.9.3/swim | java-sources/ai/swim/swim-linker/3.9.3/swim/linker/AuthDef.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.linker;
import swim.api.auth.Authenticator;
import swim.api.auth.Credentials;
import swim.api.auth.Identity;
import swim.api.policy.PolicyDirective;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Value;
public abstract class AuthDef implements Authenticator {
protected AuthenticatorContext context;
public AuthenticatorContext getContext() {
return this.context;
}
public void setContext(AuthenticatorContext context) {
this.context = context;
}
public abstract PolicyDirective<Identity> authenticate(Credentials credentials);
public abstract Value toValue();
private static Form<AuthDef> authForm;
@Kind
public static Form<AuthDef> authForm() {
if (authForm == null) {
authForm = new AuthForm();
}
return authForm;
}
}
final class AuthForm extends Form<AuthDef> {
@Override
public Class<?> type() {
return AuthDef.class;
}
@Override
public Item mold(AuthDef authDef) {
if (authDef != null) {
return authDef.toValue();
} else {
return Item.extant();
}
}
@Override
public AuthDef cast(Item value) {
AuthDef authDef = GoogleIdAuthDef.form().cast(value);
if (authDef != null) {
return authDef;
}
authDef = OpenIdAuthDef.form().cast(value);
if (authDef != null) {
return authDef;
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-linker/3.9.3/swim | java-sources/ai/swim/swim-linker/3.9.3/swim/linker/AuthenticatorContext.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.linker;
import swim.concurrent.Schedule;
import swim.io.http.HttpEndpoint;
public interface AuthenticatorContext {
Schedule schedule();
HttpEndpoint endpoint();
}
|
0 | java-sources/ai/swim/swim-linker/3.9.3/swim | java-sources/ai/swim/swim-linker/3.9.3/swim/linker/ClientLinker.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.linker;
import swim.api.client.Client;
public interface ClientLinker extends Client {
// TODO: ClientLinker materialize(ClientDef clientDef);
}
|
0 | java-sources/ai/swim/swim-linker/3.9.3/swim | java-sources/ai/swim/swim-linker/3.9.3/swim/linker/GoogleIdAuthDef.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.linker;
import swim.api.auth.Authenticated;
import swim.api.auth.Credentials;
import swim.api.auth.Identity;
import swim.api.policy.PolicyDirective;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.codec.ParserException;
import swim.collections.FingerTrieSeq;
import swim.collections.HashTrieSet;
import swim.concurrent.AbstractTimer;
import swim.concurrent.TimerFunction;
import swim.concurrent.TimerRef;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
import swim.http.header.Host;
import swim.io.TlsSettings;
import swim.io.http.AbstractHttpClient;
import swim.io.http.AbstractHttpRequester;
import swim.io.http.HttpSettings;
import swim.security.GoogleIdToken;
import swim.security.JsonWebKey;
import swim.security.PublicKeyDef;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Record;
import swim.structure.Value;
import swim.uri.Uri;
import swim.uri.UriAuthority;
import swim.util.Builder;
import swim.util.Murmur3;
public final class GoogleIdAuthDef extends AuthDef implements Debug {
final FingerTrieSeq<String> audiences;
HashTrieSet<String> emails;
final Uri publicKeyUri;
HttpSettings httpSettings;
TimerRef publicKeyRefreshTimer;
FingerTrieSeq<PublicKeyDef> publicKeyDefs;
public GoogleIdAuthDef(FingerTrieSeq<String> audiences, HashTrieSet<String> emails) {
this(audiences, emails, PUBLIC_KEY_URI);
}
public GoogleIdAuthDef(FingerTrieSeq<String> audiences, HashTrieSet<String> emails, Uri publicKeyUri) {
this.audiences = audiences;
this.emails = emails;
this.publicKeyUri = publicKeyUri;
}
@Override
public void setContext(AuthenticatorContext context) {
super.setContext(context);
refreshPublicKeys();
if (this.publicKeyRefreshTimer != null) {
this.publicKeyRefreshTimer.cancel();
}
this.publicKeyRefreshTimer = context.schedule().setTimer(PUBLIC_KEY_REFRESH_INTERVAL,
new GoogleIdPublicKeyTimer(this));
}
public FingerTrieSeq<String> audiences() {
return this.audiences;
}
public HashTrieSet<String> emails() {
return this.emails;
}
public void addEmail(String email) {
this.emails = emails.added(email);
}
public void removeEmail(String email) {
this.emails = emails.removed(email);
}
public FingerTrieSeq<PublicKeyDef> getPublicKeyDefs() {
return this.publicKeyDefs;
}
public void setPublicKeyDefs(FingerTrieSeq<PublicKeyDef> publicKeyDefs) {
this.publicKeyDefs = publicKeyDefs;
}
public void refreshPublicKeys() {
if (this.httpSettings == null) {
this.httpSettings = HttpSettings.standard().tlsSettings(TlsSettings.standard());
}
final UriAuthority authority = this.publicKeyUri.authority();
final String address = authority.host().address();
int port = authority.port().number();
if (port == 0) {
port = 443;
}
context.endpoint().connectHttps(address, port, new GoogleIdPublicKeyClient(this), this.httpSettings);
}
@Override
public PolicyDirective<Identity> authenticate(Credentials credentials) {
String compactJws = credentials.claims().get("idToken").stringValue(null);
if (compactJws == null) {
compactJws = credentials.claims().get("googleIdToken").stringValue(null);
}
if (compactJws != null) {
final GoogleIdToken idToken = GoogleIdToken.verify(compactJws, this.publicKeyDefs);
if (idToken != null) {
if (this.emails .isEmpty() || this.emails .contains(idToken.email())) {
return PolicyDirective.<Identity>allow(new Authenticated(
credentials.requestUri(), credentials.fromUri(), idToken.toValue()));
}
}
}
return null;
}
@Override
public Value toValue() {
return form().mold(this).toValue();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof GoogleIdAuthDef) {
final GoogleIdAuthDef that = (GoogleIdAuthDef) other;
return this.audiences.equals(that.audiences) && this.emails.equals(that.emails)
&& this.publicKeyUri.equals(that.publicKeyUri);
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(GoogleIdAuthDef.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed,
this.audiences.hashCode()), this.emails.hashCode()),
this.publicKeyUri.hashCode()));
}
@Override
public void debug(Output<?> output) {
output = output.write("new").write(' ').write("GoogleIdAuthDef").write('(')
.debug(this.audiences).write(", ").debug(this.emails);
if (!PUBLIC_KEY_URI.equals(this.publicKeyUri)) {
output = output.write(", ").debug(this.publicKeyUri);
}
output = output.write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
static final Uri PUBLIC_KEY_URI;
static final long PUBLIC_KEY_REFRESH_INTERVAL;
private static int hashSeed;
private static Form<GoogleIdAuthDef> form;
@Kind
public static Form<GoogleIdAuthDef> form() {
if (form == null) {
form = new GoogleIdAuthForm();
}
return form;
}
static {
Uri publicKeyUri;
try {
publicKeyUri = Uri.parse(System.getProperty("swim.auth.google.public.key.uri"));
} catch (NullPointerException | ParserException e) {
publicKeyUri = Uri.parse("https://www.googleapis.com/oauth2/v3/certs");
}
PUBLIC_KEY_URI = publicKeyUri;
long publicKeyRefreshInterval;
try {
publicKeyRefreshInterval = Long.parseLong(System.getProperty("swim.auth.google.public.key.refresh.interval"));
} catch (NumberFormatException e) {
publicKeyRefreshInterval = (long) (60 * 60 * 1000);
}
PUBLIC_KEY_REFRESH_INTERVAL = publicKeyRefreshInterval;
}
}
final class GoogleIdPublicKeyTimer extends AbstractTimer implements TimerFunction {
final GoogleIdAuthDef authDef;
GoogleIdPublicKeyTimer(GoogleIdAuthDef authDef) {
this.authDef = authDef;
}
@Override
public void runTimer() {
this.authDef.refreshPublicKeys();
this.reschedule(GoogleIdAuthDef.PUBLIC_KEY_REFRESH_INTERVAL);
}
}
final class GoogleIdPublicKeyClient extends AbstractHttpClient {
final GoogleIdAuthDef authDef;
GoogleIdPublicKeyClient(GoogleIdAuthDef authDef) {
this.authDef = authDef;
}
@Override
public void didConnect() {
super.didConnect();
doRequest(new GoogleIdPublicKeyRequester(this.authDef));
}
}
final class GoogleIdPublicKeyRequester extends AbstractHttpRequester<Value> {
final GoogleIdAuthDef authDef;
GoogleIdPublicKeyRequester(GoogleIdAuthDef authDef) {
this.authDef = authDef;
}
@Override
public void doRequest() {
final Uri publicKeyUri = this.authDef.publicKeyUri;
final Uri requestUri = Uri.from(publicKeyUri.path());
final HttpRequest<?> request = HttpRequest.get(requestUri, Host.from(publicKeyUri.authority()));
writeRequest(request);
}
@Override
public void didRespond(HttpResponse<Value> response) {
FingerTrieSeq<PublicKeyDef> publicKeyDefs = FingerTrieSeq.empty();
try {
for (Item item : response.entity().get().get("keys")) {
final PublicKeyDef publicKeyDef = JsonWebKey.from(item.toValue()).publicKeyDef();
if (publicKeyDef != null) {
publicKeyDefs = publicKeyDefs.appended(publicKeyDef);
}
}
this.authDef.setPublicKeyDefs(publicKeyDefs);
} finally {
close();
}
}
}
final class GoogleIdAuthForm extends Form<GoogleIdAuthDef> {
@Override
public String tag() {
return "googleId";
}
@Override
public Class<?> type() {
return GoogleIdAuthDef.class;
}
@Override
public Item mold(GoogleIdAuthDef authDef) {
if (authDef != null) {
final Record record = Record.create().attr(tag());
for (String audience : authDef.audiences) {
record.add(Record.create(1).attr("audience", audience));
}
for (String email : authDef.emails) {
record.add(Record.create(1).attr("email", email));
}
return record;
} else {
return Item.extant();
}
}
@Override
public GoogleIdAuthDef cast(Item item) {
final Value value = item.toValue();
final Value headers = value.getAttr(tag());
if (headers.isDefined()) {
final Builder<String, FingerTrieSeq<String>> audiences = FingerTrieSeq.builder();
HashTrieSet<String> emails = HashTrieSet.empty();
for (Item member : value) {
final String tag = member.tag();
if ("audience".equals(tag)) {
audiences.add(member.get("audience").stringValue());
} else if ("email".equals(tag)) {
emails = emails.added(member.get("email").stringValue());
}
}
return new GoogleIdAuthDef(audiences.bind(), emails);
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-linker/3.9.3/swim | java-sources/ai/swim/swim-linker/3.9.3/swim/linker/HttpServiceDef.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.linker;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.io.warp.WarpSettings;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Record;
import swim.structure.Value;
import swim.uri.Uri;
import swim.uri.UriScheme;
import swim.util.Murmur3;
public final class HttpServiceDef extends WarpServiceDef implements Debug {
final String address;
final int port;
final String planeName;
final Uri documentRoot;
final WarpSettings warpSettings;
public HttpServiceDef(String address, int port, String planeName, Uri documentRoot,
WarpSettings warpSettings) {
this.address = address;
this.port = port;
this.planeName = planeName;
this.documentRoot = documentRoot;
this.warpSettings = warpSettings;
}
@Override
public UriScheme scheme() {
return UriScheme.from("http");
}
@Override
public String address() {
return this.address;
}
@Override
public int port() {
return this.port;
}
@Override
public String planeName() {
return this.planeName;
}
@Override
public Uri documentRoot() {
return this.documentRoot;
}
@Override
public WarpSettings warpSettings() {
return this.warpSettings;
}
@Override
public Value toValue() {
return form().mold(this).toValue();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof HttpServiceDef) {
final HttpServiceDef that = (HttpServiceDef) other;
return this.address.equals(that.address) && this.port == that.port
&& (this.planeName == null ? that.planeName == null : this.planeName.equals(that.planeName))
&& (this.documentRoot == null ? that.documentRoot == null : this.documentRoot.equals(that.documentRoot))
&& this.warpSettings.equals(that.warpSettings);
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(HttpServiceDef.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(Murmur3.mix(Murmur3.mix(
hashSeed, this.address.hashCode()), this.port), Murmur3.hash(this.planeName)),
Murmur3.hash(this.documentRoot)), this.warpSettings.hashCode()));
}
@Override
public void debug(Output<?> output) {
output = output.write("new").write(' ').write("HttpServiceDef").write('(')
.debug(this.address).write(", ").debug(this.port).write(", ")
.debug(this.planeName).write(", ").debug(this.documentRoot).write(", ")
.debug(this.warpSettings).write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static Form<HttpServiceDef> form;
@Kind
public static Form<HttpServiceDef> form() {
if (form == null) {
form = new HttpServiceForm();
}
return form;
}
}
final class HttpServiceForm extends Form<HttpServiceDef> {
@Override
public String tag() {
return "http";
}
@Override
public Class<?> type() {
return HttpServiceDef.class;
}
@Override
public Item mold(HttpServiceDef serviceDef) {
if (serviceDef != null) {
Value headers = Value.absent();
if (!"0.0.0.0".equals(serviceDef.address)) {
headers = headers.updated("address", serviceDef.address);
}
if (serviceDef.port != 80) {
headers = headers.updated("port", serviceDef.port);
}
if (!headers.isDefined()) {
headers = Value.extant();
}
final Record record = Record.create().attr(tag(), headers);
if (serviceDef.planeName != null) {
record.slot("plane", serviceDef.planeName);
}
if (serviceDef.documentRoot != null) {
record.slot("documentRoot", serviceDef.documentRoot.toString());
}
return record.concat(serviceDef.warpSettings.toValue());
} else {
return Item.extant();
}
}
@Override
public HttpServiceDef cast(Item item) {
final Value value = item.toValue();
final Value headers = value.getAttr(tag());
if (headers.isDefined()) {
final String address = headers.get("address").stringValue("0.0.0.0");
final int port = headers.get("port").intValue(80);
final String planeName = value.get("plane").stringValue(null);
WarpSettings warpSettings = WarpSettings.form().cast(value);
if (warpSettings.tlsSettings() != null) {
warpSettings = warpSettings.tlsSettings(null);
}
final Uri documentRoot = value.get("documentRoot").cast(Uri.form());
return new HttpServiceDef(address, port, planeName, documentRoot, warpSettings);
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-linker/3.9.3/swim | java-sources/ai/swim/swim-linker/3.9.3/swim/linker/HttpsServiceDef.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.linker;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.io.warp.WarpSettings;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Record;
import swim.structure.Value;
import swim.uri.Uri;
import swim.uri.UriScheme;
import swim.util.Murmur3;
public final class HttpsServiceDef extends WarpServiceDef implements Debug {
final String address;
final int port;
final String planeName;
final Uri documentRoot;
final WarpSettings warpSettings;
public HttpsServiceDef(String address, int port, String planeName, Uri documentRoot,
WarpSettings warpSettings) {
this.address = address;
this.port = port;
this.planeName = planeName;
this.documentRoot = documentRoot;
this.warpSettings = warpSettings;
}
@Override
public UriScheme scheme() {
return UriScheme.from("https");
}
@Override
public String address() {
return this.address;
}
@Override
public int port() {
return this.port;
}
@Override
public String planeName() {
return this.planeName;
}
@Override
public Uri documentRoot() {
return this.documentRoot;
}
@Override
public WarpSettings warpSettings() {
return this.warpSettings;
}
@Override
public Value toValue() {
return form().mold(this).toValue();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof HttpsServiceDef) {
final HttpsServiceDef that = (HttpsServiceDef) other;
return this.address.equals(that.address) && this.port == that.port
&& (this.planeName == null ? that.planeName == null : this.planeName.equals(that.planeName))
&& (this.documentRoot == null ? that.documentRoot == null : this.documentRoot.equals(that.documentRoot))
&& this.warpSettings.equals(that.warpSettings);
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(HttpsServiceDef.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(Murmur3.mix(Murmur3.mix(
hashSeed, this.address.hashCode()), this.port), Murmur3.hash(this.planeName)),
Murmur3.hash(this.documentRoot)), this.warpSettings.hashCode()));
}
@Override
public void debug(Output<?> output) {
output = output.write("new").write(' ').write("HttpsServiceDef").write('(')
.debug(this.address).write(", ").debug(this.port).write(", ")
.debug(this.planeName).write(", ").debug(this.documentRoot).write(", ")
.debug(this.warpSettings).write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static Form<HttpsServiceDef> form;
@Kind
public static Form<HttpsServiceDef> form() {
if (form == null) {
form = new HttpsServiceForm();
}
return form;
}
}
final class HttpsServiceForm extends Form<HttpsServiceDef> {
@Override
public String tag() {
return "https";
}
@Override
public Class<?> type() {
return HttpsServiceDef.class;
}
@Override
public Item mold(HttpsServiceDef serviceDef) {
if (serviceDef != null) {
Value headers = Value.absent();
if (!"0.0.0.0".equals(serviceDef.address)) {
headers = headers.updated("address", serviceDef.address);
}
if (serviceDef.port != 443) {
headers = headers.updated("port", serviceDef.port);
}
if (!headers.isDefined()) {
headers = Value.extant();
}
final Record record = Record.create().attr(tag(), headers);
if (serviceDef.planeName != null) {
record.slot("plane", serviceDef.planeName);
}
if (serviceDef.documentRoot != null) {
record.slot("documentRoot", serviceDef.documentRoot.toString());
}
return record.concat(serviceDef.warpSettings.toValue());
} else {
return Item.extant();
}
}
@Override
public HttpsServiceDef cast(Item item) {
final Value value = item.toValue();
final Value headers = value.getAttr(tag());
if (headers.isDefined()) {
final String address = headers.get("address").stringValue("0.0.0.0");
final int port = headers.get("port").intValue(443);
final String planeName = value.get("plane").stringValue(null);
final WarpSettings swimSettings = WarpSettings.form().cast(value);
final Uri documentRoot = value.get("documentRoot").cast(Uri.form());
return new HttpsServiceDef(address, port, planeName, documentRoot, swimSettings);
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-linker/3.9.3/swim | java-sources/ai/swim/swim-linker/3.9.3/swim/linker/OpenIdAuthDef.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.linker;
import swim.api.auth.Authenticated;
import swim.api.auth.Credentials;
import swim.api.auth.Identity;
import swim.api.policy.PolicyDirective;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.collections.FingerTrieSeq;
import swim.security.JsonWebSignature;
import swim.security.OpenIdToken;
import swim.security.PublicKeyDef;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Record;
import swim.structure.Value;
import swim.uri.Uri;
import swim.util.Builder;
import swim.util.Murmur3;
public final class OpenIdAuthDef extends AuthDef implements Debug {
final FingerTrieSeq<String> issuers;
final FingerTrieSeq<String> audiences;
final FingerTrieSeq<PublicKeyDef> publicKeyDefs;
public OpenIdAuthDef(FingerTrieSeq<String> issuers, FingerTrieSeq<String> audiences,
FingerTrieSeq<PublicKeyDef> publicKeyDefs) {
this.issuers = issuers;
this.audiences = audiences;
this.publicKeyDefs = publicKeyDefs;
}
public FingerTrieSeq<String> issuers() {
return this.issuers;
}
public FingerTrieSeq<String> audiences() {
return this.audiences;
}
public FingerTrieSeq<PublicKeyDef> publicKeyDefs() {
return this.publicKeyDefs;
}
public PolicyDirective<Identity> authenticate(Uri requestUri, Uri fromUri, JsonWebSignature jws) {
final Value payloadValue = jws.payload();
if (payloadValue.isDefined()) {
final OpenIdToken idToken = new OpenIdToken(payloadValue);
// TODO: check payload
for (int i = 0, n = this.publicKeyDefs.size(); i < n; i += 1) {
if (jws.verifySignature(this.publicKeyDefs.get(i).publicKey())) {
return PolicyDirective.<Identity>allow(new Authenticated(requestUri, fromUri, idToken.toValue()));
}
}
}
return null;
}
@Override
public PolicyDirective<Identity> authenticate(Credentials credentials) {
String compactJws = credentials.claims().get("idToken").stringValue(null);
if (compactJws == null) {
compactJws = credentials.claims().get("openIdToken").stringValue(null);
}
if (compactJws != null) {
final JsonWebSignature jws = JsonWebSignature.parse(compactJws);
if (jws != null) {
return authenticate(credentials.requestUri(), credentials.fromUri(), jws);
}
}
return null;
}
@Override
public Value toValue() {
return form().mold(this).toValue();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof OpenIdAuthDef) {
final OpenIdAuthDef that = (OpenIdAuthDef) other;
return this.issuers.equals(that.issuers) && this.audiences.equals(that.audiences)
&& this.publicKeyDefs.equals(that.publicKeyDefs);
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(OpenIdAuthDef.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed,
this.issuers.hashCode()), this.audiences.hashCode()), this.publicKeyDefs.hashCode()));
}
@Override
public void debug(Output<?> output) {
output = output.write("new").write(' ').write("OpenIdAuthDef").write('(')
.debug(this.issuers).write(", ").debug(this.audiences).write(", ")
.debug(this.publicKeyDefs).write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static Form<OpenIdAuthDef> form;
@Kind
public static Form<OpenIdAuthDef> form() {
if (form == null) {
form = new OpenIdAuthForm();
}
return form;
}
}
final class OpenIdAuthForm extends Form<OpenIdAuthDef> {
@Override
public String tag() {
return "openId";
}
@Override
public Class<?> type() {
return OpenIdAuthDef.class;
}
@Override
public Item mold(OpenIdAuthDef authDef) {
if (authDef != null) {
final Record record = Record.create().attr(tag());
Value issuers = Value.absent();
for (String issuer : authDef.issuers) {
issuers = issuers.appended(issuer);
}
if (issuers.isDefined()) {
record.slot("issuers", issuers);
}
Value audiences = Value.absent();
for (String audience : authDef.audiences) {
audiences = audiences.appended(audience);
}
if (audiences.isDefined()) {
record.slot("audiences", audiences);
}
for (PublicKeyDef publicKeyDef : authDef.publicKeyDefs) {
record.add(publicKeyDef.toValue());
}
return record;
} else {
return Item.extant();
}
}
@Override
public OpenIdAuthDef cast(Item item) {
final Value value = item.toValue();
final Value headers = value.getAttr(tag());
if (headers.isDefined()) {
final Builder<String, FingerTrieSeq<String>> issuers = FingerTrieSeq.builder();
final Builder<String, FingerTrieSeq<String>> audiences = FingerTrieSeq.builder();
final Builder<PublicKeyDef, FingerTrieSeq<PublicKeyDef>> publicKeyDefs = FingerTrieSeq.builder();
for (Item member : value) {
final String tag = member.tag();
if ("issuer".equals(tag)) {
issuers.add(member.get("issuer").stringValue());
} else if ("audience".equals(tag)) {
audiences.add(member.get("audience").stringValue());
} else {
final PublicKeyDef publicKeyDef = PublicKeyDef.publicKeyForm().cast(member.toValue());
if (publicKeyDef != null) {
publicKeyDefs.add(publicKeyDef);
}
}
}
return new OpenIdAuthDef(issuers.bind(), audiences.bind(), publicKeyDefs.bind());
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-linker/3.9.3/swim | java-sources/ai/swim/swim-linker/3.9.3/swim/linker/PlaneDef.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.linker;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.collections.FingerTrieSeq;
import swim.collections.HashTrieMap;
import swim.io.TlsSettings;
import swim.io.warp.WarpSettings;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Record;
import swim.structure.Value;
import swim.util.Murmur3;
public final class PlaneDef implements Debug {
final String name;
final String className;
final HashTrieMap<String, AgentTypeDef> agentTypeDefs;
final FingerTrieSeq<AuthDef> authDefs;
final WarpSettings warpSettings;
final Record record;
public PlaneDef(String name, String className, HashTrieMap<String, AgentTypeDef> agentTypeDefs,
FingerTrieSeq<AuthDef> authDefs, WarpSettings warpSettings) {
this(name, className, agentTypeDefs, authDefs, warpSettings, Record.empty());
}
public PlaneDef(String name, String className, HashTrieMap<String, AgentTypeDef> agentTypeDefs,
FingerTrieSeq<AuthDef> authDefs, WarpSettings warpSettings, Record record) {
this.name = name;
this.className = className;
this.agentTypeDefs = agentTypeDefs;
this.authDefs = authDefs;
this.warpSettings = warpSettings;
this.record = record;
}
public String name() {
return this.name;
}
public PlaneDef name(String name) {
return new PlaneDef(name, this.className, this.agentTypeDefs, this.authDefs, this.warpSettings);
}
public String className() {
return this.className;
}
public PlaneDef className(String className) {
return new PlaneDef(this.name, className, this.agentTypeDefs, this.authDefs, this.warpSettings);
}
public HashTrieMap<String, AgentTypeDef> agentTypeDefs() {
return this.agentTypeDefs;
}
public AgentTypeDef getAgentTypeDef(String agentName) {
return this.agentTypeDefs.get(agentName);
}
public PlaneDef agentTypeDef(AgentTypeDef agentTypeDef) {
return new PlaneDef(this.name, this.className, this.agentTypeDefs.updated(agentTypeDef.name(), agentTypeDef),
this.authDefs, this.warpSettings);
}
public FingerTrieSeq<AuthDef> authDefs() {
return this.authDefs;
}
public PlaneDef authDef(AuthDef authDef) {
return new PlaneDef(this.name, this.className, this.agentTypeDefs, this.authDefs.appended(authDef),
this.warpSettings);
}
public WarpSettings warpSettings() {
return this.warpSettings;
}
public PlaneDef warpSettings(WarpSettings warpSettings) {
return new PlaneDef(this.name, this.className, this.agentTypeDefs, this.authDefs, warpSettings);
}
public Record record() {
return record;
}
public Value toValue() {
return form().mold(this).toValue();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof PlaneDef) {
final PlaneDef that = (PlaneDef) other;
return this.name.equals(that.name)
&& (this.className == null ? that.className == null : this.className.equals(that.className))
&& this.agentTypeDefs.equals(that.agentTypeDefs) && this.authDefs.equals(that.authDefs)
&& this.warpSettings.equals(that.warpSettings);
}
return false;
}
@Override
public int hashCode() {
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed,
this.name.hashCode()), Murmur3.hash(this.className)), this.agentTypeDefs.hashCode()),
this.authDefs.hashCode()), this.warpSettings.hashCode()));
}
@Override
public void debug(Output<?> output) {
output = output.write("new").write(' ').write("PlaneDef").write('(')
.debug(this.name).write(", ").debug(this.agentTypeDefs).write(", ")
.debug(this.authDefs).write(", ").debug(this.warpSettings).write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static Form<PlaneDef> form;
@Kind
public static Form<PlaneDef> form() {
if (form == null) {
form = new PlaneForm();
}
return form;
}
}
final class PlaneForm extends Form<PlaneDef> {
@Override
public String tag() {
return "plane";
}
@Override
public Class<?> type() {
return PlaneDef.class;
}
@Override
public Item mold(PlaneDef planeDef) {
if (planeDef != null) {
final Record record = Record.create().attr(tag(), planeDef.name);
if (planeDef.className != null) {
record.slot("class", planeDef.className);
}
for (AgentTypeDef agentTypeDef : planeDef.agentTypeDefs.values()) {
record.item(agentTypeDef.toValue());
}
for (AuthDef authDef : planeDef.authDefs) {
record.item(authDef.toValue());
}
record.addAll((Record) planeDef.warpSettings.toValue());
return record;
} else {
return Item.extant();
}
}
@Override
public PlaneDef cast(Item value) {
final String name = value.getAttr(tag()).stringValue(null);
if (name != null) {
final String className = value.get("class").stringValue(null);
HashTrieMap<String, AgentTypeDef> agentTypeDefs = HashTrieMap.empty();
FingerTrieSeq<AuthDef> authDefs = FingerTrieSeq.empty();
for (int i = 0, n = value.length(); i < n; i += 1) {
final Value item = value.getItem(i).toValue();
final AgentTypeDef agentTypeDef = AgentTypeDef.form().cast(item);
if (agentTypeDef != null) {
agentTypeDefs = agentTypeDefs.updated(agentTypeDef.name(), agentTypeDef);
continue;
}
final AuthDef authDef = AuthDef.authForm().cast(item);
if (authDef != null) {
authDefs = authDefs.appended(authDef);
continue;
}
}
WarpSettings warpSettings = WarpSettings.form().cast(value);
if (warpSettings.tlsSettings() == null) {
warpSettings = warpSettings.tlsSettings(TlsSettings.standard());
}
return new PlaneDef(name, className, agentTypeDefs, authDefs, warpSettings, (Record) value);
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-linker/3.9.3/swim | java-sources/ai/swim/swim-linker/3.9.3/swim/linker/ServerDef.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.linker;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.collections.HashTrieMap;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Record;
import swim.structure.Value;
import swim.uri.Uri;
import swim.util.Murmur3;
public final class ServerDef implements Debug {
final HashTrieMap<String, PlaneDef> planeDefs;
final HashTrieMap<Uri, ServiceDef> serviceDefs;
final StoreDef storeDef;
public ServerDef(HashTrieMap<String, PlaneDef> planeDefs,
HashTrieMap<Uri, ServiceDef> serviceDefs, StoreDef storeDef) {
this.planeDefs = planeDefs;
this.serviceDefs = serviceDefs;
this.storeDef = storeDef;
}
public HashTrieMap<String, PlaneDef> planeDefs() {
return this.planeDefs;
}
public PlaneDef getPlaneDef(String planeName) {
return this.planeDefs.get(planeName);
}
public ServerDef planeDef(PlaneDef planeDef) {
return new ServerDef(this.planeDefs.updated(planeDef.name(), planeDef), this.serviceDefs, this.storeDef);
}
public HashTrieMap<Uri, ServiceDef> serviceDefs() {
return this.serviceDefs;
}
public ServiceDef getServiceDef(Uri serviceUri) {
return this.serviceDefs.get(serviceUri);
}
public ServerDef serviceDef(ServiceDef serviceDef) {
return new ServerDef(this.planeDefs, this.serviceDefs.updated(serviceDef.uri(), serviceDef), this.storeDef);
}
public StoreDef storeDef() {
return this.storeDef;
}
public ServerDef storeDef(StoreDef storeDef) {
return new ServerDef(this.planeDefs, this.serviceDefs, this.storeDef);
}
public Value toValue() {
return form().mold(this).toValue();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof ServerDef) {
final ServerDef that = (ServerDef) other;
return this.planeDefs.equals(that.planeDefs)
&& this.serviceDefs.equals(that.serviceDefs)
&& this.storeDef.equals(that.storeDef);
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(ServerDef.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed,
this.planeDefs.hashCode()), this.serviceDefs.hashCode()),
this.storeDef.hashCode()));
}
@Override
public void debug(Output<?> output) {
output = output.write("new").write(' ').write("ServerDef").write('(')
.debug(this.planeDefs).write(", ").debug(this.serviceDefs).write(", ")
.debug(this.storeDef).write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static Form<ServerDef> form;
@Kind
public static Form<ServerDef> form() {
if (form == null) {
form = new ServerForm();
}
return form;
}
}
final class ServerForm extends Form<ServerDef> {
@Override
public String tag() {
return "server";
}
@Override
public Class<?> type() {
return ServerDef.class;
}
@Override
public Item mold(ServerDef serverDef) {
if (serverDef != null) {
final Record record = Record.create().attr(tag());
for (PlaneDef planeDef : serverDef.planeDefs.values()) {
record.add(planeDef.toValue());
}
for (ServiceDef serviceDef : serverDef.serviceDefs.values()) {
record.add(serviceDef.toValue());
}
record.add(serverDef.storeDef.toValue());
return record;
} else {
return Item.extant();
}
}
@Override
public ServerDef cast(Item item) {
final Value value = item.toValue();
final Value header = value.getAttr(tag());
if (header.isDefined()) {
HashTrieMap<String, PlaneDef> planeDefs = HashTrieMap.empty();
HashTrieMap<Uri, ServiceDef> serviceDefs = HashTrieMap.empty();
StoreDef storeDef = null;
for (int i = 0, n = value.length(); i < n; i += 1) {
final Item member = value.getItem(i);
final PlaneDef planeDef = PlaneDef.form().cast(member);
if (planeDef != null) {
planeDefs = planeDefs.updated(planeDef.name(), planeDef);
}
final HttpServiceDef httpServiceDef = HttpServiceDef.form().cast(member);
if (httpServiceDef != null) {
serviceDefs = serviceDefs.updated(httpServiceDef.uri(), httpServiceDef);
}
final HttpsServiceDef httpsServiceDef = HttpsServiceDef.form().cast(member);
if (httpsServiceDef != null) {
serviceDefs = serviceDefs.updated(httpsServiceDef.uri(), httpsServiceDef);
}
final StoreDef newStoreDef = StoreDef.form().cast(member);
if (newStoreDef != null) {
storeDef = newStoreDef;
}
}
if (storeDef == null) {
storeDef = new StoreDef(null);
}
return new ServerDef(planeDefs, serviceDefs, storeDef);
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-linker/3.9.3/swim | java-sources/ai/swim/swim-linker/3.9.3/swim/linker/ServerLinker.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.linker;
import swim.api.server.ServerContext;
public interface ServerLinker extends ServerContext {
ServerLinker materialize(ServerDef serverDef);
}
|
0 | java-sources/ai/swim/swim-linker/3.9.3/swim | java-sources/ai/swim/swim-linker/3.9.3/swim/linker/ServiceDef.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.linker;
import swim.structure.Value;
import swim.uri.Uri;
import swim.uri.UriAuthority;
import swim.uri.UriHost;
import swim.uri.UriPort;
import swim.uri.UriScheme;
public abstract class ServiceDef {
protected Uri uri;
public abstract UriScheme scheme();
public abstract String address();
public abstract int port();
public UriAuthority authority() {
return UriAuthority.from(UriHost.parse(address()), UriPort.from(port()));
}
public Uri uri() {
if (this.uri == null) {
this.uri = Uri.from(scheme(), authority());
}
return this.uri;
}
public abstract Value toValue();
}
|
0 | java-sources/ai/swim/swim-linker/3.9.3/swim | java-sources/ai/swim/swim-linker/3.9.3/swim/linker/StorageLinker.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.linker;
import swim.store.StorageContext;
public interface StorageLinker extends StorageContext {
StorageLinker materialize(StoreDef storeDef);
}
|
0 | java-sources/ai/swim/swim-linker/3.9.3/swim | java-sources/ai/swim/swim-linker/3.9.3/swim/linker/StoreDef.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.linker;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Value;
import swim.util.Murmur3;
public final class StoreDef implements Debug {
final String path;
final Value settings;
public StoreDef(String path) {
this(path, Value.empty());
}
public StoreDef(String path, Value settings) {
this.path = path;
this.settings = settings;
}
public String path() {
return this.path;
}
public StoreDef path(String path) {
return new StoreDef(path, this.settings);
}
public Value settings() {
return this.settings;
}
public StoreDef settings(Value settings) {
return new StoreDef(this.path, settings);
}
public Value toValue() {
return form().mold(this).toValue();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof StoreDef) {
final StoreDef that = (StoreDef) other;
return this.path.equals(that.path) && this.settings.equals(that.settings);
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(StoreDef.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(hashSeed,
Murmur3.hash(this.path)), this.settings.hashCode()));
}
@Override
public void debug(Output<?> output) {
output = output.write("new").write(' ').write("StoreDef").write('(')
.debug(this.path).write(", ").debug(this.settings).write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static Form<StoreDef> form;
@Kind
public static Form<StoreDef> form() {
if (form == null) {
form = new StoreForm();
}
return form;
}
}
final class StoreForm extends Form<StoreDef> {
@Override
public String tag() {
return "store";
}
@Override
public Class<?> type() {
return StoreDef.class;
}
@Override
public Item mold(StoreDef storeDef) {
if (storeDef != null) {
return storeDef.settings;
} else {
return Item.extant();
}
}
@Override
public StoreDef cast(Item item) {
final Value value = item.toValue();
if (value.getAttr(tag()).isDefined()) {
final String path = value.get("path").stringValue(null);
return new StoreDef(path, value);
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-linker/3.9.3/swim | java-sources/ai/swim/swim-linker/3.9.3/swim/linker/WarpServiceDef.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.linker;
import swim.io.warp.WarpSettings;
import swim.uri.Uri;
public abstract class WarpServiceDef extends ServiceDef {
public abstract String planeName();
public abstract Uri documentRoot();
public abstract WarpSettings warpSettings();
}
|
0 | java-sources/ai/swim/swim-linker/3.9.3/swim | java-sources/ai/swim/swim-linker/3.9.3/swim/linker/package-info.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* Runtime configuration interfaces.
*/
package swim.linker;
|
0 | java-sources/ai/swim/swim-loader | java-sources/ai/swim/swim-loader/3.9.3/module-info.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* Dynamic runtime loader.
*/
module swim.loader {
requires transitive swim.api;
requires transitive swim.linker;
requires transitive swim.recon;
exports swim.loader;
uses swim.api.client.Client;
uses swim.api.client.ClientContext;
uses swim.api.router.Router;
uses swim.api.server.Server;
uses swim.api.server.ServerContext;
uses swim.api.storage.Storage;
}
|
0 | java-sources/ai/swim/swim-loader/3.9.3/swim | java-sources/ai/swim/swim-loader/3.9.3/swim/loader/ClientLoader.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.loader;
import java.util.Iterator;
import java.util.ServiceLoader;
import swim.api.SwimContext;
import swim.api.client.Client;
import swim.api.client.ClientContext;
import swim.api.router.Router;
import swim.linker.ClientLinker;
public final class ClientLoader {
private ClientLoader() {
// nop
}
public static Client load() {
final ClientContext context = loadClientContext();
final Router router = RouterLoader.loadRouter();
context.setRouter(router);
final Client client = loadClient(context);
if (context instanceof ClientLinker) {
// TODO: materialize client
}
return client;
}
public static Client loadClient(ClientContext context) {
try {
SwimContext.setClientContext(context);
final ServiceLoader<Client> clientLoader = ServiceLoader.load(Client.class);
final Iterator<Client> clients = clientLoader.iterator();
if (clients.hasNext()) {
return clients.next();
}
return new GenericClient();
} finally {
SwimContext.setClientContext(null);
}
}
public static ClientContext loadClientContext() {
final ServiceLoader<ClientContext> clientContextLoader = ServiceLoader.load(ClientContext.class);
final Iterator<ClientContext> clientContexts = clientContextLoader.iterator();
if (clientContexts.hasNext()) {
return clientContexts.next();
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-loader/3.9.3/swim | java-sources/ai/swim/swim-loader/3.9.3/swim/loader/GenericClient.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.loader;
import swim.api.client.AbstractClient;
import swim.api.client.ClientContext;
final class GenericClient extends AbstractClient {
GenericClient(ClientContext context) {
super(context);
}
GenericClient() {
super();
}
}
|
0 | java-sources/ai/swim/swim-loader/3.9.3/swim | java-sources/ai/swim/swim-loader/3.9.3/swim/loader/GenericServer.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.loader;
import swim.api.server.AbstractServer;
import swim.api.server.ServerContext;
final class GenericServer extends AbstractServer {
GenericServer(ServerContext context) {
super(context);
}
GenericServer() {
super();
}
}
|
0 | java-sources/ai/swim/swim-loader/3.9.3/swim | java-sources/ai/swim/swim-loader/3.9.3/swim/loader/RouterLoader.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.loader;
import java.util.Iterator;
import java.util.ServiceLoader;
import swim.api.router.Router;
public final class RouterLoader {
private RouterLoader() {
// nop
}
public static Router loadRouter() {
final ServiceLoader<Router> routerLoader = ServiceLoader.load(Router.class);
final Iterator<Router> routers = routerLoader.iterator();
Router router;
if (routers.hasNext()) {
router = routers.next();
while (routers.hasNext()) {
// TODO: configurable router injection
router = router.injectRouter(routers.next());
}
} else {
router = null;
}
return router;
}
}
|
0 | java-sources/ai/swim/swim-loader/3.9.3/swim | java-sources/ai/swim/swim-loader/3.9.3/swim/loader/ServerLoader.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.loader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.ServiceLoader;
import swim.api.SwimContext;
import swim.api.plane.Plane;
import swim.api.plane.PlaneException;
import swim.api.router.Router;
import swim.api.server.Server;
import swim.api.server.ServerContext;
import swim.api.storage.Storage;
import swim.codec.Utf8;
import swim.linker.ServerDef;
import swim.linker.ServerLinker;
import swim.linker.StorageLinker;
import swim.recon.Recon;
import swim.structure.Value;
public final class ServerLoader {
private ServerLoader() {
// nop
}
public static void main(String[] args) throws IOException {
final ServerContext server = loadServerContext();
if (server instanceof ServerLinker) {
final ServiceLoader<Plane> planeLoader = ServiceLoader.load(Plane.class);
planeLoader.stream().forEach((ServiceLoader.Provider<Plane> planeProvider) -> {
try {
final ServerDef serverDef = loadServerDef(planeProvider.type().getModule());
((ServerLinker) server).materialize(serverDef);
} catch (IOException error) {
throw new PlaneException(error);
}
});
}
server.start();
server.run(); // blocks until termination
}
public static Server load(Module module) throws IOException {
final ServerContext context = loadServerContext();
final Router router = RouterLoader.loadRouter();
context.setRouter(router);
final Storage storage = StorageLoader.loadStorage();
context.setStorage(storage);
final Server server = loadServer(context);
if (context instanceof ServerLinker) {
final ServerDef serverDef = loadServerDef(module);
if (storage instanceof StorageLinker) {
((StorageLinker) storage).materialize(serverDef.storeDef());
}
((ServerLinker) context).materialize(serverDef);
}
return server;
}
public static Server loadServer(ServerContext context) {
try {
SwimContext.setServerContext(context);
final ServiceLoader<Server> serverLoader = ServiceLoader.load(Server.class);
final Iterator<Server> servers = serverLoader.iterator();
if (servers.hasNext()) {
return servers.next();
}
return new GenericServer();
} finally {
SwimContext.setServerContext(null);
}
}
public static ServerContext loadServerContext() {
final ServiceLoader<ServerContext> serverContextLoader = ServiceLoader.load(ServerContext.class);
final Iterator<ServerContext> serverContexts = serverContextLoader.iterator();
if (serverContexts.hasNext()) {
return serverContexts.next();
}
return null;
}
private static ServerDef loadServerDef(Module module) throws IOException {
final Value configValue = loadConfigValue(module);
return ServerDef.form().cast(configValue);
}
private static Value loadConfigValue(Module module) throws IOException {
String configPath = System.getProperty("swim.config");
if (configPath == null) {
configPath = "/server.recon";
}
InputStream configInput = null;
final Value configValue;
try {
final File configFile = new File(configPath);
if (configFile.exists()) {
configInput = new FileInputStream(configFile);
} else {
configInput = module.getResourceAsStream(configPath);
}
if (configInput != null) {
configValue = Utf8.read(Recon.structureParser().blockParser(), configInput);
} else {
configValue = Value.absent();
}
} finally {
try {
if (configInput != null) {
configInput.close();
}
} catch (IOException swallow) {
}
}
return configValue;
}
}
|
0 | java-sources/ai/swim/swim-loader/3.9.3/swim | java-sources/ai/swim/swim-loader/3.9.3/swim/loader/StorageLoader.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.loader;
import java.util.Iterator;
import java.util.ServiceLoader;
import swim.api.storage.Storage;
public final class StorageLoader {
private StorageLoader() {
// nop
}
public static Storage loadStorage() {
final ServiceLoader<Storage> storageLoader = ServiceLoader.load(Storage.class);
final Iterator<Storage> storages = storageLoader.iterator();
Storage storage;
if (storages.hasNext()) {
storage = storages.next();
while (storages.hasNext()) {
// TODO: configurable storage injection
storage = storage.injectStorage(storages.next());
}
} else {
storage = null;
}
return storage;
}
}
|
0 | java-sources/ai/swim/swim-loader/3.9.3/swim | java-sources/ai/swim/swim-loader/3.9.3/swim/loader/package-info.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* Dynamic runtime loader.
*/
package swim.loader;
|
0 | java-sources/ai/swim/swim-math | java-sources/ai/swim/swim-math/3.10.0/module-info.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* Mathematical and geometric structures.
*/
module swim.math {
requires swim.util;
requires transitive swim.codec;
requires transitive swim.structure;
exports swim.math;
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/AffineSpace.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
public interface AffineSpace<P, V, S> {
VectorSpace<V, S> vector();
Field<S> scalar();
P origin();
P translate(P p, V v);
V difference(P p, P q);
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/Boundary.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
public interface Boundary<T> {
boolean contains(T outer, T inner);
boolean intersects(T s, T t);
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/BoxR2.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.structure.Kind;
import swim.structure.Value;
import swim.util.Murmur3;
public class BoxR2 extends R2Shape implements Debug {
public final double xMin;
public final double yMin;
public final double xMax;
public final double yMax;
public BoxR2(double xMin, double yMin, double xMax, double yMax) {
this.xMin = xMin <= xMax ? xMin : xMax;
this.yMin = yMin <= yMax ? yMin : yMax;
this.xMax = xMin <= xMax ? xMax : xMin;
this.yMax = yMin <= yMax ? yMax : yMin;
}
@Override
public final double xMin() {
return this.xMin;
}
@Override
public final double yMin() {
return this.yMin;
}
@Override
public final double xMax() {
return this.xMax;
}
@Override
public final double yMax() {
return this.yMax;
}
@Override
public boolean contains(R2Shape shape) {
if (shape instanceof PointR2) {
return contains((PointR2) shape);
} else if (shape instanceof BoxR2) {
return contains((BoxR2) shape);
} else if (shape instanceof CircleR2) {
return contains((CircleR2) shape);
} else {
return this.xMin <= shape.xMin() && shape.xMax() <= this.xMax
&& this.yMin <= shape.yMin() && shape.yMax() <= this.yMax;
}
}
public boolean contains(PointR2 point) {
return this.xMin <= point.x && point.x <= this.xMax
&& this.yMin <= point.y && point.y <= this.yMax;
}
public boolean contains(BoxR2 box) {
return this.xMin <= box.xMin && box.xMax <= this.xMax
&& this.yMin <= box.yMin && box.yMax <= this.yMax;
}
public boolean contains(CircleR2 circle) {
return this.xMin <= circle.cx - circle.r && circle.cx + circle.r <= this.xMax
&& this.yMin <= circle.cy - circle.r && circle.cy + circle.r <= this.yMax;
}
@Override
public boolean intersects(R2Shape shape) {
if (shape instanceof PointR2) {
return intersects((PointR2) shape);
} else if (shape instanceof BoxR2) {
return intersects((BoxR2) shape);
} else if (shape instanceof CircleR2) {
return intersects((CircleR2) shape);
} else {
return shape.intersects(this);
}
}
public boolean intersects(PointR2 point) {
return this.xMin <= point.x && point.x <= this.xMax
&& this.yMin <= point.y && point.y <= this.yMax;
}
public boolean intersects(BoxR2 box) {
return this.xMin <= box.xMax && box.xMin <= this.xMax
&& this.yMin <= box.yMax && box.yMin <= this.yMax;
}
public boolean intersects(CircleR2 circle) {
final double dx = (circle.cx < this.xMin ? this.xMin : this.xMax < circle.cx ? this.xMax : circle.cx) - circle.cx;
final double dy = (circle.cy < this.yMin ? this.yMin : this.yMax < circle.cy ? this.yMax : circle.cy) - circle.cy;
return dx * dx + dy * dy <= circle.r * circle.r;
}
@Override
public BoxZ2 transform(R2ToZ2Function f) {
return new BoxZ2(f.transformX(this.xMin, this.yMin), f.transformY(this.xMin, this.yMin),
f.transformX(this.xMax, this.yMax), f.transformY(this.xMax, this.yMax));
}
@Override
public Value toValue() {
return form().mold(this).toValue();
}
protected boolean canEqual(BoxR2 that) {
return true;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof BoxR2) {
final BoxR2 that = (BoxR2) other;
return that.canEqual(this) && this.xMin == that.xMin && this.yMin == that.yMin
&& this.xMax == that.xMax && this.yMax == that.yMax;
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(BoxR2.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed,
Murmur3.hash(this.xMin)), Murmur3.hash(this.yMin)),
Murmur3.hash(this.xMax)), Murmur3.hash(this.yMax)));
}
@Override
public void debug(Output<?> output) {
output.write("BoxR2").write('.').write("of").write('(')
.debug(this.xMin).write(", ").debug(this.yMin).write(", ")
.debug(this.xMax).write(", ").debug(this.yMax).write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static R2Form<BoxR2> form;
public static BoxR2 of(double xMin, double yMin, double xMax, double yMax) {
return new BoxR2(xMin, yMin, xMax, yMax);
}
@Kind
public static R2Form<BoxR2> form() {
if (form == null) {
form = new BoxR2Form();
}
return form;
}
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/BoxR2Form.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
import swim.structure.Item;
import swim.structure.Record;
import swim.structure.Value;
final class BoxR2Form extends R2Form<BoxR2> {
@Override
public String tag() {
return "box";
}
@Override
public Class<?> type() {
return BoxR2.class;
}
@Override
public double getXMin(BoxR2 box) {
return box.xMin;
}
@Override
public double getYMin(BoxR2 box) {
return box.yMin;
}
@Override
public double getXMax(BoxR2 box) {
return box.xMax;
}
@Override
public double getYMax(BoxR2 box) {
return box.yMax;
}
@Override
public boolean contains(BoxR2 outer, BoxR2 inner) {
return outer.contains(inner);
}
@Override
public boolean intersects(BoxR2 s, BoxR2 t) {
return s.intersects(t);
}
@Override
public Item mold(BoxR2 box) {
if (box != null) {
return Record.create(1).attr(tag(), Record.create(4)
.item(box.xMin).item(box.yMin)
.item(box.xMax).item(box.yMax));
} else {
return Item.extant();
}
}
@Override
public BoxR2 cast(Item item) {
final Value header = item.toValue().header(tag());
if (header.isDefined()) {
final double xMin = header.getItem(0).doubleValue(0.0);
final double yMin = header.getItem(1).doubleValue(0.0);
final double xMax = header.getItem(2).doubleValue(0.0);
final double yMax = header.getItem(3).doubleValue(0.0);
return new BoxR2(xMin, yMin, xMax, yMax);
} else {
return null;
}
}
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/BoxR3.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.structure.Kind;
import swim.structure.Value;
import swim.util.Murmur3;
public class BoxR3 extends R3Shape implements Debug {
public final double xMin;
public final double yMin;
public final double zMin;
public final double xMax;
public final double yMax;
public final double zMax;
public BoxR3(double xMin, double yMin, double zMin, double xMax, double yMax, double zMax) {
this.xMin = xMin <= xMax ? xMin : xMax;
this.yMin = yMin <= yMax ? yMin : yMax;
this.zMin = zMin <= zMax ? zMin : zMax;
this.xMax = xMin <= xMax ? xMax : xMin;
this.yMax = yMin <= yMax ? yMax : yMin;
this.zMax = zMin <= zMax ? zMax : zMin;
}
@Override
public final double xMin() {
return this.xMin;
}
@Override
public final double yMin() {
return this.yMin;
}
@Override
public final double zMin() {
return this.zMin;
}
@Override
public final double xMax() {
return this.xMax;
}
@Override
public final double yMax() {
return this.yMax;
}
@Override
public final double zMax() {
return this.zMax;
}
@Override
public boolean contains(R3Shape shape) {
if (shape instanceof PointR3) {
return contains((PointR3) shape);
} else if (shape instanceof BoxR3) {
return contains((BoxR3) shape);
} else if (shape instanceof SphereR3) {
return contains((SphereR3) shape);
} else {
return this.xMin <= shape.xMin() && shape.xMax() <= this.xMax
&& this.yMin <= shape.yMin() && shape.yMax() <= this.yMax
&& this.zMin <= shape.zMin() && shape.zMax() <= this.zMax;
}
}
public boolean contains(PointR3 point) {
return this.xMin <= point.x && point.x <= this.xMax
&& this.yMin <= point.y && point.y <= this.yMax
&& this.zMin <= point.z && point.z <= this.zMax;
}
public boolean contains(BoxR3 box) {
return this.xMin <= box.xMin && box.xMax <= this.xMax
&& this.yMin <= box.yMin && box.yMax <= this.yMax
&& this.zMin <= box.zMin && box.zMax <= this.zMax;
}
public boolean contains(SphereR3 sphere) {
return this.xMin <= sphere.cx - sphere.r && sphere.cx + sphere.r <= this.xMax
&& this.yMin <= sphere.cy - sphere.r && sphere.cy + sphere.r <= this.yMax
&& this.zMin <= sphere.cz - sphere.r && sphere.cz + sphere.r <= this.zMax;
}
@Override
public boolean intersects(R3Shape shape) {
if (shape instanceof PointR3) {
return intersects((PointR3) shape);
} else if (shape instanceof BoxR3) {
return intersects((BoxR3) shape);
} else if (shape instanceof SphereR3) {
return intersects((SphereR3) shape);
} else {
return shape.intersects(this);
}
}
public boolean intersects(PointR3 point) {
return this.xMin <= point.x && point.x <= this.xMax
&& this.yMin <= point.y && point.y <= this.yMax
&& this.zMin <= point.z && point.z <= this.zMax;
}
public boolean intersects(BoxR3 box) {
return this.xMin <= box.xMax && box.xMin <= this.xMax
&& this.yMin <= box.yMax && box.yMin <= this.yMax
&& this.zMin <= box.zMax && box.zMin <= this.zMax;
}
public boolean intersects(SphereR3 sphere) {
final double dx = (sphere.cx < this.xMin ? this.xMin : this.xMax < sphere.cx ? this.xMax : sphere.cx) - sphere.cx;
final double dy = (sphere.cy < this.yMin ? this.yMin : this.yMax < sphere.cy ? this.yMax : sphere.cy) - sphere.cy;
final double dz = (sphere.cz < this.zMin ? this.zMin : this.zMax < sphere.cz ? this.zMax : sphere.cz) - sphere.cz;
return dx * dx + dy * dy + dz * dz <= sphere.r * sphere.r;
}
@Override
public BoxZ3 transform(R3ToZ3Function f) {
return new BoxZ3(f.transformX(this.xMin, this.yMin, this.zMin),
f.transformY(this.xMin, this.yMin, this.zMin),
f.transformZ(this.xMin, this.yMin, this.zMin),
f.transformX(this.xMax, this.yMax, this.zMax),
f.transformY(this.xMax, this.yMax, this.zMax),
f.transformZ(this.zMax, this.zMax, this.zMax));
}
@Override
public Value toValue() {
return form().mold(this).toValue();
}
protected boolean canEqual(BoxR3 that) {
return true;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof BoxR3) {
final BoxR3 that = (BoxR3) other;
return that.canEqual(this)
&& this.xMin == that.xMin && this.yMin == that.yMin && this.zMin == that.zMin
&& this.xMax == that.xMax && this.yMax == that.yMax && this.zMax == that.zMax;
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(BoxR3.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed,
Murmur3.hash(this.xMin)), Murmur3.hash(this.yMin)), Murmur3.hash(this.zMin)),
Murmur3.hash(this.xMax)), Murmur3.hash(this.yMax)), Murmur3.hash(this.zMax)));
}
@Override
public void debug(Output<?> output) {
output.write("BoxR3").write('.').write("of").write('(')
.debug(this.xMin).write(", ").debug(this.yMin).write(", ").debug(this.zMin).write(", ")
.debug(this.xMax).write(", ").debug(this.yMax).write(", ").debug(this.zMax).write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static R3Form<BoxR3> form;
public static BoxR3 of(double xMin, double yMin, double zMin,
double xMax, double yMax, double zMax) {
return new BoxR3(xMin, yMin, zMin, xMax, yMax, zMax);
}
@Kind
public static R3Form<BoxR3> form() {
if (form == null) {
form = new BoxR3Form();
}
return form;
}
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/BoxR3Form.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
import swim.structure.Item;
import swim.structure.Record;
import swim.structure.Value;
final class BoxR3Form extends R3Form<BoxR3> {
@Override
public String tag() {
return "box";
}
@Override
public Class<?> type() {
return BoxR3.class;
}
@Override
public double getXMin(BoxR3 box) {
return box.xMin;
}
@Override
public double getYMin(BoxR3 box) {
return box.yMin;
}
@Override
public double getZMin(BoxR3 box) {
return box.zMin;
}
@Override
public double getXMax(BoxR3 box) {
return box.xMax;
}
@Override
public double getYMax(BoxR3 box) {
return box.yMax;
}
@Override
public double getZMax(BoxR3 box) {
return box.zMax;
}
@Override
public boolean contains(BoxR3 outer, BoxR3 inner) {
return outer.contains(inner);
}
@Override
public boolean intersects(BoxR3 s, BoxR3 t) {
return s.intersects(t);
}
@Override
public Item mold(BoxR3 box) {
if (box != null) {
return Record.create(1).attr(tag(), Record.create(6)
.item(box.xMin).item(box.yMin).item(box.zMin)
.item(box.xMax).item(box.yMax).item(box.zMax));
} else {
return Item.extant();
}
}
@Override
public BoxR3 cast(Item item) {
final Value header = item.toValue().header(tag());
if (header.isDefined()) {
final double xMin = header.getItem(0).doubleValue(0.0);
final double yMin = header.getItem(1).doubleValue(0.0);
final double zMin = header.getItem(2).doubleValue(0.0);
final double xMax = header.getItem(3).doubleValue(0.0);
final double yMax = header.getItem(4).doubleValue(0.0);
final double zMax = header.getItem(5).doubleValue(0.0);
return new BoxR3(xMin, yMin, zMin, xMax, yMax, zMax);
} else {
return null;
}
}
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/BoxZ2.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.structure.Kind;
import swim.structure.Value;
import swim.util.Murmur3;
public class BoxZ2 extends Z2Shape implements Debug {
public final long xMin;
public final long yMin;
public final long xMax;
public final long yMax;
public BoxZ2(long xMin, long yMin, long xMax, long yMax) {
this.xMin = xMin <= xMax ? xMin : xMax;
this.yMin = yMin <= yMax ? yMin : yMax;
this.xMax = xMin <= xMax ? xMax : xMin;
this.yMax = yMin <= yMax ? yMax : yMin;
}
@Override
public final long xMin() {
return this.xMin;
}
@Override
public final long yMin() {
return this.yMin;
}
@Override
public final long xMax() {
return this.xMax;
}
@Override
public final long yMax() {
return this.yMax;
}
@Override
public boolean contains(Z2Shape shape) {
if (shape instanceof PointZ2) {
return contains((PointZ2) shape);
} else if (shape instanceof BoxZ2) {
return contains((BoxZ2) shape);
} else {
return this.xMin <= shape.xMin() && shape.xMax() <= this.xMax
&& this.yMin <= shape.yMin() && shape.yMax() <= this.yMax;
}
}
public boolean contains(PointZ2 point) {
return this.xMin <= point.x && point.x <= this.xMax
&& this.yMin <= point.y && point.y <= this.yMax;
}
public boolean contains(BoxZ2 box) {
return this.xMin <= box.xMin && box.xMax <= this.xMax
&& this.yMin <= box.yMin && box.yMax <= this.yMax;
}
@Override
public boolean intersects(Z2Shape shape) {
if (shape instanceof PointZ2) {
return intersects((PointZ2) shape);
} else if (shape instanceof BoxZ2) {
return intersects((BoxZ2) shape);
} else {
return shape.intersects(this);
}
}
public boolean intersects(PointZ2 point) {
return this.xMin <= point.x && point.x <= this.xMax
&& this.yMin <= point.y && point.y <= this.yMax;
}
public boolean intersects(BoxZ2 box) {
return this.xMin <= box.xMax && box.xMin <= this.xMax
&& this.yMin <= box.yMax && box.yMin <= this.yMax;
}
@Override
public BoxR2 transform(Z2ToR2Function f) {
return new BoxR2(f.transformX(this.xMin, this.yMin), f.transformY(this.xMin, this.yMin),
f.transformX(this.xMax, this.yMax), f.transformY(this.xMax, this.yMax));
}
@Override
public Value toValue() {
return form().mold(this).toValue();
}
protected boolean canEqual(BoxZ2 that) {
return true;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof BoxZ2) {
final BoxZ2 that = (BoxZ2) other;
return that.canEqual(this) && this.xMin == that.xMin && this.yMin == that.yMin
&& this.xMax == that.xMax && this.yMax == that.yMax;
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(BoxZ2.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed,
Murmur3.hash(this.xMin)), Murmur3.hash(this.yMin)),
Murmur3.hash(this.xMax)), Murmur3.hash(this.yMax)));
}
@Override
public void debug(Output<?> output) {
output.write("BoxZ2").write('.').write("of").write('(')
.debug(this.xMin).write(", ").debug(this.yMin).write(", ")
.debug(this.xMax).write(", ").debug(this.yMax).write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static Z2Form<BoxZ2> form;
public static BoxZ2 of(long xMin, long yMin, long xMax, long yMax) {
return new BoxZ2(xMin, yMin, xMax, yMax);
}
@Kind
public static Z2Form<BoxZ2> form() {
if (form == null) {
form = new BoxZ2Form();
}
return form;
}
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/BoxZ2Form.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
import swim.structure.Item;
import swim.structure.Record;
import swim.structure.Value;
final class BoxZ2Form extends Z2Form<BoxZ2> {
@Override
public String tag() {
return "box";
}
@Override
public Class<?> type() {
return BoxZ2.class;
}
@Override
public long getXMin(BoxZ2 box) {
return box.xMin;
}
@Override
public long getYMin(BoxZ2 box) {
return box.yMin;
}
@Override
public long getXMax(BoxZ2 box) {
return box.xMax;
}
@Override
public long getYMax(BoxZ2 box) {
return box.yMax;
}
@Override
public boolean contains(BoxZ2 outer, BoxZ2 inner) {
return outer.contains(inner);
}
@Override
public boolean intersects(BoxZ2 s, BoxZ2 t) {
return s.intersects(t);
}
@Override
public Item mold(BoxZ2 box) {
if (box != null) {
return Record.create(1).attr(tag(), Record.create(4)
.item(box.xMin).item(box.yMin)
.item(box.xMax).item(box.yMax));
} else {
return Item.extant();
}
}
@Override
public BoxZ2 cast(Item item) {
final Value header = item.toValue().header(tag());
if (header.isDefined()) {
final long xMin = header.getItem(0).longValue(0L);
final long yMin = header.getItem(1).longValue(0L);
final long xMax = header.getItem(2).longValue(0L);
final long yMax = header.getItem(3).longValue(0L);
return new BoxZ2(xMin, yMin, xMax, yMax);
} else {
return null;
}
}
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/BoxZ3.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.structure.Kind;
import swim.structure.Value;
import swim.util.Murmur3;
public class BoxZ3 extends Z3Shape implements Debug {
public final long xMin;
public final long yMin;
public final long zMin;
public final long xMax;
public final long yMax;
public final long zMax;
public BoxZ3(long xMin, long yMin, long zMin, long xMax, long yMax, long zMax) {
this.xMin = xMin <= xMax ? xMin : xMax;
this.yMin = yMin <= yMax ? yMin : yMax;
this.zMin = zMin <= zMax ? zMin : zMax;
this.xMax = xMin <= xMax ? xMax : xMin;
this.yMax = yMin <= yMax ? yMax : yMin;
this.zMax = zMin <= zMax ? zMax : zMin;
}
@Override
public final long xMin() {
return this.xMin;
}
@Override
public final long yMin() {
return this.yMin;
}
@Override
public final long zMin() {
return this.zMin;
}
@Override
public final long xMax() {
return this.xMax;
}
@Override
public final long yMax() {
return this.yMax;
}
@Override
public final long zMax() {
return this.zMax;
}
@Override
public boolean contains(Z3Shape shape) {
if (shape instanceof PointZ3) {
return contains((PointZ3) shape);
} else if (shape instanceof BoxZ3) {
return contains((BoxZ3) shape);
} else {
return this.xMin <= shape.xMin() && shape.xMax() <= this.xMax
&& this.yMin <= shape.yMin() && shape.yMax() <= this.yMax
&& this.zMin <= shape.zMin() && shape.zMax() <= this.zMax;
}
}
public boolean contains(PointZ3 point) {
return this.xMin <= point.x && point.x <= this.xMax
&& this.yMin <= point.y && point.y <= this.yMax
&& this.zMin <= point.z && point.z <= this.zMax;
}
public boolean contains(BoxZ3 box) {
return this.xMin <= box.xMin && box.xMax <= this.xMax
&& this.yMin <= box.yMin && box.yMax <= this.yMax
&& this.zMin <= box.zMin && box.zMax <= this.zMax;
}
@Override
public boolean intersects(Z3Shape shape) {
if (shape instanceof PointZ3) {
return intersects((PointZ3) shape);
} else if (shape instanceof BoxZ3) {
return intersects((BoxZ3) shape);
} else {
return shape.intersects(this);
}
}
public boolean intersects(PointZ3 point) {
return this.xMin <= point.x && point.x <= this.xMax
&& this.yMin <= point.y && point.y <= this.yMax
&& this.zMin <= point.z && point.z <= this.zMax;
}
public boolean intersects(BoxZ3 box) {
return this.xMin <= box.xMax && box.xMin <= this.xMax
&& this.yMin <= box.yMax && box.yMin <= this.yMax
&& this.zMin <= box.zMax && box.zMin <= this.zMax;
}
@Override
public BoxR3 transform(Z3ToR3Function f) {
return new BoxR3(f.transformX(this.xMin, this.yMin, this.zMin),
f.transformY(this.xMin, this.yMin, this.zMin),
f.transformZ(this.xMin, this.yMin, this.zMin),
f.transformX(this.xMax, this.yMax, this.zMax),
f.transformY(this.xMax, this.yMax, this.zMax),
f.transformZ(this.xMax, this.yMax, this.zMax));
}
@Override
public Value toValue() {
return form().mold(this).toValue();
}
protected boolean canEqual(BoxZ3 that) {
return true;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof BoxZ3) {
final BoxZ3 that = (BoxZ3) other;
return that.canEqual(this)
&& this.xMin == that.xMin && this.yMin == that.yMin && this.zMin == that.zMin
&& this.xMax == that.xMax && this.yMax == that.yMax && this.zMax == that.zMax;
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(BoxZ3.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed,
Murmur3.hash(this.xMin)), Murmur3.hash(this.yMin)), Murmur3.hash(this.zMin)),
Murmur3.hash(this.xMax)), Murmur3.hash(this.yMax)), Murmur3.hash(this.zMax)));
}
@Override
public void debug(Output<?> output) {
output.write("BoxZ3").write('.').write("of").write('(')
.debug(this.xMin).write(", ").debug(this.yMin).write(", ").debug(this.zMin).write(", ")
.debug(this.xMax).write(", ").debug(this.yMax).write(", ").debug(this.zMax).write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static Z3Form<BoxZ3> form;
public static BoxZ3 of(long xMin, long yMin, long zMin,
long xMax, long yMax, long zMax) {
return new BoxZ3(xMin, yMin, zMin, xMax, yMax, zMax);
}
@Kind
public static Z3Form<BoxZ3> form() {
if (form == null) {
form = new BoxZ3Form();
}
return form;
}
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/BoxZ3Form.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
import swim.structure.Item;
import swim.structure.Record;
import swim.structure.Value;
final class BoxZ3Form extends Z3Form<BoxZ3> {
@Override
public String tag() {
return "box";
}
@Override
public Class<?> type() {
return BoxZ3.class;
}
@Override
public long getXMin(BoxZ3 box) {
return box.xMin;
}
@Override
public long getYMin(BoxZ3 box) {
return box.yMin;
}
@Override
public long getZMin(BoxZ3 box) {
return box.zMin;
}
@Override
public long getXMax(BoxZ3 box) {
return box.xMax;
}
@Override
public long getYMax(BoxZ3 box) {
return box.yMax;
}
@Override
public long getZMax(BoxZ3 box) {
return box.zMax;
}
@Override
public boolean contains(BoxZ3 outer, BoxZ3 inner) {
return outer.contains(inner);
}
@Override
public boolean intersects(BoxZ3 s, BoxZ3 t) {
return s.intersects(t);
}
@Override
public Item mold(BoxZ3 box) {
if (box != null) {
return Record.create(1).attr(tag(), Record.create(6)
.item(box.xMin).item(box.yMin).item(box.zMin)
.item(box.xMax).item(box.yMax).item(box.zMax));
} else {
return Item.extant();
}
}
@Override
public BoxZ3 cast(Item item) {
final Value header = item.toValue().header(tag());
if (header.isDefined()) {
final long xMin = header.getItem(0).longValue(0L);
final long yMin = header.getItem(1).longValue(0L);
final long zMin = header.getItem(2).longValue(0L);
final long xMax = header.getItem(3).longValue(0L);
final long yMax = header.getItem(4).longValue(0L);
final long zMax = header.getItem(5).longValue(0L);
return new BoxZ3(xMin, yMin, zMin, xMax, yMax, zMax);
} else {
return null;
}
}
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/CircleR2.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.structure.Kind;
import swim.structure.Value;
import swim.util.Murmur3;
public class CircleR2 extends R2Shape implements Debug {
public final double cx;
public final double cy;
public final double r;
public CircleR2(double cx, double cy, double r) {
this.cx = cx;
this.cy = cy;
this.r = r;
}
@Override
public final double xMin() {
return this.cx - this.r;
}
@Override
public final double yMin() {
return this.cy - this.r;
}
@Override
public final double xMax() {
return this.cx + this.r;
}
@Override
public final double yMax() {
return this.cy + this.r;
}
@Override
public boolean contains(R2Shape shape) {
if (shape instanceof PointR2) {
return contains((PointR2) shape);
} else if (shape instanceof BoxR2) {
return contains((BoxR2) shape);
} else if (shape instanceof CircleR2) {
return contains((CircleR2) shape);
} else {
return false;
}
}
public boolean contains(PointR2 point) {
final double dx = point.x - this.cx;
final double dy = point.y - this.cy;
return dx * dx + dy * dy <= this.r * this.r;
}
public boolean contains(BoxR2 box) {
final double dxMin = box.xMin - this.cx;
final double dyMin = box.yMin - this.cy;
final double dxMax = box.xMax - this.cx;
final double dyMax = box.yMax - this.cy;
final double r2 = this.r * this.r;
return dxMin * dxMin + dyMin * dyMin <= r2
&& dxMin * dxMin + dyMax * dyMax <= r2
&& dxMax * dxMax + dyMin * dyMin <= r2
&& dxMax * dxMax + dyMax * dyMax <= r2;
}
public boolean contains(CircleR2 circle) {
final double dx = circle.cx - this.cx;
final double dy = circle.cy - this.cy;
return dx * dx + dy * dy + circle.r * circle.r <= this.r * this.r;
}
@Override
public boolean intersects(R2Shape shape) {
if (shape instanceof PointR2) {
return intersects((PointR2) shape);
} else if (shape instanceof BoxR2) {
return intersects((BoxR2) shape);
} else if (shape instanceof CircleR2) {
return intersects((CircleR2) shape);
} else {
return shape.intersects(this);
}
}
public boolean intersects(PointR2 point) {
final double dx = point.x - this.cx;
final double dy = point.y - this.cy;
return dx * dx + dy * dy <= this.r * this.r;
}
public boolean intersects(BoxR2 box) {
final double dx = (this.cx < box.xMin ? box.xMin : box.xMax < this.cx ? box.xMax : this.cx) - this.cx;
final double dy = (this.cy < box.yMin ? box.yMin : box.yMax < this.cy ? box.yMax : this.cy) - this.cy;
return dx * dx + dy * dy <= this.r * this.r;
}
public boolean intersects(CircleR2 circle) {
final double dx = circle.cx - this.cx;
final double dy = circle.cy - this.cy;
final double rr = this.r + circle.r;
return dx * dx + dy * dy <= rr * rr;
}
@Override
public BoxZ2 transform(R2ToZ2Function f) {
final double xMin = this.cx - this.r;
final double yMin = this.cy - this.r;
final double xMax = this.cx + this.r;
final double yMax = this.cy + this.r;
return new BoxZ2(f.transformX(xMin, yMin), f.transformY(xMin, yMin),
f.transformX(xMax, yMax), f.transformY(xMax, yMax));
}
@Override
public Value toValue() {
return form().mold(this).toValue();
}
protected boolean canEqual(CircleR2 that) {
return true;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof CircleR2) {
final CircleR2 that = (CircleR2) other;
return that.canEqual(this) && this.cx == that.cx && this.cy == that.cy && this.r == that.r;
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(CircleR2.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed,
Murmur3.hash(this.cx)), Murmur3.hash(this.cy)), Murmur3.hash(this.r)));
}
@Override
public void debug(Output<?> output) {
output.write("CircleR2").write('.').write("of").write('(')
.debug(this.cx).write(", ").debug(this.cy).write(", ").debug(this.r).write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static R2Form<CircleR2> form;
public static CircleR2 of(double cx, double cy, double r) {
return new CircleR2(cx, cy, r);
}
@Kind
public static R2Form<CircleR2> form() {
if (form == null) {
form = new CircleR2Form();
}
return form;
}
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/CircleR2Form.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
import swim.structure.Item;
import swim.structure.Record;
import swim.structure.Value;
final class CircleR2Form extends R2Form<CircleR2> {
@Override
public String tag() {
return "circle";
}
@Override
public Class<?> type() {
return CircleR2.class;
}
@Override
public double getXMin(CircleR2 circle) {
return circle.xMin();
}
@Override
public double getYMin(CircleR2 circle) {
return circle.yMin();
}
@Override
public double getXMax(CircleR2 circle) {
return circle.xMax();
}
@Override
public double getYMax(CircleR2 circle) {
return circle.yMax();
}
@Override
public boolean contains(CircleR2 outer, CircleR2 inner) {
return outer.contains(inner);
}
@Override
public boolean intersects(CircleR2 s, CircleR2 t) {
return s.intersects(t);
}
@Override
public Item mold(CircleR2 circle) {
if (circle != null) {
return Record.create(1).attr(tag(), Record.create(3)
.item(circle.cx).item(circle.cy).item(circle.r));
} else {
return Item.absent();
}
}
@Override
public CircleR2 cast(Item item) {
final Value header = item.toValue().header(tag());
if (header.isDefined()) {
final double cx = header.getItem(0).doubleValue(0.0);
final double cy = header.getItem(1).doubleValue(0.0);
final double r = header.getItem(2).doubleValue(0.0);
return new CircleR2(cx, cy, r);
} else {
return null;
}
}
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/CompleteField.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
public interface CompleteField<S> extends Field<S> {
S exp(S a);
S log(S a);
S pow(S b, S e);
S sqrt(S a);
S hypot(S x, S y);
S sin(S a);
S cos(S a);
S tan(S a);
S asin(S a);
S acos(S a);
S atan(S a);
S atan2(S y, S x);
S sinh(S x);
S cosh(S x);
S tanh(S x);
S sigmoid(S x);
S rectify(S x);
S ceil(S a);
S floor(S a);
S round(S a);
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/DimensionException.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
public class DimensionException extends RuntimeException {
private static final long serialVersionUID = 1L;
public DimensionException(String message, Throwable cause) {
super(message, cause);
}
public DimensionException(String message) {
super(message);
}
public DimensionException(Throwable cause) {
super(cause);
}
public DimensionException(int dimension) {
super(Integer.toString(dimension));
}
public DimensionException() {
super();
}
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/Distribution.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
public abstract class Distribution {
public abstract double density(double x);
public abstract double sample();
public MutableTensor sample(TensorDims dims, Precision prec) {
if (prec.isDouble()) {
final double[] us = new double[dims.size * dims.stride];
sample(dims, us, 0);
return new MutableTensor(dims, us);
} else if (prec.isSingle()) {
final float[] us = new float[dims.size * dims.stride];
sample(dims, us, 0);
return new MutableTensor(dims, us);
} else {
throw new IllegalArgumentException(prec.toString());
}
}
void sample(TensorDims ud, double[] us, int ui) {
final int un = ui + ud.size * ud.stride;
if (ud.next != null) {
while (ui < un) {
sample(ud.next, us, ui);
ui += ud.stride;
}
} else {
while (ui < un) {
us[ui] = sample();
ui += ud.stride;
}
}
}
void sample(TensorDims ud, float[] us, int ui) {
final int un = ui + ud.size * ud.stride;
if (ud.next != null) {
while (ui < un) {
sample(ud.next, us, ui);
ui += ud.stride;
}
} else {
while (ui < un) {
us[ui] = (float) sample();
ui += ud.stride;
}
}
}
public static Distribution sigmoidUniform(Random random, double fanIn, double fanOut) {
final double r = 4.0 * Math.sqrt(6.0 / (fanIn + fanOut));
return new UniformDistribution(-r, r);
}
public static Distribution sigmoidUniform(double fanIn, double fanOut) {
return sigmoidUniform(Random.get(), fanIn, fanOut);
}
public static Distribution reluUniform(Random random, double fanIn, double fanOut) {
final double u = Math.sqrt(6.0 / fanIn);
return new UniformDistribution(-u, u);
}
public static Distribution reluUniform(double fanIn, double fanOut) {
return reluUniform(Random.get(), fanIn, fanOut);
}
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/F2.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
public interface F2<V, S> extends VectorModule<V, S> {
V of(S x, S y);
S getX(V v);
S getY(V v);
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/F3.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
public interface F3<V, S> extends VectorModule<V, S> {
V of(S x, S y, S z);
S getX(V v);
S getY(V v);
S getZ(V v);
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/FN.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
public interface FN<V, S> extends VectorModule<V, S> {
int size();
V of(Object... vs);
S get(V v, int i);
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/Field.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
public interface Field<S> extends Ring<S> {
S inverse(S a);
S divide(S a, S b);
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/MersenneTwister64.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
public class MersenneTwister64 extends Random {
final long[] state;
int index;
public MersenneTwister64(long seed) {
state = new long[312];
index = 0;
state[0] = seed;
for (int i = 1; i < 312; i += 1) {
state[i] = 6364136223846793005L * (state[i - 1] ^ state[i - 1] >>> 62) + (long) i;
}
}
public MersenneTwister64(long[] key) {
this(19650218L);
int i = 1;
int j = 0;
int k = Math.max(312, key.length);
while (k != 0) {
state[i] = (state[i] ^ ((state[i - 1] ^ state[i - 1] >>> 62) * 3935559000370003845L)) + key[j] + (long) j;
i += 1;
j += 1;
if (i > 311) {
state[0] = state[311];
i = 1;
}
if (j >= key.length) {
j = 0;
}
k -= 1;
}
k = 311;
while (k != 0) {
state[i] = (state[i] ^ ((state[i - 1] ^ state[i - 1] >>> 62) * 2862933555777941757L)) - (long) i;
i += 1;
if (i > 311) {
state[0] = state[311];
i = 1;
}
k -= 1;
}
state[0] = 1L << 63;
}
public MersenneTwister64() {
this(System.currentTimeMillis());
}
void generate() {
final long[] state = this.state;
long x = 0L;
int i = 0;
while (i < 156) {
x = state[i] & 0xffffffff80000000L | state[i + 1] & 0x000000007fffffffL;
state[i] = state[i + 156] ^ x >>> 1 ^ ((x & 1L) == 0L ? 0L : 0xb5026f5aa96619e9L);
i += 1;
}
while (i < 311) {
x = state[i] & 0xffffffff80000000L | state[i + 1] & 0x000000007fffffffL;
state[i] = state[i - 156] ^ x >>> 1 ^ ((x & 1L) == 0L ? 0L : 0xb5026f5aa96619e9L);
i += 1;
}
x = state[311] & 0xffffffff80000000L | state[0] & 0x000000007fffffffL;
state[311] = state[155] ^ x >>> 1 ^ ((x & 1L) == 0L ? 0L : 0xb5026f5aa96619e9L);
}
long next() {
if (index >= 312) {
generate();
index = 0;
}
long x = state[index];
x ^= x >>> 29 & 0x5555555555555555L;
x ^= x << 17 & 0x71d67fffeda60000L;
x ^= x << 37 & 0xfff7eee000000000L;
x ^= x >>> 43;
index += 1;
return x;
}
@Override
public byte nextByte() {
return (byte) next();
}
@Override
public short nextShort() {
return (short) next();
}
@Override
public int nextInt() {
return (int) next();
}
@Override
public long nextLong() {
return next();
}
@Override
public float nextFloat() {
return (float) (nextInt() >>> 8) / (float) (1 << 24);
}
@Override
public double nextDouble() {
return (double) (nextLong() >>> 11) / (double) (1L << 53);
}
@Override
public boolean nextBoolean() {
return (next() >>> 63) != 0;
}
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/MutableTensor.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
import swim.codec.Output;
public class MutableTensor extends Tensor {
protected MutableTensor(TensorDims dims, Object array, int offset) {
super(dims, array, offset);
}
public MutableTensor(TensorDims dims, double[] array, int offset) {
super(dims, array, offset);
}
public MutableTensor(TensorDims dims, float[] array, int offset) {
super(dims, array, offset);
}
public MutableTensor(TensorDims dims, double... array) {
super(dims, array);
}
public MutableTensor(TensorDims dims, float... array) {
super(dims, array);
}
@Override
public void debug(Output<?> output) {
output = output.write("MutableTensor").write('.').write("of").write('(')
.debug(this.dims).write(", ").debug(this.offset);
final Object us = this.array;
if (us instanceof double[]) {
Tensor.debug(output, (double[]) us);
} else if (us instanceof float[]) {
Tensor.debug(output, (float[]) us);
} else {
throw new AssertionError();
}
output = output.write(')');
}
public static MutableTensor zero(TensorDims dims, Precision prec) {
if (prec.isDouble()) {
return new MutableTensor(dims, new double[dims.size * dims.stride]);
} else if (prec.isSingle()) {
return new MutableTensor(dims, new float[dims.size * dims.stride]);
} else {
throw new AssertionError();
}
}
public static MutableTensor zero(TensorDims dims) {
return zero(dims, Precision.f32());
}
public static MutableTensor of(TensorDims dims, int offset, double... array) {
return new MutableTensor(dims, array, offset);
}
public static MutableTensor of(TensorDims dims, int offset, float... array) {
return new MutableTensor(dims, array, offset);
}
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/OrderedField.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
public interface OrderedField<S> extends OrderedRing<S>, Field<S> {
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/OrderedRing.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
import java.util.Comparator;
public interface OrderedRing<S> extends Comparator<S>, Ring<S> {
S abs(S a);
S min(S a, S b);
S max(S a, S b);
@Override
int compare(S a, S b);
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/PointR2.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.structure.Kind;
import swim.structure.Value;
import swim.util.Murmur3;
public class PointR2 extends R2Shape implements Debug {
public final double x;
public final double y;
public PointR2(double x, double y) {
this.x = x;
this.y = y;
}
public final PointR2 plus(VectorR2 vector) {
return new PointR2(this.x + vector.x, this.y + vector.y);
}
public final PointR2 minux(VectorR2 vector) {
return new PointR2(this.x - vector.x, this.y - vector.y);
}
public final VectorR2 minus(PointR2 that) {
return new VectorR2(this.x - that.x, this.y - that.y);
}
@Override
public final double xMin() {
return this.x;
}
@Override
public final double yMin() {
return this.y;
}
@Override
public final double xMax() {
return this.x;
}
@Override
public final double yMax() {
return this.y;
}
@Override
public boolean contains(R2Shape shape) {
return this.x <= shape.xMin() && shape.xMax() <= this.x
&& this.y <= shape.yMin() && shape.yMax() <= this.y;
}
@Override
public boolean intersects(R2Shape shape) {
return shape.intersects(this);
}
@Override
public PointZ2 transform(R2ToZ2Function f) {
return new PointZ2(f.transformX(this.x, this.y), f.transformY(this.x, this.y));
}
@Override
public Value toValue() {
return form().mold(this).toValue();
}
protected boolean canEqual(PointR2 that) {
return true;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof PointR2) {
final PointR2 that = (PointR2) other;
return that.canEqual(this) && this.x == that.x && this.y == that.y;
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(PointR2.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(hashSeed,
Murmur3.hash(this.x)), Murmur3.hash(this.y)));
}
@Override
public void debug(Output<?> output) {
output.write("PointR2").write('.').write("of").write('(')
.debug(this.x).write(", ").debug(this.y).write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static PointR2 origin;
private static R2Form<PointR2> form;
public static PointR2 origin() {
if (origin == null) {
origin = new PointR2(0.0, 0.0);
}
return origin;
}
public static PointR2 of(double x, double y) {
return new PointR2(x, y);
}
@Kind
public static R2Form<PointR2> form() {
if (form == null) {
form = new PointR2Form();
}
return form;
}
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/PointR2Form.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
import swim.structure.Item;
import swim.structure.Record;
import swim.structure.Value;
final class PointR2Form extends R2Form<PointR2> {
@Override
public String tag() {
return "point";
}
@Override
public PointR2 unit() {
return PointR2.origin();
}
@Override
public Class<?> type() {
return PointR2.class;
}
@Override
public double getXMin(PointR2 point) {
return point.x;
}
@Override
public double getYMin(PointR2 point) {
return point.y;
}
@Override
public double getXMax(PointR2 point) {
return point.x;
}
@Override
public double getYMax(PointR2 point) {
return point.y;
}
@Override
public boolean contains(PointR2 outer, PointR2 inner) {
return outer.contains(inner);
}
@Override
public boolean intersects(PointR2 s, PointR2 t) {
return s.intersects(t);
}
@Override
public Item mold(PointR2 point) {
if (point != null) {
return Record.create(1).attr(tag(), Record.create(2)
.item(point.x).item(point.y));
} else {
return Item.extant();
}
}
@Override
public PointR2 cast(Item item) {
final Value header = item.toValue().header(tag());
if (header.isDefined()) {
final double x = header.getItem(0).doubleValue(0.0);
final double y = header.getItem(1).doubleValue(0.0);
return new PointR2(x, y);
} else {
return null;
}
}
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/PointR3.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.structure.Kind;
import swim.structure.Value;
import swim.util.Murmur3;
public class PointR3 extends R3Shape implements Debug {
public final double x;
public final double y;
public final double z;
public PointR3(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public final PointR3 plus(VectorR3 vector) {
return new PointR3(this.x + vector.x, this.y + vector.y, this.z + vector.z);
}
public final PointR3 minux(VectorR3 vector) {
return new PointR3(this.x - vector.x, this.y - vector.y, this.z - vector.z);
}
public final VectorR3 minus(PointR3 that) {
return new VectorR3(this.x - that.x, this.y - that.y, this.z - that.z);
}
@Override
public final double xMin() {
return this.x;
}
@Override
public final double yMin() {
return this.y;
}
@Override
public final double zMin() {
return this.z;
}
@Override
public final double xMax() {
return this.x;
}
@Override
public final double yMax() {
return this.y;
}
@Override
public final double zMax() {
return this.z;
}
@Override
public boolean contains(R3Shape shape) {
return this.x <= shape.xMin() && shape.xMax() <= this.x
&& this.y <= shape.yMin() && shape.yMax() <= this.y
&& this.z <= shape.zMin() && shape.zMax() <= this.z;
}
@Override
public boolean intersects(R3Shape shape) {
return shape.intersects(this);
}
@Override
public PointZ3 transform(R3ToZ3Function f) {
return new PointZ3(f.transformX(this.x, this.y, this.z),
f.transformY(this.x, this.y, this.z),
f.transformZ(this.x, this.y, this.z));
}
@Override
public Value toValue() {
return form().mold(this).toValue();
}
protected boolean canEqual(PointR3 that) {
return true;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof PointR3) {
final PointR3 that = (PointR3) other;
return that.canEqual(this) && this.x == that.x && this.y == that.y && this.z == that.z;
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(PointR3.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed,
Murmur3.hash(this.x)), Murmur3.hash(this.y)), Murmur3.hash(this.z)));
}
@Override
public void debug(Output<?> output) {
output.write("PointR3").write('.').write("of").write('(')
.debug(this.x).write(", ").debug(this.y).write(", ").debug(this.z).write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static PointR3 origin;
private static R3Form<PointR3> form;
public static PointR3 origin() {
if (origin == null) {
origin = new PointR3(0.0, 0.0, 0.0);
}
return origin;
}
public static PointR3 of(double x, double y, double z) {
return new PointR3(x, y, z);
}
@Kind
public static R3Form<PointR3> form() {
if (form == null) {
form = new PointR3Form();
}
return form;
}
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/PointR3Form.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
import swim.structure.Item;
import swim.structure.Record;
import swim.structure.Value;
final class PointR3Form extends R3Form<PointR3> {
@Override
public String tag() {
return "point";
}
@Override
public PointR3 unit() {
return PointR3.origin();
}
@Override
public Class<?> type() {
return PointR3.class;
}
@Override
public double getXMin(PointR3 point) {
return point.x;
}
@Override
public double getYMin(PointR3 point) {
return point.y;
}
@Override
public double getZMin(PointR3 point) {
return point.z;
}
@Override
public double getXMax(PointR3 point) {
return point.x;
}
@Override
public double getYMax(PointR3 point) {
return point.y;
}
@Override
public double getZMax(PointR3 point) {
return point.z;
}
@Override
public boolean contains(PointR3 outer, PointR3 inner) {
return outer.contains(inner);
}
@Override
public boolean intersects(PointR3 s, PointR3 t) {
return s.intersects(t);
}
@Override
public Item mold(PointR3 point) {
if (point != null) {
return Record.create(1).attr(tag(), Record.create(3)
.item(point.x).item(point.y).item(point.z));
} else {
return Item.extant();
}
}
@Override
public PointR3 cast(Item item) {
final Value header = item.toValue().header(tag());
if (header.isDefined()) {
final double x = header.getItem(0).doubleValue(0.0);
final double y = header.getItem(1).doubleValue(0.0);
final double z = header.getItem(2).doubleValue(0.0);
return new PointR3(x, y, z);
} else {
return null;
}
}
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/PointZ2.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.structure.Kind;
import swim.structure.Value;
import swim.util.Murmur3;
public class PointZ2 extends Z2Shape implements Debug {
public final long x;
public final long y;
public PointZ2(long x, long y) {
this.x = x;
this.y = y;
}
public final PointZ2 plus(VectorZ2 vector) {
return new PointZ2(this.x + vector.x, this.y + vector.y);
}
public final PointZ2 minux(VectorZ2 vector) {
return new PointZ2(this.x - vector.x, this.y - vector.y);
}
public final VectorZ2 minus(PointZ2 that) {
return new VectorZ2(this.x - that.x, this.y - that.y);
}
@Override
public final long xMin() {
return this.x;
}
@Override
public final long yMin() {
return this.y;
}
@Override
public final long xMax() {
return this.x;
}
@Override
public final long yMax() {
return this.y;
}
@Override
public boolean contains(Z2Shape shape) {
return this.x <= shape.xMin() && shape.xMax() <= this.x
&& this.y <= shape.yMin() && shape.yMax() <= this.y;
}
@Override
public boolean intersects(Z2Shape shape) {
return shape.intersects(this);
}
@Override
public PointR2 transform(Z2ToR2Function f) {
return new PointR2(f.transformX(this.x, this.y), f.transformY(this.x, this.y));
}
@Override
public Value toValue() {
return form().mold(this).toValue();
}
protected boolean canEqual(PointZ2 that) {
return true;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof PointZ2) {
final PointZ2 that = (PointZ2) other;
return that.canEqual(this) && this.x == that.x && this.y == that.y;
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(PointZ2.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(hashSeed,
Murmur3.hash(this.x)), Murmur3.hash(this.y)));
}
@Override
public void debug(Output<?> output) {
output.write("PointZ2").write('.').write("of").write('(')
.debug(this.x).write(", ").debug(this.y).write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static PointZ2 origin;
private static Z2Form<PointZ2> form;
public static PointZ2 origin() {
if (origin == null) {
origin = new PointZ2(0L, 0L);
}
return origin;
}
public static PointZ2 of(long x, long y) {
return new PointZ2(x, y);
}
@Kind
public static Z2Form<PointZ2> form() {
if (form == null) {
form = new PointZ2Form();
}
return form;
}
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/PointZ2Form.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
import swim.structure.Item;
import swim.structure.Record;
import swim.structure.Value;
final class PointZ2Form extends Z2Form<PointZ2> {
@Override
public String tag() {
return "point";
}
@Override
public PointZ2 unit() {
return PointZ2.origin();
}
@Override
public Class<?> type() {
return PointZ2.class;
}
@Override
public long getXMin(PointZ2 point) {
return point.x;
}
@Override
public long getYMin(PointZ2 point) {
return point.y;
}
@Override
public long getXMax(PointZ2 point) {
return point.x;
}
@Override
public long getYMax(PointZ2 point) {
return point.y;
}
@Override
public boolean contains(PointZ2 outer, PointZ2 inner) {
return outer.contains(inner);
}
@Override
public boolean intersects(PointZ2 s, PointZ2 t) {
return s.intersects(t);
}
@Override
public Item mold(PointZ2 point) {
if (point != null) {
return Record.create(1).attr(tag(), Record.create(2)
.item(point.x).item(point.y));
} else {
return Item.absent();
}
}
@Override
public PointZ2 cast(Item item) {
final Value header = item.toValue().header(tag());
if (header.isDefined()) {
final long x = header.getItem(0).longValue(0L);
final long y = header.getItem(1).longValue(0L);
return new PointZ2(x, y);
} else {
return null;
}
}
}
|
0 | java-sources/ai/swim/swim-math/3.10.0/swim | java-sources/ai/swim/swim-math/3.10.0/swim/math/PointZ3.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.math;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.structure.Kind;
import swim.structure.Value;
import swim.util.Murmur3;
public class PointZ3 extends Z3Shape implements Debug {
public final long x;
public final long y;
public final long z;
public PointZ3(long x, long y, long z) {
this.x = x;
this.y = y;
this.z = z;
}
public final PointZ3 plus(VectorZ3 vector) {
return new PointZ3(this.x + vector.x, this.y + vector.y, this.z + vector.z);
}
public final PointZ3 minux(VectorZ3 vector) {
return new PointZ3(this.x - vector.x, this.y - vector.y, this.z - vector.z);
}
public final VectorZ3 minus(PointZ3 that) {
return new VectorZ3(this.x - that.x, this.y - that.y, this.z - that.z);
}
@Override
public final long xMin() {
return this.x;
}
@Override
public final long yMin() {
return this.y;
}
@Override
public final long zMin() {
return this.z;
}
@Override
public final long xMax() {
return this.x;
}
@Override
public final long yMax() {
return this.y;
}
@Override
public final long zMax() {
return this.z;
}
@Override
public boolean contains(Z3Shape shape) {
return this.x <= shape.xMin() && shape.xMax() <= this.x
&& this.y <= shape.yMin() && shape.yMax() <= this.y
&& this.z <= shape.zMin() && shape.zMax() <= this.z;
}
@Override
public boolean intersects(Z3Shape shape) {
return shape.intersects(this);
}
@Override
public PointR3 transform(Z3ToR3Function f) {
return new PointR3(f.transformX(this.x, this.y, this.z),
f.transformY(this.x, this.y, this.z),
f.transformZ(this.x, this.y, this.z));
}
@Override
public Value toValue() {
return form().mold(this).toValue();
}
protected boolean canEqual(PointZ3 that) {
return true;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof PointZ3) {
final PointZ3 that = (PointZ3) other;
return that.canEqual(this) && this.x == that.x && this.y == that.y && this.z == that.z;
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(PointZ3.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed,
Murmur3.hash(this.x)), Murmur3.hash(this.y)), Murmur3.hash(this.z)));
}
@Override
public void debug(Output<?> output) {
output.write("PointZ3").write('.').write("of").write('(')
.debug(this.x).write(", ").debug(this.y).write(", ").debug(this.z).write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static PointZ3 origin;
private static Z3Form<PointZ3> form;
public static PointZ3 origin() {
if (origin == null) {
origin = new PointZ3(0L, 0L, 0L);
}
return origin;
}
public static PointZ3 of(long x, long y, long z) {
return new PointZ3(x, y, z);
}
@Kind
public static Z3Form<PointZ3> form() {
if (form == null) {
form = new PointZ3Form();
}
return form;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.