index int64 | repo_id string | file_path string | content string |
|---|---|---|---|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/PolicyDef.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.runtime;
public interface PolicyDef {
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/PushRequest.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.runtime;
import swim.api.auth.Identity;
import swim.uri.Uri;
import swim.warp.Envelope;
public interface PushRequest {
Uri meshUri();
Uri hostUri();
Uri nodeUri();
float prio();
Identity identity();
Envelope envelope();
void didDeliver();
void didDecline();
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/TierBinding.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.runtime;
public interface TierBinding {
TierContext tierContext();
boolean isClosed();
boolean isOpened();
boolean isLoaded();
boolean isStarted();
void open();
void load();
void start();
void stop();
void unload();
void close();
void didClose();
void didFail(Throwable error);
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/TierContext.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.runtime;
public interface TierContext {
void close();
void willOpen();
void didOpen();
void willLoad();
void didLoad();
void willStart();
void didStart();
void willStop();
void didStop();
void willUnload();
void didUnload();
void willClose();
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/UplinkError.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.runtime;
import swim.runtime.http.HttpErrorUplinkModem;
import swim.runtime.warp.WarpErrorUplinkModem;
import swim.structure.Record;
import swim.structure.Value;
public final class UplinkError {
private UplinkError() {
// static
}
static void rejectWarp(WarpBinding link, Value body) {
final WarpErrorUplinkModem linkContext = new WarpErrorUplinkModem(link, body);
link.setLinkContext(linkContext);
linkContext.cueDown();
}
static void rejectHttp(HttpBinding link) {
final HttpErrorUplinkModem linkContext = new HttpErrorUplinkModem(link);
link.setLinkContext(linkContext);
}
public static void rejectMeshNotFound(LinkBinding link) {
if (link instanceof WarpBinding) {
rejectWarp((WarpBinding) link, Record.create(1).attr("meshNotFound"));
} else if (link instanceof HttpBinding) {
rejectHttp((HttpBinding) link);
} else {
throw new AssertionError();
}
}
public static void rejectPartNotFound(LinkBinding link) {
if (link instanceof WarpBinding) {
rejectWarp((WarpBinding) link, Record.create(1).attr("partNotFound"));
} else if (link instanceof HttpBinding) {
rejectHttp((HttpBinding) link);
} else {
throw new AssertionError();
}
}
public static void rejectHostNotFound(LinkBinding link) {
if (link instanceof WarpBinding) {
rejectWarp((WarpBinding) link, Record.create(1).attr("hostNotFound"));
} else if (link instanceof HttpBinding) {
rejectHttp((HttpBinding) link);
} else {
throw new AssertionError();
}
}
public static void rejectNodeNotFound(LinkBinding link) {
if (link instanceof WarpBinding) {
rejectWarp((WarpBinding) link, Record.create(1).attr("nodeNotFound"));
} else if (link instanceof HttpBinding) {
rejectHttp((HttpBinding) link);
} else {
throw new AssertionError();
}
}
public static void rejectLaneNotFound(LinkBinding link) {
if (link instanceof WarpBinding) {
rejectWarp((WarpBinding) link, Record.create(1).attr("laneNotFound"));
} else if (link instanceof HttpBinding) {
rejectHttp((HttpBinding) link);
} else {
throw new AssertionError();
}
}
public static void rejectUnsupported(LinkBinding link) {
if (link instanceof WarpBinding) {
rejectWarp((WarpBinding) link, Record.create(1).attr("unsupported"));
} else if (link instanceof HttpBinding) {
rejectHttp((HttpBinding) link);
} else {
throw new AssertionError();
}
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/WarpBinding.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.runtime;
import swim.structure.Value;
import swim.warp.Envelope;
public interface WarpBinding extends LinkBinding {
@Override
WarpBinding linkWrapper();
@Override
WarpContext linkContext();
float prio();
float rate();
Value body();
boolean keepLinked();
boolean keepSynced();
void feedDown();
void pushDown(Envelope envelope);
void skipDown();
void pullUp();
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/WarpContext.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.runtime;
import swim.warp.Envelope;
public interface WarpContext extends LinkContext {
@Override
WarpBinding linkWrapper();
void pullDown();
void feedUp();
void pushUp(Envelope envelope);
void skipUp();
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/WarpProxy.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.runtime;
import java.net.InetSocketAddress;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.Collection;
import swim.api.auth.Identity;
import swim.structure.Value;
import swim.uri.Uri;
import swim.warp.Envelope;
public class WarpProxy implements WarpBinding, WarpContext {
protected final WarpBinding linkBinding;
protected WarpContext linkContext;
public WarpProxy(WarpBinding linkBinding) {
this.linkBinding = linkBinding;
}
@Override
public final WarpBinding linkWrapper() {
return this.linkBinding.linkWrapper();
}
public final WarpBinding linkBinding() {
return this.linkBinding;
}
@Override
public final WarpContext linkContext() {
return this.linkContext;
}
@Override
public void setLinkContext(LinkContext linkContext) {
this.linkContext = (WarpContext) linkContext;
this.linkBinding.setLinkContext(this);
}
@Override
public CellContext cellContext() {
return this.linkBinding.cellContext();
}
@Override
public void setCellContext(CellContext cellContext) {
this.linkBinding.setCellContext(cellContext);
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrapLink(Class<T> linkClass) {
if (linkClass.isAssignableFrom(getClass())) {
return (T) this;
} else {
return this.linkContext.unwrapLink(linkClass);
}
}
@Override
public Uri meshUri() {
return this.linkBinding.meshUri();
}
@Override
public Uri hostUri() {
return this.linkBinding.hostUri();
}
@Override
public Uri nodeUri() {
return this.linkBinding.nodeUri();
}
@Override
public Uri laneUri() {
return this.linkBinding.laneUri();
}
@Override
public Value linkKey() {
return this.linkContext.linkKey();
}
@Override
public float prio() {
return this.linkBinding.prio();
}
@Override
public float rate() {
return this.linkBinding.rate();
}
@Override
public Value body() {
return this.linkBinding.body();
}
@Override
public boolean keepLinked() {
return this.linkBinding.keepLinked();
}
@Override
public boolean keepSynced() {
return this.linkBinding.keepSynced();
}
@Override
public boolean isConnectedDown() {
return this.linkBinding.isConnectedDown();
}
@Override
public boolean isRemoteDown() {
return this.linkBinding.isRemoteDown();
}
@Override
public boolean isSecureDown() {
return this.linkBinding.isSecureDown();
}
@Override
public String securityProtocolDown() {
return this.linkBinding.securityProtocolDown();
}
@Override
public String cipherSuiteDown() {
return this.linkBinding.cipherSuiteDown();
}
@Override
public InetSocketAddress localAddressDown() {
return this.linkBinding.localAddressDown();
}
@Override
public Identity localIdentityDown() {
return this.linkBinding.localIdentityDown();
}
@Override
public Principal localPrincipalDown() {
return this.linkBinding.localPrincipalDown();
}
@Override
public Collection<Certificate> localCertificatesDown() {
return this.linkBinding.localCertificatesDown();
}
@Override
public InetSocketAddress remoteAddressDown() {
return this.linkBinding.remoteAddressDown();
}
@Override
public Identity remoteIdentityDown() {
return this.linkBinding.remoteIdentityDown();
}
@Override
public Principal remotePrincipalDown() {
return this.linkBinding.remotePrincipalDown();
}
@Override
public Collection<Certificate> remoteCertificatesDown() {
return this.linkBinding.remoteCertificatesDown();
}
@Override
public boolean isConnectedUp() {
return this.linkContext.isConnectedUp();
}
@Override
public boolean isRemoteUp() {
return this.linkContext.isRemoteUp();
}
@Override
public boolean isSecureUp() {
return this.linkContext.isSecureUp();
}
@Override
public String securityProtocolUp() {
return this.linkContext.securityProtocolUp();
}
@Override
public String cipherSuiteUp() {
return this.linkContext.cipherSuiteUp();
}
@Override
public InetSocketAddress localAddressUp() {
return this.linkContext.localAddressUp();
}
@Override
public Identity localIdentityUp() {
return this.linkContext.localIdentityUp();
}
@Override
public Principal localPrincipalUp() {
return this.linkContext.localPrincipalUp();
}
@Override
public Collection<Certificate> localCertificatesUp() {
return this.linkContext.localCertificatesUp();
}
@Override
public InetSocketAddress remoteAddressUp() {
return this.linkContext.remoteAddressUp();
}
@Override
public Identity remoteIdentityUp() {
return this.linkContext.remoteIdentityUp();
}
@Override
public Principal remotePrincipalUp() {
return this.linkContext.remotePrincipalUp();
}
@Override
public Collection<Certificate> remoteCertificatesUp() {
return this.linkContext.remoteCertificatesUp();
}
@Override
public void feedDown() {
this.linkBinding.feedDown();
}
@Override
public void pullDown() {
this.linkContext.pullDown();
}
@Override
public void pushDown(Envelope envelope) {
this.linkBinding.pushDown(envelope);
}
@Override
public void skipDown() {
this.linkBinding.skipDown();
}
@Override
public void openDown() {
this.linkBinding.openDown();
}
@Override
public void closeDown() {
this.linkBinding.closeDown();
}
@Override
public void feedUp() {
this.linkContext.feedUp();
}
@Override
public void pullUp() {
this.linkBinding.pullUp();
}
@Override
public void pushUp(Envelope envelope) {
this.linkContext.pushUp(envelope);
}
@Override
public void skipUp() {
this.linkContext.skipUp();
}
@Override
public void closeUp() {
this.linkContext.closeUp();
}
@Override
public void reopen() {
this.linkBinding.reopen();
}
@Override
public void didOpenDown() {
this.linkContext.didOpenDown();
}
@Override
public void didConnect() {
this.linkBinding.didConnect();
}
@Override
public void didDisconnect() {
this.linkBinding.didDisconnect();
}
@Override
public void didCloseDown() {
this.linkContext.didCloseDown();
}
@Override
public void didCloseUp() {
this.linkBinding.didCloseUp();
}
@Override
public void didFail(Throwable error) {
this.linkBinding.didFail(error);
}
@Override
public void traceDown(Object message) {
this.linkBinding.traceDown(message);
}
@Override
public void debugDown(Object message) {
this.linkBinding.debugDown(message);
}
@Override
public void infoDown(Object message) {
this.linkBinding.infoDown(message);
}
@Override
public void warnDown(Object message) {
this.linkBinding.warnDown(message);
}
@Override
public void errorDown(Object message) {
this.linkBinding.errorDown(message);
}
@Override
public void traceUp(Object message) {
this.linkContext.traceUp(message);
}
@Override
public void debugUp(Object message) {
this.linkContext.debugUp(message);
}
@Override
public void infoUp(Object message) {
this.linkContext.infoUp(message);
}
@Override
public void warnUp(Object message) {
this.linkContext.warnUp(message);
}
@Override
public void errorUp(Object message) {
this.linkContext.errorUp(message);
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/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 runtime interfaces.
*/
package swim.runtime;
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/agent/AgentLane.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.runtime.agent;
import swim.api.Downlink;
import swim.api.auth.Identity;
import swim.api.policy.Policy;
import swim.concurrent.Schedule;
import swim.concurrent.Stage;
import swim.runtime.LaneBinding;
import swim.runtime.LaneContext;
import swim.runtime.LinkBinding;
import swim.runtime.NodeBinding;
import swim.runtime.PushRequest;
import swim.store.StoreBinding;
import swim.structure.Value;
import swim.uri.Uri;
public class AgentLane implements LaneContext {
protected final AgentNode node;
protected final LaneBinding lane;
protected final Uri laneUri;
public AgentLane(AgentNode node, LaneBinding lane, Uri laneUri) {
this.node = node;
this.lane = lane;
this.laneUri = laneUri;
}
@Override
public final NodeBinding node() {
return this.node;
}
@Override
public final LaneBinding laneWrapper() {
return this.lane.laneWrapper();
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrapLane(Class<T> laneClass) {
if (laneClass.isAssignableFrom(getClass())) {
return (T) this;
} else {
return null;
}
}
@Override
public final Uri meshUri() {
return this.node.meshUri();
}
@Override
public final Value partKey() {
return this.node.partKey();
}
@Override
public final Uri hostUri() {
return this.node.hostUri();
}
@Override
public final Uri nodeUri() {
return this.node.nodeUri();
}
@Override
public final Uri laneUri() {
return this.laneUri;
}
@Override
public final Identity identity() {
return this.node.nodeContext().identity();
}
@Override
public Policy policy() {
return this.node.policy();
}
@Override
public Schedule schedule() {
return this.node;
}
@Override
public Stage stage() {
return this.node;
}
@Override
public StoreBinding store() {
return this.node.store();
}
@Override
public LinkBinding bindDownlink(Downlink downlink) {
return this.node.bindDownlink(downlink);
}
@Override
public void openDownlink(LinkBinding link) {
this.node.openDownlink(link);
}
@Override
public void closeDownlink(LinkBinding link) {
// nop
}
@Override
public void pushDown(PushRequest pushRequest) {
this.node.pushDown(pushRequest);
}
@Override
public void trace(Object message) {
this.node.trace(message);
}
@Override
public void debug(Object message) {
this.node.debug(message);
}
@Override
public void info(Object message) {
this.node.info(message);
}
@Override
public void warn(Object message) {
this.node.warn(message);
}
@Override
public void error(Object message) {
this.node.error(message);
}
@Override
public void close() {
this.node.closeLane(this.laneUri);
}
@Override
public void willOpen() {
this.lane.open();
}
@Override
public void didOpen() {
// nop
}
@Override
public void willLoad() {
this.lane.load();
}
@Override
public void didLoad() {
// nop
}
@Override
public void willStart() {
this.lane.start();
}
@Override
public void didStart() {
// nop
}
@Override
public void willStop() {
this.lane.stop();
}
@Override
public void didStop() {
// nop
}
@Override
public void willUnload() {
this.lane.unload();
}
@Override
public void didUnload() {
// nop
}
@Override
public void willClose() {
this.lane.close();
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/agent/AgentModel.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.runtime.agent;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import swim.api.SwimContext;
import swim.api.agent.Agent;
import swim.api.agent.AgentFactory;
import swim.concurrent.Conts;
import swim.runtime.LaneBinding;
import swim.runtime.NodeContext;
import swim.runtime.PushRequest;
import swim.structure.Value;
public class AgentModel extends AgentNode {
protected final Value props;
volatile Object views; // AgentView | AgentView[]
public AgentModel(Value props) {
this.props = props.commit();
}
@Override
public void setNodeContext(NodeContext nodeContext) {
super.setNodeContext(nodeContext);
}
public Value props() {
return this.props;
}
public AgentView createAgent(AgentFactory<?> agentFactory, Value props) {
final AgentView view = new AgentView(this, props);
final Agent agent;
try {
SwimContext.setAgentContext(view);
agent = agentFactory.createAgent(view);
} finally {
SwimContext.clear();
}
view.setAgent(agent);
return view;
}
public AgentView getAgentView(Value props) {
final Object views = this.views;
AgentView view;
if (views instanceof AgentView) {
view = (AgentView) views;
if (props.equals(view.props)) {
return view;
}
} else if (views instanceof AgentView[]) {
final AgentView[] viewArray = (AgentView[]) views;
for (int i = 0, n = viewArray.length; i < n; i += 1) {
view = viewArray[i];
if (props.equals(view.props)) {
return view;
}
}
}
return null;
}
@SuppressWarnings("unchecked")
public <S extends Agent> S getAgent(Class<S> agentClass) {
Agent agent;
if (views instanceof AgentView) {
agent = ((AgentView) views).agent;
if (agentClass.isInstance(agent)) {
return (S) agent;
}
} else if (views instanceof AgentView[]) {
final AgentView[] viewArray = (AgentView[]) views;
for (int i = 0, n = viewArray.length; i < n; i += 1) {
agent = viewArray[i].agent;
if (agentClass.isInstance(agent)) {
return (S) agent;
}
}
}
return null;
}
public AgentView addAgentView(AgentView view) {
final Value props = view.props();
Object oldViews;
Object newViews;
AgentView oldView;
do {
oldViews = this.views;
if (oldViews instanceof AgentView) {
oldView = (AgentView) oldViews;
if (props.equals(oldView.props())) {
return oldView;
} else {
newViews = new AgentView[]{oldView, view};
}
} else if (oldViews instanceof AgentView[]) {
final AgentView[] oldViewArray = (AgentView[]) oldViews;
final int n = oldViewArray.length;
final AgentView[] newViewArray = new AgentView[n + 1];
for (int i = 0; i < n; i += 1) {
oldView = oldViewArray[i];
if (props.equals(oldView.props())) {
return oldView;
}
newViewArray[i] = oldViewArray[i];
}
newViewArray[n] = view;
newViews = newViewArray;
} else {
newViews = view;
}
} while (!VIEWS.compareAndSet(this, oldViews, newViews));
activate(view);
didAddAgentView(view);
return view;
}
@SuppressWarnings("unchecked")
public <S extends Agent> S addAgent(Value props, AgentFactory<S> agentFactory) {
Object oldViews;
Object newViews;
AgentView oldView;
AgentView view = null;
do {
oldViews = this.views;
if (oldViews instanceof AgentView) {
oldView = (AgentView) oldViews;
if (props.equals(oldView.props())) {
return (S) oldView.agent;
} else {
if (view == null) {
view = createAgent(agentFactory, props);
}
newViews = new AgentView[]{oldView, view};
}
} else if (oldViews instanceof AgentView[]) {
final AgentView[] oldViewArray = (AgentView[]) oldViews;
final int n = oldViewArray.length;
final AgentView[] newViewArray = new AgentView[n + 1];
for (int i = 0; i < n; i += 1) {
oldView = oldViewArray[i];
if (props.equals(oldView.props())) {
return (S) oldView.agent;
}
newViewArray[i] = oldViewArray[i];
}
if (view == null) {
view = createAgent(agentFactory, props);
}
newViewArray[n] = view;
newViews = newViewArray;
} else {
if (view == null) {
view = createAgent(agentFactory, props);
}
newViews = view;
}
} while (!VIEWS.compareAndSet(this, oldViews, newViews));
activate(view);
didAddAgentView(view);
return (S) view.agent;
}
public void removeAgentView(AgentView view) {
Object oldViews;
Object newViews;
do {
oldViews = this.views;
if (oldViews instanceof AgentView) {
if (oldViews == view) {
newViews = null;
continue;
}
} else if (oldViews instanceof AgentView[]) {
final AgentView[] oldViewArray = (AgentView[]) oldViews;
final int n = oldViewArray.length;
if (n == 2) {
if (oldViewArray[0] == view) {
newViews = oldViewArray[1];
continue;
} else if (oldViewArray[1] == view) {
newViews = oldViewArray[0];
continue;
}
} else { // n > 2
final AgentView[] newViewArray = new AgentView[n - 1];
int i = 0;
while (i < n) {
if (oldViewArray[i] != view) {
if (i < n - 1) {
newViewArray[i] = oldViewArray[i];
}
i += 1;
} else {
break;
}
}
if (i < n) {
System.arraycopy(oldViewArray, i + 1, newViewArray, i, n - (i + 1));
newViews = newViewArray;
continue;
}
}
}
newViews = oldViews;
break;
} while (!VIEWS.compareAndSet(this, oldViews, newViews));
if (oldViews != newViews) {
didRemoveAgentView(view);
}
}
@Override
public void pushUp(PushRequest pushRequest) {
execute(new AgentModelPushUp(this, pushRequest));
}
protected void didAddAgentView(AgentView view) {
// stub
}
protected void didRemoveAgentView(AgentView view) {
// stub
}
@Override
protected void willOpen() {
super.willOpen();
final Object views = this.views;
if (views instanceof AgentView) {
((AgentView) views).willOpen();
} else if (views instanceof AgentView[]) {
final AgentView[] viewArray = (AgentView[]) views;
for (int i = 0, n = viewArray.length; i < n; i += 1) {
(viewArray[i]).willOpen();
}
}
}
@Override
protected void didOpen() {
super.didOpen();
final Object views = this.views;
if (views instanceof AgentView) {
((AgentView) views).didOpen();
} else if (views instanceof AgentView[]) {
final AgentView[] viewArray = (AgentView[]) views;
for (int i = 0, n = viewArray.length; i < n; i += 1) {
(viewArray[i]).didOpen();
}
}
}
@Override
protected void willLoad() {
super.willLoad();
execute(new AgentModelWillLoad(this));
}
@Override
protected void didLoad() {
super.didLoad();
execute(new AgentModelDidLoad(this));
}
@Override
protected void willStart() {
super.willStart();
execute(new AgentModelWillStart(this));
}
@Override
protected void didStart() {
super.didStart();
execute(new AgentModelDidStart(this));
}
@Override
protected void willStop() {
super.willStop();
execute(new AgentModelWillStop(this));
}
@Override
protected void didStop() {
super.didStop();
execute(new AgentModelDidStop(this));
}
@Override
protected void willUnload() {
super.willUnload();
execute(new AgentModelWillUnload(this));
}
@Override
protected void didUnload() {
super.didUnload();
execute(new AgentModelDidUnload(this));
}
@Override
public void willClose() {
super.willClose();
execute(new AgentModelWillClose(this));
}
@Override
public void didClose() {
super.didClose();
execute(new AgentModelDidClose(this));
}
@Override
public void didFail(Throwable error) {
super.didFail(error);
final Object views = this.views;
if (views instanceof AgentView) {
try {
((AgentView) views).didFail(error);
} catch (Throwable cause) {
if (Conts.isNonFatal(cause)) {
cause.printStackTrace();
} else {
throw cause;
}
}
} else if (views instanceof AgentView[]) {
final AgentView[] viewArray = (AgentView[]) views;
for (int i = 0, n = viewArray.length; i < n; i += 1) {
try {
viewArray[i].didFail(error);
} catch (Throwable cause) {
if (Conts.isNonFatal(cause)) {
cause.printStackTrace();
} else {
throw cause;
}
}
}
}
}
static final AtomicReferenceFieldUpdater<AgentModel, Object> VIEWS =
AtomicReferenceFieldUpdater.newUpdater(AgentModel.class, Object.class, "views");
}
final class AgentModelPushUp implements Runnable {
final AgentNode node;
final PushRequest pushRequest;
AgentModelPushUp(AgentNode node, PushRequest pushRequest) {
this.node = node;
this.pushRequest = pushRequest;
}
@Override
public void run() {
try {
final LaneBinding laneBinding = this.node.getLane(this.pushRequest.envelope().laneUri());
if (laneBinding != null) {
laneBinding.pushUp(this.pushRequest);
} else {
this.pushRequest.didDecline();
}
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
this.node.didFail(error);
} else {
throw error;
}
}
}
}
abstract class AgentModelCallback implements Runnable {
final AgentModel model;
AgentModelCallback(AgentModel model) {
this.model = model;
}
@Override
public final void run() {
final Object views = this.model.views;
if (views instanceof AgentView) {
try {
call((AgentView) views);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
((AgentView) views).didFail(error);
} else {
throw error;
}
}
} else if (views instanceof AgentView[]) {
final AgentView[] viewArray = (AgentView[]) views;
for (int i = 0, n = viewArray.length; i < n; i += 1) {
try {
call(viewArray[i]);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
viewArray[i].didFail(error);
} else {
throw error;
}
}
}
}
}
abstract void call(AgentView view);
}
final class AgentModelWillLoad extends AgentModelCallback {
AgentModelWillLoad(AgentModel model) {
super(model);
}
@Override
void call(AgentView view) {
view.willLoad();
}
}
final class AgentModelDidLoad extends AgentModelCallback {
AgentModelDidLoad(AgentModel model) {
super(model);
}
@Override
void call(AgentView view) {
view.didLoad();
}
}
final class AgentModelWillStart extends AgentModelCallback {
AgentModelWillStart(AgentModel model) {
super(model);
}
@Override
void call(AgentView view) {
view.willStart();
}
}
final class AgentModelDidStart extends AgentModelCallback {
AgentModelDidStart(AgentModel model) {
super(model);
}
@Override
void call(AgentView view) {
view.didStart();
}
}
final class AgentModelWillStop extends AgentModelCallback {
AgentModelWillStop(AgentModel model) {
super(model);
}
@Override
void call(AgentView view) {
view.willStop();
}
}
final class AgentModelDidStop extends AgentModelCallback {
AgentModelDidStop(AgentModel model) {
super(model);
}
@Override
void call(AgentView view) {
view.didStop();
}
}
final class AgentModelWillUnload extends AgentModelCallback {
AgentModelWillUnload(AgentModel model) {
super(model);
}
@Override
void call(AgentView view) {
view.willUnload();
}
}
final class AgentModelDidUnload extends AgentModelCallback {
AgentModelDidUnload(AgentModel model) {
super(model);
}
@Override
void call(AgentView view) {
view.didUnload();
}
}
final class AgentModelWillClose extends AgentModelCallback {
AgentModelWillClose(AgentModel model) {
super(model);
}
@Override
void call(AgentView view) {
view.willClose();
}
}
final class AgentModelDidClose extends AgentModelCallback {
AgentModelDidClose(AgentModel model) {
super(model);
}
@Override
void call(AgentView view) {
view.didClose();
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/agent/AgentNode.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.runtime.agent;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import swim.api.Downlink;
import swim.api.Lane;
import swim.api.agent.Agent;
import swim.api.agent.AgentDef;
import swim.api.agent.AgentFactory;
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.LaneFactory;
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.api.policy.Policy;
import swim.api.ws.WsLane;
import swim.collections.HashTrieMap;
import swim.concurrent.Call;
import swim.concurrent.Cont;
import swim.concurrent.Conts;
import swim.concurrent.Schedule;
import swim.concurrent.Stage;
import swim.concurrent.Task;
import swim.concurrent.TaskContext;
import swim.concurrent.TaskFunction;
import swim.concurrent.TaskRef;
import swim.concurrent.TimerFunction;
import swim.concurrent.TimerRef;
import swim.math.R2Shape;
import swim.math.Z2Form;
import swim.runtime.AbstractTierBinding;
import swim.runtime.CellContext;
import swim.runtime.HostBinding;
import swim.runtime.LaneBinding;
import swim.runtime.LaneContext;
import swim.runtime.LaneView;
import swim.runtime.LinkBinding;
import swim.runtime.NodeBinding;
import swim.runtime.NodeContext;
import swim.runtime.PushRequest;
import swim.runtime.TierContext;
import swim.runtime.UplinkError;
import swim.runtime.WarpBinding;
import swim.runtime.http.RestLaneView;
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.spatial.GeoProjection;
import swim.store.StoreBinding;
import swim.structure.Value;
import swim.uri.Uri;
public class AgentNode extends AbstractTierBinding implements NodeBinding, CellContext, LaneFactory, Schedule, Stage, Task {
protected NodeContext nodeContext;
protected TaskContext taskContext;
volatile HashTrieMap<Uri, LaneBinding> lanes;
final ConcurrentLinkedQueue<Runnable> mailbox;
final long createdTime;
public AgentNode() {
this.lanes = HashTrieMap.empty();
this.mailbox = new ConcurrentLinkedQueue<Runnable>();
this.createdTime = System.currentTimeMillis();
}
@Override
public final TierContext tierContext() {
return this.nodeContext;
}
@Override
public final HostBinding host() {
return this.nodeContext.host();
}
@Override
public final NodeBinding nodeWrapper() {
return this;
}
@Override
public final NodeContext nodeContext() {
return this.nodeContext;
}
@Override
public void setNodeContext(NodeContext nodeContext) {
this.nodeContext = nodeContext;
nodeContext.stage().task(this);
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrapNode(Class<T> nodeClass) {
if (nodeClass.isAssignableFrom(getClass())) {
return (T) this;
} else {
return this.nodeContext.unwrapNode(nodeClass);
}
}
@Override
public final TaskContext taskContext() {
return this.taskContext;
}
@Override
public void setTaskContext(TaskContext taskContext) {
this.taskContext = taskContext;
}
protected LaneContext createLaneContext(LaneBinding lane, Uri laneUri) {
return new AgentLane(this, lane, laneUri);
}
@Override
public final Uri meshUri() {
return this.nodeContext.meshUri();
}
@Override
public final Value partKey() {
return this.nodeContext.partKey();
}
@Override
public final Uri hostUri() {
return this.nodeContext.hostUri();
}
@Override
public final Uri nodeUri() {
return this.nodeContext.nodeUri();
}
@Override
public long createdTime() {
return this.createdTime;
}
@Override
public void openLanes(NodeBinding node) {
this.nodeContext.openLanes(node);
}
@Override
public AgentFactory<?> createAgentFactory(AgentDef agentDef) {
return this.nodeContext.createAgentFactory(agentDef);
}
@Override
public <A extends Agent> AgentFactory<A> createAgentFactory(Class<? extends A> agentClass) {
return this.nodeContext.createAgentFactory(agentClass);
}
@Override
public void openAgents(NodeBinding node) {
this.nodeContext.openAgents(node);
}
protected static Uri normalizezLaneUri(Uri laneUri) {
if (laneUri.query().isDefined() || laneUri.fragment().isDefined()) {
laneUri = Uri.from(laneUri.scheme(), laneUri.authority(), laneUri.path());
}
return laneUri;
}
@Override
public HashTrieMap<Uri, LaneBinding> lanes() {
return this.lanes;
}
@Override
public LaneBinding getLane(Uri laneUri) {
laneUri = normalizezLaneUri(laneUri);
return this.lanes.get(laneUri);
}
public LaneBinding openLaneView(Uri laneUri, LaneView laneView) {
laneUri = normalizezLaneUri(laneUri);
HashTrieMap<Uri, LaneBinding> oldLanes;
HashTrieMap<Uri, LaneBinding> newLanes;
LaneBinding laneBinding = null;
do {
oldLanes = this.lanes;
if (oldLanes.containsKey(laneUri)) {
laneBinding = oldLanes.get(laneUri);
newLanes = oldLanes;
break;
} else {
if (laneBinding == null) {
laneBinding = this.nodeContext.injectLane(laneUri, laneView.createLaneBinding());
final LaneContext laneContext = createLaneContext(laneBinding, laneUri);
laneBinding.setLaneContext(laneContext);
laneBinding = laneBinding.laneWrapper();
}
newLanes = oldLanes.updated(laneUri, laneBinding);
}
} while (oldLanes != newLanes && !LANES.compareAndSet(this, oldLanes, newLanes));
laneBinding.openLaneView(laneView);
if (oldLanes != newLanes) {
activate(laneBinding);
}
return laneBinding;
}
public LaneBinding openLane(Uri laneUri, Lane lane) {
return openLaneView(laneUri, (LaneView) lane);
}
@Override
public LaneBinding openLane(Uri laneUri) {
laneUri = normalizezLaneUri(laneUri);
HashTrieMap<Uri, LaneBinding> oldLanes;
HashTrieMap<Uri, LaneBinding> newLanes;
LaneBinding laneBinding = null;
do {
oldLanes = this.lanes;
final LaneBinding lane = oldLanes.get(laneUri);
if (lane != null) {
if (laneBinding != null) {
// Lost creation race.
laneBinding.close();
}
laneBinding = lane;
newLanes = oldLanes;
break;
} else if (laneBinding == null) {
laneBinding = this.nodeContext.createLane(laneUri);
if (laneBinding != null) {
laneBinding = this.nodeContext.injectLane(laneUri, laneBinding);
final LaneContext laneContext = createLaneContext(laneBinding, laneUri);
laneBinding.setLaneContext(laneContext);
laneBinding = laneBinding.laneWrapper();
newLanes = oldLanes.updated(laneUri, laneBinding);
} else {
newLanes = oldLanes;
break;
}
} else {
newLanes = oldLanes.updated(laneUri, laneBinding);
}
} while (oldLanes != newLanes && !LANES.compareAndSet(this, oldLanes, newLanes));
if (laneBinding != null) {
activate(laneBinding);
}
return laneBinding;
}
@Override
public LaneBinding openLane(Uri laneUri, LaneBinding lane) {
laneUri = normalizezLaneUri(laneUri);
HashTrieMap<Uri, LaneBinding> oldLanes;
HashTrieMap<Uri, LaneBinding> newLanes;
LaneBinding laneBinding = null;
do {
oldLanes = this.lanes;
if (oldLanes.containsKey(laneUri)) {
laneBinding = null;
newLanes = oldLanes;
break;
} else {
if (laneBinding == null) {
laneBinding = this.nodeContext.injectLane(laneUri, lane);
final LaneContext laneContext = createLaneContext(laneBinding, laneUri);
laneBinding.setLaneContext(laneContext);
laneBinding = laneBinding.laneWrapper();
}
newLanes = oldLanes.updated(laneUri, laneBinding);
}
} while (oldLanes != newLanes && !LANES.compareAndSet(this, oldLanes, newLanes));
if (laneBinding != null) {
activate(laneBinding);
}
return laneBinding;
}
public void closeLane(Uri laneUri) {
laneUri = normalizezLaneUri(laneUri);
HashTrieMap<Uri, LaneBinding> oldLanes;
HashTrieMap<Uri, LaneBinding> newLanes;
LaneBinding laneBinding = null;
do {
oldLanes = this.lanes;
final LaneBinding lane = oldLanes.get(laneUri);
if (lane != null) {
laneBinding = lane;
newLanes = oldLanes.removed(laneUri);
} else {
laneBinding = null;
newLanes = oldLanes;
break;
}
} while (oldLanes != newLanes && !LANES.compareAndSet(this, oldLanes, newLanes));
if (laneBinding != null) {
laneBinding.didClose();
}
}
@Override
public <V> CommandLane<V> commandLane() {
return new CommandLaneView<V>(null, null);
}
@Override
public <V> DemandLane<V> demandLane() {
return new DemandLaneView<V>(null, null);
}
@Override
public <K, V> DemandMapLane<K, V> demandMapLane() {
return new DemandMapLaneView<K, V>(null, null, null);
}
@Override
public <V> HttpLane<V> httpLane() {
return new RestLaneView<V>(null, null);
}
@Override
public <L, K, V> JoinMapLane<L, K, V> joinMapLane() {
return new JoinMapLaneView<L, K, V>(null, null, null, null);
}
@Override
public <K, V> JoinValueLane<K, V> joinValueLane() {
return new JoinValueLaneView<K, V>(null, null, null);
}
@Override
public <V> ListLane<V> listLane() {
return new ListLaneView<V>(null, null);
}
@Override
public <K, V> MapLane<K, V> mapLane() {
return new MapLaneView<K, V>(null, null, null);
}
@Override
public <K, S, V> SpatialLane<K, S, V> spatialLane(Z2Form<S> shapeForm) {
return new SpatialLaneView<K, S, V>(null, null, shapeForm, null);
}
@Override
public <K, V> SpatialLane<K, R2Shape, V> geospatialLane() {
return new SpatialLaneView<K, R2Shape, V>(null, null, GeoProjection.wgs84Form(), null);
}
@Override
public <V> SupplyLane<V> supplyLane() {
return new SupplyLaneView<V>(null, null);
}
@Override
public <V> ValueLane<V> valueLane() {
return new ValueLaneView<V>(null, null);
}
@Override
public <I, O> WsLane<I, O> wsLane() {
throw new UnsupportedOperationException(); // TODO
}
@Override
public void openUplink(LinkBinding link) {
final Uri laneUri = normalizezLaneUri(link.laneUri());
final LaneBinding laneBinding = getLane(laneUri);
if (laneBinding != null) {
laneBinding.openUplink(link);
} else if (link instanceof WarpBinding) {
UplinkError.rejectLaneNotFound(link);
}
}
@Override
public LinkBinding bindDownlink(Downlink downlink) {
return this.nodeContext.bindDownlink(downlink);
}
@Override
public void openDownlink(LinkBinding link) {
this.nodeContext.openDownlink(link);
}
@Override
public void closeDownlink(LinkBinding link) {
// nop
}
@Override
public void pushUp(PushRequest pushRequest) {
final LaneBinding laneBinding = getLane(pushRequest.envelope().laneUri());
if (laneBinding != null) {
laneBinding.pushUp(pushRequest);
} else {
pushRequest.didDecline();
}
}
@Override
public void pushDown(PushRequest pushRequest) {
this.nodeContext.pushDown(pushRequest);
}
@Override
public void trace(Object message) {
this.nodeContext.trace(message);
}
@Override
public void debug(Object message) {
this.nodeContext.debug(message);
}
@Override
public void info(Object message) {
this.nodeContext.info(message);
}
@Override
public void warn(Object message) {
this.nodeContext.warn(message);
}
@Override
public void error(Object message) {
this.nodeContext.error(message);
}
@Override
protected void willOpen() {
super.willOpen();
final Iterator<LaneBinding> lanesIterator = this.lanes.valueIterator();
while (lanesIterator.hasNext()) {
lanesIterator.next().open();
}
}
@Override
protected void willLoad() {
super.willLoad();
final Iterator<LaneBinding> lanesIterator = this.lanes.valueIterator();
while (lanesIterator.hasNext()) {
lanesIterator.next().load();
}
}
@Override
protected void willStart() {
super.willStart();
final Iterator<LaneBinding> lanesIterator = this.lanes.valueIterator();
while (lanesIterator.hasNext()) {
lanesIterator.next().start();
}
}
@Override
protected void willStop() {
super.willStop();
final Iterator<LaneBinding> lanesIterator = this.lanes.valueIterator();
while (lanesIterator.hasNext()) {
lanesIterator.next().stop();
}
}
@Override
protected void willUnload() {
super.willUnload();
final Iterator<LaneBinding> lanesIterator = this.lanes.valueIterator();
while (lanesIterator.hasNext()) {
lanesIterator.next().unload();
}
}
@Override
protected void willClose() {
super.willClose();
final Iterator<LaneBinding> lanesIterator = this.lanes.valueIterator();
while (lanesIterator.hasNext()) {
lanesIterator.next().close();
}
}
@Override
public void didClose() {
// nop
}
@Override
public void didFail(Throwable error) {
error.printStackTrace();
}
@Override
public Policy policy() {
return this.nodeContext.policy();
}
@Override
public Schedule schedule() {
return this;
}
@Override
public Stage stage() {
return this;
}
@Override
public StoreBinding store() {
return this.nodeContext.store();
}
@Override
public TimerRef timer(TimerFunction timer) {
final Schedule schedule = this.nodeContext.schedule();
final AgentTimer agentTimer = new AgentTimer(this, timer);
schedule.timer(timer);
return agentTimer;
}
@Override
public TimerRef setTimer(long millis, TimerFunction timer) {
final Schedule schedule = this.nodeContext.schedule();
final AgentTimer agentTimer = new AgentTimer(this, timer);
schedule.setTimer(millis, agentTimer);
return agentTimer;
}
@Override
public TaskRef task(TaskFunction task) {
return this.nodeContext.stage().task(task);
}
@Override
public <T> Call<T> call(Cont<T> future) {
return this.nodeContext.stage().call(future);
}
@Override
public void execute(Runnable command) {
this.mailbox.add(command);
this.taskContext.cue();
}
@Override
public boolean taskWillBlock() {
return false;
}
@Override
public void runTask() {
do {
final Runnable command = this.mailbox.poll();
if (command != null) {
try {
command.run();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
didFail(error);
} else {
throw error;
}
}
} else {
break;
}
} while (true);
}
@Override
public void taskWillCue() {
// nop
}
@Override
public void taskDidCancel() {
// nop
}
@SuppressWarnings("unchecked")
static final AtomicReferenceFieldUpdater<AgentNode, HashTrieMap<Uri, LaneBinding>> LANES =
AtomicReferenceFieldUpdater.newUpdater(AgentNode.class, (Class<HashTrieMap<Uri, LaneBinding>>) (Class<?>) HashTrieMap.class, "lanes");
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/agent/AgentTimer.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.runtime.agent;
import swim.concurrent.Conts;
import swim.concurrent.Schedule;
import swim.concurrent.Timer;
import swim.concurrent.TimerContext;
import swim.concurrent.TimerFunction;
import swim.concurrent.TimerRef;
public class AgentTimer implements Timer, TimerContext, TimerRef, Runnable {
protected final AgentNode node;
protected final TimerFunction timer;
protected TimerContext timerContext;
public AgentTimer(AgentNode node, TimerFunction timer) {
this.node = node;
this.timer = timer;
}
@Override
public TimerContext timerContext() {
return this.timerContext;
}
@Override
public void setTimerContext(TimerContext timerContext) {
this.timerContext = timerContext;
if (this.timer instanceof Timer) {
((Timer) this.timer).setTimerContext(this);
}
}
@Override
public void runTimer() {
this.node.execute(this);
}
@Override
public void timerWillSchedule(long millis) {
if (this.timer instanceof Timer) {
((Timer) this.timer).timerWillSchedule(millis);
}
}
@Override
public void timerDidCancel() {
if (this.timer instanceof Timer) {
((Timer) this.timer).timerDidCancel();
}
}
@Override
public Schedule schedule() {
return this.node;
}
@Override
public boolean isScheduled() {
return this.timerContext.isScheduled();
}
@Override
public void reschedule(long millis) {
this.timerContext.reschedule(millis);
}
@Override
public boolean cancel() {
return this.timerContext.cancel();
}
@Override
public void run() {
try {
this.timer.runTimer();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
this.node.didFail(error);
} else {
throw error;
}
}
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/agent/AgentView.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.runtime.agent;
import swim.api.Downlink;
import swim.api.Lane;
import swim.api.Link;
import swim.api.SwimContext;
import swim.api.agent.Agent;
import swim.api.agent.AgentContext;
import swim.api.agent.AgentFactory;
import swim.api.data.ListData;
import swim.api.data.MapData;
import swim.api.data.SpatialData;
import swim.api.data.ValueData;
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.api.policy.Policy;
import swim.api.ws.WsLane;
import swim.collections.FingerTrieSeq;
import swim.concurrent.Schedule;
import swim.concurrent.Stage;
import swim.math.R2Shape;
import swim.math.Z2Form;
import swim.runtime.AbstractTierBinding;
import swim.runtime.LaneView;
import swim.runtime.LinkBinding;
import swim.runtime.PushRequest;
import swim.runtime.TierContext;
import swim.runtime.http.RestLaneView;
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.spatial.GeoProjection;
import swim.store.StoreBinding;
import swim.structure.Text;
import swim.structure.Value;
import swim.uri.Uri;
import swim.util.Builder;
public class AgentView extends AbstractTierBinding implements TierContext, AgentContext {
protected final AgentModel node;
protected final Value props;
protected Agent agent;
public AgentView(AgentModel node, Value props) {
this.node = node;
this.props = props.commit();
}
public final Agent agent() {
return this.agent;
}
void setAgent(Agent agent) {
this.agent = agent;
}
@Override
public TierContext tierContext() {
return this;
}
@SuppressWarnings("unchecked")
public <T> T unwrapNode(Class<T> nodeClass) {
if (nodeClass.isAssignableFrom(getClass())) {
return (T) this;
} else if (nodeClass.isAssignableFrom(this.agent.getClass())) {
return (T) this.agent;
} else {
return null;
}
}
@Override
public final Uri meshUri() {
return this.node.meshUri();
}
@Override
public final Uri hostUri() {
return this.node.hostUri();
}
@Override
public final Uri nodeUri() {
return this.node.nodeUri();
}
@Override
public final Value props() {
return this.props;
}
@Override
public Value getProp(Value key) {
return this.props.get(key);
}
@Override
public Value getProp(String name) {
return this.props.get(name);
}
@Override
public Policy policy() {
return this.node.policy();
}
@Override
public Schedule schedule() {
return this.node.schedule();
}
@Override
public Stage stage() {
return this.node.stage();
}
@Override
public StoreBinding store() {
return this.node.store();
}
@Override
public Lane lane() {
return SwimContext.getLane();
}
@Override
public Link link() {
return SwimContext.getLink();
}
@Override
public Lane getLane(Uri laneUri) {
return this.node.getLane(laneUri).getLaneView(this);
}
@Override
public Lane openLane(Uri laneUri, Lane lane) {
this.node.openLaneView(laneUri, (LaneView) lane);
return lane;
}
public <A extends Agent> AgentFactory<A> createAgentFactory(Class<? extends A> agentClass) {
return this.node.createAgentFactory(agentClass);
}
@Override
public FingerTrieSeq<Agent> agents() {
final Object views = this.node.views;
final Builder<Agent, FingerTrieSeq<Agent>> agents = FingerTrieSeq.builder();
if (views instanceof AgentView) {
agents.add(((AgentView) views).agent);
} else if (views instanceof AgentView[]) {
final AgentView[] viewArray = (AgentView[]) views;
for (int i = 0, n = viewArray.length; i < n; i += 1) {
agents.add(viewArray[i].agent);
}
}
return agents.bind();
}
@Override
public Agent getAgent(Value props) {
final AgentView view = this.node.getAgentView(props);
if (view != null) {
return view.agent;
} else {
return null;
}
}
@Override
public Agent getAgent(String name) {
return getAgent(Text.from(name));
}
@Override
public <A extends Agent> A getAgent(Class<? extends A> agentClass) {
return this.node.getAgent(agentClass);
}
@SuppressWarnings("unchecked")
@Override
public <A extends Agent> A addAgent(Value props, AgentFactory<A> agentFactory) {
return this.node.addAgent(props, agentFactory);
}
@Override
public <A extends Agent> A addAgent(String name, AgentFactory<A> agentFactory) {
return addAgent(Text.from(name), agentFactory);
}
@Override
public <A extends Agent> A addAgent(Value props, Class<? extends A> agentClass) {
return addAgent(props, createAgentFactory(agentClass));
}
@Override
public <A extends Agent> A addAgent(String name, Class<? extends A> agentClass) {
return addAgent(Text.from(name), agentClass);
}
@Override
public void removeAgent(Value props) {
final AgentView view = this.node.getAgentView(props);
if (view != null) {
this.node.removeAgentView(view);
}
}
@Override
public void removeAgent(String name) {
removeAgent(Text.from(name));
}
@Override
public <V> CommandLane<V> commandLane() {
return new CommandLaneView<V>(this, null);
}
@Override
public <V> DemandLane<V> demandLane() {
return new DemandLaneView<V>(this, null);
}
@Override
public <K, V> DemandMapLane<K, V> demandMapLane() {
return new DemandMapLaneView<K, V>(this, null, null);
}
@Override
public <V> HttpLane<V> httpLane() {
return new RestLaneView<V>(this, null);
}
@Override
public <L, K, V> JoinMapLane<L, K, V> joinMapLane() {
return new JoinMapLaneView<L, K, V>(this, null, null, null);
}
@Override
public <K, V> JoinValueLane<K, V> joinValueLane() {
return new JoinValueLaneView<K, V>(this, null, null);
}
@Override
public <V> ListLane<V> listLane() {
return new ListLaneView<V>(this, null);
}
@Override
public <K, V> MapLane<K, V> mapLane() {
return new MapLaneView<K, V>(this, null, null);
}
@Override
public <K, S, V> SpatialLane<K, S, V> spatialLane(Z2Form<S> shapeForm) {
return new SpatialLaneView<K, S, V>(this, null, shapeForm, null);
}
@Override
public <K, V> SpatialLane<K, R2Shape, V> geospatialLane() {
return new SpatialLaneView<K, R2Shape, V>(this, null, GeoProjection.wgs84Form(), null);
}
@Override
public <V> SupplyLane<V> supplyLane() {
return new SupplyLaneView<V>(this, null);
}
@Override
public <V> ValueLane<V> valueLane() {
return new ValueLaneView<V>(this, null);
}
@Override
public <I, O> WsLane<I, O> wsLane() {
throw new UnsupportedOperationException(); // TODO
}
@Override
public ListData<Value> listData(Value name) {
return store().listData(name);
}
@Override
public ListData<Value> listData(String name) {
return store().listData(name);
}
@Override
public MapData<Value, Value> mapData(Value name) {
return store().mapData(name);
}
@Override
public MapData<Value, Value> mapData(String name) {
return store().mapData(name);
}
@Override
public <S> SpatialData<Value, S, Value> spatialData(Value name, Z2Form<S> shapeForm) {
return store().spatialData(name, shapeForm);
}
@Override
public <S> SpatialData<Value, S, Value> spatialData(String name, Z2Form<S> shapeForm) {
return store().spatialData(name, shapeForm);
}
@Override
public SpatialData<Value, R2Shape, Value> geospatialData(Value name) {
return store().geospatialData(name);
}
@Override
public SpatialData<Value, R2Shape, Value> geospatialData(String name) {
return store().geospatialData(name);
}
@Override
public ValueData<Value> valueData(Value name) {
return store().valueData(name);
}
@Override
public ValueData<Value> valueData(String name) {
return store().valueData(name);
}
@Override
public LinkBinding bindDownlink(Downlink downlink) {
return this.node.bindDownlink(downlink);
}
@Override
public void openDownlink(LinkBinding link) {
this.node.openDownlink(link);
}
@Override
public void closeDownlink(LinkBinding link) {
this.node.closeDownlink(link);
}
@Override
public void pushDown(PushRequest pushRequest) {
this.node.pushDown(pushRequest);
}
@Override
public void trace(Object message) {
this.node.trace(message);
}
@Override
public void debug(Object message) {
this.node.debug(message);
}
@Override
public void info(Object message) {
this.node.info(message);
}
@Override
public void warn(Object message) {
this.node.warn(message);
}
@Override
public void error(Object message) {
this.node.error(message);
}
@Override
public void willOpen() {
this.agent.willOpen();
}
@Override
public void didOpen() {
this.agent.didOpen();
}
@Override
public void willLoad() {
this.agent.willLoad();
}
@Override
public void didLoad() {
this.agent.didLoad();
}
@Override
public void willStart() {
this.agent.willStart();
}
@Override
public void didStart() {
this.agent.didStart();
}
@Override
public void willStop() {
this.agent.willStop();
}
@Override
public void didStop() {
this.agent.didStop();
}
@Override
public void willUnload() {
this.agent.willUnload();
}
@Override
public void didUnload() {
this.agent.didUnload();
}
@Override
public void willClose() {
this.agent.willClose();
this.node.close();
}
@Override
public void didClose() {
this.agent.didClose();
}
@Override
public void didFail(Throwable error) {
this.agent.didFail(error);
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/agent/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.
/**
* Web Agent runtime implementation.
*/
package swim.runtime.agent;
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/downlink/EventDownlinkModel.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.runtime.downlink;
import swim.runtime.DownlinkRelay;
import swim.runtime.warp.SupplyDownlinkModem;
import swim.structure.Form;
import swim.structure.Value;
import swim.uri.Uri;
import swim.warp.EventMessage;
public class EventDownlinkModel extends SupplyDownlinkModem<EventDownlinkView<?>> {
public EventDownlinkModel(Uri meshUri, Uri hostUri, Uri nodeUri, Uri laneUri,
float prio, float rate, Value body) {
super(meshUri, hostUri, nodeUri, laneUri, prio, rate, body);
}
@Override
protected void pushDownEvent(EventMessage message) {
onEvent(message);
new EventDownlinkRelayOnEvent(this, message).run();
}
public void command(Value body) {
pushUp(body);
}
}
final class EventDownlinkRelayOnEvent extends DownlinkRelay<EventDownlinkModel, EventDownlinkView<?>> {
final EventMessage message;
Form<Object> valueForm;
Object object;
EventDownlinkRelayOnEvent(EventDownlinkModel model, EventMessage message) {
super(model, 3);
this.message = message;
}
@SuppressWarnings("unchecked")
@Override
protected boolean runPhase(EventDownlinkView<?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.downlinkWillReceive(this.message);
}
return view.dispatchWillReceive(this.message.body(), preemptive);
} else if (phase == 1) {
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.object = valueForm.cast(message.body());
if (this.object == null) {
this.object = valueForm.unit();
}
}
if (preemptive) {
((EventDownlinkView<Object>) view).downlinkOnEvent(this.object);
}
return ((EventDownlinkView<Object>) view).dispatchOnEvent(this.object, preemptive);
} else if (phase == 2) {
if (preemptive) {
view.downlinkDidReceive(this.message);
}
return view.dispatchDidReceive(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
this.model.cueDown();
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/downlink/EventDownlinkView.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.runtime.downlink;
import swim.api.DownlinkException;
import swim.api.Link;
import swim.api.SwimContext;
import swim.api.downlink.EventDownlink;
import swim.api.function.DidClose;
import swim.api.function.DidConnect;
import swim.api.function.DidDisconnect;
import swim.api.function.DidFail;
import swim.api.warp.function.DidLink;
import swim.api.warp.function.DidReceive;
import swim.api.warp.function.DidSync;
import swim.api.warp.function.DidUnlink;
import swim.api.warp.function.OnEvent;
import swim.api.warp.function.WillCommand;
import swim.api.warp.function.WillLink;
import swim.api.warp.function.WillReceive;
import swim.api.warp.function.WillSync;
import swim.api.warp.function.WillUnlink;
import swim.concurrent.Conts;
import swim.concurrent.Stage;
import swim.runtime.CellContext;
import swim.runtime.LinkBinding;
import swim.runtime.warp.WarpDownlinkView;
import swim.structure.Form;
import swim.structure.Value;
import swim.uri.Uri;
public class EventDownlinkView<V> extends WarpDownlinkView implements EventDownlink<V> {
protected final Form<V> valueForm;
protected EventDownlinkModel model;
public EventDownlinkView(CellContext cellContext, Stage stage, Uri meshUri,
Uri hostUri, Uri nodeUri, Uri laneUri, float prio,
float rate, Value body, int flags, Form<V> valueForm,
Object observers) {
super(cellContext, stage, meshUri, hostUri, nodeUri, laneUri, prio, rate,
body, flags, observers);
this.valueForm = valueForm;
}
public EventDownlinkView(CellContext cellContext, Stage stage, Uri meshUri,
Uri hostUri, Uri nodeUri, Uri laneUri, float prio,
float rate, Value body, Form<V> valueForm) {
this(cellContext, stage, meshUri, hostUri, nodeUri, laneUri, prio, rate,
body, KEEP_LINKED, valueForm, null);
}
@Override
public EventDownlinkModel downlinkModel() {
return this.model;
}
@Override
public EventDownlinkView<V> hostUri(Uri hostUri) {
return new EventDownlinkView<V>(this.cellContext, this.stage, this.meshUri,
hostUri, this.nodeUri, this.laneUri,
this.prio, this.rate, this.body, this.flags,
this.valueForm, this.observers);
}
@Override
public EventDownlinkView<V> hostUri(String hostUri) {
return hostUri(Uri.parse(hostUri));
}
@Override
public EventDownlinkView<V> nodeUri(Uri nodeUri) {
return new EventDownlinkView<V>(this.cellContext, this.stage, this.meshUri,
this.hostUri, nodeUri, this.laneUri,
this.prio, this.rate, this.body, this.flags,
this.valueForm, this.observers);
}
@Override
public EventDownlinkView<V> nodeUri(String nodeUri) {
return nodeUri(Uri.parse(nodeUri));
}
@Override
public EventDownlinkView<V> laneUri(Uri laneUri) {
return new EventDownlinkView<V>(this.cellContext, this.stage, this.meshUri,
this.hostUri, this.nodeUri, laneUri,
this.prio, this.rate, this.body, this.flags,
this.valueForm, this.observers);
}
@Override
public EventDownlinkView<V> laneUri(String laneUri) {
return laneUri(Uri.parse(laneUri));
}
@Override
public EventDownlinkView<V> prio(float prio) {
return new EventDownlinkView<V>(this.cellContext, this.stage, this.meshUri,
this.hostUri, this.nodeUri, this.laneUri,
prio, this.rate, this.body, this.flags,
this.valueForm, this.observers);
}
@Override
public EventDownlinkView<V> rate(float rate) {
return new EventDownlinkView<V>(this.cellContext, this.stage, this.meshUri,
this.hostUri, this.nodeUri, this.laneUri,
this.prio, rate, this.body, this.flags,
valueForm, this.observers);
}
@Override
public EventDownlinkView<V> body(Value body) {
return new EventDownlinkView<V>(this.cellContext, this.stage, this.meshUri,
this.hostUri, this.nodeUri, this.laneUri,
this.prio, this.rate, body, this.flags,
this.valueForm, this.observers);
}
@Override
public EventDownlinkView<V> keepLinked(boolean keepLinked) {
if (keepLinked) {
this.flags |= KEEP_LINKED;
} else {
this.flags &= ~KEEP_LINKED;
}
return this;
}
@Override
public EventDownlinkView<V> keepSynced(boolean keepSynced) {
if (keepSynced) {
this.flags |= KEEP_SYNCED;
} else {
this.flags &= ~KEEP_SYNCED;
}
return this;
}
@Override
public final Form<V> valueForm() {
return valueForm;
}
@Override
public <V2> EventDownlinkView<V2> valueForm(Form<V2> valueForm) {
return new EventDownlinkView<V2>(this.cellContext, this.stage, this.meshUri,
this.hostUri, this.nodeUri, this.laneUri,
this.prio, this.rate, this.body, this.flags,
valueForm, typesafeObservers(this.observers));
}
@Override
public <V2> EventDownlinkView<V2> valueClass(Class<V2> valueClass) {
return valueForm(Form.<V2>forClass(valueClass));
}
protected Object typesafeObservers(Object observers) {
// TODO: filter out OnEvent
return observers;
}
@SuppressWarnings("unchecked")
@Override
public EventDownlinkView<V> observe(Object observer) {
return (EventDownlinkView<V>) super.observe(observer);
}
@SuppressWarnings("unchecked")
@Override
public EventDownlinkView<V> unobserve(Object observer) {
return (EventDownlinkView<V>) super.unobserve(observer);
}
@Override
public EventDownlinkView<V> onEvent(OnEvent<V> onEvent) {
return observe(onEvent);
}
@Override
public EventDownlinkView<V> willReceive(WillReceive willReceive) {
return observe(willReceive);
}
@Override
public EventDownlinkView<V> didReceive(DidReceive didReceive) {
return observe(didReceive);
}
@Override
public EventDownlinkView<V> willCommand(WillCommand willCommand) {
return observe(willCommand);
}
@Override
public EventDownlinkView<V> willLink(WillLink willLink) {
return observe(willLink);
}
@Override
public EventDownlinkView<V> didLink(DidLink didLink) {
return observe(didLink);
}
@Override
public EventDownlinkView<V> willSync(WillSync willSync) {
return observe(willSync);
}
@Override
public EventDownlinkView<V> didSync(DidSync didSync) {
return observe(didSync);
}
@Override
public EventDownlinkView<V> willUnlink(WillUnlink willUnlink) {
return observe(willUnlink);
}
@Override
public EventDownlinkView<V> didUnlink(DidUnlink didUnlink) {
return observe(didUnlink);
}
@Override
public EventDownlinkView<V> didConnect(DidConnect didConnect) {
return observe(didConnect);
}
@Override
public EventDownlinkView<V> didDisconnect(DidDisconnect didDisconnect) {
return observe(didDisconnect);
}
@Override
public EventDownlinkView<V> didClose(DidClose didClose) {
return observe(didClose);
}
@Override
public EventDownlinkView<V> didFail(DidFail didFail) {
return observe(didFail);
}
@SuppressWarnings("unchecked")
public boolean dispatchOnEvent(V value, boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof OnEvent<?>) {
if (((OnEvent<?>) observers).isPreemptive() == preemptive) {
try {
((OnEvent<V>) observers).onEvent(value);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof OnEvent<?>) {
if (((OnEvent<?>) observer).isPreemptive() == preemptive) {
try {
((OnEvent<V>) observer).onEvent(value);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
public void downlinkOnEvent(V value) {
}
@Override
public EventDownlinkModel createDownlinkModel() {
return new EventDownlinkModel(this.meshUri, this.hostUri, this.nodeUri,
this.laneUri, this.prio, this.rate, this.body);
}
@Override
public EventDownlinkView<V> open() {
if (this.model == null) {
final LinkBinding linkBinding = this.cellContext.bindDownlink(this);
if (linkBinding instanceof EventDownlinkModel) {
this.model = (EventDownlinkModel) linkBinding;
this.model.addDownlink(this);
} else {
throw new DownlinkException("downlink type mismatch");
}
}
return this;
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/downlink/ListDownlinkModel.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.runtime.downlink;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import swim.collections.STreeList;
import swim.concurrent.Stage;
import swim.runtime.DownlinkRelay;
import swim.runtime.DownlinkView;
import swim.runtime.warp.ListDownlinkModem;
import swim.runtime.warp.ListLinkDelta;
import swim.structure.Form;
import swim.structure.Value;
import swim.uri.Uri;
import swim.warp.EventMessage;
public class ListDownlinkModel extends ListDownlinkModem<ListDownlinkView<?>> {
protected int flags;
protected final STreeList<Value> state;
public ListDownlinkModel(Uri meshUri, Uri hostUri, Uri nodeUri, Uri laneUri,
float prio, float rate, Value body) {
super(meshUri, hostUri, nodeUri, laneUri, prio, rate, body);
this.flags = 0;
state = STreeList.empty();
}
public final boolean isStateful() {
return (this.flags & STATEFUL) != 0;
}
public ListDownlinkModel isStateful(boolean isStateful) {
if (isStateful) {
this.flags |= STATEFUL;
} else {
this.flags &= ~STATEFUL;
}
final Object views = this.views;
if (views instanceof DownlinkView) {
((ListDownlinkView<?>) views).didSetStateful(isStateful);
} else if (views instanceof DownlinkView[]) {
final DownlinkView[] viewArray = (DownlinkView[]) views;
for (int i = 0, n = viewArray.length; i < n; i += 1) {
((ListDownlinkView<?>) viewArray[i]).didSetStateful(isStateful);
}
}
return this;
}
@Override
protected void pushDownEvent(EventMessage message) {
onEvent(message);
final Value payload = message.body();
final String tag = payload.tag();
if ("update".equals(tag)) {
final Value header = payload.header("update");
final int index = header.get("index").intValue(-1);
if (index > -1) {
final Object key;
if (header.get("key").isDistinct()) {
key = header.get("key");
} else {
key = null;
}
final Value value = payload.body();
new ListDownlinkRelayUpdate(this, message, index, value, key).run();
}
} else if ("move".equals(tag)) {
final Value header = payload.header("move");
final int fromIndex = header.get("from").intValue(-1);
final int toIndex = header.get("to").intValue(-1);
if (fromIndex > -1 && toIndex > -1) {
final Object key;
if (header.get("key").isDistinct()) {
key = header.get("key");
} else {
key = null;
}
new ListDownlinkRelayMove(this, message, fromIndex, toIndex, key).run();
}
} else if ("remove".equals(tag)) {
final Value header = payload.header("remove");
final int index = header.get("index").intValue(-1);
if (index > -1) {
final Object key;
if (header.get("key").isDistinct()) {
key = header.get("key");
} else {
key = null;
}
new ListDownlinkRelayRemove(this, message, index, key).run();
}
} else if ("drop".equals(tag)) {
final Value header = payload.header("drop");
final int lower = header.intValue(0);
new ListDownlinkRelayDrop(this, message, lower).run();
} else if ("take".equals(tag)) {
final Value header = payload.header("take");
final int upper = header.intValue(0);
new ListDownlinkRelayTake(this, message, upper).run();
} else if ("clear".equals(tag)) {
new ListDownlinkRelayClear(this, message).run();
}
}
@Override
protected void didAddDownlink(ListDownlinkView<?> view) {
if (this.views instanceof DownlinkView) {
isStateful(((ListDownlinkView<?>) view).isStateful());
}
}
public boolean isEmpty() {
return this.state.isEmpty();
}
public int size() {
return this.state.size();
}
public boolean contains(Object value) {
if (value != null) {
return this.state.contains(value);
} else {
return false;
}
}
public int indexOf(Object o) {
return this.state.indexOf(o);
}
public int lastIndexOf(Object o) {
return this.state.lastIndexOf(o);
}
public List<Value> subList(int fromIndex, int toIndex) {
return this.state.subList(fromIndex, toIndex);
}
public Object[] toArray() {
return this.state.toArray();
}
public <V> V[] toArray(V[] array) {
return this.state.toArray(array);
}
public ListIterator<Map.Entry<Object, Value>> entryIterator() {
return this.state.entryIterator();
}
public Iterator<Value> iterator() {
return this.state.iterator();
}
public ListIterator<Value> listIterator() {
return this.state.listIterator();
}
public ListIterator<Value> listIterator(int index) {
return this.state.listIterator(index);
}
public ListIterator<Object> keyIterator() {
return this.state.keyIterator();
}
public Map.Entry<Object, Value> getEntry(int index) {
return this.state.getEntry(index);
}
public Map.Entry<Object, Value> getEntry(int index, Object key) {
return this.state.getEntry(index, key);
}
public Value get(int index, Object key) {
final Value value = this.state.get(index, key);
if (value != null) {
return value;
}
return Value.absent();
}
@SuppressWarnings("unchecked")
public <V> boolean add(ListDownlinkView<V> view, int index, V newObject) {
return add(view, index, newObject, null);
}
@SuppressWarnings("unchecked")
public <V> boolean add(ListDownlinkView<V> view, int index, V newObject, Object key) {
final Form<V> valueForm = view.valueForm;
final Value newValue = valueForm.mold(newObject).toValue();
final ListDownlinkRelayUpdate relay = new ListDownlinkRelayUpdate(this, view.stage(), index, newValue, key);
relay.valueForm = (Form<Object>) valueForm;
relay.newObject = newObject;
relay.run();
if (relay.isDone() && relay.valueForm == valueForm) {
return relay.oldObject != null;
} else {
return false;
}
}
@SuppressWarnings("unchecked")
public <V> V set(ListDownlinkView<V> view, int index, V newObject) {
return set(view, index, newObject, null);
}
@SuppressWarnings("unchecked")
public <V> V set(ListDownlinkView<V> view, int index, V newObject, Object key) {
final Form<V> valueForm = view.valueForm;
final Value newValue = valueForm.mold(newObject).toValue();
final ListDownlinkRelayUpdate relay = new ListDownlinkRelayUpdate(this, view.stage(), index, newValue, key);
relay.valueForm = (Form<Object>) valueForm;
relay.oldObject = newObject;
relay.newObject = newObject;
relay.run();
if (relay.isDone() && relay.valueForm == valueForm) {
return (V) relay.oldObject;
} else {
return null;
}
}
public <V> void move(ListDownlinkView<V> view, int fromIndex, int toIndex) {
move(view, fromIndex, toIndex, null);
}
public <V> void move(ListDownlinkView<V> view, int fromIndex, int toIndex, Object key) {
final ListDownlinkRelayMove relay = new ListDownlinkRelayMove(this, view.stage(), fromIndex, toIndex, key);
relay.run();
}
@SuppressWarnings("unchecked")
public <V> V remove(ListDownlinkView<V> view, int index) {
return remove(view, index, null);
}
@SuppressWarnings("unchecked")
public <V> V remove(ListDownlinkView<V> view, int index, Object key) {
final Form<V> valueForm = view.valueForm;
final Map.Entry<Object, Value> entry = getEntry(index, key);
if (entry != null) {
final Object actualKey = key == null ? entry.getKey() : key;
final ListDownlinkRelayRemove relay = new ListDownlinkRelayRemove(this, view.stage(), index, actualKey);
relay.valueForm = (Form<Object>) valueForm;
relay.run();
if (relay.isDone()) {
if (relay.valueForm != valueForm && valueForm != null) {
relay.oldObject = valueForm.cast(relay.oldValue);
if (relay.oldObject == null) {
relay.oldObject = valueForm.unit();
}
}
return (V) relay.oldObject;
} else {
return null;
}
} else {
return null;
}
}
public void drop(ListDownlinkView<?> view, int lower) {
pushUp(ListLinkDelta.drop(lower));
//final ListDownlinkRelayDrop relay = new ListDownlinkRelayDrop(this, view.stage(), lower);
//relay.run();
}
public void take(ListDownlinkView<?> view, int upper) {
pushUp(ListLinkDelta.take(upper));
//final ListDownlinkRelayTake relay = new ListDownlinkRelayTake(this, view.stage(), upper);
//relay.run();
}
public void clear(ListDownlinkView<?> view) {
final ListDownlinkRelayClear relay = new ListDownlinkRelayClear(this, view.stage());
relay.run();
}
protected static final int STATEFUL = 1 << 0;
}
final class ListDownlinkRelayUpdate extends DownlinkRelay<ListDownlinkModel, ListDownlinkView<?>> {
final EventMessage message;
Object key;
final int index;
Form<Object> valueForm;
Value oldValue;
Value newValue;
Object oldObject;
Object newObject;
ListDownlinkRelayUpdate(ListDownlinkModel model, EventMessage message, int index, Value newValue, Object key) {
super(model, 4);
this.message = message;
this.index = index;
this.key = key;
this.newValue = newValue;
}
ListDownlinkRelayUpdate(ListDownlinkModel model, Stage stage, int index, Value newValue, Object key) {
super(model, 1, 3, stage);
this.message = null;
this.index = index;
this.key = key;
this.newValue = newValue;
}
@SuppressWarnings("unchecked")
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
if (this.model.isStateful()) {
final Map.Entry<Object, Value> entry;
if (this.index < this.model.state.size()) {
entry = this.model.state.getEntry(this.index, this.key);
} else {
entry = null;
}
if (entry == null) {
if (this.key == null) {
final byte[] bytes = new byte[6];
ThreadLocalRandom.current().nextBytes(bytes);
this.key = Value.fromObject(bytes);
}
this.model.state.add(this.index, this.newValue, this.key);
} else {
this.oldValue = entry.getValue();
this.key = entry.getKey();
this.model.state.set(this.index, this.newValue, this.key);
}
}
if (this.oldValue == null) {
this.oldValue = Value.absent();
}
}
}
@SuppressWarnings("unchecked")
@Override
protected boolean runPhase(ListDownlinkView<?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.downlinkWillReceive(this.message);
}
return view.dispatchWillReceive(this.message.body(), preemptive);
} else if (phase == 1) {
this.newValue = view.downlinkWillUpdateValue(this.index, this.newValue);
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
if (this.oldValue != null) {
this.oldObject = valueForm.cast(this.oldValue);
}
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
newObject = valueForm.cast(newValue);
}
if (preemptive) {
this.newObject = ((ListDownlinkView<Object>) view).downlinkWillUpdate(this.index, this.newObject);
}
final Map.Entry<Boolean, Object> result = ((ListDownlinkView<Object>) view).dispatchWillUpdate(this.index, this.newObject, preemptive);
if (this.newObject != result.getValue()) {
this.oldObject = this.newObject;
this.newObject = result.getValue();
this.newValue = valueForm.mold(this.newObject).toValue();
}
return result.getKey();
} else if (phase == 2) {
view.downlinkDidUpdateValue(this.index, this.newValue, this.oldValue);
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.oldObject = valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
this.newObject = valueForm.cast(this.newValue);
if (this.newObject == null) {
this.newObject = valueForm.unit();
}
}
if (preemptive) {
((ListDownlinkView<Object>) view).downlinkDidUpdate(this.index, this.newObject, this.oldObject);
}
return ((ListDownlinkView<Object>) view).dispatchDidUpdate(this.index, this.newObject, this.oldObject, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.downlinkDidReceive(this.message);
}
return view.dispatchDidReceive(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
if (this.message != null) {
this.model.cueDown();
} else {
this.model.pushUp(ListLinkDelta.update(this.index, Value.fromObject(this.key), this.newValue));
}
}
}
final class ListDownlinkRelayMove extends DownlinkRelay<ListDownlinkModel, ListDownlinkView<?>> {
final EventMessage message;
final int fromIndex;
final int toIndex;
Object key;
Form<Object> valueForm;
Value value;
Object object;
ListDownlinkRelayMove(ListDownlinkModel model, EventMessage message, int fromIndex, int toIndex, Object key) {
super(model, 4);
this.message = message;
this.fromIndex = fromIndex;
this.toIndex = toIndex;
this.key = key;
}
ListDownlinkRelayMove(ListDownlinkModel model, Stage stage, int fromIndex, int toIndex, Object key) {
super(model, 1, 3, stage);
this.message = null;
this.fromIndex = fromIndex;
this.toIndex = toIndex;
this.key = key;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
final Map.Entry<Object, Value> entry = this.model.state.getEntry(this.fromIndex);
this.model.state.move(this.fromIndex, this.toIndex, this.key);
this.key = entry.getKey();
this.value = entry.getValue();
if (this.value == null) {
this.value = Value.absent();
}
if (this.valueForm != null) {
this.object = this.valueForm.cast(this.value);
if (this.object == null) {
this.object = this.valueForm.unit();
}
}
}
}
@SuppressWarnings("unchecked")
@Override
protected boolean runPhase(ListDownlinkView<?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.downlinkWillReceive(this.message);
}
return view.dispatchWillReceive(this.message.body(), preemptive);
} else if (phase == 1) {
view.downlinkWillMoveValue(this.fromIndex, this.toIndex, this.value);
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
if (this.value != null) {
this.object = valueForm.cast(this.value);
}
if (this.object == null) {
this.object = valueForm.unit();
}
}
if (preemptive) {
((ListDownlinkView<Object>) view).downlinkWillMove(this.fromIndex, this.toIndex, this.value);
}
return ((ListDownlinkView<Object>) view).dispatchWillMove(this.fromIndex, this.toIndex, this.value, preemptive);
} else if (phase == 2) {
view.downlinkDidMoveValue(this.fromIndex, this.toIndex, this.value);
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.object = valueForm.cast(this.value);
if (this.object == null) {
this.object = valueForm.unit();
}
}
if (preemptive) {
((ListDownlinkView<Object>) view).downlinkDidMove(this.fromIndex, this.toIndex, this.object);
}
return ((ListDownlinkView<Object>) view).dispatchDidMove(this.fromIndex, this.toIndex, this.object, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.downlinkDidReceive(this.message);
}
return view.dispatchDidReceive(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
if (this.message != null) {
this.model.cueDown();
} else {
this.model.pushUp(ListLinkDelta.move(this.fromIndex, this.toIndex, Value.fromObject(this.key)));
}
}
}
final class ListDownlinkRelayRemove extends DownlinkRelay<ListDownlinkModel, ListDownlinkView<?>> {
final EventMessage message;
final int index;
Object key;
Form<Object> valueForm;
Value oldValue;
Object oldObject;
ListDownlinkRelayRemove(ListDownlinkModel model, EventMessage message, int index, Object key) {
super(model, 4);
this.message = message;
this.index = index;
this.key = key;
}
ListDownlinkRelayRemove(ListDownlinkModel model, Stage stage, int index, Object key) {
super(model, 1, 3, stage);
this.message = null;
this.index = index;
this.key = key;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
this.model.state.remove(this.index, this.key);
if (this.oldValue == null) {
this.oldValue = Value.absent();
}
if (this.valueForm != null) {
this.oldObject = this.valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = this.valueForm.unit();
}
}
}
}
@SuppressWarnings("unchecked")
@Override
protected boolean runPhase(ListDownlinkView<?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.downlinkWillReceive(this.message);
}
return view.dispatchWillReceive(this.message.body(), preemptive);
} else if (phase == 1) {
view.downlinkWillRemoveValue(this.index);
final Form<Object> valueForm = (Form<Object>) view.valueForm;
this.valueForm = valueForm;
final Map.Entry<Object, Value> entry = this.model.state.getEntry(this.index, this.key);
this.oldValue = entry.getValue();
this.key = entry.getKey();
this.oldObject = valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
if (preemptive) {
view.downlinkWillRemove(this.index);
}
return view.dispatchWillRemove(this.index, preemptive);
} else if (phase == 2) {
view.downlinkDidRemoveValue(this.index, this.oldValue);
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
if (this.oldValue != null) {
this.oldObject = valueForm.cast(this.oldValue);
}
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
}
if (preemptive) {
((ListDownlinkView<Object>) view).downlinkDidRemove(this.index, this.oldObject);
}
return ((ListDownlinkView<Object>) view).dispatchDidRemove(this.index, this.oldObject, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.downlinkDidReceive(this.message);
}
return view.dispatchDidReceive(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
if (this.message != null) {
this.model.cueDown();
} else {
this.model.pushUp(ListLinkDelta.remove(this.index, Value.fromObject(this.key)));
}
}
}
final class ListDownlinkRelayDrop extends DownlinkRelay<ListDownlinkModel, ListDownlinkView<?>> {
final EventMessage message;
final int lower;
ListDownlinkRelayDrop(ListDownlinkModel model, EventMessage message, int lower) {
super(model, 4);
this.message = message;
this.lower = lower;
}
ListDownlinkRelayDrop(ListDownlinkModel model, Stage stage, int lower) {
super(model, 1, 3, stage);
this.message = null;
this.lower = lower;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
if (this.model.isStateful()) {
this.model.state.drop(this.lower);
}
}
}
@Override
protected boolean runPhase(ListDownlinkView<?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.downlinkWillReceive(this.message);
}
return view.dispatchWillReceive(this.message.body(), preemptive);
} else if (phase == 1) {
if (preemptive) {
view.downlinkWillDrop(this.lower);
}
return view.dispatchWillDrop(this.lower, preemptive);
} else if (phase == 2) {
if (preemptive) {
view.downlinkDidDrop(this.lower);
}
return view.dispatchDidDrop(this.lower, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.downlinkDidReceive(this.message);
}
return view.dispatchDidReceive(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
if (this.message != null) {
this.model.cueDown();
} else {
this.model.pushUp(ListLinkDelta.drop(this.lower));
}
}
}
final class ListDownlinkRelayTake extends DownlinkRelay<ListDownlinkModel, ListDownlinkView<?>> {
final EventMessage message;
final int upper;
ListDownlinkRelayTake(ListDownlinkModel model, EventMessage message, int upper) {
super(model, 4);
this.message = message;
this.upper = upper;
}
ListDownlinkRelayTake(ListDownlinkModel model, Stage stage, int upper) {
super(model, 1, 3, stage);
this.message = null;
this.upper = upper;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
if (this.model.isStateful()) {
this.model.state.take(this.upper);
}
}
}
@Override
protected boolean runPhase(ListDownlinkView<?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.downlinkWillReceive(this.message);
}
return view.dispatchWillReceive(this.message.body(), preemptive);
} else if (phase == 1) {
if (preemptive) {
view.downlinkWillTake(this.upper);
}
return view.dispatchWillTake(this.upper, preemptive);
} else if (phase == 2) {
if (preemptive) {
view.downlinkDidTake(this.upper);
}
return view.dispatchDidTake(this.upper, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.downlinkDidReceive(this.message);
}
return view.dispatchDidReceive(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
if (this.message != null) {
this.model.cueDown();
} else {
this.model.pushUp(ListLinkDelta.drop(this.upper));
}
}
}
final class ListDownlinkRelayClear extends DownlinkRelay<ListDownlinkModel, ListDownlinkView<?>> {
final EventMessage message;
ListDownlinkRelayClear(ListDownlinkModel model, EventMessage message) {
super(model, 0, 3, null);
this.message = message;
}
ListDownlinkRelayClear(ListDownlinkModel model, Stage stage) {
super(model, 3, 4, stage);
this.message = null;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
if (this.model.isStateful()) {
this.model.state.clear();
}
}
}
@Override
protected boolean runPhase(ListDownlinkView<?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.downlinkWillReceive(this.message);
}
return view.dispatchWillReceive(this.message.body(), preemptive);
} else if (phase == 1) {
if (preemptive) {
view.downlinkWillClear();
}
return view.dispatchWillClear(preemptive);
} else if (phase == 2) {
if (preemptive) {
view.downlinkDidClear();
}
return view.dispatchDidClear(preemptive);
} else if (phase == 3) {
if (preemptive) {
view.downlinkDidReceive(this.message);
}
return view.dispatchDidReceive(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
if (this.message != null) {
this.model.cueDown();
} else {
this.model.pushUp(ListLinkDelta.clear());
}
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/downlink/ListDownlinkView.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.runtime.downlink;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import swim.api.DownlinkException;
import swim.api.Link;
import swim.api.SwimContext;
import swim.api.downlink.ListDownlink;
import swim.api.function.DidClose;
import swim.api.function.DidConnect;
import swim.api.function.DidDisconnect;
import swim.api.function.DidFail;
import swim.api.warp.function.DidLink;
import swim.api.warp.function.DidReceive;
import swim.api.warp.function.DidSync;
import swim.api.warp.function.DidUnlink;
import swim.api.warp.function.WillCommand;
import swim.api.warp.function.WillLink;
import swim.api.warp.function.WillReceive;
import swim.api.warp.function.WillSync;
import swim.api.warp.function.WillUnlink;
import swim.concurrent.Conts;
import swim.concurrent.Stage;
import swim.observable.function.DidClear;
import swim.observable.function.DidDrop;
import swim.observable.function.DidMoveIndex;
import swim.observable.function.DidRemoveIndex;
import swim.observable.function.DidTake;
import swim.observable.function.DidUpdateIndex;
import swim.observable.function.WillClear;
import swim.observable.function.WillDrop;
import swim.observable.function.WillMoveIndex;
import swim.observable.function.WillRemoveIndex;
import swim.observable.function.WillTake;
import swim.observable.function.WillUpdateIndex;
import swim.runtime.CellContext;
import swim.runtime.LinkBinding;
import swim.runtime.warp.WarpDownlinkView;
import swim.structure.Form;
import swim.structure.Value;
import swim.structure.collections.ValueIterator;
import swim.structure.collections.ValueList;
import swim.structure.collections.ValueListIterator;
import swim.uri.Uri;
public class ListDownlinkView<V> extends WarpDownlinkView implements ListDownlink<V> {
protected final Form<V> valueForm;
protected ListDownlinkModel model;
public ListDownlinkView(CellContext cellContext, Stage stage, Uri meshUri,
Uri hostUri, Uri nodeUri, Uri laneUri, float prio, float rate, Value body,
int flags, Form<V> valueForm, Object observers) {
super(cellContext, stage, meshUri, hostUri, nodeUri, laneUri, prio, rate,
body, flags, observers);
this.valueForm = valueForm;
}
public ListDownlinkView(CellContext cellContext, Stage stage, Uri meshUri,
Uri hostUri, Uri nodeUri, Uri laneUri, float prio, float rate,
Value body, Form<V> valueForm) {
this(cellContext, stage, meshUri, hostUri, nodeUri, laneUri, prio, rate,
body, KEEP_LINKED | KEEP_SYNCED | STATEFUL, valueForm, null);
}
@Override
public ListDownlinkModel downlinkModel() {
return this.model;
}
@Override
public ListDownlinkView<V> hostUri(Uri hostUri) {
return new ListDownlinkView<V>(this.cellContext, this.stage, this.meshUri,
hostUri, this.nodeUri, this.laneUri, this.prio,
this.rate, this.body, this.flags, this.valueForm,
this.observers);
}
@Override
public ListDownlinkView<V> hostUri(String hostUri) {
return hostUri(Uri.parse(hostUri));
}
@Override
public ListDownlinkView<V> nodeUri(Uri nodeUri) {
return new ListDownlinkView<V>(this.cellContext, this.stage, this.meshUri,
this.hostUri, nodeUri, this.laneUri, this.prio,
this.rate, this.body, this.flags, this.valueForm,
this.observers);
}
@Override
public ListDownlinkView<V> nodeUri(String nodeUri) {
return nodeUri(Uri.parse(nodeUri));
}
@Override
public ListDownlinkView<V> laneUri(Uri laneUri) {
return new ListDownlinkView<V>(this.cellContext, this.stage, this.meshUri,
this.hostUri, this.nodeUri, laneUri, this.prio,
this.rate, this.body, this.flags, this.valueForm,
this.observers);
}
@Override
public ListDownlinkView<V> laneUri(String laneUri) {
return laneUri(Uri.parse(laneUri));
}
@Override
public ListDownlinkView<V> prio(float prio) {
return new ListDownlinkView<V>(this.cellContext, this.stage, this.meshUri,
this.hostUri, this.nodeUri, this.laneUri, prio,
this.rate, this.body, this.flags, this.valueForm,
this.observers);
}
@Override
public ListDownlinkView<V> rate(float rate) {
return new ListDownlinkView<V>(this.cellContext, this.stage, this.meshUri,
this.hostUri, this.nodeUri, this.laneUri, this.prio,
rate, this.body, this.flags, this.valueForm,
this.observers);
}
@Override
public ListDownlinkView<V> body(Value body) {
return new ListDownlinkView<V>(this.cellContext, this.stage, this.meshUri,
this.hostUri, this.nodeUri, this.laneUri, this.prio,
this.rate, body, this.flags, this.valueForm,
this.observers);
}
@Override
public ListDownlinkView<V> keepLinked(boolean keepLinked) {
if (keepLinked) {
this.flags |= KEEP_LINKED;
} else {
this.flags &= ~KEEP_LINKED;
}
return this;
}
@Override
public ListDownlinkView<V> keepSynced(boolean keepSynced) {
if (keepSynced) {
this.flags |= KEEP_SYNCED;
} else {
this.flags &= ~KEEP_SYNCED;
}
return this;
}
@Override
public final boolean isStateful() {
return (this.flags & STATEFUL) != 0;
}
@Override
public ListDownlinkView<V> isStateful(boolean isStateful) {
if (isStateful) {
this.flags |= STATEFUL;
} else {
this.flags &= ~STATEFUL;
}
final ListDownlinkModel model = this.model;
if (model != null) {
model.isStateful(isStateful);
}
return this;
}
void didSetStateful(boolean isStateful) {
if (isStateful) {
this.flags |= STATEFUL;
} else {
this.flags &= ~STATEFUL;
}
}
@Override
public final Form<V> valueForm() {
return this.valueForm;
}
@Override
public <V2> ListDownlinkView<V2> valueForm(Form<V2> valueForm) {
return new ListDownlinkView<V2>(this.cellContext, this.stage, this.meshUri,
this.hostUri, this.nodeUri, this.laneUri, this.prio,
this.rate, this.body, this.flags, valueForm,
typesafeObservers(this.observers));
}
@Override
public <V2> ListDownlinkView<V2> valueClass(Class<V2> valueClass) {
return valueForm(Form.<V2>forClass(valueClass));
}
protected Object typesafeObservers(Object observers) {
// TODO: filter out WillUpdateIndex, DidUpdateIndex,
// WillMoveIndex, DidMoveIndex, WillRemoveIndex, DidRemoveIndex,
// WillDrop, DidDrop, WillTake, DidTake, WillClear, DidClear
return observers;
}
@SuppressWarnings("unchecked")
@Override
public ListDownlinkView<V> observe(Object observer) {
return (ListDownlinkView<V>) super.observe(observer);
}
@SuppressWarnings("unchecked")
@Override
public ListDownlinkView<V> unobserve(Object observer) {
return (ListDownlinkView<V>) super.unobserve(observer);
}
@Override
public ListDownlink<V> willMove(WillMoveIndex<V> willMove) {
return observe(willMove);
}
@Override
public ListDownlink<V> didMove(DidMoveIndex<V> didMove) {
return observe(didMove);
}
@Override
public ListDownlinkView<V> willUpdate(WillUpdateIndex<V> willUpdate) {
return observe(willUpdate);
}
@Override
public ListDownlinkView<V> didUpdate(DidUpdateIndex<V> didUpdate) {
return observe(didUpdate);
}
@Override
public ListDownlinkView<V> willRemove(WillRemoveIndex willRemove) {
return observe(willRemove);
}
@Override
public ListDownlinkView<V> didRemove(DidRemoveIndex<V> didRemove) {
return observe(didRemove);
}
@Override
public ListDownlinkView<V> willDrop(WillDrop willDrop) {
return observe(willDrop);
}
@Override
public ListDownlinkView<V> didDrop(DidDrop didDrop) {
return observe(didDrop);
}
@Override
public ListDownlinkView<V> willTake(WillTake willTake) {
return observe(willTake);
}
@Override
public ListDownlinkView<V> didTake(DidTake didTake) {
return observe(didTake);
}
@Override
public ListDownlinkView<V> willClear(WillClear willClear) {
return observe(willClear);
}
@Override
public ListDownlinkView<V> didClear(DidClear didClear) {
return observe(didClear);
}
@Override
public ListDownlinkView<V> willReceive(WillReceive willReceive) {
return observe(willReceive);
}
@Override
public ListDownlinkView<V> didReceive(DidReceive didReceive) {
return observe(didReceive);
}
@Override
public ListDownlinkView<V> willCommand(WillCommand willCommand) {
return observe(willCommand);
}
@Override
public ListDownlinkView<V> willLink(WillLink willLink) {
return observe(willLink);
}
@Override
public ListDownlinkView<V> didLink(DidLink didLink) {
return observe(didLink);
}
@Override
public ListDownlinkView<V> willSync(WillSync willSync) {
return observe(willSync);
}
@Override
public ListDownlinkView<V> didSync(DidSync didSync) {
return observe(didSync);
}
@Override
public ListDownlinkView<V> willUnlink(WillUnlink willUnlink) {
return observe(willUnlink);
}
@Override
public ListDownlinkView<V> didUnlink(DidUnlink didUnlink) {
return observe(didUnlink);
}
@Override
public ListDownlinkView<V> didConnect(DidConnect didConnect) {
return observe(didConnect);
}
@Override
public ListDownlinkView<V> didDisconnect(DidDisconnect didDisconnect) {
return observe(didDisconnect);
}
@Override
public ListDownlinkView<V> didClose(DidClose didClose) {
return observe(didClose);
}
@Override
public ListDownlinkView<V> didFail(DidFail didFail) {
return observe(didFail);
}
@SuppressWarnings("unchecked")
public Map.Entry<Boolean, V> dispatchWillUpdate(int index, V newValue, boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillUpdateIndex<?>) {
if (((WillUpdateIndex<?>) observers).isPreemptive() == preemptive) {
try {
newValue = ((WillUpdateIndex<V>) observers).willUpdate(index, newValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillUpdateIndex<?>) {
if (((WillUpdateIndex<?>) observer).isPreemptive() == preemptive) {
try {
newValue = ((WillUpdateIndex<V>) observer).willUpdate(index, newValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return new AbstractMap.SimpleImmutableEntry<Boolean, V>(complete, newValue);
} finally {
SwimContext.setLink(oldLink);
}
}
@SuppressWarnings("unchecked")
public boolean dispatchDidUpdate(int index, V newValue, V oldValue, boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidUpdateIndex<?>) {
if (((DidUpdateIndex<?>) observers).isPreemptive() == preemptive) {
try {
((DidUpdateIndex<V>) observers).didUpdate(index, newValue, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidUpdateIndex<?>) {
if (((DidUpdateIndex<?>) observer).isPreemptive() == preemptive) {
try {
((DidUpdateIndex<V>) observer).didUpdate(index, newValue, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
@SuppressWarnings("unchecked")
public boolean dispatchWillMove(int fromIndex, int toIndex, V value, boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillMoveIndex<?>) {
if (((WillMoveIndex<?>) observers).isPreemptive() == preemptive) {
try {
((WillMoveIndex<V>) observers).willMove(fromIndex, toIndex, value);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillMoveIndex<?>) {
if (((WillMoveIndex<?>) observer).isPreemptive() == preemptive) {
try {
((WillMoveIndex<V>) observer).willMove(fromIndex, toIndex, value);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
@SuppressWarnings("unchecked")
public boolean dispatchDidMove(int fromIndex, int toIndex, V value, boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidMoveIndex<?>) {
if (((DidMoveIndex<?>) observers).isPreemptive() == preemptive) {
try {
((DidMoveIndex<V>) observers).didMove(fromIndex, toIndex, value);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidMoveIndex<?>) {
if (((DidMoveIndex<?>) observer).isPreemptive() == preemptive) {
try {
((DidMoveIndex<V>) observer).didMove(fromIndex, toIndex, value);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
public boolean dispatchWillRemove(int index, boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillRemoveIndex) {
if (((WillRemoveIndex) observers).isPreemptive() == preemptive) {
try {
((WillRemoveIndex) observers).willRemove(index);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillRemoveIndex) {
if (((WillRemoveIndex) observer).isPreemptive() == preemptive) {
try {
((WillRemoveIndex) observer).willRemove(index);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
@SuppressWarnings("unchecked")
public boolean dispatchDidRemove(int index, V oldValue, boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidRemoveIndex<?>) {
if (((DidRemoveIndex<?>) observers).isPreemptive() == preemptive) {
try {
((DidRemoveIndex<V>) observers).didRemove(index, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidRemoveIndex<?>) {
if (((DidRemoveIndex<?>) observer).isPreemptive() == preemptive) {
try {
((DidRemoveIndex<V>) observer).didRemove(index, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
public boolean dispatchWillDrop(int lower, boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillDrop) {
if (((WillDrop) observers).isPreemptive() == preemptive) {
try {
((WillDrop) observers).willDrop(lower);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillDrop) {
if (((WillDrop) observer).isPreemptive() == preemptive) {
try {
((WillDrop) observer).willDrop(lower);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
public boolean dispatchDidDrop(int lower, boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidDrop) {
if (((DidDrop) observers).isPreemptive() == preemptive) {
try {
((DidDrop) observers).didDrop(lower);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidDrop) {
if (((DidDrop) observer).isPreemptive() == preemptive) {
try {
((DidDrop) observer).didDrop(lower);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
public boolean dispatchWillTake(int upper, boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillTake) {
if (((WillTake) observers).isPreemptive() == preemptive) {
try {
((WillTake) observers).willTake(upper);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillTake) {
if (((WillTake) observer).isPreemptive() == preemptive) {
try {
((WillTake) observer).willTake(upper);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
public boolean dispatchDidTake(int upper, boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidTake) {
if (((DidTake) observers).isPreemptive() == preemptive) {
try {
((DidTake) observers).didTake(upper);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidTake) {
if (((DidTake) observer).isPreemptive() == preemptive) {
try {
((DidTake) observer).didTake(upper);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
public boolean dispatchWillClear(boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillClear) {
if (((WillClear) observers).isPreemptive() == preemptive) {
try {
((WillClear) observers).willClear();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillClear) {
if (((WillClear) observer).isPreemptive() == preemptive) {
try {
((WillClear) observer).willClear();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
public boolean dispatchDidClear(boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidClear) {
if (((DidClear) observers).isPreemptive() == preemptive) {
try {
((DidClear) observers).didClear();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidClear) {
if (((DidClear) observer).isPreemptive() == preemptive) {
try {
((DidClear) observer).didClear();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
public Value downlinkWillInsertValue(int index, Value newValue) {
return newValue;
}
public void downlinkDidInsertValue(int index, Value newValue) {
}
public V downlinkWillInsert(int index, V newValue) {
return newValue;
}
public void downlinkDidInsert(int index, V newValue) {
}
public Value downlinkWillUpdateValue(int index, Value newValue) {
return newValue;
}
public void downlinkDidUpdateValue(int index, Value newValue, Value oldValue) {
}
public V downlinkWillUpdate(int index, V newValue) {
return newValue;
}
public void downlinkDidUpdate(int index, V newValue, V oldValue) {
}
public void downlinkWillMoveValue(int fromIndex, int toIndex, Value value) {
}
public void downlinkDidMoveValue(int fromIndex, int toIndex, Value value) {
}
public void downlinkWillMove(int fromIndex, int toIndex, V value) {
}
public void downlinkDidMove(int fromIndex, int toIndex, V value) {
}
public void downlinkWillRemoveValue(int index) {
}
public void downlinkDidRemoveValue(int index, Value oldValue) {
}
public void downlinkWillRemove(int index) {
}
public void downlinkDidRemove(int index, V oldValue) {
}
public void downlinkWillDrop(int lower) {
}
public void downlinkDidDrop(int lower) {
}
public void downlinkWillTake(int upper) {
}
public void downlinkDidTake(int upper) {
}
public void downlinkWillClear() {
}
public void downlinkDidClear() {
}
@Override
public ListDownlinkModel createDownlinkModel() {
return new ListDownlinkModel(this.meshUri, this.hostUri, this.nodeUri,
this.laneUri, this.prio, this.rate, this.body);
}
@Override
public ListDownlinkView<V> open() {
if (this.model == null) {
final LinkBinding linkBinding = this.cellContext.bindDownlink(this);
if (linkBinding instanceof ListDownlinkModel) {
this.model = (ListDownlinkModel) linkBinding;
this.model.addDownlink(this);
} else {
throw new DownlinkException("downlink type mismatch");
}
}
return this;
}
@Override
public boolean isEmpty() {
return this.model.isEmpty();
}
@Override
public boolean contains(Object o) {
return this.model.contains(o);
}
@Override
public int size() {
return this.model.size();
}
@SuppressWarnings("unchecked")
@Override
public V get(int index) {
return get(index, null);
}
@Override
public V set(int index, V element) {
return this.model.set(this, index, element);
}
@Override
public void add(int index, V element) {
this.model.add(this, index, element);
}
@SuppressWarnings("unchecked")
@Override
public V remove(int index) {
return this.model.remove(this, index);
}
@Override
public int indexOf(Object o) {
return this.model.indexOf(o);
}
@Override
public int lastIndexOf(Object o) {
return this.model.lastIndexOf(o);
}
@SuppressWarnings("unchecked")
@Override
public ListIterator<V> listIterator() {
if (this.valueForm != Form.forValue()) {
return new ValueListIterator<V>(this.model.listIterator(), this.valueForm);
} else {
return (ListIterator<V>) this.model.listIterator();
}
}
@SuppressWarnings("unchecked")
@Override
public ListIterator<V> listIterator(int index) {
if (this.valueForm != Form.forValue()) {
return new ValueListIterator<V>(this.model.listIterator(index), this.valueForm);
} else {
return (ListIterator<V>) this.model.listIterator(index);
}
}
@Override
public List<V> subList(int fromIndex, int toIndex) {
return new ValueList<V>(this.model.subList(fromIndex, toIndex), this.valueForm);
}
@Override
public void drop(int lower) {
this.model.drop(this, lower);
}
@Override
public void take(int upper) {
this.model.take(this, upper);
}
@Override
public void clear() {
this.model.clear(this);
}
@SuppressWarnings("unchecked")
@Override
public Iterator<V> iterator() {
if (this.valueForm != Form.forValue()) {
return new ValueIterator<V>(this.model.iterator(), this.valueForm);
} else {
return (Iterator<V>) this.model.iterator();
}
}
@Override
public Object[] toArray() {
return this.model.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return this.model.toArray(a);
}
@Override
public boolean add(V v) {
return this.model.add(this, size(), v);
}
@Override
public boolean remove(Object o) {
final int index = indexOf(o);
if (index != -1) {
final V oldObject = this.model.remove(this, index);
return oldObject != null && oldObject != this.valueForm.unit(); // TODO?
}
return false;
}
@Override
public boolean containsAll(Collection<?> elements) {
for (Object element: elements) {
if (!contains(element)) {
return false;
}
}
return true;
}
@Override
public boolean addAll(Collection<? extends V> elements) {
boolean added = false;
for (V element: elements) {
added = added || add(element);
}
return added;
}
@Override
public boolean addAll(int index, Collection<? extends V> elements) {
for (V element: elements) {
add(index, element);
}
return elements.isEmpty();
}
@Override
public boolean removeAll(Collection<?> elements) {
boolean removed = false;
for (Object element: elements) {
removed = removed || remove(element);
}
return removed;
}
@Override
public boolean retainAll(Collection<?> elements) {
boolean modified = false;
for (Object element: elements) {
if (!elements.contains(element)) {
modified = modified || remove(element);
}
}
return modified;
}
@Override
public V get(int index, Object key) {
final Value value = this.model.get(index, key);
final V object = this.valueForm.cast(value);
if (object != null) {
return object;
} else {
return this.valueForm.unit();
}
}
@SuppressWarnings("unchecked")
@Override
public Map.Entry<Object, V> getEntry(int index) {
if (this.valueForm != Form.forValue()) {
return new ListDownlinkViewEntry<V>(this.model.getEntry(index), this.valueForm);
} else {
return (Map.Entry<Object, V>) this.model.getEntry(index);
}
}
@SuppressWarnings("unchecked")
@Override
public Map.Entry<Object, V> getEntry(int index, Object key) {
if (this.valueForm != Form.forValue()) {
return new ListDownlinkViewEntry<V>(this.model.getEntry(index, key), this.valueForm);
} else {
return (Map.Entry<Object, V>) this.model.getEntry(index, key);
}
}
@Override
public V set(int index, V element, Object key) {
return this.model.set(this, index, element, key);
}
@Override
public boolean add(V element, Object key) {
return this.model.add(this, size(), element, key);
}
@Override
public void add(int index, V element, Object key) {
this.model.add(this, index, element, key);
}
@Override
public V remove(int index, Object key) {
return this.model.remove(this, index, key);
}
@Override
public void move(int fromIndex, int toIndex) {
this.model.move(this, fromIndex, toIndex, null);
}
@Override
public void move(int fromIndex, int toIndex, Object key) {
this.model.move(this, fromIndex, toIndex, key);
}
@Override
public ListIterator<Object> keyIterator() {
return this.model.keyIterator();
}
@Override
public ListIterator<Map.Entry<Object, V>> entryIterator() {
return new ListDownlinkViewEntryIterator<V>(this.model.entryIterator(), this.valueForm);
}
protected static final int STATEFUL = 1 << 2;
}
final class ListDownlinkViewEntry<V> implements Map.Entry<Object, V> {
final Map.Entry<Object, Value> entry;
final Form<V> valueForm;
ListDownlinkViewEntry(Map.Entry<Object, Value> entry, Form<V> valueForm) {
this.entry = entry;
this.valueForm = valueForm;
}
@Override
public Object getKey() {
return this.entry.getKey();
}
@Override
public V getValue() {
return this.valueForm.cast(this.entry.getValue());
}
@Override
public V setValue(V value) {
throw new UnsupportedOperationException();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof Map.Entry<?, ?>) {
final Map.Entry<?, ?> that = (Map.Entry<?, ?>) other;
final Object key = getKey();
if (key == null ? that.getKey() != null : !key.equals(that.getKey())) {
return false;
}
final V value = getValue();
if (value == null ? that.getValue() != null : !value.equals(that.getValue())) {
return false;
}
return true;
}
return false;
}
@Override
public int hashCode() {
final Object key = getKey();
final V value = getValue();
return (key == null ? 0 : key.hashCode())
^ (value == null ? 0 : value.hashCode());
}
@Override
public String toString() {
return new StringBuilder().append(getKey()).append('=').append(getValue()).toString();
}
}
final class ListDownlinkViewEntryIterator<V> implements ListIterator<Map.Entry<Object, V>> {
private final ListIterator<Map.Entry<Object, Value>> iterator;
private final Form<V> valueForm;
ListDownlinkViewEntryIterator(ListIterator<Map.Entry<Object, Value>> iterator, Form<V> valueForm) {
this.iterator = iterator;
this.valueForm = valueForm;
}
@Override
public boolean hasNext() {
return this.iterator.hasNext();
}
@Override
public int nextIndex() {
return this.iterator.nextIndex();
}
@Override
public Map.Entry<Object, V> next() {
return new ListDownlinkViewEntry<V>(this.iterator.next(), this.valueForm);
}
@Override
public boolean hasPrevious() {
return this.iterator.hasPrevious();
}
@Override
public int previousIndex() {
return this.iterator.previousIndex();
}
@Override
public Map.Entry<Object, V> previous() {
return new ListDownlinkViewEntry<V>(this.iterator.previous(), this.valueForm);
}
@Override
public void remove() {
this.iterator.remove();
}
@Override
public void set(Map.Entry<Object, V> entry) {
throw new UnsupportedOperationException();
}
@Override
public void add(Map.Entry<Object, V> entry) {
throw new UnsupportedOperationException();
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/downlink/MapDownlinkModel.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.runtime.downlink;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import swim.collections.BTreeMap;
import swim.concurrent.Stage;
import swim.runtime.DownlinkRelay;
import swim.runtime.DownlinkView;
import swim.runtime.warp.PartialDownlinkModem;
import swim.structure.Attr;
import swim.structure.Form;
import swim.structure.Record;
import swim.structure.Value;
import swim.uri.Uri;
import swim.util.Cursor;
import swim.util.OrderedMap;
import swim.util.OrderedMapCursor;
import swim.warp.EventMessage;
public class MapDownlinkModel extends PartialDownlinkModem<MapDownlinkView<?, ?>> {
protected int flags;
protected final BTreeMap<Value, Value, Value> state;
public MapDownlinkModel(Uri meshUri, Uri hostUri, Uri nodeUri, Uri laneUri,
float prio, float rate, Value body) {
super(meshUri, hostUri, nodeUri, laneUri, prio, rate, body);
this.flags = 0;
this.state = BTreeMap.empty();
}
public final boolean isStateful() {
return (this.flags & STATEFUL) != 0;
}
public MapDownlinkModel isStateful(boolean isStateful) {
if (isStateful) {
this.flags |= STATEFUL;
} else {
this.flags &= ~STATEFUL;
}
final Object views = this.views;
if (views instanceof DownlinkView) {
((MapDownlinkView<?, ?>) views).didSetStateful(isStateful);
} else if (views instanceof DownlinkView[]) {
final DownlinkView[] viewArray = (DownlinkView[]) views;
for (int i = 0, n = viewArray.length; i < n; i += 1) {
((MapDownlinkView<?, ?>) viewArray[i]).didSetStateful(isStateful);
}
}
return this;
}
@Override
protected void pushDownEvent(EventMessage message) {
onEvent(message);
final Value payload = message.body();
final String tag = payload.tag();
if ("update".equals(tag)) {
final Value header = payload.header("update");
final Value key = header.get("key");
final Value value = payload.body();
new MapDownlinkRelayUpdate(this, message, key, value).run();
} else if ("remove".equals(tag)) {
final Value header = payload.header("remove");
final Value key = header.get("key");
new MapDownlinkRelayRemove(this, message, key).run();
} else if ("drop".equals(tag)) {
final Value header = payload.header("drop");
final int lower = header.intValue(0);
new MapDownlinkRelayDrop(this, message, lower).run();
} else if ("take".equals(tag)) {
final Value header = payload.header("take");
final int upper = header.intValue(0);
new MapDownlinkRelayTake(this, message, upper).run();
} else if ("clear".equals(tag)) {
new MapDownlinkRelayClear(this, message).run();
}
}
@Override
protected Value nextUpKey(Value key) {
final Value value = this.state.get(key);
if (value != null) {
return Attr.of("update", Record.create(1).slot("key", key)).concat(value);
} else {
return null;
}
}
@Override
protected void didAddDownlink(MapDownlinkView<?, ?> view) {
if (this.views instanceof DownlinkView) {
isStateful(((MapDownlinkView<?, ?>) view).isStateful());
}
}
public boolean isEmpty() {
return this.state.isEmpty();
}
public int size() {
return this.state.size();
}
public boolean containsKey(Object key) {
if (key != null) {
return this.state.containsKey(key);
} else {
return false;
}
}
public boolean containsValue(Object value) {
if (value != null) {
return this.state.containsValue(value);
} else {
return false;
}
}
public int indexOf(Object key) {
return this.state.indexOf(key);
}
public Value get(Object key) {
if (key != null) {
final Value value = this.state.get(key);
if (value != null) {
return value;
}
}
return Value.absent();
}
public Map.Entry<Value, Value> getEntry(Object key) {
return this.state.getEntry(key);
}
public Map.Entry<Value, Value> getIndex(int index) {
return this.state.getIndex(index);
}
public Map.Entry<Value, Value> firstEntry() {
return this.state.firstEntry();
}
public Value firstKey() {
return this.state.firstKey();
}
public Value firstValue() {
return this.state.firstValue();
}
public Map.Entry<Value, Value> lastEntry() {
return this.state.lastEntry();
}
public Value lastKey() {
return this.state.lastKey();
}
public Value lastValue() {
return this.state.lastValue();
}
public Map.Entry<Value, Value> nextEntry(Value key) {
return this.state.nextEntry(key);
}
public Value nextKey(Value key) {
return this.state.nextKey(key);
}
public Value nextValue(Value key) {
return this.state.nextValue(key);
}
public Map.Entry<Value, Value> previousEntry(Value key) {
return this.state.previousEntry(key);
}
public Value previousKey(Value key) {
return this.state.previousKey(key);
}
public Value previousValue(Value key) {
return this.state.previousValue(key);
}
@SuppressWarnings("unchecked")
public <K, V> V put(MapDownlinkView<K, V> view, K keyObject, V newObject) {
final Form<K> keyForm = view.keyForm;
final Form<V> valueForm = view.valueForm;
final Value key = keyForm.mold(keyObject).toValue();
final Value newValue = valueForm.mold(newObject).toValue();
final MapDownlinkRelayUpdate relay = new MapDownlinkRelayUpdate(this, view.stage(), key, newValue);
relay.keyForm = (Form<Object>) keyForm;
relay.valueForm = (Form<Object>) valueForm;
relay.keyObject = keyObject;
relay.oldObject = newObject;
relay.newObject = newObject;
relay.run();
if (relay.isDone() && relay.valueForm == valueForm) {
return (V) relay.oldObject;
} else {
return null;
}
}
@SuppressWarnings("unchecked")
public <K, V> V remove(MapDownlinkView<K, V> view, K keyObject) {
final Form<K> keyForm = view.keyForm;
final Form<V> valueForm = view.valueForm;
final Value key = keyForm.mold(keyObject).toValue();
final MapDownlinkRelayRemove relay = new MapDownlinkRelayRemove(this, view.stage(), key);
relay.keyForm = (Form<Object>) keyForm;
relay.valueForm = (Form<Object>) valueForm;
relay.keyObject = keyObject;
relay.run();
if (relay.isDone()) {
if (relay.valueForm != valueForm && valueForm != null) {
relay.oldObject = valueForm.cast(relay.oldValue);
if (relay.oldObject == null) {
relay.oldObject = valueForm.unit();
}
}
return (V) relay.oldObject;
} else {
return null;
}
}
public void drop(MapDownlinkView<?, ?> view, int lower) {
if (lower > 0) {
pushUp(Record.create(1).attr("drop", lower)); // TODO: drop top key
}
//final MapDownlinkRelayDrop relay = new MapDownlinkRelayDrop(this, view.stage(), lower);
//relay.run();
}
public void take(MapDownlinkView<?, ?> view, int upper) {
if (upper > 0) {
pushUp(Record.create(1).attr("take", upper)); // TODO: take to key
}
//final MapDownlinkRelayTake relay = new MapDownlinkRelayTake(this, view.stage(), upper);
//relay.run();
}
public void clear(MapDownlinkView<?, ?> view) {
final MapDownlinkRelayClear relay = new MapDownlinkRelayClear(this, view.stage());
relay.run();
}
public OrderedMap<Value, Value> headMap(Value toKey) {
return this.state.headMap(toKey);
}
public OrderedMap<Value, Value> tailMap(Value fromKey) {
return this.state.tailMap(fromKey);
}
public OrderedMap<Value, Value> subMap(Value fromKey, Value toKey) {
return this.state.subMap(fromKey, toKey);
}
public Set<Map.Entry<Value, Value>> entrySet() {
return this.state.entrySet();
}
public Set<Value> keySet() {
return this.state.keySet();
}
public Collection<Value> values() {
return this.state.values();
}
public OrderedMapCursor<Value, Value> iterator() {
return this.state.iterator();
}
public Cursor<Value> keyIterator() {
return this.state.keyIterator();
}
public Cursor<Value> valueIterator() {
return this.state.valueIterator();
}
protected static final int STATEFUL = 1 << 0;
}
final class MapDownlinkRelayUpdate extends DownlinkRelay<MapDownlinkModel, MapDownlinkView<?, ?>> {
final EventMessage message;
Form<Object> keyForm;
Form<Object> valueForm;
final Value key;
Object keyObject;
Value oldValue;
Value newValue;
Object oldObject;
Object newObject;
MapDownlinkRelayUpdate(MapDownlinkModel model, EventMessage message, Value key, Value newValue) {
super(model, 4);
this.message = message;
this.key = key;
this.newValue = newValue;
}
MapDownlinkRelayUpdate(MapDownlinkModel model, Stage stage, Value key, Value newValue) {
super(model, 1, 3, stage);
this.message = null;
this.key = key;
this.newValue = newValue;
this.stage = stage;
}
@SuppressWarnings("unchecked")
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
if (this.model.isStateful()) {
this.oldValue = this.model.state.put(this.key, this.newValue);
}
if (this.oldValue == null) {
this.oldValue = Value.absent();
}
}
}
@SuppressWarnings("unchecked")
@Override
protected boolean runPhase(MapDownlinkView<?, ?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.downlinkWillReceive(this.message);
}
return view.dispatchWillReceive(this.message.body(), preemptive);
} else if (phase == 1) {
this.newValue = view.downlinkWillUpdateValue(this.key, this.newValue);
final Form<Object> keyForm = (Form<Object>) view.keyForm;
if (this.keyForm != keyForm && keyForm != null) {
this.keyForm = keyForm;
this.keyObject = keyForm.cast(this.key);
if (this.keyObject == null) {
this.keyObject = keyForm.unit();
}
}
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
if (this.oldValue != null) {
this.oldObject = valueForm.cast(this.oldValue);
}
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
newObject = valueForm.cast(this.newValue);
}
if (preemptive) {
this.newObject = ((MapDownlinkView<Object, Object>) view).downlinkWillUpdate(this.keyObject, this.newObject);
}
final Map.Entry<Boolean, Object> result = ((MapDownlinkView<Object, Object>) view).dispatchWillUpdate(this.keyObject, this.newObject, preemptive);
if (this.newObject != result.getValue()) {
this.oldObject = this.newObject; //FIXME: Is this right?
this.newObject = result.getValue();
this.newValue = valueForm.mold(this.newObject).toValue();
}
return result.getKey();
} else if (phase == 2) {
view.downlinkDidUpdateValue(this.key, this.newValue, this.oldValue);
final Form<Object> keyForm = (Form<Object>) view.keyForm;
if (this.keyForm != keyForm && keyForm != null) {
this.keyForm = keyForm;
this.keyObject = keyForm.cast(this.key);
if (this.keyObject == null) {
this.keyObject = keyForm.unit();
}
}
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.oldObject = valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
this.newObject = valueForm.cast(this.newValue);
if (this.newObject == null) {
this.newObject = valueForm.unit();
}
}
if (preemptive) {
((MapDownlinkView<Object, Object>) view).downlinkDidUpdate(this.keyObject, this.newObject, this.oldObject);
}
return ((MapDownlinkView<Object, Object>) view).dispatchDidUpdate(this.keyObject, this.newObject, this.oldObject, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.downlinkDidReceive(this.message);
}
return view.dispatchDidReceive(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
if (this.message != null) {
this.model.cueDown();
} else {
this.model.cueUpKey(this.key);
}
}
}
final class MapDownlinkRelayRemove extends DownlinkRelay<MapDownlinkModel, MapDownlinkView<?, ?>> {
final EventMessage message;
Form<Object> keyForm;
Form<Object> valueForm;
final Value key;
Object keyObject;
Value oldValue;
Object oldObject;
MapDownlinkRelayRemove(MapDownlinkModel model, EventMessage message, Value key) {
super(model, 4);
this.message = message;
this.key = key;
}
MapDownlinkRelayRemove(MapDownlinkModel model, Stage stage, Value key) {
super(model, 1, 3, stage);
this.message = null;
this.key = key;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
if (this.model.isStateful()) {
this.oldValue = this.model.state.remove(this.key);
}
if (this.oldValue == null) {
this.oldValue = Value.absent();
}
if (this.valueForm != null) {
this.oldObject = this.valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = this.valueForm.unit();
}
}
}
}
@SuppressWarnings("unchecked")
@Override
protected boolean runPhase(MapDownlinkView<?, ?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.downlinkWillReceive(this.message);
}
return view.dispatchWillReceive(this.message.body(), preemptive);
} else if (phase == 1) {
view.downlinkWillRemoveValue(this.key);
final Form<Object> keyForm = (Form<Object>) view.keyForm;
if (this.keyForm != keyForm && keyForm != null) {
this.keyForm = keyForm;
this.keyObject = keyForm.cast(this.key);
if (this.keyObject == null) {
this.keyObject = keyForm.unit();
}
}
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
if (this.oldValue != null) {
this.oldObject = valueForm.cast(this.oldValue);
}
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
}
if (preemptive) {
((MapDownlinkView<Object, Object>) view).downlinkWillRemove(this.keyObject);
}
return ((MapDownlinkView<Object, Object>) view).dispatchWillRemove(this.keyObject, preemptive);
} else if (phase == 2) {
view.downlinkDidRemoveValue(this.key, this.oldValue);
final Form<Object> keyForm = (Form<Object>) view.keyForm;
if (this.keyForm != keyForm && keyForm != null) {
this.keyForm = keyForm;
this.keyObject = keyForm.cast(this.key);
if (this.keyObject == null) {
this.keyObject = keyForm.unit();
}
}
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.oldObject = valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
}
if (preemptive) {
((MapDownlinkView<Object, Object>) view).downlinkDidRemove(this.keyObject, this.oldObject);
}
return ((MapDownlinkView<Object, Object>) view).dispatchDidRemove(this.keyObject, this.oldObject, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.downlinkDidReceive(this.message);
}
return view.dispatchDidReceive(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
if (this.message != null) {
this.model.cueDown();
} else {
final Record header = Record.create(1).slot("key", this.key);
this.model.pushUp(Record.create(1).attr("remove", header));
}
}
}
final class MapDownlinkRelayDrop extends DownlinkRelay<MapDownlinkModel, MapDownlinkView<?, ?>> {
final EventMessage message;
final int lower;
MapDownlinkRelayDrop(MapDownlinkModel model, EventMessage message, int lower) {
super(model, 4);
this.message = message;
this.lower = lower;
}
MapDownlinkRelayDrop(MapDownlinkModel model, Stage stage, int lower) {
super(model, 1, 3, stage);
this.message = null;
this.lower = lower;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
if (this.model.isStateful()) {
this.model.state.drop(this.lower);
}
}
}
@Override
protected boolean runPhase(MapDownlinkView<?, ?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.downlinkWillReceive(this.message);
}
return view.dispatchWillReceive(this.message.body(), preemptive);
} else if (phase == 1) {
if (preemptive) {
view.downlinkWillDrop(this.lower);
}
return view.dispatchWillDrop(this.lower, preemptive);
} else if (phase == 2) {
if (preemptive) {
view.downlinkDidDrop(this.lower);
}
return view.dispatchDidDrop(this.lower, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.downlinkDidReceive(this.message);
}
return view.dispatchDidReceive(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
if (this.message != null) {
this.model.cueDown();
} else {
this.model.pushUp(Record.create(1).attr("drop", this.lower));
}
}
}
final class MapDownlinkRelayTake extends DownlinkRelay<MapDownlinkModel, MapDownlinkView<?, ?>> {
final EventMessage message;
final int upper;
MapDownlinkRelayTake(MapDownlinkModel model, EventMessage message, int upper) {
super(model, 4);
this.message = message;
this.upper = upper;
}
MapDownlinkRelayTake(MapDownlinkModel model, Stage stage, int upper) {
super(model, 1, 3, stage);
this.message = null;
this.upper = upper;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
if (this.model.isStateful()) {
this.model.state.take(this.upper);
}
}
}
@Override
protected boolean runPhase(MapDownlinkView<?, ?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.downlinkWillReceive(this.message);
}
return view.dispatchWillReceive(this.message.body(), preemptive);
} else if (phase == 1) {
if (preemptive) {
view.downlinkWillTake(this.upper);
}
return view.dispatchWillTake(this.upper, preemptive);
} else if (phase == 2) {
if (preemptive) {
view.downlinkDidTake(this.upper);
}
return view.dispatchDidTake(this.upper, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.downlinkDidReceive(this.message);
}
return view.dispatchDidReceive(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
if (this.message != null) {
this.model.cueDown();
} else {
this.model.pushUp(Record.create(1).attr("take", this.upper));
}
}
}
final class MapDownlinkRelayClear extends DownlinkRelay<MapDownlinkModel, MapDownlinkView<?, ?>> {
final EventMessage message;
MapDownlinkRelayClear(MapDownlinkModel model, EventMessage message) {
super(model, 4);
this.message = message;
}
MapDownlinkRelayClear(MapDownlinkModel model, Stage stage) {
super(model, 1, 3, stage);
this.message = null;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
if (this.model.isStateful()) {
this.model.state.clear();
}
}
}
@Override
protected boolean runPhase(MapDownlinkView<?, ?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.downlinkWillReceive(this.message);
}
return view.dispatchWillReceive(this.message.body(), preemptive);
} else if (phase == 1) {
if (preemptive) {
view.downlinkWillClear();
}
return view.dispatchWillClear(preemptive);
} else if (phase == 2) {
if (preemptive) {
view.downlinkDidClear();
}
return view.dispatchDidClear(preemptive);
} else if (phase == 3) {
if (preemptive) {
view.downlinkDidReceive(this.message);
}
return view.dispatchDidReceive(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
if (this.message != null) {
this.model.cueDown();
} else {
this.model.pushUp(Record.create(1).attr("clear"));
}
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/downlink/MapDownlinkView.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.runtime.downlink;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import swim.api.DownlinkException;
import swim.api.Link;
import swim.api.SwimContext;
import swim.api.downlink.MapDownlink;
import swim.api.function.DidClose;
import swim.api.function.DidConnect;
import swim.api.function.DidDisconnect;
import swim.api.function.DidFail;
import swim.api.warp.function.DidLink;
import swim.api.warp.function.DidReceive;
import swim.api.warp.function.DidSync;
import swim.api.warp.function.DidUnlink;
import swim.api.warp.function.WillCommand;
import swim.api.warp.function.WillLink;
import swim.api.warp.function.WillReceive;
import swim.api.warp.function.WillSync;
import swim.api.warp.function.WillUnlink;
import swim.collections.HashTrieMap;
import swim.concurrent.Conts;
import swim.concurrent.Stage;
import swim.observable.function.DidClear;
import swim.observable.function.DidDrop;
import swim.observable.function.DidRemoveKey;
import swim.observable.function.DidTake;
import swim.observable.function.DidUpdateKey;
import swim.observable.function.WillClear;
import swim.observable.function.WillDrop;
import swim.observable.function.WillRemoveKey;
import swim.observable.function.WillTake;
import swim.observable.function.WillUpdateKey;
import swim.runtime.CellContext;
import swim.runtime.LinkBinding;
import swim.runtime.warp.WarpDownlinkView;
import swim.streamlet.Inlet;
import swim.streamlet.KeyEffect;
import swim.streamlet.KeyOutlet;
import swim.streamlet.MapInlet;
import swim.streamlet.MapOutlet;
import swim.streamlet.Outlet;
import swim.structure.Form;
import swim.structure.Value;
import swim.structure.collections.ValueCollection;
import swim.structure.collections.ValueCursor;
import swim.structure.collections.ValueEntry;
import swim.structure.collections.ValueMapEntrySet;
import swim.structure.collections.ValueOrderedMap;
import swim.structure.collections.ValueOrderedMapCursor;
import swim.structure.collections.ValueSet;
import swim.uri.Uri;
import swim.util.Cursor;
import swim.util.OrderedMap;
import swim.util.OrderedMapCursor;
public class MapDownlinkView<K, V> extends WarpDownlinkView implements MapDownlink<K, V> {
protected final Form<K> keyForm;
protected final Form<V> valueForm;
protected MapDownlinkModel model;
protected MapOutlet<K, V, ? extends Map<K, V>> input;
protected HashTrieMap<K, KeyEffect> effects;
protected HashTrieMap<K, KeyOutlet<K, V>> outlets;
protected Inlet<? super MapDownlink<K, V>>[] outputs; // TODO: unify with observers
protected int version;
public MapDownlinkView(CellContext cellContext, Stage stage, Uri meshUri,
Uri hostUri, Uri nodeUri, Uri laneUri, float prio,
float rate, Value body, int flags, Form<K> keyForm,
Form<V> valueForm, Object observers) {
super(cellContext, stage, meshUri, hostUri, nodeUri, laneUri, prio, rate,
body, flags, observers);
this.keyForm = keyForm;
this.valueForm = valueForm;
this.input = null;
this.effects = HashTrieMap.empty();
this.outlets = HashTrieMap.empty();
this.outputs = null;
this.version = -1;
}
public MapDownlinkView(CellContext cellContext, Stage stage, Uri meshUri,
Uri hostUri, Uri nodeUri, Uri laneUri, float prio,
float rate, Value body, Form<K> keyForm, Form<V> valueForm) {
this(cellContext, stage, meshUri, hostUri, nodeUri, laneUri, prio, rate,
body, KEEP_LINKED | KEEP_SYNCED | STATEFUL, keyForm, valueForm, null);
}
@Override
public MapDownlinkModel downlinkModel() {
return this.model;
}
@Override
public MapDownlinkView<K, V> hostUri(Uri hostUri) {
return new MapDownlinkView<K, V>(this.cellContext, this.stage, this.meshUri,
hostUri, this.nodeUri, this.laneUri,
this.prio, this.rate, this.body, this.flags,
this.keyForm, this.valueForm, this.observers);
}
@Override
public MapDownlinkView<K, V> hostUri(String hostUri) {
return hostUri(Uri.parse(hostUri));
}
@Override
public MapDownlinkView<K, V> nodeUri(Uri nodeUri) {
return new MapDownlinkView<K, V>(this.cellContext, this.stage, this.meshUri,
this.hostUri, nodeUri, this.laneUri,
this.prio, this.rate, this.body, this.flags,
this.keyForm, this.valueForm, this.observers);
}
@Override
public MapDownlinkView<K, V> nodeUri(String nodeUri) {
return nodeUri(Uri.parse(nodeUri));
}
@Override
public MapDownlinkView<K, V> laneUri(Uri laneUri) {
return new MapDownlinkView<K, V>(this.cellContext, this.stage, this.meshUri,
this.hostUri, this.nodeUri, laneUri,
this.prio, this.rate, this.body, this.flags,
this.keyForm, this.valueForm, this.observers);
}
@Override
public MapDownlinkView<K, V> laneUri(String laneUri) {
return laneUri(Uri.parse(laneUri));
}
@Override
public MapDownlinkView<K, V> prio(float prio) {
return new MapDownlinkView<K, V>(this.cellContext, this.stage, this.meshUri,
this.hostUri, this.nodeUri, this.laneUri,
prio, this.rate, this.body, this.flags,
this.keyForm, this.valueForm, this.observers);
}
@Override
public MapDownlinkView<K, V> rate(float rate) {
return new MapDownlinkView<K, V>(this.cellContext, this.stage, this.meshUri,
this.hostUri, this.nodeUri, this.laneUri,
this.prio, rate, this.body, this.flags,
this.keyForm, this.valueForm, this.observers);
}
@Override
public MapDownlinkView<K, V> body(Value body) {
return new MapDownlinkView<K, V>(this.cellContext, this.stage, this.meshUri,
this.hostUri, this.nodeUri, this.laneUri,
this.prio, this.rate, body, this.flags,
this.keyForm, this.valueForm, this.observers);
}
@Override
public MapDownlinkView<K, V> keepLinked(boolean keepLinked) {
if (keepLinked) {
this.flags |= KEEP_LINKED;
} else {
this.flags &= ~KEEP_LINKED;
}
return this;
}
@Override
public MapDownlinkView<K, V> keepSynced(boolean keepSynced) {
if (keepSynced) {
this.flags |= KEEP_SYNCED;
} else {
this.flags &= ~KEEP_SYNCED;
}
return this;
}
@Override
public final boolean isStateful() {
return (this.flags & STATEFUL) != 0;
}
@Override
public MapDownlinkView<K, V> isStateful(boolean isStateful) {
if (isStateful) {
this.flags |= STATEFUL;
} else {
this.flags &= ~STATEFUL;
}
final MapDownlinkModel model = this.model;
if (model != null) {
model.isStateful(isStateful);
}
return this;
}
void didSetStateful(boolean isStateful) {
if (isStateful) {
this.flags |= STATEFUL;
} else {
this.flags &= ~STATEFUL;
}
}
@Override
public final Form<K> keyForm() {
return this.keyForm;
}
@Override
public <K2> MapDownlinkView<K2, V> keyForm(Form<K2> keyForm) {
return new MapDownlinkView<K2, V>(this.cellContext, this.stage, this.meshUri,
this.hostUri, this.nodeUri, this.laneUri,
this.prio, this.rate, this.body, this.flags,
keyForm, this.valueForm, typesafeObservers(this.observers));
}
@Override
public <K2> MapDownlinkView<K2, V> keyClass(Class<K2> keyClass) {
return keyForm(Form.<K2>forClass(keyClass));
}
@Override
public final Form<V> valueForm() {
return this.valueForm;
}
@Override
public <V2> MapDownlinkView<K, V2> valueForm(Form<V2> valueForm) {
return new MapDownlinkView<K, V2>(this.cellContext, this.stage, this.meshUri,
this.hostUri, this.nodeUri, this.laneUri,
this.prio, this.rate, this.body, this.flags,
this.keyForm, valueForm, typesafeObservers(this.observers));
}
@Override
public <V2> MapDownlinkView<K, V2> valueClass(Class<V2> valueClass) {
return valueForm(Form.<V2>forClass(valueClass));
}
protected Object typesafeObservers(Object observers) {
// TODO: filter out WillUpdateKey, DidUpdateKey, WillRemoveKey, DidRemoveKey,
// WillDrop, DidDrop, WillTake, DidTake, WillClear, DidClear
return observers;
}
@SuppressWarnings("unchecked")
@Override
public MapDownlinkView<K, V> observe(Object observer) {
return (MapDownlinkView<K, V>) super.observe(observer);
}
@SuppressWarnings("unchecked")
@Override
public MapDownlinkView<K, V> unobserve(Object observer) {
return (MapDownlinkView<K, V>) super.unobserve(observer);
}
@Override
public MapDownlinkView<K, V> willUpdate(WillUpdateKey<K, V> willUpdate) {
return observe(willUpdate);
}
@Override
public MapDownlinkView<K, V> didUpdate(DidUpdateKey<K, V> didUpdate) {
return observe(didUpdate);
}
@Override
public MapDownlinkView<K, V> willRemove(WillRemoveKey<K> willRemove) {
return observe(willRemove);
}
@Override
public MapDownlinkView<K, V> didRemove(DidRemoveKey<K, V> didRemove) {
return observe(didRemove);
}
@Override
public MapDownlink<K, V> willDrop(WillDrop willDrop) {
return observe(willDrop);
}
@Override
public MapDownlink<K, V> didDrop(DidDrop didDrop) {
return observe(didDrop);
}
@Override
public MapDownlink<K, V> willTake(WillTake willTake) {
return observe(willTake);
}
@Override
public MapDownlink<K, V> didTake(DidTake didTake) {
return observe(didTake);
}
@Override
public MapDownlinkView<K, V> willClear(WillClear willClear) {
return observe(willClear);
}
@Override
public MapDownlinkView<K, V> didClear(DidClear didClear) {
return observe(didClear);
}
@Override
public MapDownlinkView<K, V> willReceive(WillReceive willReceive) {
return observe(willReceive);
}
@Override
public MapDownlinkView<K, V> didReceive(DidReceive didReceive) {
return observe(didReceive);
}
@Override
public MapDownlinkView<K, V> willCommand(WillCommand willCommand) {
return observe(willCommand);
}
@Override
public MapDownlinkView<K, V> willLink(WillLink willLink) {
return observe(willLink);
}
@Override
public MapDownlinkView<K, V> didLink(DidLink didLink) {
return observe(didLink);
}
@Override
public MapDownlinkView<K, V> willSync(WillSync willSync) {
return observe(willSync);
}
@Override
public MapDownlinkView<K, V> didSync(DidSync didSync) {
return observe(didSync);
}
@Override
public MapDownlinkView<K, V> willUnlink(WillUnlink willUnlink) {
return observe(willUnlink);
}
@Override
public MapDownlinkView<K, V> didUnlink(DidUnlink didUnlink) {
return observe(didUnlink);
}
@Override
public MapDownlinkView<K, V> didConnect(DidConnect didConnect) {
return observe(didConnect);
}
@Override
public MapDownlinkView<K, V> didDisconnect(DidDisconnect didDisconnect) {
return observe(didDisconnect);
}
@Override
public MapDownlinkView<K, V> didClose(DidClose didClose) {
return observe(didClose);
}
@Override
public MapDownlinkView<K, V> didFail(DidFail didFail) {
return observe(didFail);
}
public Value downlinkWillUpdateValue(Value key, Value newValue) {
return newValue;
}
public void downlinkDidUpdateValue(Value key, Value newValue, Value oldValue) {
}
public V downlinkWillUpdate(K key, V newValue) {
return newValue;
}
public void downlinkDidUpdate(K key, V newValue, V oldValue) {
invalidateInputKey(key, KeyEffect.UPDATE);
reconcileInput(0); // TODO: debounce and track version
}
public void downlinkWillRemoveValue(Value key) {
}
public void downlinkDidRemoveValue(Value key, Value oldValue) {
}
public void downlinkWillRemove(K key) {
}
public void downlinkDidRemove(K key, V oldValue) {
invalidateInputKey(key, KeyEffect.REMOVE);
reconcileInput(0); // TODO: debounce and track version
}
public void downlinkWillDrop(int lower) {
}
public void downlinkDidDrop(int lower) {
}
public void downlinkWillTake(int upper) {
}
public void downlinkDidTake(int upper) {
}
public void downlinkWillClear() {
}
public void downlinkDidClear() {
}
@SuppressWarnings("unchecked")
public Entry<Boolean, V> dispatchWillUpdate(K key, V newValue, boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillUpdateKey<?, ?>) {
if (((WillUpdateKey<?, ?>) observers).isPreemptive() == preemptive) {
try {
newValue = ((WillUpdateKey<K, V>) observers).willUpdate(key, newValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillUpdateKey<?, ?>) {
if (((WillUpdateKey<?, ?>) observer).isPreemptive() == preemptive) {
try {
newValue = ((WillUpdateKey<K, V>) observer).willUpdate(key, newValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return new AbstractMap.SimpleImmutableEntry<Boolean, V>(complete, newValue);
} finally {
SwimContext.setLink(oldLink);
}
}
@SuppressWarnings("unchecked")
public boolean dispatchDidUpdate(K key, V newValue, V oldValue, boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidUpdateKey<?, ?>) {
if (((DidUpdateKey<?, ?>) observers).isPreemptive() == preemptive) {
try {
((DidUpdateKey<K, V>) observers).didUpdate(key, newValue, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidUpdateKey<?, ?>) {
if (((DidUpdateKey<?, ?>) observer).isPreemptive() == preemptive) {
try {
((DidUpdateKey<K, V>) observer).didUpdate(key, newValue, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
@SuppressWarnings("unchecked")
public boolean dispatchWillRemove(K key, boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillRemoveKey<?>) {
if (((WillRemoveKey<?>) observers).isPreemptive() == preemptive) {
try {
((WillRemoveKey<K>) observers).willRemove(key);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillRemoveKey<?>) {
if (((WillRemoveKey<?>) observer).isPreemptive() == preemptive) {
try {
((WillRemoveKey<K>) observer).willRemove(key);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
@SuppressWarnings("unchecked")
public boolean dispatchDidRemove(K key, V oldValue, boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidRemoveKey<?, ?>) {
if (((DidRemoveKey<?, ?>) observers).isPreemptive() == preemptive) {
try {
((DidRemoveKey<K, V>) observers).didRemove(key, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidRemoveKey<?, ?>) {
if (((DidRemoveKey<?, ?>) observer).isPreemptive() == preemptive) {
try {
((DidRemoveKey<K, V>) observer).didRemove(key, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
public boolean dispatchWillDrop(int lower, boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillDrop) {
if (((WillDrop) observers).isPreemptive() == preemptive) {
try {
((WillDrop) observers).willDrop(lower);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillDrop) {
if (((WillDrop) observer).isPreemptive() == preemptive) {
try {
((WillDrop) observer).willDrop(lower);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
public boolean dispatchDidDrop(int lower, boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidDrop) {
if (((DidDrop) observers).isPreemptive() == preemptive) {
try {
((DidDrop) observers).didDrop(lower);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidDrop) {
if (((DidDrop) observer).isPreemptive() == preemptive) {
try {
((DidDrop) observer).didDrop(lower);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
public boolean dispatchWillTake(int upper, boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillTake) {
if (((WillTake) observers).isPreemptive() == preemptive) {
try {
((WillTake) observers).willTake(upper);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillTake) {
if (((WillTake) observer).isPreemptive() == preemptive) {
try {
((WillTake) observer).willTake(upper);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
public boolean dispatchDidTake(int upper, boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidTake) {
if (((DidTake) observers).isPreemptive() == preemptive) {
try {
((DidTake) observers).didTake(upper);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidTake) {
if (((DidTake) observer).isPreemptive() == preemptive) {
try {
((DidTake) observer).didTake(upper);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
public boolean dispatchWillClear(boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillClear) {
if (((WillClear) observers).isPreemptive() == preemptive) {
try {
((WillClear) observers).willClear();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillClear) {
if (((WillClear) observer).isPreemptive() == preemptive) {
try {
((WillClear) observer).willClear();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
public boolean dispatchDidClear(boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidClear) {
if (((DidClear) observers).isPreemptive() == preemptive) {
try {
((DidClear) observers).didClear();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidClear) {
if (((DidClear) observer).isPreemptive() == preemptive) {
try {
((DidClear) observer).didClear();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
@Override
public MapDownlinkModel createDownlinkModel() {
return new MapDownlinkModel(this.meshUri, this.hostUri, this.nodeUri,
this.laneUri, this.prio, this.rate, this.body);
}
@Override
public MapDownlinkView<K, V> open() {
if (this.model == null) {
final LinkBinding linkBinding = this.cellContext.bindDownlink(this);
if (linkBinding instanceof MapDownlinkModel) {
this.model = (MapDownlinkModel) linkBinding;
this.model.addDownlink(this);
} else {
throw new DownlinkException("downlink type mismatch");
}
}
return this;
}
@Override
public boolean isEmpty() {
return this.model.isEmpty();
}
@Override
public int size() {
return this.model.size();
}
@SuppressWarnings("unchecked")
@Override
public boolean containsKey(Object keyObject) {
final Class<?> keyType = this.keyForm.type();
if (keyType == null || keyType.isInstance(keyObject)) {
final Value key = this.keyForm.mold((K) keyObject).toValue();
return this.model.containsKey(key);
}
return false;
}
@SuppressWarnings("unchecked")
@Override
public boolean containsValue(Object valueObject) {
final Class<?> valueType = this.valueForm.type();
if (valueType == null || valueType.isInstance(valueObject)) {
final Value value = this.valueForm.mold((V) valueObject).toValue();
return this.model.containsValue(value);
}
return false;
}
@SuppressWarnings("unchecked")
@Override
public int indexOf(Object keyObject) {
final Class<?> keyType = this.keyForm.type();
if (keyType == null || keyType.isInstance(keyObject)) {
final Value key = this.keyForm.mold((K) keyObject).toValue();
return this.model.indexOf(key);
}
throw new IllegalArgumentException(keyObject.toString());
}
@SuppressWarnings("unchecked")
@Override
public V get(Object keyObject) {
final Class<?> keyType = this.keyForm.type();
if (keyType == null || keyType.isInstance(keyObject)) {
final Value key = this.keyForm.mold((K) keyObject).toValue();
final Value value = this.model.get(key);
final V valueObject = this.valueForm.cast(value);
if (valueObject != null) {
return valueObject;
}
}
return this.valueForm.unit();
}
@SuppressWarnings("unchecked")
@Override
public Entry<K, V> getEntry(Object keyObject) {
final Class<?> keyType = this.keyForm.type();
if (keyType == null || keyType.isInstance(keyObject)) {
final Value key = this.keyForm.mold((K) keyObject).toValue();
final Entry<Value, Value> entry = this.model.getEntry(key);
if (entry != null) {
return new ValueEntry<K, V>(entry, this.keyForm, this.valueForm);
}
}
return null;
}
@Override
public Entry<K, V> getIndex(int index) {
final Entry<Value, Value> entry = this.model.getIndex(index);
if (entry != null) {
return new ValueEntry<K, V>(entry, this.keyForm, this.valueForm);
}
return null;
}
@Override
public Entry<K, V> firstEntry() {
final Entry<Value, Value> entry = this.model.firstEntry();
if (entry != null) {
return new ValueEntry<K, V>(entry, this.keyForm, this.valueForm);
}
return null;
}
@Override
public K firstKey() {
final Value key = this.model.firstKey();
final K keyObject = this.keyForm.cast(key);
if (keyObject != null) {
return keyObject;
}
return this.keyForm.unit();
}
@Override
public V firstValue() {
final Value value = this.model.firstValue();
final V object = this.valueForm.cast(value);
if (object != null) {
return object;
}
return this.valueForm.unit();
}
@Override
public Entry<K, V> lastEntry() {
final Entry<Value, Value> entry = this.model.lastEntry();
if (entry != null) {
return new ValueEntry<K, V>(entry, this.keyForm, this.valueForm);
}
return null;
}
@Override
public K lastKey() {
final Value key = this.model.lastKey();
final K keyObject = this.keyForm.cast(key);
if (keyObject != null) {
return keyObject;
}
return this.keyForm.unit();
}
@Override
public V lastValue() {
final Value value = this.model.lastValue();
final V object = this.valueForm.cast(value);
if (object != null) {
return object;
}
return this.valueForm.unit();
}
@SuppressWarnings("unchecked")
@Override
public Entry<K, V> nextEntry(Object keyObject) {
final Class<?> keyType = this.keyForm.type();
if (keyType == null || keyType.isInstance(keyObject)) {
final Value key = this.keyForm.mold((K) keyObject).toValue();
final Entry<Value, Value> entry = this.model.nextEntry(key);
if (entry != null) {
return new ValueEntry<K, V>(entry, this.keyForm, this.valueForm);
}
}
return null;
}
@SuppressWarnings("unchecked")
@Override
public K nextKey(Object keyObject) {
final Class<?> keyType = this.keyForm.type();
if (keyType == null || keyType.isInstance(keyObject)) {
final Value key = this.keyForm.mold((K) keyObject).toValue();
final Value nextKey = this.model.nextKey(key);
final K nextKeyObject = this.keyForm.cast(nextKey);
if (nextKeyObject != null) {
return nextKeyObject;
}
return this.keyForm.unit();
}
return null;
}
@SuppressWarnings("unchecked")
@Override
public V nextValue(Object keyObject) {
final Class<?> keyType = this.keyForm.type();
if (keyType == null || keyType.isInstance(keyObject)) {
final Value key = this.keyForm.mold((K) keyObject).toValue();
final Value nextValue = this.model.nextValue(key);
final V nextObject = this.valueForm.cast(nextValue);
if (nextObject != null) {
return nextObject;
}
return this.valueForm.unit();
}
return null;
}
@SuppressWarnings("unchecked")
@Override
public Entry<K, V> previousEntry(Object keyObject) {
final Class<?> keyType = this.keyForm.type();
if (keyType == null || keyType.isInstance(keyObject)) {
final Value key = this.keyForm.mold((K) keyObject).toValue();
final Entry<Value, Value> entry = this.model.previousEntry(key);
if (entry != null) {
return new ValueEntry<K, V>(entry, this.keyForm, this.valueForm);
}
}
return null;
}
@SuppressWarnings("unchecked")
@Override
public K previousKey(Object keyObject) {
final Class<?> keyType = this.keyForm.type();
if (keyType == null || keyType.isInstance(keyObject)) {
final Value key = this.keyForm.mold((K) keyObject).toValue();
final Value previousKey = this.model.previousKey(key);
final K previousKeyObject = this.keyForm.cast(previousKey);
if (previousKeyObject != null) {
return previousKeyObject;
}
return this.keyForm.unit();
}
return null;
}
@SuppressWarnings("unchecked")
@Override
public V previousValue(Object keyObject) {
final Class<?> keyType = this.keyForm.type();
if (keyType == null || keyType.isInstance(keyObject)) {
final Value key = this.keyForm.mold((K) keyObject).toValue();
final Value previousValue = this.model.previousValue(key);
final V previousObject = this.valueForm.cast(previousValue);
if (previousObject != null) {
return previousObject;
}
return this.valueForm.unit();
}
return null;
}
@Override
public V put(K key, V value) {
return this.model.put(this, key, value);
}
@Override
public void putAll(Map<? extends K, ? extends V> map) {
for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
this.model.put(this, entry.getKey(), entry.getValue());
}
}
@SuppressWarnings("unchecked")
@Override
public V remove(Object key) {
return this.model.remove(this, (K) key);
}
@Override
public void drop(int lower) {
this.model.drop(this, lower);
}
@Override
public void take(int upper) {
this.model.take(this, upper);
}
@Override
public void clear() {
this.model.clear(this);
}
@SuppressWarnings("unchecked")
@Override
public OrderedMap<K, V> headMap(K toKeyObject) {
if (this.keyForm != Form.forValue() || this.valueForm != Form.forValue()) {
final Value toKey = this.keyForm.mold(toKeyObject).toValue();
return new ValueOrderedMap<K, V>(this.model.headMap(toKey), this.keyForm, this.valueForm);
} else {
return (OrderedMap<K, V>) (OrderedMap<?, ?>) this.model.headMap((Value) toKeyObject);
}
}
@SuppressWarnings("unchecked")
@Override
public OrderedMap<K, V> tailMap(K fromKeyObject) {
if (this.keyForm != Form.forValue() || this.valueForm != Form.forValue()) {
final Value fromKey = this.keyForm.mold(fromKeyObject).toValue();
return new ValueOrderedMap<K, V>(this.model.tailMap(fromKey), this.keyForm, this.valueForm);
} else {
return (OrderedMap<K, V>) (OrderedMap<?, ?>) this.model.tailMap((Value) fromKeyObject);
}
}
@SuppressWarnings("unchecked")
@Override
public OrderedMap<K, V> subMap(K fromKeyObject, K toKeyObject) {
if (this.keyForm != Form.forValue() || this.valueForm != Form.forValue()) {
final Value fromKey = this.keyForm.mold(fromKeyObject).toValue();
final Value toKey = this.keyForm.mold(toKeyObject).toValue();
return new ValueOrderedMap<K, V>(this.model.subMap(fromKey, toKey), this.keyForm, this.valueForm);
} else {
return (OrderedMap<K, V>) (OrderedMap<?, ?>) this.model.subMap((Value) fromKeyObject, (Value) toKeyObject);
}
}
@SuppressWarnings("unchecked")
@Override
public Set<Entry<K, V>> entrySet() {
if (this.keyForm != Form.forValue() || this.valueForm != Form.forValue()) {
return new ValueMapEntrySet<K, V>(this.model.state, this.keyForm, this.valueForm);
} else {
return (Set<Entry<K, V>>) (Set<?>) this.model.entrySet();
}
}
@SuppressWarnings("unchecked")
@Override
public Set<K> keySet() {
if (this.keyForm != Form.forValue()) {
return new ValueSet<K>(this.model.keySet(), this.keyForm);
} else {
return (Set<K>) this.model.keySet();
}
}
@SuppressWarnings("unchecked")
@Override
public Collection<V> values() {
if (this.valueForm != Form.forValue()) {
return new ValueCollection<V>(this.model.values(), this.valueForm);
} else {
return (Collection<V>) this.model.values();
}
}
@SuppressWarnings("unchecked")
@Override
public OrderedMapCursor<K, V> iterator() {
if (this.keyForm != Form.forValue() || this.valueForm != Form.forValue()) {
return new ValueOrderedMapCursor<K, V>(this.model.iterator(), this.keyForm, this.valueForm);
} else {
return (OrderedMapCursor<K, V>) (OrderedMapCursor<?, ?>) this.model.iterator();
}
}
@SuppressWarnings("unchecked")
public Cursor<K> keyIterator() {
if (this.keyForm != Form.forValue()) {
return new ValueCursor<K>(this.model.keyIterator(), this.keyForm);
} else {
return (Cursor<K>) this.model.keyIterator();
}
}
@SuppressWarnings("unchecked")
public Cursor<V> valueIterator() {
if (this.valueForm != Form.forValue()) {
return new ValueCursor<V>(this.model.valueIterator(), this.valueForm);
} else {
return (Cursor<V>) this.model.valueIterator();
}
}
@Override
public Comparator<? super K> comparator() {
return null;
}
@Override
public MapDownlink<K, V> get() {
return this;
}
@Override
public MapOutlet<K, V, ? extends Map<K, V>> input() {
return this.input;
}
@SuppressWarnings("unchecked")
@Override
public void bindInput(Outlet<? extends Map<K, V>> input) {
if (input instanceof MapOutlet<?, ?, ?>) {
bindInput((MapOutlet<K, V, ? extends Map<K, V>>) input);
} else {
throw new IllegalArgumentException(input.toString());
}
}
public void bindInput(MapOutlet<K, V, ? extends Map<K, V>> input) {
if (this.input != null) {
this.input.unbindOutput(this);
}
this.input = input;
if (this.input != null) {
this.input.bindOutput(this);
}
}
@Override
public void unbindInput() {
if (this.input != null) {
this.input.unbindOutput(this);
}
this.input = null;
}
@Override
public void disconnectInputs() {
final MapOutlet<K, V, ? extends Map<K, V>> input = this.input;
if (input != null) {
input.unbindOutput(this);
this.input = null;
input.disconnectInputs();
}
}
@Override
public Outlet<V> outlet(K key) {
KeyOutlet<K, V> outlet = this.outlets.get(key);
if (outlet == null) {
outlet = new KeyOutlet<K, V>(this, key);
this.outlets = this.outlets.updated(key, outlet);
}
return outlet;
}
@Override
public Iterator<Inlet<? super MapDownlink<K, V>>> outputIterator() {
return this.outputs != null ? Cursor.array(this.outputs) : Cursor.empty();
}
@SuppressWarnings("unchecked")
@Override
public void bindOutput(Inlet<? super MapDownlink<K, V>> output) {
final Inlet<? super MapDownlink<K, V>>[] oldOutputs = this.outputs;
final int n = oldOutputs != null ? oldOutputs.length : 0;
final Inlet<? super MapDownlink<K, V>>[] newOutputs = (Inlet<? super MapDownlink<K, V>>[]) new Inlet<?>[n + 1];
if (n > 0) {
System.arraycopy(oldOutputs, 0, newOutputs, 0, n);
}
newOutputs[n] = output;
this.outputs = newOutputs;
}
@SuppressWarnings("unchecked")
@Override
public void unbindOutput(Inlet<? super MapDownlink<K, V>> output) {
final Inlet<? super MapDownlink<K, V>>[] oldOutputs = this.outputs;
final int n = oldOutputs != null ? oldOutputs.length : 0;
for (int i = 0; i < n; i += 1) {
if (oldOutputs[i] == output) {
if (n > 1) {
final Inlet<? super MapDownlink<K, V>>[] newOutputs = (Inlet<? super MapDownlink<K, V>>[]) new Inlet<?>[n - 1];
System.arraycopy(oldOutputs, 0, newOutputs, 0, i);
System.arraycopy(oldOutputs, i + 1, newOutputs, i, (n - 1) - i);
this.outputs = newOutputs;
} else {
this.outputs = null;
}
break;
}
}
}
@Override
public void unbindOutputs() {
final HashTrieMap<K, KeyOutlet<K, V>> outlets = this.outlets;
if (!outlets.isEmpty()) {
this.outlets = HashTrieMap.empty();
final Iterator<KeyOutlet<K, V>> keyOutlets = outlets.valueIterator();
while (keyOutlets.hasNext()) {
final KeyOutlet<K, V> keyOutlet = keyOutlets.next();
keyOutlet.unbindOutputs();
}
}
final Inlet<? super MapDownlink<K, V>>[] outputs = this.outputs;
if (outputs != null) {
this.outputs = null;
for (int i = 0, n = outputs.length; i < n; i += 1) {
final Inlet<? super MapDownlink<K, V>> output = outputs[i];
output.unbindInput();
}
}
}
@Override
public void disconnectOutputs() {
final HashTrieMap<K, KeyOutlet<K, V>> outlets = this.outlets;
if (!outlets.isEmpty()) {
this.outlets = HashTrieMap.empty();
final Iterator<KeyOutlet<K, V>> keyOutlets = outlets.valueIterator();
while (keyOutlets.hasNext()) {
final KeyOutlet<K, V> keyOutlet = keyOutlets.next();
keyOutlet.disconnectOutputs();
}
}
final Inlet<? super MapDownlink<K, V>>[] outputs = this.outputs;
if (outputs != null) {
this.outputs = null;
for (int i = 0, n = outputs.length; i < n; i += 1) {
final Inlet<? super MapDownlink<K, V>> output = outputs[i];
output.unbindInput();
output.disconnectOutputs();
}
}
}
@Override
public void invalidateOutputKey(K key, KeyEffect effect) {
invalidateKey(key, effect);
}
@Override
public void invalidateInputKey(K key, KeyEffect effect) {
invalidateKey(key, effect);
}
@SuppressWarnings("unchecked")
public void invalidateKey(K key, KeyEffect effect) {
final HashTrieMap<K, KeyEffect> oldEffects = this.effects;
if (oldEffects.get(key) != effect) {
willInvalidateKey(key, effect);
this.effects = oldEffects.updated(key, effect);
this.version = -1;
onInvalidateKey(key, effect);
final int n = this.outputs != null ? this.outputs.length : 0;
for (int i = 0; i < n; i += 1) {
final Inlet<?> output = this.outputs[i];
if (output instanceof MapInlet<?, ?, ?>) {
((MapInlet<K, V, ? super MapDownlink<K, V>>) output).invalidateOutputKey(key, effect);
} else {
output.invalidateOutput();
}
}
final KeyOutlet<K, V> outlet = this.outlets.get(key);
if (outlet != null) {
outlet.invalidateInput();
}
didInvalidateKey(key, effect);
}
}
@Override
public void invalidateOutput() {
invalidate();
}
@Override
public void invalidateInput() {
invalidate();
}
public void invalidate() {
if (this.version >= 0) {
willInvalidate();
this.version = -1;
onInvalidate();
final int n = this.outputs != null ? this.outputs.length : 0;
for (int i = 0; i < n; i += 1) {
this.outputs[i].invalidateOutput();
}
final Iterator<KeyOutlet<K, V>> outlets = this.outlets.valueIterator();
while (outlets.hasNext()) {
outlets.next().invalidateInput();
}
didInvalidate();
}
}
@Override
public void reconcileOutputKey(K key, int version) {
reconcileKey(key, version);
}
@Override
public void reconcileInputKey(K key, int version) {
reconcileKey(key, version);
}
@SuppressWarnings("unchecked")
public void reconcileKey(K key, int version) {
if (this.version < 0) {
final HashTrieMap<K, KeyEffect> oldEffects = this.effects;
final KeyEffect effect = oldEffects.get(key);
if (effect != null) {
willReconcileKey(key, effect, version);
this.effects = oldEffects.removed(key);
if (this.input != null) {
this.input.reconcileInputKey(key, version);
}
onReconcileKey(key, effect, version);
for (int i = 0, n = this.outputs != null ? this.outputs.length : 0; i < n; i += 1) {
final Inlet<?> output = this.outputs[i];
if (output instanceof MapInlet<?, ?, ?>) {
((MapInlet<K, V, ? super MapDownlink<K, V>>) output).reconcileOutputKey(key, version);
}
}
final KeyOutlet<K, V> outlet = this.outlets.get(key);
if (outlet != null) {
outlet.reconcileInput(version);
}
didReconcileKey(key, effect, version);
}
}
}
@Override
public void reconcileOutput(int version) {
reconcile(version);
}
@Override
public void reconcileInput(int version) {
reconcile(version);
}
public void reconcile(int version) {
if (this.version < 0) {
willReconcile(version);
final Iterator<K> keys = this.effects.keyIterator();
while (keys.hasNext()) {
reconcileKey(keys.next(), version);
}
this.version = version;
onReconcile(version);
for (int i = 0, n = this.outputs != null ? this.outputs.length : 0; i < n; i += 1) {
this.outputs[i].reconcileOutput(version);
}
didReconcile(version);
}
}
protected void willInvalidateKey(K key, KeyEffect effect) {
// stub
}
protected void onInvalidateKey(K key, KeyEffect effect) {
// stub
}
protected void didInvalidateKey(K key, KeyEffect effect) {
// stub
}
protected void willInvalidate() {
// stub
}
protected void onInvalidate() {
// stub
}
protected void didInvalidate() {
// stub
}
protected void willUpdate(int version) {
// stub
}
protected void didUpdate(int version) {
// stub
}
protected void willReconcileKey(K key, KeyEffect effect, int version) {
// stub
}
protected void onReconcileKey(K key, KeyEffect effect, int version) {
if (effect == KeyEffect.UPDATE) {
if (this.input != null) {
final V value = this.input.get(key);
if (value != null) {
put(key, value);
} else {
remove(key);
}
}
} else if (effect == KeyEffect.REMOVE) {
if (containsKey(key)) {
remove(key);
}
}
}
protected void didReconcileKey(K key, KeyEffect effect, int version) {
// stub
}
protected void willReconcile(int version) {
// stub
}
protected void onReconcile(int version) {
// stub
}
protected void didReconcile(int version) {
// stub
}
protected static final int STATEFUL = 1 << 2;
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/downlink/ValueDownlinkModel.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.runtime.downlink;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import swim.concurrent.Stage;
import swim.runtime.DownlinkRelay;
import swim.runtime.DownlinkView;
import swim.runtime.warp.DemandDownlinkModem;
import swim.structure.Form;
import swim.structure.Value;
import swim.uri.Uri;
import swim.warp.EventMessage;
public class ValueDownlinkModel extends DemandDownlinkModem<ValueDownlinkView<?>> {
protected int flags;
protected volatile Value state;
public ValueDownlinkModel(Uri meshUri, Uri hostUri, Uri nodeUri, Uri laneUri,
float prio, float rate, Value body) {
super(meshUri, hostUri, nodeUri, laneUri, prio, rate, body);
this.flags = 0;
this.state = Value.absent();
}
public final boolean isStateful() {
return (this.flags & STATEFUL) != 0;
}
public ValueDownlinkModel isStateful(boolean isStateful) {
if (isStateful) {
this.flags |= STATEFUL;
} else {
this.flags &= ~STATEFUL;
}
final Object views = this.views;
if (views instanceof DownlinkView) {
((ValueDownlinkView<?>) views).didSetStateful(isStateful);
} else if (views instanceof DownlinkView[]) {
final DownlinkView[] viewArray = (DownlinkView[]) views;
for (int i = 0, n = viewArray.length; i < n; i += 1) {
((ValueDownlinkView<?>) viewArray[i]).didSetStateful(isStateful);
}
}
return this;
}
@Override
protected void pushDownEvent(EventMessage message) {
new ValueDownlinkRelaySet(this, message, message.body()).run();
}
@Override
protected Value nextUpCue() {
return this.state;
}
@Override
protected void didAddDownlink(ValueDownlinkView<?> view) {
if (this.views instanceof DownlinkView) {
isStateful(((ValueDownlinkView<?>) view).isStateful());
}
}
public Value get() {
return this.state;
}
@SuppressWarnings("unchecked")
public <V> V set(ValueDownlinkView<V> view, V newObject) {
final Form<V> valueForm = view.valueForm;
final Value newValue = valueForm.mold(newObject).toValue();
final ValueDownlinkRelaySet relay = new ValueDownlinkRelaySet(this, view.stage(), newValue);
relay.valueForm = (Form<Object>) valueForm;
relay.oldObject = newObject;
relay.newObject = newObject;
relay.run();
if (relay.isDone()) {
if (relay.valueForm != valueForm && valueForm != null) {
relay.oldObject = valueForm.cast(relay.oldValue);
if (relay.oldObject == null) {
relay.oldObject = valueForm.unit();
}
}
return (V) relay.oldObject;
} else {
return null;
}
}
public Value setValue(Value newValue) {
final ValueDownlinkRelaySet relay = new ValueDownlinkRelaySet(this, newValue);
relay.run();
if (relay.isDone()) {
return relay.oldValue;
} else {
return Value.absent();
}
}
protected Value willSet(Value newValue) {
return newValue;
}
protected void didSet(Value newValue, Value oldValue) {
}
protected static final int STATEFUL = 1 << 0;
static final AtomicReferenceFieldUpdater<ValueDownlinkModel, Value> STATE =
AtomicReferenceFieldUpdater.newUpdater(ValueDownlinkModel.class, Value.class, "state");
}
final class ValueDownlinkRelaySet extends DownlinkRelay<ValueDownlinkModel, ValueDownlinkView<?>> {
final EventMessage message;
Form<Object> valueForm;
Value oldValue;
Value newValue;
Object oldObject;
Object newObject;
ValueDownlinkRelaySet(ValueDownlinkModel model, EventMessage message, Value newValue) {
super(model, 4);
this.message = message;
this.oldValue = newValue;
this.newValue = newValue;
}
ValueDownlinkRelaySet(ValueDownlinkModel model, Stage stage, Value newValue) {
super(model, 1, 3, stage);
this.message = null;
this.oldValue = newValue;
this.newValue = newValue;
}
ValueDownlinkRelaySet(ValueDownlinkModel model, Value newValue) {
super(model, 1, 3, null);
this.message = null;
this.oldValue = newValue;
this.newValue = newValue;
}
@Override
protected void beginPhase(int phase) {
if (phase == 1) {
this.newValue = this.model.willSet(this.newValue);
} else if (phase == 2) {
if (this.model.isStateful()) {
do {
this.oldValue = this.model.state;
} while (this.oldValue != this.newValue && !ValueDownlinkModel.STATE.compareAndSet(this.model, this.oldValue, this.newValue));
}
this.model.didSet(this.newValue, this.oldValue);
}
}
@SuppressWarnings("unchecked")
@Override
protected boolean runPhase(ValueDownlinkView<?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.downlinkWillReceive(this.message);
}
return view.dispatchWillReceive(this.message.body(), preemptive);
} else if (phase == 1) {
this.newValue = view.downlinkWillSetValue(this.newValue);
final Form<Object> valueForm = (Form<Object>) view.valueForm();
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.oldObject = valueForm.cast(this.newValue);
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
newObject = valueForm.cast(newValue);
}
if (preemptive) {
this.newObject = ((ValueDownlinkView<Object>) view).downlinkWillSet(this.newObject);
}
final Map.Entry<Boolean, Object> result = ((ValueDownlinkView<Object>) view).dispatchWillSet(this.oldObject, preemptive);
this.newObject = result.getValue();
if (this.oldObject != result.getValue()) {
this.oldObject = this.newObject; //FIXME: Is this right?
this.newObject = result.getValue();
this.newValue = valueForm.mold(this.newObject).toValue();
}
return result.getKey();
} else if (phase == 2) {
view.downlinkDidSetValue(this.newValue, this.oldValue);
final Form<Object> valueForm = (Form<Object>) view.valueForm();
if (valueForm != null) {
this.valueForm = valueForm;
this.oldObject = valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
this.newObject = valueForm.cast(this.newValue);
if (this.newObject == null) {
this.newObject = valueForm.unit();
}
}
if (preemptive) {
((ValueDownlinkView<Object>) view).downlinkDidSet(this.newObject, this.oldObject);
}
return ((ValueDownlinkView<Object>) view).dispatchDidSet(this.newObject, this.oldObject, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.downlinkDidReceive(this.message);
}
return view.dispatchDidReceive(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
if (this.message != null) {
this.model.cueDown();
} else {
this.model.cueUp();
}
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/downlink/ValueDownlinkView.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.runtime.downlink;
import java.util.AbstractMap;
import java.util.Iterator;
import java.util.Map;
import swim.api.DownlinkException;
import swim.api.Link;
import swim.api.SwimContext;
import swim.api.downlink.ValueDownlink;
import swim.api.function.DidClose;
import swim.api.function.DidConnect;
import swim.api.function.DidDisconnect;
import swim.api.function.DidFail;
import swim.api.warp.function.DidLink;
import swim.api.warp.function.DidReceive;
import swim.api.warp.function.DidSync;
import swim.api.warp.function.DidUnlink;
import swim.api.warp.function.WillCommand;
import swim.api.warp.function.WillLink;
import swim.api.warp.function.WillReceive;
import swim.api.warp.function.WillSync;
import swim.api.warp.function.WillUnlink;
import swim.concurrent.Conts;
import swim.concurrent.Stage;
import swim.observable.function.DidSet;
import swim.observable.function.WillSet;
import swim.runtime.CellContext;
import swim.runtime.LinkBinding;
import swim.runtime.warp.WarpDownlinkView;
import swim.streamlet.Inlet;
import swim.streamlet.Outlet;
import swim.structure.Form;
import swim.structure.Value;
import swim.uri.Uri;
import swim.util.Cursor;
public class ValueDownlinkView<V> extends WarpDownlinkView implements ValueDownlink<V> {
protected final Form<V> valueForm;
protected ValueDownlinkModel model;
protected Outlet<? extends V> input;
protected Inlet<? super V>[] outputs; // TODO: unify with observers
protected int version;
public ValueDownlinkView(CellContext cellContext, Stage stage, Uri meshUri,
Uri hostUri, Uri nodeUri, Uri laneUri, float prio,
float rate, Value body, int flags, Form<V> valueForm,
Object observers) {
super(cellContext, stage, meshUri, hostUri, nodeUri, laneUri, prio, rate,
body, flags, observers);
this.valueForm = valueForm;
this.input = null;
this.outputs = null;
this.version = -1;
}
public ValueDownlinkView(CellContext cellContext, Stage stage, Uri meshUri,
Uri hostUri, Uri nodeUri, Uri laneUri, float prio,
float rate, Value body, Form<V> valueForm) {
this(cellContext, stage, meshUri, hostUri, nodeUri, laneUri, prio, rate,
body, KEEP_LINKED | KEEP_SYNCED | STATEFUL, valueForm, null);
}
@Override
public ValueDownlinkModel downlinkModel() {
return this.model;
}
@Override
public ValueDownlinkView<V> hostUri(Uri hostUri) {
return new ValueDownlinkView<V>(this.cellContext, this.stage, this.meshUri,
hostUri, this.nodeUri, this.laneUri,
this.prio, this.rate, this.body, this.flags,
this.valueForm, this.observers);
}
@Override
public ValueDownlinkView<V> hostUri(String hostUri) {
return hostUri(Uri.parse(hostUri));
}
@Override
public ValueDownlinkView<V> nodeUri(Uri nodeUri) {
return new ValueDownlinkView<V>(this.cellContext, this.stage, this.meshUri,
this.hostUri, nodeUri, this.laneUri,
this.prio, this.rate, this.body, this.flags,
this.valueForm, this.observers);
}
@Override
public ValueDownlinkView<V> nodeUri(String nodeUri) {
return nodeUri(Uri.parse(nodeUri));
}
@Override
public ValueDownlinkView<V> laneUri(Uri laneUri) {
return new ValueDownlinkView<V>(this.cellContext, this.stage, this.meshUri,
this.hostUri, this.nodeUri, laneUri,
this.prio, this.rate, this.body, this.flags,
this.valueForm, this.observers);
}
@Override
public ValueDownlinkView<V> laneUri(String laneUri) {
return laneUri(Uri.parse(laneUri));
}
@Override
public ValueDownlinkView<V> prio(float prio) {
return new ValueDownlinkView<V>(this.cellContext, this.stage, this.meshUri,
this.hostUri, this.nodeUri, this.laneUri,
prio, this.rate, this.body, this.flags,
this.valueForm, this.observers);
}
@Override
public ValueDownlinkView<V> rate(float rate) {
return new ValueDownlinkView<V>(this.cellContext, this.stage, this.meshUri,
this.hostUri, this.nodeUri, this.laneUri,
this.prio, rate, this.body, this.flags,
this.valueForm, this.observers);
}
@Override
public ValueDownlinkView<V> body(Value body) {
return new ValueDownlinkView<V>(this.cellContext, this.stage, this.meshUri,
this.hostUri, this.nodeUri, this.laneUri,
this.prio, this.rate, body, this.flags,
this.valueForm, this.observers);
}
@Override
public ValueDownlinkView<V> keepLinked(boolean keepLinked) {
if (keepLinked) {
this.flags |= KEEP_LINKED;
} else {
this.flags &= ~KEEP_LINKED;
}
return this;
}
@Override
public ValueDownlinkView<V> keepSynced(boolean keepSynced) {
if (keepSynced) {
this.flags |= KEEP_SYNCED;
} else {
this.flags &= ~KEEP_SYNCED;
}
return this;
}
@Override
public final boolean isStateful() {
return (this.flags & STATEFUL) != 0;
}
@Override
public ValueDownlinkView<V> isStateful(boolean isStateful) {
if (isStateful) {
this.flags |= STATEFUL;
} else {
this.flags &= ~STATEFUL;
}
final ValueDownlinkModel model = this.model;
if (this.model != null) {
this.model.isStateful(isStateful);
}
return this;
}
void didSetStateful(boolean isStateful) {
if (isStateful) {
this.flags |= STATEFUL;
} else {
this.flags &= ~STATEFUL;
}
}
@Override
public final Form<V> valueForm() {
return this.valueForm;
}
@Override
public <V2> ValueDownlinkView<V2> valueForm(Form<V2> valueForm) {
return new ValueDownlinkView<V2>(this.cellContext, this.stage, this.meshUri,
this.hostUri, this.nodeUri, this.laneUri,
this.prio, this.rate, this.body, this.flags,
valueForm, typesafeObservers(this.observers));
}
@Override
public <V2> ValueDownlinkView<V2> valueClass(Class<V2> valueClass) {
return valueForm(Form.<V2>forClass(valueClass));
}
protected Object typesafeObservers(Object observers) {
// TODO: filter out WillSet, DidSet
return observers;
}
@SuppressWarnings("unchecked")
@Override
public ValueDownlinkView<V> observe(Object observer) {
return (ValueDownlinkView<V>) super.observe(observer);
}
@SuppressWarnings("unchecked")
@Override
public ValueDownlinkView<V> unobserve(Object observer) {
return (ValueDownlinkView<V>) super.unobserve(observer);
}
@Override
public ValueDownlinkView<V> willSet(WillSet<V> willSet) {
return observe(willSet);
}
@Override
public ValueDownlinkView<V> didSet(DidSet<V> didSet) {
return observe(didSet);
}
@Override
public ValueDownlinkView<V> willReceive(WillReceive willReceive) {
return observe(willReceive);
}
@Override
public ValueDownlinkView<V> didReceive(DidReceive didReceive) {
return observe(didReceive);
}
@Override
public ValueDownlinkView<V> willCommand(WillCommand willCommand) {
return observe(willCommand);
}
@Override
public ValueDownlinkView<V> willLink(WillLink willLink) {
return observe(willLink);
}
@Override
public ValueDownlinkView<V> didLink(DidLink didLink) {
return observe(didLink);
}
@Override
public ValueDownlinkView<V> willSync(WillSync willSync) {
return observe(willSync);
}
@Override
public ValueDownlinkView<V> didSync(DidSync didSync) {
return observe(didSync);
}
@Override
public ValueDownlinkView<V> willUnlink(WillUnlink willUnlink) {
return observe(willUnlink);
}
@Override
public ValueDownlinkView<V> didUnlink(DidUnlink didUnlink) {
return observe(didUnlink);
}
@Override
public ValueDownlinkView<V> didConnect(DidConnect didConnect) {
return observe(didConnect);
}
@Override
public ValueDownlinkView<V> didDisconnect(DidDisconnect didDisconnect) {
return observe(didDisconnect);
}
@Override
public ValueDownlinkView<V> didClose(DidClose didClose) {
return observe(didClose);
}
@Override
public ValueDownlinkView<V> didFail(DidFail didFail) {
return observe(didFail);
}
@SuppressWarnings("unchecked")
public Map.Entry<Boolean, V> dispatchWillSet(V newValue, boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillSet<?>) {
if (((WillSet<?>) observers).isPreemptive() == preemptive) {
try {
newValue = ((WillSet<V>) observers).willSet(newValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillSet<?>) {
if (((WillSet<?>) observer).isPreemptive() == preemptive) {
try {
newValue = ((WillSet<V>) observer).willSet(newValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return new AbstractMap.SimpleImmutableEntry<Boolean, V>(complete, newValue);
} finally {
SwimContext.setLink(oldLink);
}
}
@SuppressWarnings("unchecked")
public boolean dispatchDidSet(V newValue, V oldValue, boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidSet<?>) {
if (((DidSet<?>) observers).isPreemptive() == preemptive) {
try {
((DidSet<V>) observers).didSet(newValue, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidSet<?>) {
if (((DidSet<?>) observer).isPreemptive() == preemptive) {
try {
((DidSet<V>) observer).didSet(newValue, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
public Value downlinkWillSetValue(Value newValue) {
return newValue;
}
public void downlinkDidSetValue(Value newValue, Value oldValue) {
}
public V downlinkWillSet(V newValue) {
return newValue;
}
public void downlinkDidSet(V newValue, V oldValue) {
invalidate();
reconcile(0); // TODO: debounce and track version
}
@Override
public ValueDownlinkModel createDownlinkModel() {
return new ValueDownlinkModel(this.meshUri, this.hostUri, this.nodeUri,
this.laneUri, this.prio, this.rate, this.body);
}
@Override
public ValueDownlinkView<V> open() {
if (this.model == null) {
final LinkBinding linkBinding = this.cellContext.bindDownlink(this);
if (linkBinding instanceof ValueDownlinkModel) {
this.model = (ValueDownlinkModel) linkBinding;
this.model.addDownlink(this);
} else {
throw new DownlinkException("downlink type mismatch");
}
}
return this;
}
@Override
public V get() {
final V state = this.valueForm.cast(this.model.get());
if (state == null) {
return this.valueForm.unit();
}
return state;
}
@Override
public V set(V newValue) {
return this.model.set(this, newValue);
}
@Override
public Outlet<? extends V> input() {
return this.input;
}
@Override
public void bindInput(Outlet<? extends V> input) {
if (this.input != null) {
this.input.unbindOutput(this);
}
this.input = input;
if (this.input != null) {
this.input.bindOutput(this);
}
}
@Override
public void unbindInput() {
if (this.input != null) {
this.input.unbindOutput(this);
}
this.input = null;
}
@Override
public void disconnectInputs() {
final Outlet<? extends V> input = this.input;
if (input != null) {
input.unbindOutput(this);
this.input = null;
input.disconnectInputs();
}
}
@Override
public Iterator<Inlet<? super V>> outputIterator() {
return this.outputs != null ? Cursor.array(this.outputs) : Cursor.empty();
}
@SuppressWarnings("unchecked")
@Override
public void bindOutput(Inlet<? super V> output) {
final Inlet<? super V>[] oldOutputs = this.outputs;
final int n = oldOutputs != null ? oldOutputs.length : 0;
final Inlet<? super V>[] newOutputs = (Inlet<? super V>[]) new Inlet<?>[n + 1];
if (n > 0) {
System.arraycopy(oldOutputs, 0, newOutputs, 0, n);
}
newOutputs[n] = output;
this.outputs = newOutputs;
}
@SuppressWarnings("unchecked")
@Override
public void unbindOutput(Inlet<? super V> output) {
final Inlet<? super V>[] oldOutputs = this.outputs;
final int n = oldOutputs != null ? oldOutputs.length : 0;
for (int i = 0; i < n; i += 1) {
if (oldOutputs[i] == output) {
if (n > 1) {
final Inlet<? super V>[] newOutputs = (Inlet<? super V>[]) new Inlet<?>[n - 1];
System.arraycopy(oldOutputs, 0, newOutputs, 0, i);
System.arraycopy(oldOutputs, i + 1, newOutputs, i, (n - 1) - i);
this.outputs = newOutputs;
} else {
this.outputs = null;
}
break;
}
}
}
@Override
public void unbindOutputs() {
final Inlet<? super V>[] outputs = this.outputs;
if (outputs != null) {
this.outputs = null;
for (int i = 0, n = outputs.length; i < n; i += 1) {
final Inlet<? super V> output = outputs[i];
output.unbindInput();
}
}
}
@Override
public void disconnectOutputs() {
final Inlet<? super V>[] outputs = this.outputs;
if (outputs != null) {
this.outputs = null;
for (int i = 0, n = outputs.length; i < n; i += 1) {
final Inlet<? super V> output = outputs[i];
output.unbindInput();
output.disconnectOutputs();
}
}
}
@Override
public void invalidateOutput() {
invalidate();
}
@Override
public void invalidateInput() {
invalidate();
}
public void invalidate() {
if (this.version >= 0) {
willInvalidate();
this.version = -1;
onInvalidate();
final int n = this.outputs != null ? this.outputs.length : 0;
for (int i = 0; i < n; i += 1) {
this.outputs[i].invalidateOutput();
}
didInvalidate();
}
}
@Override
public void reconcileOutput(int version) {
reconcile(version);
}
@Override
public void reconcileInput(int version) {
reconcile(version);
}
public void reconcile(int version) {
if (this.version < 0) {
willReconcile(version);
this.version = version;
if (this.input != null) {
this.input.reconcileInput(version);
}
onReconcile(version);
final int n = this.outputs != null ? this.outputs.length : 0;
for (int i = 0; i < n; i += 1) {
this.outputs[i].reconcileOutput(version);
}
didReconcile(version);
}
}
protected void willInvalidate() {
// stub
}
protected void onInvalidate() {
// stub
}
protected void didInvalidate() {
// stub
}
protected void willReconcile(int version) {
// stub
}
protected void onReconcile(int version) {
if (this.input != null) {
final V value = this.input.get();
set(value);
}
}
protected void didReconcile(int version) {
// stub
}
protected static final int STATEFUL = 1 << 2;
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/downlink/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.
/**
* Downlink runtime implementation.
*/
package swim.runtime.downlink;
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/http/HttpErrorUplinkModem.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.runtime.http;
import java.net.InetSocketAddress;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.Collection;
import swim.api.auth.Identity;
import swim.codec.Decoder;
import swim.collections.FingerTrieSeq;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
import swim.http.HttpStatus;
import swim.runtime.HttpBinding;
import swim.runtime.HttpContext;
import swim.structure.Value;
public class HttpErrorUplinkModem implements HttpContext {
protected final HttpBinding linkBinding;
public HttpErrorUplinkModem(HttpBinding linkBinding) {
this.linkBinding = linkBinding;
}
@Override
public final HttpBinding linkWrapper() {
return this.linkBinding.linkWrapper();
}
public final HttpBinding linkBinding() {
return this.linkBinding;
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrapLink(Class<T> linkClass) {
if (linkClass.isAssignableFrom(getClass())) {
return (T) this;
} else {
return null;
}
}
@Override
public Value linkKey() {
return Value.absent(); // never opened
}
@Override
public boolean isConnectedUp() {
return true;
}
@Override
public boolean isRemoteUp() {
return false;
}
@Override
public boolean isSecureUp() {
return true;
}
@Override
public String securityProtocolUp() {
return null;
}
@Override
public String cipherSuiteUp() {
return null;
}
@Override
public InetSocketAddress localAddressUp() {
return null;
}
@Override
public Identity localIdentityUp() {
return null;
}
@Override
public Principal localPrincipalUp() {
return null;
}
@Override
public Collection<Certificate> localCertificatesUp() {
return FingerTrieSeq.empty();
}
@Override
public InetSocketAddress remoteAddressUp() {
return null;
}
@Override
public Identity remoteIdentityUp() {
return null;
}
@Override
public Principal remotePrincipalUp() {
return null;
}
@Override
public Collection<Certificate> remoteCertificatesUp() {
return FingerTrieSeq.empty();
}
@Override
public Decoder<Object> decodeRequest(HttpRequest<?> request) {
return request.contentDecoder();
}
@Override
public void willRequest(HttpRequest<?> request) {
// nop
}
@Override
public void didRequest(HttpRequest<Object> request) {
// nop
}
@Override
public void doRespond(HttpRequest<Object> request) {
this.linkBinding.writeResponse(HttpResponse.from(HttpStatus.NOT_FOUND));
}
@Override
public void willRespond(HttpResponse<?> response) {
// nop
}
@Override
public void didRespond(HttpResponse<?> response) {
// nop
}
public void close() {
this.linkBinding.closeDown();
}
@Override
public void closeUp() {
// nop
}
@Override
public void didOpenDown() {
// nop
}
@Override
public void didCloseDown() {
// nop
}
@Override
public void traceUp(Object message) {
// nop
}
@Override
public void debugUp(Object message) {
// nop
}
@Override
public void infoUp(Object message) {
// nop
}
@Override
public void warnUp(Object message) {
// nop
}
@Override
public void errorUp(Object message) {
// nop
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/http/HttpLaneModel.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.runtime.http;
import swim.codec.Decoder;
import swim.http.HttpBody;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
import swim.http.HttpStatus;
import swim.runtime.HttpBinding;
import swim.runtime.LaneModel;
import swim.runtime.LaneRelay;
import swim.runtime.LaneView;
import swim.runtime.LinkBinding;
import swim.runtime.PushRequest;
import swim.warp.CommandMessage;
public abstract class HttpLaneModel<View extends HttpLaneView<?>, U extends HttpUplinkModem> extends LaneModel<View, U> {
@Override
public String laneType() {
return "http";
}
@Override
protected U createUplink(LinkBinding link) {
if (link instanceof HttpBinding) {
return createHttpUplink((HttpBinding) link);
}
return null;
}
protected abstract U createHttpUplink(HttpBinding link);
@Override
public void pushUp(PushRequest pushRequest) {
pushRequest.didDecline();
}
@Override
public void pushUpCommand(CommandMessage message) {
throw new UnsupportedOperationException();
}
@Override
protected void didOpenLaneView(View view) {
// nop
}
protected Decoder<Object> decodeRequestDefault(U uplink, HttpRequest<?> request) {
return request.contentDecoder();
}
protected HttpResponse<?> doRespondDefault(U uplink, HttpRequest<?> request) {
return HttpResponse.from(HttpStatus.NOT_FOUND).entity(HttpBody.empty());
}
protected Decoder<Object> decodeRequest(U uplink, HttpRequest<?> request) {
final Object views = this.views;
HttpLaneView<?> view;
Decoder<Object> decoder = null;
if (views instanceof HttpLaneView) {
view = (HttpLaneView<?>) views;
decoder = view.dispatchDecodeRequest(uplink, request);
if (decoder == null) {
decoder = view.laneDecodeRequest(uplink, request);
}
} else if (views instanceof LaneView[]) {
final LaneView[] viewArray = (LaneView[]) views;
for (int i = 0, n = viewArray.length; i < n; i += 1) {
view = (HttpLaneView<?>) viewArray[i];
decoder = view.dispatchDecodeRequest(uplink, request);
if (decoder == null) {
decoder = view.laneDecodeRequest(uplink, request);
}
if (decoder != null) {
break;
}
}
}
if (decoder == null) {
decoder = decodeRequestDefault(uplink, request);
}
return decoder;
}
protected void willRequest(U uplink, HttpRequest<?> request) {
new HttpLaneRelayWillRequest<View>(this, uplink, request).run();
}
protected void didRequest(U uplink, HttpRequest<Object> request) {
new HttpLaneRelayDidRequest<View>(this, uplink, request).run();
}
protected void doRespond(U uplink, HttpRequest<Object> request) {
new HttpLaneRelayDoRespond<View, U>(this, uplink, request).run();
}
protected void willRespond(U uplink, HttpResponse<?> response) {
new HttpLaneRelayWillRespond<View>(this, uplink, response).run();
}
protected void didRespond(U uplink, HttpResponse<?> response) {
new HttpLaneRelayDidRespond<View>(this, uplink, response).run();
}
}
final class HttpLaneRelayWillRequest<View extends HttpLaneView<?>> extends LaneRelay<HttpLaneModel<View, ?>, View> {
final HttpUplinkModem uplink;
final HttpRequest<?> request;
HttpLaneRelayWillRequest(HttpLaneModel<View, ?> model, HttpUplinkModem uplink, HttpRequest<?> request) {
super(model);
this.uplink = uplink;
this.request = request;
}
@Override
protected boolean runPhase(View view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneWillRequest(this.uplink, this.request);
}
return view.dispatchWillRequest(this.uplink, this.request, preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
}
final class HttpLaneRelayDidRequest<View extends HttpLaneView<?>> extends LaneRelay<HttpLaneModel<View, ?>, View> {
final HttpUplinkModem uplink;
final HttpRequest<Object> request;
HttpLaneRelayDidRequest(HttpLaneModel<View, ?> model, HttpUplinkModem uplink, HttpRequest<Object> request) {
super(model);
this.uplink = uplink;
this.request = request;
}
@Override
protected boolean runPhase(View view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneDidRequest(this.uplink, this.request);
}
return view.dispatchDidRequest(this.uplink, this.request, preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
}
final class HttpLaneRelayDoRespond<View extends HttpLaneView<?>, U extends HttpUplinkModem> extends LaneRelay<HttpLaneModel<View, U>, View> {
final U uplink;
final HttpRequest<Object> request;
HttpResponse<?> response;
HttpLaneRelayDoRespond(HttpLaneModel<View, U> model, U uplink, HttpRequest<Object> request) {
super(model);
this.uplink = uplink;
this.request = request;
}
@Override
protected boolean runPhase(View view, int phase, boolean preemptive) {
if (phase == 0) {
Object response = this.response;
if (response == null) {
response = view.dispatchDoRespond(this.uplink, this.request, preemptive);
}
final boolean complete = response == Boolean.TRUE;
if (complete) {
response = view.laneDoRespond(this.uplink, this.request);
}
if (response instanceof HttpResponse<?>) {
this.response = (HttpResponse<?>) response;
return true;
}
return complete;
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
if (this.response == null) {
this.response = this.model.doRespondDefault(this.uplink, this.request);
}
this.uplink.writeResponse(this.response);
}
}
final class HttpLaneRelayWillRespond<View extends HttpLaneView<?>> extends LaneRelay<HttpLaneModel<View, ?>, View> {
final HttpUplinkModem uplink;
final HttpResponse<?> response;
HttpLaneRelayWillRespond(HttpLaneModel<View, ?> model, HttpUplinkModem uplink, HttpResponse<?> response) {
super(model);
this.uplink = uplink;
this.response = response;
}
@Override
protected boolean runPhase(View view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneWillRespond(this.uplink, this.response);
}
return view.dispatchWillRespond(this.uplink, this.response, preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
}
final class HttpLaneRelayDidRespond<View extends HttpLaneView<?>> extends LaneRelay<HttpLaneModel<View, ?>, View> {
final HttpUplinkModem uplink;
final HttpResponse<?> response;
HttpLaneRelayDidRespond(HttpLaneModel<View, ?> model, HttpUplinkModem uplink, HttpResponse<?> response) {
super(model);
this.uplink = uplink;
this.response = response;
}
@Override
protected boolean runPhase(View view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneDidRespond(this.uplink, this.response);
}
return view.dispatchDidRespond(this.uplink, this.response, preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/http/HttpLaneView.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.runtime.http;
import swim.api.Lane;
import swim.api.Link;
import swim.api.SwimContext;
import swim.api.http.HttpLane;
import swim.api.http.HttpUplink;
import swim.api.http.function.DecodeRequestHttp;
import swim.api.http.function.DidRequestHttp;
import swim.api.http.function.DidRespondHttp;
import swim.api.http.function.DoRespondHttp;
import swim.api.http.function.WillRequestHttp;
import swim.api.http.function.WillRespondHttp;
import swim.codec.Decoder;
import swim.concurrent.Conts;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
import swim.runtime.LaneView;
public abstract class HttpLaneView<V> extends LaneView implements HttpLane<V> {
public HttpLaneView(Object observers) {
super(observers);
}
@Override
public HttpLaneView<V> observe(Object observer) {
super.observe(observer);
return this;
}
@Override
public HttpLaneView<V> unobserve(Object observer) {
super.unobserve(observer);
return this;
}
@Override
public abstract HttpLaneView<V> decodeRequest(DecodeRequestHttp<V> decodeRequest);
@Override
public abstract HttpLaneView<V> willRequest(WillRequestHttp<?> willRequest);
@Override
public abstract HttpLaneView<V> didRequest(DidRequestHttp<V> didRequest);
@Override
public abstract HttpLaneView<V> doRespond(DoRespondHttp<V> doRespond);
@Override
public abstract HttpLaneView<V> willRespond(WillRespondHttp<?> willRespond);
@Override
public abstract HttpLaneView<V> didRespond(DidRespondHttp<?> didRespond);
@SuppressWarnings("unchecked")
protected Decoder<Object> dispatchDecodeRequest(HttpUplink uplink, HttpRequest<?> request) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
SwimContext.setLane(this);
SwimContext.setLink(uplink);
try {
final Object observers = this.observers;
if (observers instanceof DecodeRequestHttp<?>) {
try {
final Decoder<Object> decoder = ((DecodeRequestHttp<Object>) observers).decodeRequest((HttpRequest<Object>) request);
if (decoder != null) {
return decoder;
}
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DecodeRequestHttp<?>) {
try {
final Decoder<Object> decoder = ((DecodeRequestHttp<Object>) observer).decodeRequest((HttpRequest<Object>) request);
if (decoder != null) {
return decoder;
}
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
}
}
}
return null;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
@SuppressWarnings("unchecked")
protected boolean dispatchWillRequest(HttpUplink uplink, HttpRequest<?> request, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
SwimContext.setLane(this);
SwimContext.setLink(uplink);
try {
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillRequestHttp<?>) {
if (((WillRequestHttp<?>) observers).isPreemptive() == preemptive) {
try {
((WillRequestHttp<Object>) observers).willRequest((HttpRequest<Object>) request);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillRequestHttp<?>) {
if (((WillRequestHttp<?>) observer).isPreemptive() == preemptive) {
try {
((WillRequestHttp<Object>) observer).willRequest((HttpRequest<Object>) request);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
@SuppressWarnings("unchecked")
protected boolean dispatchDidRequest(HttpUplink uplink, HttpRequest<Object> request, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
SwimContext.setLane(this);
SwimContext.setLink(uplink);
try {
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidRequestHttp<?>) {
if (((DidRequestHttp<?>) observers).isPreemptive() == preemptive) {
try {
((DidRequestHttp<Object>) observers).didRequest(request);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidRequestHttp<?>) {
if (((DidRequestHttp<?>) observer).isPreemptive() == preemptive) {
try {
((DidRequestHttp<Object>) observer).didRequest(request);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
@SuppressWarnings("unchecked")
protected Object dispatchDoRespond(HttpUplink uplink, HttpRequest<Object> request, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
SwimContext.setLane(this);
SwimContext.setLink(uplink);
try {
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DoRespondHttp<?>) {
if (((DoRespondHttp<?>) observers).isPreemptive() == preemptive) {
try {
final HttpResponse<?> response = ((DoRespondHttp<Object>) observers).doRespond(request);
if (response != null) {
return response;
}
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DoRespondHttp<?>) {
if (((DoRespondHttp<?>) observer).isPreemptive() == preemptive) {
try {
final HttpResponse<?> response = ((DoRespondHttp<Object>) observer).doRespond(request);
if (response != null) {
return response;
}
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
@SuppressWarnings("unchecked")
protected boolean dispatchWillRespond(HttpUplink uplink, HttpResponse<?> response, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
SwimContext.setLane(this);
SwimContext.setLink(uplink);
try {
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillRespondHttp<?>) {
if (((WillRespondHttp<?>) observers).isPreemptive() == preemptive) {
try {
((WillRespondHttp<Object>) observers).willRespond((HttpResponse<Object>) response);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillRespondHttp<?>) {
if (((WillRespondHttp<?>) observer).isPreemptive() == preemptive) {
try {
((WillRespondHttp<Object>) observer).willRespond((HttpResponse<Object>) response);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
@SuppressWarnings("unchecked")
protected boolean dispatchDidRespond(HttpUplink uplink, HttpResponse<?> response, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
SwimContext.setLane(this);
SwimContext.setLink(uplink);
try {
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidRespondHttp<?>) {
if (((DidRespondHttp<?>) observers).isPreemptive() == preemptive) {
try {
((DidRespondHttp<Object>) observers).didRespond((HttpResponse<Object>) response);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidRespondHttp<?>) {
if (((DidRespondHttp<?>) observer).isPreemptive() == preemptive) {
try {
((DidRespondHttp<Object>) observer).didRespond((HttpResponse<Object>) response);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
public Decoder<Object> laneDecodeRequest(HttpUplink uplink, HttpRequest<?> request) {
return null;
}
public void laneWillRequest(HttpUplink uplink, HttpRequest<?> request) {
// stub
}
public void laneDidRequest(HttpUplink uplink, HttpRequest<Object> request) {
// stub
}
public HttpResponse<?> laneDoRespond(HttpUplink uplink, HttpRequest<Object> request) {
return null;
}
public void laneWillRespond(HttpUplink uplink, HttpResponse<?> response) {
// stub
}
public void laneDidRespond(HttpUplink uplink, HttpResponse<?> response) {
// stub
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/http/HttpUplinkModem.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.runtime.http;
import swim.api.http.HttpUplink;
import swim.codec.Decoder;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
import swim.runtime.AbstractUplinkContext;
import swim.runtime.HttpBinding;
import swim.runtime.HttpContext;
import swim.runtime.LinkKeys;
import swim.structure.Value;
import swim.uri.Uri;
public abstract class HttpUplinkModem extends AbstractUplinkContext implements HttpContext, HttpUplink {
protected final HttpBinding linkBinding;
protected final Value linkKey;
protected HttpUplinkModem(HttpBinding linkBinding, Value linkKey) {
this.linkBinding = linkBinding;
this.linkKey = linkKey.commit();
}
protected HttpUplinkModem(HttpBinding linkBinding) {
this(linkBinding, LinkKeys.generateLinkKey());
}
@Override
public final HttpBinding linkWrapper() {
return this.linkBinding.linkWrapper();
}
@Override
public final HttpBinding linkBinding() {
return this.linkBinding;
}
@Override
public final Uri hostUri() {
return this.linkBinding.hostUri();
}
@Override
public final Uri nodeUri() {
return this.linkBinding.nodeUri();
}
@Override
public final Uri laneUri() {
return this.linkBinding.laneUri();
}
@Override
public final Value linkKey() {
return this.linkKey;
}
@Override
public final Uri requestUri() {
return this.linkBinding.requestUri();
}
@Override
public final HttpRequest<?> request() {
return this.linkBinding.request();
}
@Override
public HttpUplinkModem observe(Object observer) {
super.observe(observer);
return this;
}
@Override
public HttpUplinkModem unobserve(Object observer) {
super.unobserve(observer);
return this;
}
@Override
public abstract Decoder<Object> decodeRequest(HttpRequest<?> request);
@Override
public abstract void willRequest(HttpRequest<?> request);
@Override
public abstract void didRequest(HttpRequest<Object> request);
@Override
public abstract void doRespond(HttpRequest<Object> request);
@Override
public abstract void willRespond(HttpResponse<?> response);
public void writeResponse(HttpResponse<?> response) {
this.linkBinding.writeResponse(response);
}
@Override
public abstract void didRespond(HttpResponse<?> response);
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/http/RestLaneModel.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.runtime.http;
import swim.runtime.HttpBinding;
public class RestLaneModel extends HttpLaneModel<RestLaneView<?>, RestLaneUplink> {
@Override
protected RestLaneUplink createHttpUplink(HttpBinding link) {
return new RestLaneUplink(this, link);
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/http/RestLaneUplink.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.runtime.http;
import swim.codec.Decoder;
import swim.concurrent.Stage;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
import swim.runtime.HttpBinding;
public class RestLaneUplink extends HttpUplinkModem {
protected final RestLaneModel laneBinding;
public RestLaneUplink(RestLaneModel laneBinding, HttpBinding linkBinding) {
super(linkBinding);
this.laneBinding = laneBinding;
}
@Override
public final RestLaneModel laneBinding() {
return this.laneBinding;
}
@Override
public Stage stage() {
return this.laneBinding.stage();
}
@Override
public Decoder<Object> decodeRequest(HttpRequest<?> request) {
return this.laneBinding.decodeRequest(this, request);
}
@Override
public void willRequest(HttpRequest<?> request) {
this.laneBinding.willRequest(this, request);
}
@Override
public void didRequest(HttpRequest<Object> request) {
this.laneBinding.didRequest(this, request);
}
@Override
public void doRespond(HttpRequest<Object> request) {
this.laneBinding.doRespond(this, request);
}
@Override
public void willRespond(HttpResponse<?> response) {
this.laneBinding.willRespond(this, response);
}
@Override
public void didRespond(HttpResponse<?> response) {
this.laneBinding.didRespond(this, response);
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/http/RestLaneView.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.runtime.http;
import swim.api.agent.AgentContext;
import swim.api.http.function.DecodeRequestHttp;
import swim.api.http.function.DidRequestHttp;
import swim.api.http.function.DidRespondHttp;
import swim.api.http.function.DoRespondHttp;
import swim.api.http.function.WillRequestHttp;
import swim.api.http.function.WillRespondHttp;
public class RestLaneView<V> extends HttpLaneView<V> {
protected final AgentContext agentContext;
protected RestLaneModel laneBinding;
public RestLaneView(AgentContext agentContext, Object observers) {
super(observers);
this.agentContext = agentContext;
}
@Override
public AgentContext agentContext() {
return this.agentContext;
}
@Override
public RestLaneModel laneBinding() {
return this.laneBinding;
}
void setLaneBinding(RestLaneModel laneBinding) {
this.laneBinding = laneBinding;
}
@Override
public RestLaneModel createLaneBinding() {
return new RestLaneModel();
}
@Override
public void close() {
this.laneBinding.closeLaneView(this);
}
@Override
public RestLaneView<V> observe(Object observer) {
super.observe(observer);
return this;
}
@Override
public RestLaneView<V> unobserve(Object observer) {
super.unobserve(observer);
return this;
}
@Override
public RestLaneView<V> decodeRequest(DecodeRequestHttp<V> decodeRequest) {
return observe(decodeRequest);
}
@Override
public RestLaneView<V> willRequest(WillRequestHttp<?> willRequest) {
return observe(willRequest);
}
@Override
public RestLaneView<V> didRequest(DidRequestHttp<V> didRequest) {
return observe(didRequest);
}
@Override
public RestLaneView<V> doRespond(DoRespondHttp<V> doRespond) {
return observe(doRespond);
}
@Override
public RestLaneView<V> willRespond(WillRespondHttp<?> willRespond) {
return observe(willRespond);
}
@Override
public RestLaneView<V> didRespond(DidRespondHttp<?> didRespond) {
return observe(didRespond);
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/http/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.
/**
* HTTP lane and downlink runtime implementations.
*/
package swim.runtime.http;
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/CommandLaneModel.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.runtime.lane;
import swim.api.Link;
import swim.runtime.LaneRelay;
import swim.runtime.WarpBinding;
import swim.runtime.warp.WarpLaneModel;
import swim.structure.Form;
import swim.warp.CommandMessage;
public class CommandLaneModel extends WarpLaneModel<CommandLaneView<?>, CommandLaneUplink> {
@Override
public String laneType() {
return "command";
}
@Override
protected CommandLaneUplink createWarpUplink(WarpBinding link) {
return new CommandLaneUplink(this, link);
}
@Override
protected void didOpenLaneView(CommandLaneView<?> view) {
view.setLaneBinding(this);
}
@Override
public void onCommand(CommandMessage message) {
new CommandLaneRelayCommand(this, null, message).run();
}
}
final class CommandLaneRelayCommand extends LaneRelay<CommandLaneModel, CommandLaneView<?>> {
final Link link;
final CommandMessage message;
Form<?> valueForm;
Object object;
CommandLaneRelayCommand(CommandLaneModel model, Link link, CommandMessage message) {
super(model, 3);
this.link = link;
this.message = message;
}
@SuppressWarnings("unchecked")
@Override
protected boolean runPhase(CommandLaneView<?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneWillCommand(this.message);
}
return view.dispatchWillCommand(this.message.body(), preemptive);
} else if (phase == 1) {
final Form<?> valueForm = view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.object = valueForm.cast(this.message.body());
if (this.object == null) {
this.object = valueForm.unit();
}
}
if (preemptive) {
((CommandLaneView<Object>) view).laneOnCommand(this.object);
}
return ((CommandLaneView<Object>) view).dispatchOnCommand(this.link, this.object, preemptive);
} else if (phase == 2) {
if (preemptive) {
view.laneDidCommand(this.message);
}
return view.dispatchDidCommand(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
this.model.sendDown(this.message.body());
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/CommandLaneUplink.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.runtime.lane;
import swim.concurrent.Stage;
import swim.runtime.WarpBinding;
import swim.runtime.warp.SupplyUplinkModem;
public class CommandLaneUplink extends SupplyUplinkModem {
final CommandLaneModel laneBinding;
public CommandLaneUplink(CommandLaneModel laneBinding, WarpBinding linkBinding) {
super(linkBinding);
this.laneBinding = laneBinding;
}
@Override
public CommandLaneModel laneBinding() {
return this.laneBinding;
}
@Override
public Stage stage() {
return this.laneBinding.stage();
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/CommandLaneView.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.runtime.lane;
import swim.api.Lane;
import swim.api.Link;
import swim.api.SwimContext;
import swim.api.agent.AgentContext;
import swim.api.lane.CommandLane;
import swim.api.warp.function.DidCommand;
import swim.api.warp.function.DidEnter;
import swim.api.warp.function.DidLeave;
import swim.api.warp.function.DidUplink;
import swim.api.warp.function.OnCommand;
import swim.api.warp.function.WillCommand;
import swim.api.warp.function.WillEnter;
import swim.api.warp.function.WillLeave;
import swim.api.warp.function.WillUplink;
import swim.concurrent.Conts;
import swim.runtime.warp.WarpLaneView;
import swim.structure.Form;
public class CommandLaneView<V> extends WarpLaneView implements CommandLane<V> {
protected final AgentContext agentContext;
protected Form<V> valueForm;
protected CommandLaneModel laneBinding;
public CommandLaneView(AgentContext agentContext, Form<V> valueForm, Object observers) {
super(observers);
this.agentContext = agentContext;
this.valueForm = valueForm;
}
public CommandLaneView(AgentContext agentContext, Form<V> valueForm) {
this(agentContext, valueForm, null);
}
@Override
public AgentContext agentContext() {
return this.agentContext;
}
@Override
public CommandLaneModel laneBinding() {
return this.laneBinding;
}
void setLaneBinding(CommandLaneModel laneBinding) {
this.laneBinding = laneBinding;
}
@Override
public CommandLaneModel createLaneBinding() {
return new CommandLaneModel();
}
@Override
public final Form<V> valueForm() {
return this.valueForm;
}
@Override
public <V2> CommandLaneView<V2> valueForm(Form<V2> valueForm) {
return new CommandLaneView<V2>(this.agentContext, valueForm,
typesafeObservers(this.observers));
}
@Override
public <V2> CommandLaneView<V2> valueClass(Class<V2> valueClass) {
return valueForm(Form.<V2>forClass(valueClass));
}
public void setValueForm(Form<V> valueForm) {
this.valueForm = valueForm;
}
protected Object typesafeObservers(Object observers) {
// TODO: filter out OnCommand
return observers;
}
@Override
public void close() {
this.laneBinding.closeLaneView(this);
}
@Override
public CommandLaneView<V> observe(Object observer) {
super.observe(observer);
return this;
}
@Override
public CommandLaneView<V> unobserve(Object observer) {
super.unobserve(observer);
return this;
}
@Override
public CommandLaneView<V> onCommand(OnCommand<V> onCommand) {
return observe(onCommand);
}
@Override
public CommandLaneView<V> willCommand(WillCommand willCommand) {
return observe(willCommand);
}
@Override
public CommandLaneView<V> didCommand(DidCommand didCommand) {
return observe(didCommand);
}
@Override
public CommandLaneView<V> willUplink(WillUplink willUplink) {
return observe(willUplink);
}
@Override
public CommandLaneView<V> didUplink(DidUplink didUplink) {
return observe(didUplink);
}
@Override
public CommandLaneView<V> willEnter(WillEnter willEnter) {
return observe(willEnter);
}
@Override
public CommandLaneView<V> didEnter(DidEnter didEnter) {
return observe(didEnter);
}
@Override
public CommandLaneView<V> willLeave(WillLeave willLeave) {
return observe(willLeave);
}
@Override
public CommandLaneView<V> didLeave(DidLeave didLeave) {
return observe(didLeave);
}
public void laneOnCommand(V value) {
}
@SuppressWarnings("unchecked")
public boolean dispatchOnCommand(Link link, V value, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof OnCommand<?>) {
if (((OnCommand<?>) observers).isPreemptive() == preemptive) {
try {
((OnCommand<V>) observers).onCommand(value);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof OnCommand<?>) {
if (((OnCommand<?>) observer).isPreemptive() == preemptive) {
try {
((OnCommand<V>) observer).onCommand(value);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/DemandLaneModel.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.runtime.lane;
import swim.api.warp.WarpUplink;
import swim.runtime.LaneView;
import swim.runtime.WarpBinding;
import swim.runtime.warp.WarpLaneModel;
import swim.structure.Value;
public class DemandLaneModel extends WarpLaneModel<DemandLaneView<?>, DemandLaneUplink> {
@Override
public String laneType() {
return "demand";
}
@Override
protected DemandLaneUplink createWarpUplink(WarpBinding link) {
return new DemandLaneUplink(this, link);
}
@Override
protected void didOpenLaneView(DemandLaneView<?> view) {
view.setLaneBinding(this);
}
Value nextDownCue(WarpUplink uplink) {
final Object views = this.views;
if (views instanceof DemandLaneView<?>) {
return ((DemandLaneView<?>) views).nextDownCue(uplink);
} else if (views instanceof LaneView[]) {
final LaneView[] viewArray = (LaneView[]) views;
for (int i = 0, n = viewArray.length; i < n; i += 1) {
final Value value = ((DemandLaneView<?>) viewArray[i]).nextDownCue(uplink);
if (value != null) {
return value;
}
}
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/DemandLaneUplink.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.runtime.lane;
import swim.concurrent.Stage;
import swim.runtime.WarpBinding;
import swim.runtime.warp.DemandUplinkModem;
import swim.structure.Value;
import swim.warp.SyncRequest;
public class DemandLaneUplink extends DemandUplinkModem {
final DemandLaneModel laneBinding;
public DemandLaneUplink(DemandLaneModel laneBinding, WarpBinding linkBinding) {
super(linkBinding);
this.laneBinding = laneBinding;
}
@Override
public DemandLaneModel laneBinding() {
return this.laneBinding;
}
@Override
public Stage stage() {
return this.laneBinding.stage();
}
@Override
protected Value nextDownCue() {
return this.laneBinding.nextDownCue(this);
}
@Override
protected void willSync(SyncRequest request) {
cueDown();
super.willSync(request);
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/DemandLaneView.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.runtime.lane;
import swim.api.Lane;
import swim.api.Link;
import swim.api.SwimContext;
import swim.api.agent.AgentContext;
import swim.api.lane.DemandLane;
import swim.api.lane.function.OnCue;
import swim.api.warp.WarpUplink;
import swim.api.warp.function.DidCommand;
import swim.api.warp.function.DidEnter;
import swim.api.warp.function.DidLeave;
import swim.api.warp.function.DidUplink;
import swim.api.warp.function.WillCommand;
import swim.api.warp.function.WillEnter;
import swim.api.warp.function.WillLeave;
import swim.api.warp.function.WillUplink;
import swim.concurrent.Conts;
import swim.runtime.warp.WarpLaneView;
import swim.structure.Form;
import swim.structure.Value;
public class DemandLaneView<V> extends WarpLaneView implements DemandLane<V> {
protected final AgentContext agentContext;
protected Form<V> valueForm;
protected DemandLaneModel laneBinding;
protected volatile OnCue<V> onCue;
public DemandLaneView(AgentContext agentContext, Form<V> valueForm, Object observers) {
super(observers);
this.agentContext = agentContext;
this.valueForm = valueForm;
this.onCue = onCue;
}
public DemandLaneView(AgentContext agentContext, Form<V> valueForm) {
this(agentContext, valueForm, null);
}
@Override
public AgentContext agentContext() {
return this.agentContext;
}
@Override
public DemandLaneModel laneBinding() {
return this.laneBinding;
}
void setLaneBinding(DemandLaneModel laneBinding) {
this.laneBinding = laneBinding;
}
@Override
public DemandLaneModel createLaneBinding() {
return new DemandLaneModel();
}
@Override
public final Form<V> valueForm() {
return this.valueForm;
}
@Override
public <V2> DemandLaneView<V2> valueForm(Form<V2> valueForm) {
return new DemandLaneView<V2>(this.agentContext, valueForm, typesafeObservers(this.observers));
}
@Override
public <V2> DemandLaneView<V2> valueClass(Class<V2> valueClass) {
return valueForm(Form.<V2>forClass(valueClass));
}
public void setValueForm(Form<V> valueForm) {
this.valueForm = valueForm;
}
protected Object typesafeObservers(Object observers) {
// TODO: filter out OnCue
return observers;
}
@Override
public void close() {
this.laneBinding.closeLaneView(this);
}
@Override
public DemandLaneView<V> observe(Object observer) {
super.observe(observer);
return this;
}
@Override
public DemandLaneView<V> unobserve(Object observer) {
super.unobserve(observer);
return this;
}
@Override
public DemandLaneView<V> onCue(OnCue<V> onCue) {
return observe(onCue);
}
@Override
public DemandLaneView<V> willCommand(WillCommand willCommand) {
return observe(willCommand);
}
@Override
public DemandLaneView<V> didCommand(DidCommand didCommand) {
return observe(didCommand);
}
@Override
public DemandLaneView<V> willUplink(WillUplink willUplink) {
return observe(willUplink);
}
@Override
public DemandLaneView<V> didUplink(DidUplink didUplink) {
return observe(didUplink);
}
@Override
public DemandLaneView<V> willEnter(WillEnter willEnter) {
return observe(willEnter);
}
@Override
public DemandLaneView<V> didEnter(DidEnter didEnter) {
return observe(didEnter);
}
@Override
public DemandLaneView<V> willLeave(WillLeave willLeave) {
return observe(willLeave);
}
@Override
public DemandLaneView<V> didLeave(DidLeave didLeave) {
return observe(didLeave);
}
@SuppressWarnings("unchecked")
public V dispatchOnCue(WarpUplink uplink) {
final Lane lane = SwimContext.getLane();
final Link link = SwimContext.getLink();
SwimContext.setLane(this);
SwimContext.setLink(uplink);
try {
final Object observers = this.observers;
if (observers instanceof OnCue<?>) {
try {
final V value = ((OnCue<V>) observers).onCue(uplink);
if (value != null) {
return value;
}
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof OnCue<?>) {
try {
final V value = ((OnCue<V>) observer).onCue(uplink);
if (value != null) {
return value;
}
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
}
}
}
return null;
} finally {
SwimContext.setLink(link);
SwimContext.setLane(lane);
}
}
Value nextDownCue(WarpUplink uplink) {
final V object = dispatchOnCue(uplink);
if (object != null) {
return this.valueForm.mold(object).toValue();
} else {
return null;
}
}
@Override
public void cue() {
this.laneBinding.cueDown();
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/DemandMapLaneModel.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.runtime.lane;
import java.util.Iterator;
import java.util.Map;
import swim.api.warp.WarpUplink;
import swim.collections.FingerTrieSeq;
import swim.runtime.LaneView;
import swim.runtime.WarpBinding;
import swim.runtime.warp.WarpLaneModel;
import swim.structure.Record;
import swim.structure.Value;
public class DemandMapLaneModel extends WarpLaneModel<DemandMapLaneView<?, ?>, DemandMapLaneUplink> {
@Override
public String laneType() {
return "map";
}
@Override
protected DemandMapLaneUplink createWarpUplink(WarpBinding link) {
return new DemandMapLaneUplink(this, link);
}
@Override
protected void didOpenLaneView(DemandMapLaneView<?, ?> view) {
view.setLaneBinding(this);
}
void cueDownKey(Value key) {
FingerTrieSeq<DemandMapLaneUplink> uplinks;
do {
uplinks = this.uplinks;
for (int i = 0, n = uplinks.size(); i < n; i += 1) {
uplinks.get(i).cueDownKey(key);
}
} while (uplinks != this.uplinks);
}
void remove(Value key) {
sendDown(Record.create(1).attr("remove", Record.create(1).slot("key", key)));
}
Value nextDownCue(Value key, WarpUplink uplink) {
final Object views = this.views;
if (views instanceof DemandMapLaneView<?, ?>) {
return ((DemandMapLaneView<?, ?>) views).nextDownCue(key, uplink);
} else if (views instanceof LaneView[]) {
final LaneView[] viewArray = (LaneView[]) views;
for (int i = 0, n = viewArray.length; i < n; i += 1) {
final Value value = ((DemandMapLaneView<?, ?>) viewArray[i]).nextDownCue(key, uplink);
if (value != null) {
return value;
}
}
}
return null;
}
Iterator<Map.Entry<Value, Value>> syncKeys(WarpUplink uplink) {
final Object views = this.views;
if (views instanceof DemandMapLaneView<?, ?>) {
return ((DemandMapLaneView<?, ?>) views).syncKeys(uplink);
} else if (views instanceof LaneView[]) {
final LaneView[] viewArray = (LaneView[]) views;
for (int i = 0, n = viewArray.length; i < n; i += 1) {
final Iterator<Map.Entry<Value, Value>> iterator = ((DemandMapLaneView<?, ?>) viewArray[i]).syncKeys(uplink);
if (iterator != null) {
return iterator;
}
}
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/DemandMapLaneUplink.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.runtime.lane;
import swim.concurrent.Stage;
import swim.runtime.WarpBinding;
import swim.runtime.warp.PartialUplinkModem;
import swim.structure.Attr;
import swim.structure.Record;
import swim.structure.Value;
import swim.warp.SyncRequest;
public class DemandMapLaneUplink extends PartialUplinkModem {
final DemandMapLaneModel laneBinding;
public DemandMapLaneUplink(DemandMapLaneModel laneBinding, WarpBinding linkBinding) {
super(linkBinding);
this.laneBinding = laneBinding;
}
@Override
public DemandMapLaneModel laneBinding() {
return this.laneBinding;
}
@Override
public Stage stage() {
return this.laneBinding.stage();
}
@Override
protected Value nextDownKey(Value key) {
final Value value = this.laneBinding.nextDownCue(key, this);
if (value != null) {
return Attr.of("update", Record.create(1).slot("key", key)).concat(value);
} else {
return null;
}
}
@Override
protected void willSync(SyncRequest request) {
syncDown(this.laneBinding.syncKeys(this));
super.willSync(request);
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/DemandMapLaneView.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.runtime.lane;
import java.util.Iterator;
import java.util.Map;
import swim.api.Lane;
import swim.api.Link;
import swim.api.SwimContext;
import swim.api.agent.AgentContext;
import swim.api.lane.DemandMapLane;
import swim.api.lane.function.OnCueKey;
import swim.api.lane.function.OnSyncMap;
import swim.api.warp.WarpUplink;
import swim.api.warp.function.DidCommand;
import swim.api.warp.function.DidEnter;
import swim.api.warp.function.DidLeave;
import swim.api.warp.function.DidUplink;
import swim.api.warp.function.WillCommand;
import swim.api.warp.function.WillEnter;
import swim.api.warp.function.WillLeave;
import swim.api.warp.function.WillUplink;
import swim.concurrent.Conts;
import swim.runtime.warp.WarpLaneView;
import swim.structure.Form;
import swim.structure.Slot;
import swim.structure.Value;
public class DemandMapLaneView<K, V> extends WarpLaneView implements DemandMapLane<K, V> {
protected final AgentContext agentContext;
protected Form<K> keyForm;
protected Form<V> valueForm;
protected DemandMapLaneModel laneBinding;
public DemandMapLaneView(AgentContext agentContext, Form<K> keyForm, Form<V> valueForm, Object observers) {
super(observers);
this.agentContext = agentContext;
this.keyForm = keyForm;
this.valueForm = valueForm;
}
public DemandMapLaneView(AgentContext agentContext, Form<K> keyForm, Form<V> valueForm) {
this(agentContext, keyForm, valueForm, null);
}
@Override
public AgentContext agentContext() {
return this.agentContext;
}
@Override
public DemandMapLaneModel laneBinding() {
return this.laneBinding;
}
void setLaneBinding(DemandMapLaneModel laneBinding) {
this.laneBinding = laneBinding;
}
@Override
public DemandMapLaneModel createLaneBinding() {
return new DemandMapLaneModel();
}
@Override
public final Form<K> keyForm() {
return this.keyForm;
}
@Override
public <K2> DemandMapLaneView<K2, V> keyForm(Form<K2> keyForm) {
return new DemandMapLaneView<K2, V>(this.agentContext, keyForm, this.valueForm,
typesafeObservers(this.observers));
}
@Override
public <K2> DemandMapLaneView<K2, V> keyClass(Class<K2> keyClass) {
return keyForm(Form.<K2>forClass(keyClass));
}
public void setKeyForm(Form<K> keyForm) {
this.keyForm = keyForm;
}
@Override
public final Form<V> valueForm() {
return this.valueForm;
}
@Override
public <V2> DemandMapLaneView<K, V2> valueForm(Form<V2> valueForm) {
return new DemandMapLaneView<K, V2>(this.agentContext, this.keyForm, valueForm,
typesafeObservers(this.observers));
}
@Override
public <V2> DemandMapLaneView<K, V2> valueClass(Class<V2> valueClass) {
return valueForm(Form.<V2>forClass(valueClass));
}
public void setValueForm(Form<V> valueForm) {
this.valueForm = valueForm;
}
protected Object typesafeObservers(Object observers) {
// TODO: filter out OnCueKey, OnSyncMap
return observers;
}
@Override
public void close() {
this.laneBinding.closeLaneView(this);
}
@Override
public DemandMapLaneView<K, V> observe(Object observer) {
super.observe(observer);
return this;
}
@Override
public DemandMapLaneView<K, V> unobserve(Object observer) {
super.unobserve(observer);
return this;
}
@Override
public DemandMapLaneView<K, V> onCue(OnCueKey<K, V> onCue) {
return observe(onCue);
}
@Override
public DemandMapLaneView<K, V> onSync(OnSyncMap<K, V> onSync) {
return observe(onSync);
}
@Override
public DemandMapLaneView<K, V> willCommand(WillCommand willCommand) {
return observe(willCommand);
}
@Override
public DemandMapLaneView<K, V> didCommand(DidCommand didCommand) {
return observe(didCommand);
}
@Override
public DemandMapLaneView<K, V> willUplink(WillUplink willUplink) {
return observe(willUplink);
}
@Override
public DemandMapLaneView<K, V> didUplink(DidUplink didUplink) {
return observe(didUplink);
}
@Override
public DemandMapLaneView<K, V> willEnter(WillEnter willEnter) {
return observe(willEnter);
}
@Override
public DemandMapLaneView<K, V> didEnter(DidEnter didEnter) {
return observe(didEnter);
}
@Override
public DemandMapLaneView<K, V> willLeave(WillLeave willLeave) {
return observe(willLeave);
}
@Override
public DemandMapLaneView<K, V> didLeave(DidLeave didLeave) {
return observe(didLeave);
}
@SuppressWarnings("unchecked")
public V dispatchOnCue(K key, WarpUplink uplink) {
final Lane lane = SwimContext.getLane();
final Link link = SwimContext.getLink();
SwimContext.setLane(this);
SwimContext.setLink(uplink);
try {
final Object observers = this.observers;
if (observers instanceof OnCueKey<?, ?>) {
try {
final V value = ((OnCueKey<K, V>) observers).onCue(key, uplink);
if (value != null) {
return value;
}
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof OnCueKey<?, ?>) {
try {
final V value = ((OnCueKey<K, V>) observer).onCue(key, uplink);
if (value != null) {
return value;
}
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
}
}
}
return null;
} finally {
SwimContext.setLink(link);
SwimContext.setLane(lane);
}
}
@SuppressWarnings("unchecked")
public Iterator<Map.Entry<K, V>> dispatchOnSync(WarpUplink uplink) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
SwimContext.setLane(this);
SwimContext.setLink(uplink);
try {
final Object observers = this.observers;
if (observers instanceof OnSyncMap<?, ?>) {
try {
final Iterator<Map.Entry<K, V>> iterator = ((OnSyncMap<K, V>) observers).onSync(uplink);
if (iterator != null) {
return iterator;
}
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof OnSyncMap<?, ?>) {
try {
final Iterator<Map.Entry<K, V>> iterator = ((OnSyncMap<K, V>) observer).onSync(uplink);
if (iterator != null) {
return iterator;
}
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
}
}
}
return null;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
Value nextDownCue(Value key, WarpUplink uplink) {
final K keyObject = this.keyForm.cast(key);
final V object = dispatchOnCue(keyObject, uplink);
if (object != null) {
return this.valueForm.mold(object).toValue();
} else {
return null;
}
}
@SuppressWarnings("unchecked")
Iterator<Map.Entry<Value, Value>> syncKeys(WarpUplink uplink) {
final Iterator<Map.Entry<K, V>> iterator = dispatchOnSync(uplink);
if (iterator != null) {
if (this.keyForm == Form.forValue() && this.valueForm == Form.forValue()) {
return (Iterator<Map.Entry<Value, Value>>) (Iterator<?>) iterator;
} else {
return new DemandMapLaneIterator<K, V>(iterator, this.keyForm, this.valueForm);
}
}
return null;
}
@Override
public void cue(K key) {
this.laneBinding.cueDownKey(this.keyForm.mold(key).toValue());
}
@Override
public void remove(K key) {
this.laneBinding.remove(this.keyForm.mold(key).toValue());
}
}
final class DemandMapLaneIterator<K, V> implements Iterator<Map.Entry<Value, Value>> {
final Iterator<Map.Entry<K, V>> inner;
final Form<K> keyForm;
final Form<V> valueForm;
DemandMapLaneIterator(Iterator<Map.Entry<K, V>> inner, Form<K> keyForm, Form<V> valueForm) {
this.inner = inner;
this.keyForm = keyForm;
this.valueForm = valueForm;
}
@Override
public boolean hasNext() {
return this.inner.hasNext();
}
@Override
public Map.Entry<Value, Value> next() {
final Map.Entry<K, V> entry = this.inner.next();
final Value key = this.keyForm.mold(entry.getKey()).toValue();
final Value value = this.valueForm.mold(entry.getValue()).toValue();
return Slot.of(key, value);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/JoinMapLaneDownlink.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.runtime.lane;
import swim.concurrent.Stage;
import swim.runtime.CellContext;
import swim.runtime.downlink.MapDownlinkView;
import swim.structure.Form;
import swim.structure.Value;
import swim.uri.Uri;
public class JoinMapLaneDownlink<K, V> extends MapDownlinkView<K, V> {
protected final JoinMapLaneModel laneModel;
protected final Value key;
public JoinMapLaneDownlink(CellContext cellContext, Stage stage, JoinMapLaneModel laneModel,
Value key, Uri meshUri, Uri hostUri, Uri nodeUri, Uri laneUri,
float prio, float rate, Value body, int flags, Form<K> keyForm,
Form<V> valueForm, Object observers) {
super(cellContext, stage, meshUri, hostUri, nodeUri, laneUri, prio, rate,
body, flags, keyForm, valueForm, observers);
this.laneModel = laneModel;
this.key = key;
}
public JoinMapLaneDownlink(CellContext cellContext, Stage stage, JoinMapLaneModel laneModel,
Value key, Uri meshUri, Uri hostUri, Uri nodeUri, Uri laneUri,
float prio, float rate, Value body, Form<K> keyForm, Form<V> valueForm) {
this(cellContext, stage, laneModel, key, meshUri, hostUri, nodeUri, laneUri,
prio, rate, body, KEEP_LINKED | KEEP_SYNCED, keyForm, valueForm, null);
}
@Override
public MapDownlinkView<K, V> hostUri(Uri hostUri) {
return new JoinMapLaneDownlink<K, V>(this.cellContext, this.stage, this.laneModel,
this.key, this.meshUri, hostUri, this.nodeUri,
this.laneUri, this.prio, this.rate, this.body,
this.flags, this.keyForm, this.valueForm, this.observers);
}
@Override
public MapDownlinkView<K, V> nodeUri(Uri nodeUri) {
return new JoinMapLaneDownlink<K, V>(this.cellContext, this.stage, this.laneModel,
this.key, this.meshUri, this.hostUri, nodeUri,
this.laneUri, this.prio, this.rate, this.body,
this.flags, this.keyForm, this.valueForm, this.observers);
}
@Override
public MapDownlinkView<K, V> laneUri(Uri laneUri) {
return new JoinMapLaneDownlink<K, V>(this.cellContext, this.stage, this.laneModel,
this.key, this.meshUri, this.hostUri, this.nodeUri,
laneUri, this.prio, this.rate, this.body,
this.flags, this.keyForm, this.valueForm, this.observers);
}
@Override
public MapDownlinkView<K, V> prio(float prio) {
return new JoinMapLaneDownlink<K, V>(this.cellContext, this.stage, this.laneModel,
this.key, this.meshUri, this.hostUri, this.nodeUri,
this.laneUri, prio, this.rate, this.body,
this.flags, this.keyForm, this.valueForm, this.observers);
}
@Override
public MapDownlinkView<K, V> rate(float rate) {
return new JoinMapLaneDownlink<K, V>(this.cellContext, this.stage, this.laneModel,
this.key, this.meshUri, this.hostUri, this.nodeUri,
this.laneUri, this.prio, rate, this.body,
this.flags, this.keyForm, this.valueForm, this.observers);
}
@Override
public MapDownlinkView<K, V> body(Value body) {
return new JoinMapLaneDownlink<K, V>(this.cellContext, this.stage, this.laneModel,
this.key, this.meshUri, this.hostUri, this.nodeUri,
this.laneUri, this.prio, this.rate, body,
this.flags, this.keyForm, this.valueForm, this.observers);
}
@Override
public <K2> MapDownlinkView<K2, V> keyForm(Form<K2> keyForm) {
return new JoinMapLaneDownlink<K2, V>(this.cellContext, this.stage, this.laneModel,
this.key, this.meshUri, this.hostUri, this.nodeUri,
this.laneUri, this.prio, this.rate, this.body,
this.flags, keyForm, this.valueForm,
typesafeObservers(this.observers));
}
@Override
public <V2> MapDownlinkView<K, V2> valueForm(Form<V2> valueForm) {
return new JoinMapLaneDownlink<K, V2>(this.cellContext, this.stage, this.laneModel,
this.key, this.meshUri, this.hostUri, this.nodeUri,
this.laneUri, this.prio, this.rate, this.body,
this.flags, this.keyForm, valueForm,
typesafeObservers(this.observers));
}
@Override
public Value downlinkWillUpdateValue(Value key, Value newValue) {
return newValue;
}
@Override
public void downlinkDidUpdateValue(Value key, Value newValue, Value oldValue) {
this.laneModel.put(this, key, newValue);
}
@Override
public void downlinkWillRemoveValue(Value key) {
}
@Override
public void downlinkDidRemoveValue(Value key, Value oldValue) {
this.laneModel.remove(this, key);
}
@Override
public void downlinkWillDrop(int lower) {
}
@Override
public void downlinkDidDrop(int lower) {
}
@Override
public void downlinkWillTake(int upper) {
}
@Override
public void downlinkDidTake(int upper) {
}
@Override
public void downlinkWillClear() {
}
@Override
public void downlinkDidClear() {
//this.laneModel.clear(this);
}
@Override
public MapDownlinkView<K, V> open() {
this.laneModel.downlink(this.key, this);
return this;
}
protected void openDownlink() {
super.open();
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/JoinMapLaneModel.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.runtime.lane;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import swim.api.Link;
import swim.api.data.MapData;
import swim.api.downlink.MapDownlink;
import swim.collections.FingerTrieSeq;
import swim.collections.HashTrieMap;
import swim.concurrent.Stage;
import swim.runtime.LaneRelay;
import swim.runtime.LaneView;
import swim.runtime.WarpBinding;
import swim.runtime.warp.WarpLaneModel;
import swim.structure.Form;
import swim.structure.Record;
import swim.structure.Value;
import swim.uri.Uri;
import swim.warp.CommandMessage;
public class JoinMapLaneModel extends WarpLaneModel<JoinMapLaneView<?, ?, ?>, JoinMapLaneUplink> {
protected int flags;
protected MapData<Value, Value> data;
protected MapData<Value, Value> linkData;
protected volatile HashTrieMap<Value, JoinMapLaneDownlink<?, ?>> downlinks;
JoinMapLaneModel(int flags) {
this.flags = flags;
this.downlinks = HashTrieMap.empty();
}
public JoinMapLaneModel() {
this(0);
}
@Override
public String laneType() {
return "map";
}
@Override
protected JoinMapLaneUplink createWarpUplink(WarpBinding link) {
return new JoinMapLaneUplink(this, link);
}
protected void openDownlinks() {
for (Map.Entry<Value, Value> entry : this.linkData) {
final Value key = entry.getKey();
final Value value = entry.getValue();
final Value header = value.header("downlink");
final Uri nodeUri = header.get("node").coerce(Uri.form());
final Uri laneUri = header.get("lane").coerce(Uri.form());
final float prio = header.get("prio").floatValue(0.0f);
final float rate = header.get("rate").floatValue(0.0f);
final Value body = header.get("body");
new JoinMapLaneDownlink<Value, Value>(this.laneContext, stage(), this, key,
this.laneContext.meshUri(), this.laneContext.hostUri(), nodeUri, laneUri,
prio, rate, body, Form.forValue(), Form.forValue()).openDownlink();
}
}
protected void downlink(Value key, JoinMapLaneDownlink<?, ?> downlink) {
Value value = this.linkData.get(key);
Record header = value.headers("downlink");
if (header == null
|| !header.get("node").coerce(Uri.form()).equals(downlink.nodeUri())
|| !header.get("lane").coerce(Uri.form()).equals(downlink.laneUri())
|| header.get("prio").floatValue(0.0f) != downlink.prio()
|| header.get("rate").floatValue(0.0f) != downlink.rate()
|| !header.get("body").equals(downlink.body())) {
header = Record.of()
.slot("node", downlink.nodeUri().toString())
.slot("lane", downlink.laneUri().toString());
if (downlink.prio() != 0.0f) {
header.slot("prio", downlink.prio());
}
if (downlink.rate() != 0.0f) {
header.slot("rate", downlink.rate());
}
if (downlink.body().isDefined()) {
header.slot("body", downlink.body());
}
if ("downlink".equals(value.tag())) {
value = value.updatedAttr("downlink", header);
} else {
value = Record.of().attr("downlink", header).concat(value);
}
this.linkData.put(key, value);
}
new JoinMapLaneRelayDownlink(this, key, downlink).run();
}
protected void openDownlink(Value key, JoinMapLaneDownlink<?, ?> downlink) {
downlink.openDownlink(); // Open before CAS
HashTrieMap<Value, JoinMapLaneDownlink<?, ?>> oldDownlinks;
HashTrieMap<Value, JoinMapLaneDownlink<?, ?>> newDownlinks;
do {
oldDownlinks = this.downlinks;
newDownlinks = oldDownlinks.updated(key, downlink);
} while (oldDownlinks != newDownlinks && !DOWNLINKS.compareAndSet(this, oldDownlinks, newDownlinks));
if (oldDownlinks != newDownlinks) {
final JoinMapLaneDownlink<?, ?> oldDownlink = oldDownlinks.get(key);
if (oldDownlink != null) {
try {
oldDownlink.close();
} catch (Exception swallow) { }
}
}
}
protected void closeDownlinks() {
HashTrieMap<Value, JoinMapLaneDownlink<?, ?>> oldDownlinks;
final HashTrieMap<Value, JoinMapLaneDownlink<?, ?>> newDownlinks = HashTrieMap.empty();
do {
oldDownlinks = this.downlinks;
} while (oldDownlinks != newDownlinks && !DOWNLINKS.compareAndSet(this, oldDownlinks, newDownlinks));
if (!oldDownlinks.isEmpty()) {
for (JoinMapLaneDownlink<?, ?> downlink : oldDownlinks.values()) {
try {
downlink.close();
} catch (Exception swallow) { }
}
}
}
protected void closeDownlinkKey(Value key) {
HashTrieMap<Value, JoinMapLaneDownlink<?, ?>> oldDownlinks;
HashTrieMap<Value, JoinMapLaneDownlink<?, ?>> newDownlinks;
do {
oldDownlinks = this.downlinks;
newDownlinks = oldDownlinks.removed(key);
} while (oldDownlinks != newDownlinks && !DOWNLINKS.compareAndSet(this, oldDownlinks, newDownlinks));
if (oldDownlinks != newDownlinks) {
final JoinMapLaneDownlink<?, ?> downlink = oldDownlinks.get(key);
try {
downlink.close();
} catch (Exception swallow) { }
}
}
@Override
protected void didOpenLaneView(JoinMapLaneView<?, ?, ?> view) {
view.setLaneBinding(this);
}
@Override
public void onCommand(CommandMessage message) {
final Value payload = message.body();
final String tag = payload.tag();
if ("update".equals(tag)) {
final Value header = payload.header("update");
final Value key = header.get("key");
final Value value = payload.body();
new JoinMapLaneRelayUpdate(this, message, key, value).run();
} else if ("remove".equals(tag)) {
final Value header = payload.header("remove");
final Value key = header.get("key");
new JoinMapLaneRelayRemove(this, message, key).run();
} else if ("clear".equals(tag)) {
new JoinMapLaneRelayClear(this, message).run();
}
}
protected void cueDownKey(Value key) {
FingerTrieSeq<JoinMapLaneUplink> uplinks;
do {
uplinks = this.uplinks;
for (int i = 0, n = uplinks.size(); i < n; i += 1) {
uplinks.get(i).cueDownKey(key);
}
} while (uplinks != this.uplinks);
}
public final boolean isResident() {
return (this.flags & RESIDENT) != 0;
}
public JoinMapLaneModel isResident(boolean isResident) {
if (this.data != null) {
this.data.isResident(isResident);
}
if (this.linkData != null) {
this.linkData.isResident(isResident);
}
if (isResident) {
this.flags |= RESIDENT;
} else {
this.flags &= ~RESIDENT;
}
final Object views = this.views;
if (views instanceof ValueLaneView<?>) {
((ValueLaneView<?>) views).didSetResident(isResident);
} else if (views instanceof LaneView[]) {
final LaneView[] viewArray = (LaneView[]) views;
for (int i = 0, n = viewArray.length; i < n; i += 1) {
((ValueLaneView<?>) viewArray[i]).didSetResident(isResident);
}
}
return this;
}
public final boolean isTransient() {
return (this.flags & TRANSIENT) != 0;
}
public JoinMapLaneModel isTransient(boolean isTransient) {
if (this.data != null) {
this.data.isTransient(isTransient);
}
if (this.linkData != null) {
this.linkData.isTransient(isTransient);
}
if (isTransient) {
this.flags |= TRANSIENT;
} else {
this.flags &= ~TRANSIENT;
}
final Object views = this.views;
if (views instanceof ValueLaneView<?>) {
((ValueLaneView<?>) views).didSetTransient(isTransient);
} else if (views instanceof LaneView[]) {
final LaneView[] viewArray = (LaneView[]) views;
for (int i = 0, n = viewArray.length; i < n; i += 1) {
((ValueLaneView<?>) viewArray[i]).didSetTransient(isTransient);
}
}
return this;
}
public Value get(Object key) {
if (key != null) {
return this.data.get(key);
} else {
return Value.absent();
}
}
public JoinMapLaneDownlink<?, ?> getDownlink(Object key) {
return this.downlinks.get(key);
}
public void put(JoinMapLaneDownlink<?, ?> downlink, Value key, Value newValue) {
final JoinMapLaneRelayUpdate relay = new JoinMapLaneRelayUpdate(this, downlink, key, newValue);
relay.run();
}
@SuppressWarnings("unchecked")
public <K, V> V put(JoinMapLaneView<?, K, V> view, K keyObject, V newObject) {
final Form<K> keyForm = view.keyForm;
final Form<V> valueForm = view.valueForm;
final Value key = keyForm.mold(keyObject).toValue();
final Value newValue = valueForm.mold(newObject).toValue();
final JoinMapLaneRelayUpdate relay = new JoinMapLaneRelayUpdate(this, stage(), key, newValue);
relay.keyForm = (Form<Object>) keyForm;
relay.valueForm = (Form<Object>) valueForm;
relay.keyObject = keyObject;
relay.oldObject = newObject;
relay.newObject = newObject;
relay.run();
if (relay.valueForm != valueForm && valueForm != null) {
relay.oldObject = valueForm.cast(relay.oldValue);
if (relay.oldObject == null) {
relay.oldObject = valueForm.unit();
}
}
return (V) relay.oldObject;
}
public void remove(JoinMapLaneDownlink<?, ?> downlink, Value key) {
final JoinMapLaneRelayRemove relay = new JoinMapLaneRelayRemove(this, downlink, key);
relay.run();
}
@SuppressWarnings("unchecked")
public <K, V> V remove(JoinMapLaneView<?, K, V> view, K keyObject) {
final Form<K> keyForm = view.keyForm;
final Form<V> valueForm = view.valueForm;
final Value key = keyForm.mold(keyObject).toValue();
final JoinMapLaneRelayRemove relay = new JoinMapLaneRelayRemove(this, stage(), key);
relay.keyForm = (Form<Object>) keyForm;
relay.valueForm = (Form<Object>) valueForm;
relay.keyObject = keyObject;
relay.run();
if (relay.valueForm == valueForm) {
return (V) relay.oldObject;
} else {
return null;
}
}
public void clear(JoinMapLaneDownlink<?, ?> downlink) {
final JoinMapLaneRelayClear relay = new JoinMapLaneRelayClear(this, downlink);
relay.run();
}
public void clear(JoinMapLaneView<?, ?, ?> view) {
final JoinMapLaneRelayClear relay = new JoinMapLaneRelayClear(this, stage());
relay.run();
}
public Iterator<Map.Entry<Value, Value>> iterator() {
return this.data.iterator();
}
protected void openStore() {
this.data = this.laneContext.store().mapData(laneUri().toString())
.isTransient(isTransient())
.isResident(isResident());
this.linkData = this.laneContext.store().mapData(Record.create(1).attr("join", laneUri().toString()))
.isTransient(isTransient())
.isResident(isResident());
}
@Override
protected void willLoad() {
openStore();
super.willLoad();
}
@Override
protected void willStart() {
super.willStart();
openDownlinks();
}
static final int RESIDENT = 1 << 0;
static final int TRANSIENT = 1 << 1;
static final int SIGNED = 1 << 2;
@SuppressWarnings("unchecked")
static final AtomicReferenceFieldUpdater<JoinMapLaneModel, HashTrieMap<Value, JoinMapLaneDownlink<?, ?>>> DOWNLINKS =
AtomicReferenceFieldUpdater.newUpdater(JoinMapLaneModel.class, (Class<HashTrieMap<Value, JoinMapLaneDownlink<?, ?>>>) (Class<?>) HashTrieMap.class, "downlinks");
}
final class JoinMapLaneRelayUpdate extends LaneRelay<JoinMapLaneModel, JoinMapLaneView<?, ?, ?>> {
final Link link;
final CommandMessage message;
Form<Object> keyForm;
Form<Object> valueForm;
final Value key;
Object keyObject;
Value oldValue;
Object oldObject;
Value newValue;
Object newObject;
JoinMapLaneRelayUpdate(JoinMapLaneModel model, CommandMessage message, Value key, Value newValue) {
super(model, 4);
this.link = null;
this.message = message;
this.key = key;
this.newValue = newValue;
}
JoinMapLaneRelayUpdate(JoinMapLaneModel model, Link link, Value key, Value newValue) {
super(model, 1, 3, null);
this.link = link;
this.message = null;
this.key = key;
this.newValue = newValue;
}
JoinMapLaneRelayUpdate(JoinMapLaneModel model, Stage stage, Value key, Value newValue) {
super(model, 1, 3, stage);
this.link = null;
this.message = null;
this.key = key;
this.newValue = newValue;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
this.oldValue = this.model.data.put(this.key, this.newValue);
if (this.oldValue == null) {
this.oldValue = Value.absent();
}
}
}
@SuppressWarnings("unchecked")
@Override
protected boolean runPhase(JoinMapLaneView<?, ?, ?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneWillCommand(this.message);
}
return view.dispatchWillCommand(this.message.body(), preemptive);
} else if (phase == 1) {
final Form<Object> keyForm = (Form<Object>) view.keyForm;
if (this.keyForm != keyForm && keyForm != null) {
this.keyForm = keyForm;
this.keyObject = keyForm.cast(this.key);
if (this.keyObject == null) {
this.keyObject = keyForm.unit();
}
}
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.oldObject = valueForm.cast(this.newValue);
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
}
if (preemptive) {
this.newObject = ((JoinMapLaneView<Object, Object, Object>) view).laneWillUpdate(this.keyObject, this.oldObject);
}
final Map.Entry<Boolean, Object> result = ((JoinMapLaneView<Object, Object, Object>) view).dispatchWillUpdate(this.link, this.keyObject, this.oldObject, preemptive);
this.newObject = result.getValue();
if (this.oldObject != this.newObject) {
this.oldObject = this.newObject;
this.newValue = valueForm.mold(this.newObject).toValue();
}
return result.getKey();
} else if (phase == 2) {
final Form<Object> keyForm = (Form<Object>) view.keyForm;
if (this.keyForm != keyForm && keyForm != null) {
this.keyForm = keyForm;
this.keyObject = keyForm.cast(this.key);
if (this.keyObject == null) {
this.keyObject = keyForm.unit();
}
}
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.oldObject = valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
this.newObject = valueForm.cast(this.newValue);
if (this.newObject == null) {
this.newObject = valueForm.unit();
}
}
if (preemptive) {
((JoinMapLaneView<Object, Object, Object>) view).laneDidUpdate(this.keyObject, this.newObject, this.oldObject);
}
return ((JoinMapLaneView<Object, Object, Object>) view).dispatchDidUpdate(this.link, this.keyObject, this.newObject, this.oldObject, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.laneDidCommand(this.message);
}
return view.dispatchDidCommand(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
this.model.cueDownKey(this.key);
}
}
final class JoinMapLaneRelayRemove extends LaneRelay<JoinMapLaneModel, JoinMapLaneView<?, ?, ?>> {
final Link link;
final CommandMessage message;
Form<Object> keyForm;
Form<Object> valueForm;
final Value key;
Object keyObject;
Value oldValue;
Object oldObject;
JoinMapLaneRelayRemove(JoinMapLaneModel model, CommandMessage message, Value key) {
super(model, 4);
this.link = null;
this.message = message;
this.key = key;
}
JoinMapLaneRelayRemove(JoinMapLaneModel model, Link link, Value key) {
super(model, 1, 3, null);
this.link = link;
this.message = null;
this.key = key;
}
JoinMapLaneRelayRemove(JoinMapLaneModel model, Stage stage, Value key) {
super(model, 1, 3, null);
this.link = null;
this.message = null;
this.key = key;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
this.oldValue = this.model.data.remove(this.key);
if (this.oldValue == null) {
this.oldValue = Value.absent();
}
if (this.valueForm != null) {
this.oldObject = this.valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = this.valueForm.unit();
}
}
}
}
@SuppressWarnings("unchecked")
@Override
protected boolean runPhase(JoinMapLaneView<?, ?, ?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneWillCommand(this.message);
}
return view.dispatchWillCommand(this.message.body(), preemptive);
} else if (phase == 1) {
final Form<Object> keyForm = (Form<Object>) view.keyForm;
if (this.keyForm != keyForm && keyForm != null) {
this.keyForm = keyForm;
this.keyObject = keyForm.cast(this.key);
if (this.keyObject == null) {
this.keyObject = keyForm.unit();
}
}
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
if (this.oldValue != null) {
this.oldObject = valueForm.cast(this.oldValue);
}
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
}
if (preemptive) {
((JoinMapLaneView<Object, Object, Object>) view).laneWillRemove(this.keyObject);
}
return ((JoinMapLaneView<Object, Object, Object>) view).dispatchWillRemove(this.link, this.keyObject, preemptive);
} else if (phase == 2) {
final Form<Object> keyForm = (Form<Object>) view.keyForm;
if (this.keyForm != keyForm && keyForm != null) {
this.keyForm = keyForm;
this.keyObject = keyForm.cast(this.key);
if (this.keyObject == null) {
this.keyObject = keyForm.unit();
}
}
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.oldObject = valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
}
if (preemptive) {
((JoinMapLaneView<Object, Object, Object>) view).laneDidRemove(this.keyObject, this.oldObject);
}
return ((JoinMapLaneView<Object, Object, Object>) view).dispatchDidRemove(this.link, this.keyObject, this.oldObject, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.laneDidCommand(this.message);
}
return view.dispatchDidCommand(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
if (this.oldValue.isDefined()) {
this.model.sendDown(Record.create(1).attr("remove", Record.create(1).slot("key", this.key)));
}
}
}
final class JoinMapLaneRelayClear extends LaneRelay<JoinMapLaneModel, JoinMapLaneView<?, ?, ?>> {
final Link link;
final CommandMessage message;
JoinMapLaneRelayClear(JoinMapLaneModel model, CommandMessage message) {
super(model, 4);
this.link = null;
this.message = message;
}
JoinMapLaneRelayClear(JoinMapLaneModel model, Link link) {
super(model, 1, 3, null);
this.link = link;
this.message = null;
}
JoinMapLaneRelayClear(JoinMapLaneModel model, Stage stage) {
super(model, 1, 3, stage);
this.link = null;
this.message = null;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
this.model.closeDownlinks();
this.model.data.clear();
}
}
@Override
protected boolean runPhase(JoinMapLaneView<?, ?, ?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneWillCommand(this.message);
}
return view.dispatchWillCommand(this.message.body(), preemptive);
} else if (phase == 1) {
if (preemptive) {
view.laneWillClear();
}
return view.dispatchWillClear(this.link, preemptive);
} else if (phase == 2) {
if (preemptive) {
view.laneDidClear();
}
return view.dispatchDidClear(this.link, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.laneDidCommand(this.message);
}
return view.dispatchDidCommand(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
this.model.sendDown(Record.create(1).attr("clear"));
}
}
final class JoinMapLaneRelayDownlink extends LaneRelay<JoinMapLaneModel, JoinMapLaneView<?, ?, ?>> {
Form<Object> keyForm;
final Value key;
Object keyObject;
JoinMapLaneDownlink<Object, Object> downlink;
@SuppressWarnings("unchecked")
JoinMapLaneRelayDownlink(JoinMapLaneModel model, Value key, JoinMapLaneDownlink<?, ?> downlink) {
super(model, 2);
this.key = key;
this.downlink = (JoinMapLaneDownlink<Object, Object>) downlink;
}
@Override
protected void beginPhase(int phase) {
if (phase == 1) {
this.model.openDownlink(this.key, this.downlink);
}
}
@SuppressWarnings("unchecked")
@Override
protected boolean runPhase(JoinMapLaneView<?, ?, ?> view, int phase, boolean preemptive) {
if (phase == 0) {
final Form<Object> keyForm = (Form<Object>) view.keyForm;
if (this.keyForm != keyForm && keyForm != null) {
this.keyForm = keyForm;
this.keyObject = keyForm.cast(key);
if (this.keyObject == null) {
this.keyObject = keyForm.unit();
}
}
if (preemptive) {
this.downlink = (JoinMapLaneDownlink<Object, Object>) ((JoinMapLaneView<Object, Object, Object>) view).laneWillDownlink(this.keyObject, this.downlink);
}
final Map.Entry<Boolean, MapDownlink<?, ?>> result = ((JoinMapLaneView<Object, Object, Object>) view).dispatchWillDownlink(this.keyObject, this.downlink, preemptive);
this.downlink = (JoinMapLaneDownlink<Object, Object>) result.getValue();
return result.getKey();
} else if (phase == 1) {
final Form<Object> keyForm = (Form<Object>) view.keyForm;
if (this.keyForm != keyForm && keyForm != null) {
this.keyForm = keyForm;
this.keyObject = keyForm.cast(key);
if (this.keyObject == null) {
this.keyObject = keyForm.unit();
}
}
if (preemptive) {
((JoinMapLaneView<Object, Object, Object>) view).laneDidDownlink(this.keyObject, this.downlink);
}
return ((JoinMapLaneView<Object, Object, Object>) view).dispatchDidDownlink(this.keyObject, this.downlink, preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/JoinMapLaneUplink.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.runtime.lane;
import swim.concurrent.Stage;
import swim.runtime.WarpBinding;
import swim.runtime.warp.PartialUplinkModem;
import swim.structure.Attr;
import swim.structure.Record;
import swim.structure.Value;
import swim.warp.SyncRequest;
public class JoinMapLaneUplink extends PartialUplinkModem {
final JoinMapLaneModel laneBinding;
public JoinMapLaneUplink(JoinMapLaneModel laneBinding, WarpBinding linkBinding) {
super(linkBinding);
this.laneBinding = laneBinding;
}
@Override
public JoinMapLaneModel laneBinding() {
return this.laneBinding;
}
@Override
public Stage stage() {
return this.laneBinding.stage();
}
@Override
protected Value nextDownKey(Value key) {
final Value value = this.laneBinding.get(key);
if (value != null) {
return Attr.of("update", Record.create(1).slot("key", key)).concat(value);
} else {
return null;
}
}
@Override
protected void willSync(SyncRequest request) {
syncDown(this.laneBinding.iterator());
super.willSync(request);
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/JoinMapLaneView.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.runtime.lane;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import swim.api.Lane;
import swim.api.Link;
import swim.api.SwimContext;
import swim.api.agent.AgentContext;
import swim.api.data.MapData;
import swim.api.downlink.MapDownlink;
import swim.api.lane.JoinMapLane;
import swim.api.lane.function.DidDownlinkMap;
import swim.api.lane.function.WillDownlinkMap;
import swim.api.warp.function.DidCommand;
import swim.api.warp.function.DidEnter;
import swim.api.warp.function.DidLeave;
import swim.api.warp.function.DidUplink;
import swim.api.warp.function.WillCommand;
import swim.api.warp.function.WillEnter;
import swim.api.warp.function.WillLeave;
import swim.api.warp.function.WillUplink;
import swim.concurrent.Conts;
import swim.observable.function.DidClear;
import swim.observable.function.DidRemoveKey;
import swim.observable.function.DidUpdateKey;
import swim.observable.function.WillClear;
import swim.observable.function.WillRemoveKey;
import swim.observable.function.WillUpdateKey;
import swim.runtime.LaneContext;
import swim.runtime.warp.WarpLaneView;
import swim.structure.Form;
import swim.structure.Value;
import swim.uri.Uri;
public class JoinMapLaneView<L, K, V> extends WarpLaneView implements JoinMapLane<L, K, V> {
protected final AgentContext agentContext;
protected Form<L> linkForm;
protected Form<K> keyForm;
protected Form<V> valueForm;
protected int flags;
protected JoinMapLaneModel laneBinding;
protected MapData<K, V> dataView;
JoinMapLaneView(AgentContext agentContext, Form<L> linkForm, Form<K> keyForm,
Form<V> valueForm, int flags, Object observers) {
super(observers);
this.agentContext = agentContext;
this.linkForm = linkForm;
this.keyForm = keyForm;
this.valueForm = valueForm;
this.flags = flags;
}
public JoinMapLaneView(AgentContext agentContext, Form<L> linkForm,
Form<K> keyForm, Form<V> valueForm) {
this(agentContext, linkForm, keyForm, valueForm, RESIDENT, null);
}
@Override
public AgentContext agentContext() {
return this.agentContext;
}
@Override
public JoinMapLaneModel laneBinding() {
return this.laneBinding;
}
void setLaneBinding(JoinMapLaneModel laneBinding) {
this.laneBinding = laneBinding;
}
@Override
public JoinMapLaneModel createLaneBinding() {
return new JoinMapLaneModel(this.flags);
}
@Override
public final Form<L> linkForm() {
return this.linkForm;
}
@Override
public <L2> JoinMapLaneView<L2, K, V> linkForm(Form<L2> linkForm) {
return new JoinMapLaneView<L2, K, V>(this.agentContext, linkForm, this.keyForm, this.valueForm,
this.flags, typesafeObservers(this.observers));
}
@Override
public <L2> JoinMapLaneView<L2, K, V> linkClass(Class<L2> linkClass) {
return linkForm(Form.<L2>forClass(linkClass));
}
public void setLinkForm(Form<L> linkForm) {
this.linkForm = linkForm;
}
@Override
public final Form<K> keyForm() {
return keyForm;
}
@Override
public <K2> JoinMapLaneView<L, K2, V> keyForm(Form<K2> keyForm) {
return new JoinMapLaneView<L, K2, V>(this.agentContext, this.linkForm, keyForm, this.valueForm,
this.flags, typesafeObservers(this.observers));
}
@Override
public <K2> JoinMapLaneView<L, K2, V> keyClass(Class<K2> keyClass) {
return keyForm(Form.<K2>forClass(keyClass));
}
public void setKeyForm(Form<K> keyForm) {
this.keyForm = keyForm;
}
@Override
public final Form<V> valueForm() {
return valueForm;
}
@Override
public <V2> JoinMapLaneView<L, K, V2> valueForm(Form<V2> valueForm) {
return new JoinMapLaneView<L, K, V2>(this.agentContext, this.linkForm, this.keyForm, valueForm,
this.flags, typesafeObservers(this.observers));
}
@Override
public <V2> JoinMapLaneView<L, K, V2> valueClass(Class<V2> valueClass) {
return valueForm(Form.<V2>forClass(valueClass));
}
public void setValueForm(Form<V> valueForm) {
this.valueForm = valueForm;
}
protected Object typesafeObservers(Object observers) {
// TODO: filter out WillDownlinkMap, DidDownlinkMap, WillUpdateKey, DidUpdateKey,
// WillRemoveKey, DidRemoveKey, WillClear, DidClear
return observers;
}
public final boolean isResident() {
return (this.flags & RESIDENT) != 0;
}
@Override
public JoinMapLaneView<L, K, V> isResident(boolean isResident) {
if (isResident) {
this.flags |= RESIDENT;
} else {
this.flags &= ~RESIDENT;
}
final JoinMapLaneModel laneBinding = this.laneBinding;
if (laneBinding != null) {
laneBinding.isResident(isResident);
}
return this;
}
void didSetResident(boolean isResident) {
if (isResident) {
this.flags |= RESIDENT;
} else {
this.flags &= ~RESIDENT;
}
}
public final boolean isTransient() {
return (this.flags & TRANSIENT) != 0;
}
@Override
public JoinMapLaneView<L, K, V> isTransient(boolean isTransient) {
if (isTransient) {
this.flags |= TRANSIENT;
} else {
this.flags &= ~TRANSIENT;
}
final JoinMapLaneModel laneBinding = this.laneBinding;
if (laneBinding != null) {
laneBinding.isTransient(isTransient);
}
return this;
}
void didSetTransient(boolean isTransient) {
if (isTransient) {
this.flags |= TRANSIENT;
} else {
this.flags &= ~TRANSIENT;
}
}
@Override
protected void willLoad() {
this.dataView = this.laneBinding.data.keyForm(this.keyForm).valueForm(this.valueForm);
super.willLoad();
}
@Override
public void close() {
this.laneBinding.closeLaneView(this);
}
@Override
public JoinMapLaneView<L, K, V> observe(Object observer) {
super.observe(observer);
return this;
}
@Override
public JoinMapLaneView<L, K, V> unobserve(Object observer) {
super.unobserve(observer);
return this;
}
@Override
public JoinMapLaneView<L, K, V> willDownlink(WillDownlinkMap<L> willDownlink) {
return observe(willDownlink);
}
@Override
public JoinMapLaneView<L, K, V> didDownlink(DidDownlinkMap<L> didDownlink) {
return observe(didDownlink);
}
@Override
public JoinMapLaneView<L, K, V> willUpdate(WillUpdateKey<K, V> willUpdate) {
return observe(willUpdate);
}
@Override
public JoinMapLaneView<L, K, V> didUpdate(DidUpdateKey<K, V> didUpdate) {
return observe(didUpdate);
}
@Override
public JoinMapLaneView<L, K, V> willRemove(WillRemoveKey<K> willRemove) {
return observe(willRemove);
}
@Override
public JoinMapLaneView<L, K, V> didRemove(DidRemoveKey<K, V> didRemove) {
return observe(didRemove);
}
@Override
public JoinMapLaneView<L, K, V> willClear(WillClear willClear) {
return observe(willClear);
}
@Override
public JoinMapLaneView<L, K, V> didClear(DidClear didClear) {
return observe(didClear);
}
@Override
public JoinMapLaneView<L, K, V> willCommand(WillCommand willCommand) {
return observe(willCommand);
}
@Override
public JoinMapLaneView<L, K, V> didCommand(DidCommand didCommand) {
return observe(didCommand);
}
@Override
public JoinMapLaneView<L, K, V> willUplink(WillUplink willUplink) {
return observe(willUplink);
}
@Override
public JoinMapLaneView<L, K, V> didUplink(DidUplink didUplink) {
return observe(didUplink);
}
@Override
public JoinMapLaneView<L, K, V> willEnter(WillEnter willEnter) {
return observe(willEnter);
}
@Override
public JoinMapLaneView<L, K, V> didEnter(DidEnter didEnter) {
return observe(didEnter);
}
@Override
public JoinMapLaneView<L, K, V> willLeave(WillLeave willLeave) {
return observe(willLeave);
}
@Override
public JoinMapLaneView<L, K, V> didLeave(DidLeave didLeave) {
return observe(didLeave);
}
@SuppressWarnings("unchecked")
public Map.Entry<Boolean, V> dispatchWillUpdate(Link link, K key, V newValue, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillUpdateKey<?, ?>) {
if (((WillUpdateKey<?, ?>) observers).isPreemptive() == preemptive) {
try {
newValue = ((WillUpdateKey<K, V>) observers).willUpdate(key, newValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillUpdateKey<?, ?>) {
if (((WillUpdateKey<?, ?>) observer).isPreemptive() == preemptive) {
try {
newValue = ((WillUpdateKey<K, V>) observer).willUpdate(key, newValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return new AbstractMap.SimpleImmutableEntry<Boolean, V>(complete, newValue);
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
@SuppressWarnings("unchecked")
public boolean dispatchDidUpdate(Link link, K key, V newValue, V oldValue, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidUpdateKey<?, ?>) {
if (((DidUpdateKey<?, ?>) observers).isPreemptive() == preemptive) {
try {
((DidUpdateKey<K, V>) observers).didUpdate(key, newValue, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidUpdateKey<?, ?>) {
if (((DidUpdateKey<?, ?>) observer).isPreemptive() == preemptive) {
try {
((DidUpdateKey<K, V>) observer).didUpdate(key, newValue, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
@SuppressWarnings("unchecked")
public boolean dispatchWillRemove(Link link, K key, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillRemoveKey<?>) {
if (((WillRemoveKey<?>) observers).isPreemptive() == preemptive) {
try {
((WillRemoveKey<K>) observers).willRemove(key);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillRemoveKey<?>) {
if (((WillRemoveKey<?>) observer).isPreemptive() == preemptive) {
try {
((WillRemoveKey<K>) observer).willRemove(key);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
@SuppressWarnings("unchecked")
public boolean dispatchDidRemove(Link link, K key, V oldValue, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidRemoveKey<?, ?>) {
if (((DidRemoveKey<?, ?>) observers).isPreemptive() == preemptive) {
try {
((DidRemoveKey<K, V>) observers).didRemove(key, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidRemoveKey<?, ?>) {
if (((DidRemoveKey<?, ?>) observer).isPreemptive() == preemptive) {
try {
((DidRemoveKey<K, V>) observer).didRemove(key, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
public boolean dispatchWillClear(Link link, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillClear) {
if (((WillClear) observers).isPreemptive() == preemptive) {
try {
((WillClear) observers).willClear();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillClear) {
if (((WillClear) observer).isPreemptive() == preemptive) {
try {
((WillClear) observer).willClear();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
public boolean dispatchDidClear(Link link, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidClear) {
if (((DidClear) observers).isPreemptive() == preemptive) {
try {
((DidClear) observers).didClear();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidClear) {
if (((DidClear) observer).isPreemptive() == preemptive) {
try {
((DidClear) observer).didClear();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
@SuppressWarnings("unchecked")
public Map.Entry<Boolean, MapDownlink<?, ?>> dispatchWillDownlink(L key, MapDownlink<?, ?> downlink, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
try {
SwimContext.setLane(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillDownlinkMap<?>) {
if (((WillDownlinkMap<?>) observers).isPreemptive() == preemptive) {
try {
downlink = ((WillDownlinkMap<L>) observers).willDownlink(key, downlink);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillDownlinkMap<?>) {
if (((WillDownlinkMap<?>) observer).isPreemptive() == preemptive) {
try {
downlink = ((WillDownlinkMap<L>) observer).willDownlink(key, downlink);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return new AbstractMap.SimpleImmutableEntry<Boolean, MapDownlink<?, ?>>(complete, downlink);
} finally {
SwimContext.setLane(oldLane);
}
}
@SuppressWarnings("unchecked")
public boolean dispatchDidDownlink(L key, MapDownlink<?, ?> downlink, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
try {
SwimContext.setLane(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidDownlinkMap<?>) {
if (((DidDownlinkMap<?>) observers).isPreemptive() == preemptive) {
try {
((DidDownlinkMap<L>) observers).didDownlink(key, downlink);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidDownlinkMap<?>) {
if (((DidDownlinkMap<?>) observer).isPreemptive() == preemptive) {
try {
((DidDownlinkMap<L>) observer).didDownlink(key, downlink);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLane(oldLane);
}
}
public MapDownlink<K, V> laneWillDownlink(L key, MapDownlink<K, V> downlink) {
return downlink;
}
public void laneDidDownlink(K key, MapDownlink<K, V> downlink) {
}
public V laneWillUpdate(K key, V newValue) {
return newValue;
}
public void laneDidUpdate(K key, V newValue, V oldValue) {
}
public void laneWillRemove(K key) {
}
public void laneDidRemove(K key, V oldValue) {
}
public void laneWillClear() {
}
public void laneDidClear() {
}
@Override
public MapDownlink<K, V> downlink(L key) {
final LaneContext laneContext = this.laneBinding.laneContext();
return new JoinMapLaneDownlink<K, V>(laneContext, laneContext.stage(),
this.laneBinding, this.linkForm.mold(key).toValue(), this.laneBinding.meshUri(), Uri.empty(),
Uri.empty(), Uri.empty(), 0.0f, 0.0f, Value.absent(), this.keyForm, this.valueForm);
}
@Override
public boolean isEmpty() {
return this.dataView.isEmpty();
}
@Override
public int size() {
return this.dataView.size();
}
@Override
public boolean containsKey(Object key) {
return this.dataView.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return this.dataView.containsValue(value);
}
@Override
public V get(Object key) {
return this.dataView.get(key);
}
@SuppressWarnings("unchecked")
@Override
public MapDownlink<?, ?> getDownlink(Object key) {
return this.laneBinding.getDownlink(this.linkForm.mold((L) key));
}
@Override
public V put(K key, V value) {
return this.laneBinding.put(this, key, value);
}
@Override
public void putAll(Map<? extends K, ? extends V> map) {
for (Map.Entry<? extends K, ? extends V> entry : map.entrySet()) {
this.laneBinding.put(this, entry.getKey(), entry.getValue());
}
}
@SuppressWarnings("unchecked")
@Override
public V remove(Object key) {
final Class<?> keyType = this.keyForm.type();
if (keyType == null || keyType.isInstance(key)) {
return this.laneBinding.remove(this, (K) key);
}
return this.valueForm.unit();
}
@Override
public void clear() {
this.laneBinding.clear(this);
}
@Override
public Set<Map.Entry<K, V>> entrySet() {
return this.dataView.entrySet();
}
@Override
public Set<K> keySet() {
return this.dataView.keySet();
}
@Override
public Collection<V> values() {
return this.dataView.values();
}
@Override
public Iterator<Map.Entry<K, V>> iterator() {
return this.dataView.iterator();
}
@Override
public Iterator<K> keyIterator() {
return this.dataView.keyIterator();
}
@Override
public Iterator<V> valueIterator() {
return this.dataView.valueIterator();
}
@SuppressWarnings("unchecked")
@Override
public Iterator<Map.Entry<L, MapDownlink<?, ?>>> downlinkIterator() {
return (Iterator<Map.Entry<L, MapDownlink<?, ?>>>) (Iterator<?>) this.laneBinding.downlinks.iterator();
}
static final int RESIDENT = 1 << 0;
static final int TRANSIENT = 1 << 1;
static final int SIGNED = 1 << 2;
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/JoinValueLaneDownlink.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.runtime.lane;
import swim.concurrent.Stage;
import swim.runtime.CellContext;
import swim.runtime.downlink.ValueDownlinkView;
import swim.structure.Form;
import swim.structure.Value;
import swim.uri.Uri;
public class JoinValueLaneDownlink<V> extends ValueDownlinkView<V> {
protected final JoinValueLaneModel laneModel;
protected final Value key;
public JoinValueLaneDownlink(CellContext cellContext, Stage stage, JoinValueLaneModel laneModel,
Value key, Uri meshUri, Uri hostUri, Uri nodeUri, Uri laneUri,
float prio, float rate, Value body, int flags, Form<V> valueForm,
Object observers) {
super(cellContext, stage, meshUri, hostUri, nodeUri, laneUri, prio, rate,
body, flags, valueForm, observers);
this.laneModel = laneModel;
this.key = key;
}
public JoinValueLaneDownlink(CellContext cellContext, Stage stage, JoinValueLaneModel laneModel,
Value key, Uri meshUri, Uri hostUri, Uri nodeUri, Uri laneUri,
float prio, float rate, Value body, Form<V> valueForm) {
this(cellContext, stage, laneModel, key, meshUri, hostUri, nodeUri, laneUri,
prio, rate, body, KEEP_LINKED | KEEP_SYNCED, valueForm, null);
}
@Override
public ValueDownlinkView<V> hostUri(Uri hostUri) {
return new JoinValueLaneDownlink<V>(this.cellContext, this.stage, this.laneModel,
this.key, this.meshUri, hostUri, this.nodeUri,
this.laneUri, this.prio, this.rate, this.body,
this.flags, this.valueForm, this.observers);
}
@Override
public ValueDownlinkView<V> nodeUri(Uri nodeUri) {
return new JoinValueLaneDownlink<V>(this.cellContext, this.stage, this.laneModel,
this.key, this.meshUri, this.hostUri, nodeUri,
this.laneUri, this.prio, this.rate, this.body,
this.flags, this.valueForm, this.observers);
}
@Override
public ValueDownlinkView<V> laneUri(Uri laneUri) {
return new JoinValueLaneDownlink<V>(this.cellContext, this.stage, this.laneModel,
this.key, this.meshUri, this.hostUri, this.nodeUri,
laneUri, this.prio, this.rate, this.body,
this.flags, this.valueForm, this.observers);
}
@Override
public ValueDownlinkView<V> prio(float prio) {
return new JoinValueLaneDownlink<V>(this.cellContext, this.stage, this.laneModel,
this.key, this.meshUri, this.hostUri, this.nodeUri,
this.laneUri, prio, this.rate, this.body,
this.flags, this.valueForm, this.observers);
}
@Override
public ValueDownlinkView<V> rate(float rate) {
return new JoinValueLaneDownlink<V>(this.cellContext, this.stage, this.laneModel,
this.key, this.meshUri, this.hostUri, this.nodeUri,
this.laneUri, this.prio, rate, this.body,
this.flags, this.valueForm, this.observers);
}
@Override
public ValueDownlinkView<V> body(Value body) {
return new JoinValueLaneDownlink<V>(this.cellContext, this.stage, this.laneModel,
this.key, this.meshUri, this.hostUri, this.nodeUri,
this.laneUri, this.prio, this.rate, body,
this.flags, this.valueForm, this.observers);
}
@Override
public <V2> ValueDownlinkView<V2> valueForm(Form<V2> valueForm) {
return new JoinValueLaneDownlink<V2>(this.cellContext, this.stage, this.laneModel,
this.key, this.meshUri, this.hostUri, this.nodeUri,
this.laneUri, this.prio, this.rate, this.body,
this.flags, valueForm, typesafeObservers(this.observers));
}
@Override
public Value downlinkWillSetValue(Value newValue) {
return newValue;
}
@Override
public void downlinkDidSetValue(Value newValue, Value oldValue) {
this.laneModel.put(this, this.key, newValue);
}
@Override
public ValueDownlinkView<V> open() {
this.laneModel.downlink(this.key, this);
return this;
}
protected void openDownlink() {
super.open();
}
public Value setValue(Value newValue) {
return this.model.setValue(newValue);
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/JoinValueLaneModel.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.runtime.lane;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import swim.api.Link;
import swim.api.data.MapData;
import swim.api.downlink.ValueDownlink;
import swim.collections.FingerTrieSeq;
import swim.collections.HashTrieMap;
import swim.concurrent.Stage;
import swim.runtime.LaneRelay;
import swim.runtime.LaneView;
import swim.runtime.WarpBinding;
import swim.runtime.warp.WarpLaneModel;
import swim.structure.Attr;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Record;
import swim.structure.Value;
import swim.uri.Uri;
import swim.warp.CommandMessage;
public class JoinValueLaneModel extends WarpLaneModel<JoinValueLaneView<?, ?>, JoinValueLaneUplink> {
protected int flags;
protected MapData<Value, Value> data;
protected volatile HashTrieMap<Value, JoinValueLaneDownlink<?>> downlinks;
JoinValueLaneModel(int flags) {
this.flags = flags;
this.downlinks = HashTrieMap.empty();
}
public JoinValueLaneModel() {
this(0);
}
@Override
public String laneType() {
return "map";
}
@Override
protected JoinValueLaneUplink createWarpUplink(WarpBinding link) {
return new JoinValueLaneUplink(this, link);
}
protected void openDownlinks() {
for (Map.Entry<Value, Value> entry : this.data) {
final Value key = entry.getKey();
final Value value = entry.getValue();
final Value header = value.header("downlink");
final Uri nodeUri = header.get("node").coerce(Uri.form());
final Uri laneUri = header.get("lane").coerce(Uri.form());
final float prio = header.get("prio").floatValue(0.0f);
final float rate = header.get("rate").floatValue(0.0f);
final Value body = header.get("body");
new JoinValueLaneDownlink<Value>(this.laneContext, stage(), this, key,
this.laneContext.meshUri(), this.laneContext.hostUri(), nodeUri, laneUri,
prio, rate, body, Form.forValue()).openDownlink();
}
}
protected void downlink(Value key, JoinValueLaneDownlink<?> downlink) {
Value value = this.data.get(key);
Record header = value.headers("downlink");
if (header == null
|| !header.get("node").coerce(Uri.form()).equals(downlink.nodeUri())
|| !header.get("lane").coerce(Uri.form()).equals(downlink.laneUri())
|| header.get("prio").floatValue(0.0f) != downlink.prio()
|| header.get("rate").floatValue(0.0f) != downlink.rate()
|| !header.get("body").equals(downlink.body())) {
header = Record.of()
.slot("node", downlink.nodeUri().toString())
.slot("lane", downlink.laneUri().toString());
if (downlink.prio() != 0.0f) {
header.slot("prio", downlink.prio());
}
if (downlink.rate() != 0.0f) {
header.slot("rate", downlink.rate());
}
if (downlink.body().isDefined()) {
header.slot("body", downlink.body());
}
if ("downlink".equals(value.tag())) {
value = value.updatedAttr("downlink", header);
} else {
value = Record.of().attr("downlink", header).concat(value);
}
this.data.put(key, value);
}
new JoinValueLaneRelayDownlink(this, key, downlink).run();
}
protected void openDownlink(Value key, JoinValueLaneDownlink<?> downlink) {
downlink.openDownlink(); // Open before CAS
HashTrieMap<Value, JoinValueLaneDownlink<?>> oldDownlinks;
HashTrieMap<Value, JoinValueLaneDownlink<?>> newDownlinks;
do {
oldDownlinks = this.downlinks;
newDownlinks = oldDownlinks.updated(key, downlink);
} while (oldDownlinks != newDownlinks && !DOWNLINKS.compareAndSet(this, oldDownlinks, newDownlinks));
if (oldDownlinks != newDownlinks) {
final JoinValueLaneDownlink<?> oldDownlink = oldDownlinks.get(key);
if (oldDownlink != null) {
try {
oldDownlink.close();
} catch (Exception swallow) { }
}
}
}
protected void closeDownlinks() {
HashTrieMap<Value, JoinValueLaneDownlink<?>> oldDownlinks;
final HashTrieMap<Value, JoinValueLaneDownlink<?>> newDownlinks = HashTrieMap.empty();
do {
oldDownlinks = this.downlinks;
} while (oldDownlinks != newDownlinks && !DOWNLINKS.compareAndSet(this, oldDownlinks, newDownlinks));
if (!oldDownlinks.isEmpty()) {
for (JoinValueLaneDownlink<?> downlink : oldDownlinks.values()) {
try {
downlink.close();
} catch (Exception swallow) { }
}
}
}
protected void closeDownlinkKey(Value key) {
HashTrieMap<Value, JoinValueLaneDownlink<?>> oldDownlinks;
HashTrieMap<Value, JoinValueLaneDownlink<?>> newDownlinks;
do {
oldDownlinks = this.downlinks;
newDownlinks = oldDownlinks.removed(key);
} while (oldDownlinks != newDownlinks && !DOWNLINKS.compareAndSet(this, oldDownlinks, newDownlinks));
if (oldDownlinks != newDownlinks) {
final JoinValueLaneDownlink<?> downlink = oldDownlinks.get(key);
try {
downlink.close();
} catch (Exception swallow) { }
}
}
@Override
protected void didOpenLaneView(JoinValueLaneView<?, ?> view) {
view.setLaneBinding(this);
}
@Override
public void onCommand(CommandMessage message) {
final Value payload = message.body();
final String tag = payload.tag();
if ("update".equals(tag)) {
final Value header = payload.header("update");
final Value key = header.get("key");
final Item head = this.data.get(key).head();
final Value newValue = payload.body();
new JoinValueLaneRelayUpdate(this, message, key, newValue).run();
} else if ("remove".equals(tag)) {
final Value header = payload.header("remove");
final Value key = header.get("key");
new JoinValueLaneRelayRemove(this, message, key).run();
} else if ("clear".equals(tag)) {
new JoinValueLaneRelayClear(this, message).run();
}
}
protected void cueDownKey(Value key) {
FingerTrieSeq<JoinValueLaneUplink> uplinks;
do {
uplinks = this.uplinks;
for (int i = 0, n = uplinks.size(); i < n; i += 1) {
uplinks.get(i).cueDownKey(key);
}
} while (uplinks != this.uplinks);
}
public final boolean isResident() {
return (this.flags & RESIDENT) != 0;
}
public JoinValueLaneModel isResident(boolean isResident) {
if (this.data != null) {
this.data.isResident(isResident);
}
if (isResident) {
this.flags |= RESIDENT;
} else {
this.flags &= ~RESIDENT;
}
final Object views = this.views;
if (views instanceof ValueLaneView<?>) {
((ValueLaneView<?>) views).didSetResident(isResident);
} else if (views instanceof LaneView[]) {
final LaneView[] viewArray = (LaneView[]) views;
for (int i = 0, n = viewArray.length; i < n; i += 1) {
((ValueLaneView<?>) viewArray[i]).didSetResident(isResident);
}
}
return this;
}
public final boolean isTransient() {
return (this.flags & TRANSIENT) != 0;
}
public JoinValueLaneModel isTransient(boolean isTransient) {
if (this.data != null) {
this.data.isTransient(isTransient);
}
if (isTransient) {
this.flags |= TRANSIENT;
} else {
this.flags &= ~TRANSIENT;
}
final Object views = this.views;
if (views instanceof ValueLaneView<?>) {
((ValueLaneView<?>) views).didSetTransient(isTransient);
} else if (views instanceof LaneView[]) {
final LaneView[] viewArray = (LaneView[]) views;
for (int i = 0, n = viewArray.length; i < n; i += 1) {
((ValueLaneView<?>) viewArray[i]).didSetTransient(isTransient);
}
}
return this;
}
public Value get(Object key) {
if (key != null) {
Value value = this.data.get(key);
if ("downlink".equals(value.tag())) {
value = value.body();
}
return value;
} else {
return Value.absent();
}
}
public JoinValueLaneDownlink<?> getDownlink(Object key) {
return this.downlinks.get(key);
}
public void put(JoinValueLaneDownlink<?> downlink, Value key, Value newValue) {
final JoinValueLaneRelayUpdate relay = new JoinValueLaneRelayUpdate(this, downlink, key, newValue);
relay.run();
}
@SuppressWarnings("unchecked")
public <K, V> V put(JoinValueLaneView<K, V> view, K keyObject, V newObject) {
final Form<K> keyForm = view.keyForm;
final Form<V> valueForm = view.valueForm;
final Value key = keyForm.mold(keyObject).toValue();
final Value newValue = valueForm.mold(newObject).toValue();
final JoinValueLaneRelayUpdate relay = new JoinValueLaneRelayUpdate(this, stage(), key, newValue);
relay.keyForm = (Form<Object>) keyForm;
relay.valueForm = (Form<Object>) valueForm;
relay.keyObject = keyObject;
relay.oldObject = newObject;
relay.newObject = newObject;
relay.run();
if (relay.valueForm != valueForm && valueForm != null) {
relay.oldObject = valueForm.cast(relay.oldValue);
if (relay.oldObject == null) {
relay.oldObject = valueForm.unit();
}
}
return (V) relay.oldObject;
}
@SuppressWarnings("unchecked")
public <K, V> V remove(JoinValueLaneView<K, V> view, K keyObject) {
final Form<K> keyForm = view.keyForm;
final Form<V> valueForm = view.valueForm;
final Value key = keyForm.mold(keyObject).toValue();
final JoinValueLaneRelayRemove relay = new JoinValueLaneRelayRemove(this, stage(), key);
relay.keyForm = (Form<Object>) keyForm;
relay.valueForm = (Form<Object>) valueForm;
relay.keyObject = keyObject;
relay.run();
if (relay.valueForm == valueForm) {
return (V) relay.oldObject;
} else {
return null;
}
}
public void clear(JoinValueLaneView<?, ?> view) {
final JoinValueLaneRelayClear relay = new JoinValueLaneRelayClear(this, stage());
relay.run();
}
public Iterator<Map.Entry<Value, Value>> iterator() {
return new JoinValueLaneModelEntryIterator(this.data.iterator());
}
public Iterator<Value> keyIterator() {
return this.data.keyIterator();
}
public Iterator<Value> valueIterator() {
return new JoinValueLaneModelValueIterator(this.data.valueIterator());
}
public Set<Map.Entry<Value, Value>> entrySet() {
return this.data.entrySet();
}
public Set<Value> keySet() {
return this.data.keySet();
}
public Collection<Value> values() {
return this.data.values();
}
protected void openStore() {
this.data = this.laneContext.store().mapData(laneUri().toString())
.isTransient(isTransient())
.isResident(isResident());
}
@Override
protected void willLoad() {
openStore();
super.willLoad();
}
@Override
protected void willStart() {
super.willStart();
openDownlinks();
}
static final int RESIDENT = 1 << 0;
static final int TRANSIENT = 1 << 1;
static final int SIGNED = 1 << 2;
@SuppressWarnings("unchecked")
static final AtomicReferenceFieldUpdater<JoinValueLaneModel, HashTrieMap<Value, JoinValueLaneDownlink<?>>> DOWNLINKS =
AtomicReferenceFieldUpdater.newUpdater(JoinValueLaneModel.class, (Class<HashTrieMap<Value, JoinValueLaneDownlink<?>>>) (Class<?>) HashTrieMap.class, "downlinks");
}
final class JoinValueLaneModelEntryIterator implements Iterator<Map.Entry<Value, Value>> {
final Iterator<Map.Entry<Value, Value>> iterator;
JoinValueLaneModelEntryIterator(Iterator<Map.Entry<Value, Value>> iterator) {
this.iterator = iterator;
}
@Override
public boolean hasNext() {
return this.iterator.hasNext();
}
@Override
public Map.Entry<Value, Value> next() {
final Map.Entry<Value, Value> entry = this.iterator.next();
Value value = entry.getValue();
if ("downlink".equals(value.tag())) {
value = value.body();
}
return new AbstractMap.SimpleImmutableEntry<Value, Value>(entry.getKey(), value);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
final class JoinValueLaneModelValueIterator implements Iterator<Value> {
final Iterator<Value> iterator;
JoinValueLaneModelValueIterator(Iterator<Value> iterator) {
this.iterator = iterator;
}
@Override
public boolean hasNext() {
return this.iterator.hasNext();
}
@Override
public Value next() {
Value value = this.iterator.next();
if ("downlink".equals(value.tag())) {
value = value.body();
}
return value;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
final class JoinValueLaneRelayUpdate extends LaneRelay<JoinValueLaneModel, JoinValueLaneView<?, ?>> {
final Link link;
final CommandMessage message;
Form<Object> keyForm;
Form<Object> valueForm;
final Value key;
Object keyObject;
Value oldValue;
Object oldObject;
Value newValue;
Object newObject;
JoinValueLaneRelayUpdate(JoinValueLaneModel model, CommandMessage message, Value key, Value newValue) {
super(model, 4);
this.link = null;
this.message = message;
this.key = key;
this.newValue = newValue;
}
JoinValueLaneRelayUpdate(JoinValueLaneModel model, Link link, Value key, Value newValue) {
super(model, 1, 3, null);
this.link = link;
this.message = null;
this.key = key;
this.newValue = newValue;
}
JoinValueLaneRelayUpdate(JoinValueLaneModel model, Stage stage, Value key, Value newValue) {
super(model, 1, 3, stage);
this.link = null;
this.message = null;
this.key = key;
this.newValue = newValue;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
final Item head = this.model.data.get(this.key).head();
Value dataValue = this.newValue;
if (head instanceof Attr && "downlink".equals(((Attr) head).name())) {
dataValue = head.concat(dataValue);
}
this.oldValue = this.model.data.put(this.key, dataValue);
if ("downlink".equals(this.oldValue.tag())) {
this.oldValue = this.oldValue.body();
}
if (this.valueForm != null) {
this.oldObject = this.valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = this.valueForm.unit();
}
}
if (message != null) { // propagate to source ValueLane
final JoinValueLaneDownlink<?> downlink = this.model.getDownlink(this.key);
if (downlink != null) {
downlink.setValue(this.newValue);
}
}
}
}
@SuppressWarnings("unchecked")
@Override
protected boolean runPhase(JoinValueLaneView<?, ?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneWillCommand(this.message);
}
return view.dispatchWillCommand(this.message.body(), preemptive);
} else if (phase == 1) {
final Form<Object> keyForm = (Form<Object>) view.keyForm;
if (this.keyForm != keyForm && keyForm != null) {
this.keyForm = keyForm;
this.keyObject = keyForm.cast(this.key);
if (this.keyObject == null) {
this.keyObject = keyForm.unit();
}
}
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.oldObject = valueForm.cast(this.newValue);
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
}
if (preemptive) {
this.newObject = ((JoinValueLaneView<Object, Object>) view).laneWillUpdate(this.keyObject, this.oldObject);
}
final Map.Entry<Boolean, Object> result = ((JoinValueLaneView<Object, Object>) view).dispatchWillUpdate(this.link, this.keyObject, this.oldObject, preemptive);
this.newObject = result.getValue();
if (this.oldObject != this.newObject) {
this.oldObject = this.newObject;
this.newValue = valueForm.mold(this.newObject).toValue();
}
return result.getKey();
} else if (phase == 2) {
final Form<Object> keyForm = (Form<Object>) view.keyForm;
if (this.keyForm != keyForm && keyForm != null) {
this.keyForm = keyForm;
this.keyObject = keyForm.cast(this.key);
if (this.keyObject == null) {
this.keyObject = keyForm.unit();
}
}
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.oldObject = valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
this.newObject = valueForm.cast(this.newValue);
if (this.newObject == null) {
this.newObject = valueForm.unit();
}
}
if (preemptive) {
((JoinValueLaneView<Object, Object>) view).laneDidUpdate(this.keyObject, this.newObject, this.oldObject);
}
return ((JoinValueLaneView<Object, Object>) view).dispatchDidUpdate(this.link, this.keyObject, this.newObject, this.oldObject, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.laneDidCommand(this.message);
}
return view.dispatchDidCommand(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
this.model.cueDownKey(this.key);
}
}
final class JoinValueLaneRelayRemove extends LaneRelay<JoinValueLaneModel, JoinValueLaneView<?, ?>> {
final Link link;
final CommandMessage message;
Form<Object> keyForm;
Form<Object> valueForm;
final Value key;
Object keyObject;
Value oldValue;
Object oldObject;
JoinValueLaneRelayRemove(JoinValueLaneModel model, CommandMessage message, Value key) {
super(model, 4);
this.link = null;
this.message = message;
this.key = key;
}
JoinValueLaneRelayRemove(JoinValueLaneModel model, Link link, Value key) {
super(model, 1, 3, null);
this.link = link;
this.message = null;
this.key = key;
}
JoinValueLaneRelayRemove(JoinValueLaneModel model, Stage stage, Value key) {
super(model, 1, 3, stage);
this.link = null;
this.message = null;
this.key = key;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
this.model.closeDownlinkKey(this.key);
this.oldValue = this.model.data.remove(this.key);
if (this.valueForm != null) {
this.oldObject = this.valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = this.valueForm.unit();
}
}
}
}
@SuppressWarnings("unchecked")
@Override
protected boolean runPhase(JoinValueLaneView<?, ?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneWillCommand(this.message);
}
return view.dispatchWillCommand(this.message.body(), preemptive);
} else if (phase == 1) {
final Form<Object> keyForm = (Form<Object>) view.keyForm;
if (this.keyForm != keyForm && keyForm != null) {
this.keyForm = keyForm;
this.keyObject = keyForm.cast(this.key);
if (this.keyObject == null) {
this.keyObject = keyForm.unit();
}
}
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.oldObject = valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
}
if (preemptive) {
((JoinValueLaneView<Object, Object>) view).laneWillRemove(this.keyObject);
}
return ((JoinValueLaneView<Object, Object>) view).dispatchWillRemove(this.link, this.keyObject, preemptive);
} else if (phase == 2) {
final Form<Object> keyForm = (Form<Object>) view.keyForm;
if (this.keyForm != keyForm && keyForm != null) {
this.keyForm = keyForm;
this.keyObject = keyForm.cast(this.key);
if (this.keyObject == null) {
this.keyObject = keyForm.unit();
}
}
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.oldObject = valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
}
if (preemptive) {
((JoinValueLaneView<Object, Object>) view).laneDidRemove(this.keyObject, this.oldObject);
}
return ((JoinValueLaneView<Object, Object>) view).dispatchDidRemove(this.link, this.keyObject, this.oldObject, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.laneDidCommand(this.message);
}
return view.dispatchDidCommand(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
if (this.oldValue.isDefined()) {
this.model.sendDown(Record.create(1).attr("remove", Record.create(1).slot("key", this.key)));
}
}
}
final class JoinValueLaneRelayClear extends LaneRelay<JoinValueLaneModel, JoinValueLaneView<?, ?>> {
final Link link;
final CommandMessage message;
JoinValueLaneRelayClear(JoinValueLaneModel model, CommandMessage message) {
super(model, 4);
this.link = null;
this.message = message;
}
JoinValueLaneRelayClear(JoinValueLaneModel model, Link link) {
super(model, 1, 3, null);
this.link = link;
this.message = null;
}
JoinValueLaneRelayClear(JoinValueLaneModel model, Stage stage) {
super(model, 1, 3, stage);
this.link = null;
this.message = null;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
this.model.closeDownlinks();
this.model.data.clear();
}
}
@Override
protected boolean runPhase(JoinValueLaneView<?, ?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneWillCommand(this.message);
}
return view.dispatchWillCommand(this.message.body(), preemptive);
} else if (phase == 1) {
if (preemptive) {
view.laneWillClear();
}
return view.dispatchWillClear(this.link, preemptive);
} else if (phase == 2) {
if (preemptive) {
view.laneDidClear();
}
return view.dispatchDidClear(this.link, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.laneDidCommand(this.message);
}
return view.dispatchDidCommand(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
this.model.sendDown(Record.create(1).attr("clear"));
}
}
final class JoinValueLaneRelayDownlink extends LaneRelay<JoinValueLaneModel, JoinValueLaneView<?, ?>> {
Form<Object> keyForm;
final Value key;
Object keyObject;
JoinValueLaneDownlink<Object> downlink;
@SuppressWarnings("unchecked")
JoinValueLaneRelayDownlink(JoinValueLaneModel model, Value key, JoinValueLaneDownlink<?> downlink) {
super(model, 2);
this.key = key;
this.downlink = (JoinValueLaneDownlink<Object>) downlink;
}
@Override
protected void beginPhase(int phase) {
if (phase == 1) {
this.model.openDownlink(this.key, this.downlink);
}
}
@SuppressWarnings("unchecked")
@Override
protected boolean runPhase(JoinValueLaneView<?, ?> view, int phase, boolean preemptive) {
if (phase == 0) {
final Form<Object> keyForm = (Form<Object>) view.keyForm;
if (this.keyForm != keyForm && keyForm != null) {
this.keyForm = keyForm;
this.keyObject = keyForm.cast(this.key);
if (this.keyObject == null) {
this.keyObject = keyForm.unit();
}
}
if (preemptive) {
this.downlink = (JoinValueLaneDownlink<Object>) ((JoinValueLaneView<Object, Object>) view).laneWillDownlink(this.keyObject, this.downlink);
}
final Map.Entry<Boolean, ValueDownlink<?>> result = ((JoinValueLaneView<Object, Object>) view).dispatchWillDownlink(this.keyObject, this.downlink, preemptive);
this.downlink = (JoinValueLaneDownlink<Object>) result.getValue();
return result.getKey();
} else if (phase == 1) {
final Form<Object> keyForm = (Form<Object>) view.keyForm;
if (this.keyForm != keyForm && keyForm != null) {
this.keyForm = keyForm;
this.keyObject = keyForm.cast(this.key);
if (this.keyObject == null) {
this.keyObject = keyForm.unit();
}
}
if (preemptive) {
((JoinValueLaneView<Object, Object>) view).laneDidDownlink(this.keyObject, this.downlink);
}
return ((JoinValueLaneView<Object, Object>) view).dispatchDidDownlink(this.keyObject, this.downlink, preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/JoinValueLaneUplink.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.runtime.lane;
import swim.concurrent.Stage;
import swim.runtime.WarpBinding;
import swim.runtime.warp.PartialUplinkModem;
import swim.structure.Attr;
import swim.structure.Record;
import swim.structure.Value;
import swim.warp.SyncRequest;
public class JoinValueLaneUplink extends PartialUplinkModem {
final JoinValueLaneModel laneBinding;
public JoinValueLaneUplink(JoinValueLaneModel laneBinding, WarpBinding linkBinding) {
super(linkBinding);
this.laneBinding = laneBinding;
}
@Override
public JoinValueLaneModel laneBinding() {
return this.laneBinding;
}
@Override
public Stage stage() {
return this.laneBinding.stage();
}
@Override
protected Value nextDownKey(Value key) {
final Value value = this.laneBinding.get(key);
if (value != null) {
return Attr.of("update", Record.create(1).slot("key", key)).concat(value);
} else {
return null;
}
}
@Override
protected void willSync(SyncRequest request) {
syncDown(this.laneBinding.iterator());
super.willSync(request);
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/JoinValueLaneView.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.runtime.lane;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import swim.api.Lane;
import swim.api.Link;
import swim.api.SwimContext;
import swim.api.agent.AgentContext;
import swim.api.data.MapData;
import swim.api.downlink.ValueDownlink;
import swim.api.lane.JoinValueLane;
import swim.api.lane.function.DidDownlinkValue;
import swim.api.lane.function.WillDownlinkValue;
import swim.api.warp.function.DidCommand;
import swim.api.warp.function.DidEnter;
import swim.api.warp.function.DidLeave;
import swim.api.warp.function.DidUplink;
import swim.api.warp.function.WillCommand;
import swim.api.warp.function.WillEnter;
import swim.api.warp.function.WillLeave;
import swim.api.warp.function.WillUplink;
import swim.concurrent.Conts;
import swim.observable.function.DidClear;
import swim.observable.function.DidRemoveKey;
import swim.observable.function.DidUpdateKey;
import swim.observable.function.WillClear;
import swim.observable.function.WillRemoveKey;
import swim.observable.function.WillUpdateKey;
import swim.runtime.LaneContext;
import swim.runtime.warp.WarpLaneView;
import swim.structure.Form;
import swim.structure.Value;
import swim.structure.collections.ValueEntryIterator;
import swim.structure.collections.ValueIterator;
import swim.uri.Uri;
public class JoinValueLaneView<K, V> extends WarpLaneView implements JoinValueLane<K, V> {
protected final AgentContext agentContext;
protected Form<K> keyForm;
protected Form<V> valueForm;
protected int flags;
protected JoinValueLaneModel laneBinding;
protected MapData<K, V> dataView;
JoinValueLaneView(AgentContext agentContext, Form<K> keyForm, Form<V> valueForm,
int flags, Object observers) {
super(observers);
this.agentContext = agentContext;
this.keyForm = keyForm;
this.valueForm = valueForm;
this.flags = flags;
}
public JoinValueLaneView(AgentContext agentContext, Form<K> keyForm, Form<V> valueForm) {
this(agentContext, keyForm, valueForm, RESIDENT, null);
}
@Override
public AgentContext agentContext() {
return this.agentContext;
}
@Override
public JoinValueLaneModel laneBinding() {
return this.laneBinding;
}
void setLaneBinding(JoinValueLaneModel laneBinding) {
this.laneBinding = laneBinding;
}
@Override
public JoinValueLaneModel createLaneBinding() {
return new JoinValueLaneModel(this.flags);
}
@Override
public final Form<K> keyForm() {
return this.keyForm;
}
@Override
public <K2> JoinValueLaneView<K2, V> keyForm(Form<K2> keyForm) {
return new JoinValueLaneView<K2, V>(this.agentContext, keyForm, this.valueForm,
this.flags, typesafeObservers(this.observers));
}
@Override
public <K2> JoinValueLaneView<K2, V> keyClass(Class<K2> keyClass) {
return keyForm(Form.<K2>forClass(keyClass));
}
public void setKeyForm(Form<K> keyForm) {
this.keyForm = keyForm;
}
@Override
public final Form<V> valueForm() {
return this.valueForm;
}
@Override
public <V2> JoinValueLaneView<K, V2> valueForm(Form<V2> valueForm) {
return new JoinValueLaneView<K, V2>(this.agentContext, this.keyForm, valueForm,
this.flags, typesafeObservers(this.observers));
}
@Override
public <V2> JoinValueLaneView<K, V2> valueClass(Class<V2> valueClass) {
return valueForm(Form.<V2>forClass(valueClass));
}
public void setValueForm(Form<V> valueForm) {
this.valueForm = valueForm;
}
protected Object typesafeObservers(Object observers) {
// TODO: filter out WillDownlinkValue, DidDownlinkValue, WillUpdateKey, DidUpdateKey,
// WillRemoveKey, DidRemoveKey, WillClear, DidClear
return observers;
}
public final boolean isResident() {
return (this.flags & RESIDENT) != 0;
}
@Override
public JoinValueLaneView<K, V> isResident(boolean isResident) {
if (isResident) {
this.flags |= RESIDENT;
} else {
this.flags &= ~RESIDENT;
}
final JoinValueLaneModel laneBinding = this.laneBinding;
if (laneBinding != null) {
laneBinding.isResident(isResident);
}
return this;
}
void didSetResident(boolean isResident) {
if (isResident) {
this.flags |= RESIDENT;
} else {
this.flags &= ~RESIDENT;
}
}
public final boolean isTransient() {
return (this.flags & TRANSIENT) != 0;
}
@Override
public JoinValueLaneView<K, V> isTransient(boolean isTransient) {
if (isTransient) {
this.flags |= TRANSIENT;
} else {
this.flags &= ~TRANSIENT;
}
final JoinValueLaneModel laneBinding = this.laneBinding;
if (laneBinding != null) {
laneBinding.isTransient(isTransient);
}
return this;
}
void didSetTransient(boolean isTransient) {
if (isTransient) {
this.flags |= TRANSIENT;
} else {
this.flags &= ~TRANSIENT;
}
}
@Override
protected void willLoad() {
this.dataView = this.laneBinding.data.keyForm(this.keyForm).valueForm(this.valueForm);
super.willLoad();
}
@Override
public void close() {
this.laneBinding.closeLaneView(this);
}
@Override
public JoinValueLaneView<K, V> observe(Object observer) {
super.observe(observer);
return this;
}
@Override
public JoinValueLaneView<K, V> unobserve(Object observer) {
super.unobserve(observer);
return this;
}
@Override
public JoinValueLaneView<K, V> willDownlink(WillDownlinkValue<K> willDownlink) {
return observe(willDownlink);
}
@Override
public JoinValueLaneView<K, V> didDownlink(DidDownlinkValue<K> didDownlink) {
return observe(didDownlink);
}
@Override
public JoinValueLaneView<K, V> willUpdate(WillUpdateKey<K, V> willUpdate) {
return observe(willUpdate);
}
@Override
public JoinValueLaneView<K, V> didUpdate(DidUpdateKey<K, V> didUpdate) {
return observe(didUpdate);
}
@Override
public JoinValueLaneView<K, V> willRemove(WillRemoveKey<K> willRemove) {
return observe(willRemove);
}
@Override
public JoinValueLaneView<K, V> didRemove(DidRemoveKey<K, V> didRemove) {
return observe(didRemove);
}
@Override
public JoinValueLaneView<K, V> willClear(WillClear willClear) {
return observe(willClear);
}
@Override
public JoinValueLaneView<K, V> didClear(DidClear didClear) {
return observe(didClear);
}
@Override
public JoinValueLaneView<K, V> willCommand(WillCommand willCommand) {
return observe(willCommand);
}
@Override
public JoinValueLaneView<K, V> didCommand(DidCommand didCommand) {
return observe(didCommand);
}
@Override
public JoinValueLaneView<K, V> willUplink(WillUplink willUplink) {
return observe(willUplink);
}
@Override
public JoinValueLaneView<K, V> didUplink(DidUplink didUplink) {
return observe(didUplink);
}
@Override
public JoinValueLaneView<K, V> willEnter(WillEnter willEnter) {
return observe(willEnter);
}
@Override
public JoinValueLaneView<K, V> didEnter(DidEnter didEnter) {
return observe(didEnter);
}
@Override
public JoinValueLaneView<K, V> willLeave(WillLeave willLeave) {
return observe(willLeave);
}
@Override
public JoinValueLaneView<K, V> didLeave(DidLeave didLeave) {
return observe(didLeave);
}
@SuppressWarnings("unchecked")
public Map.Entry<Boolean, V> dispatchWillUpdate(Link link, K key, V newValue, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillUpdateKey<?, ?>) {
if (((WillUpdateKey<?, ?>) observers).isPreemptive() == preemptive) {
try {
newValue = ((WillUpdateKey<K, V>) observers).willUpdate(key, newValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillUpdateKey<?, ?>) {
if (((WillUpdateKey<?, ?>) observer).isPreemptive() == preemptive) {
try {
newValue = ((WillUpdateKey<K, V>) observer).willUpdate(key, newValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return new AbstractMap.SimpleImmutableEntry<Boolean, V>(complete, newValue);
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
@SuppressWarnings("unchecked")
public boolean dispatchDidUpdate(Link link, K key, V newValue, V oldValue, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidUpdateKey<?, ?>) {
if (((DidUpdateKey<?, ?>) observers).isPreemptive() == preemptive) {
try {
((DidUpdateKey<K, V>) observers).didUpdate(key, newValue, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidUpdateKey<?, ?>) {
if (((DidUpdateKey<?, ?>) observer).isPreemptive() == preemptive) {
try {
((DidUpdateKey<K, V>) observer).didUpdate(key, newValue, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
@SuppressWarnings("unchecked")
public boolean dispatchWillRemove(Link link, K key, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillRemoveKey<?>) {
if (((WillRemoveKey<?>) observers).isPreemptive() == preemptive) {
try {
((WillRemoveKey<K>) observers).willRemove(key);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillRemoveKey<?>) {
if (((WillRemoveKey<?>) observer).isPreemptive() == preemptive) {
try {
((WillRemoveKey<K>) observer).willRemove(key);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
@SuppressWarnings("unchecked")
public boolean dispatchDidRemove(Link link, K key, V oldValue, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidRemoveKey<?, ?>) {
if (((DidRemoveKey<?, ?>) observers).isPreemptive() == preemptive) {
try {
((DidRemoveKey<K, V>) observers).didRemove(key, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidRemoveKey<?, ?>) {
if (((DidRemoveKey<?, ?>) observer).isPreemptive() == preemptive) {
try {
((DidRemoveKey<K, V>) observer).didRemove(key, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
public boolean dispatchWillClear(Link link, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillClear) {
if (((WillClear) observers).isPreemptive() == preemptive) {
try {
((WillClear) observers).willClear();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillClear) {
if (((WillClear) observer).isPreemptive() == preemptive) {
try {
((WillClear) observer).willClear();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
public boolean dispatchDidClear(Link link, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidClear) {
if (((DidClear) observers).isPreemptive() == preemptive) {
try {
((DidClear) observers).didClear();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidClear) {
if (((DidClear) observer).isPreemptive() == preemptive) {
try {
((DidClear) observer).didClear();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
@SuppressWarnings("unchecked")
public Map.Entry<Boolean, ValueDownlink<?>> dispatchWillDownlink(K key, ValueDownlink<?> downlink, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
try {
SwimContext.setLane(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillDownlinkValue<?>) {
if (((WillDownlinkValue<?>) observers).isPreemptive() == preemptive) {
try {
downlink = ((WillDownlinkValue<K>) observers).willDownlink(key, downlink);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillDownlinkValue<?>) {
if (((WillDownlinkValue<?>) observer).isPreemptive() == preemptive) {
try {
downlink = ((WillDownlinkValue<K>) observer).willDownlink(key, downlink);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return new AbstractMap.SimpleImmutableEntry<Boolean, ValueDownlink<?>>(complete, downlink);
} finally {
SwimContext.setLane(oldLane);
}
}
@SuppressWarnings("unchecked")
public boolean dispatchDidDownlink(K key, ValueDownlink<?> downlink, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
try {
SwimContext.setLane(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidDownlinkValue<?>) {
if (((DidDownlinkValue<?>) observers).isPreemptive() == preemptive) {
try {
((DidDownlinkValue<K>) observers).didDownlink(key, downlink);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidDownlinkValue<?>) {
if (((DidDownlinkValue<?>) observer).isPreemptive() == preemptive) {
try {
((DidDownlinkValue<K>) observer).didDownlink(key, downlink);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLane(oldLane);
}
}
public ValueDownlink<V> laneWillDownlink(K key, ValueDownlink<V> downlink) {
return downlink;
}
public void laneDidDownlink(K key, ValueDownlink<V> downlink) {
}
public V laneWillUpdate(K key, V newValue) {
return newValue;
}
public void laneDidUpdate(K key, V newValue, V oldValue) {
}
public void laneWillRemove(K key) {
}
public void laneDidRemove(K key, V oldValue) {
}
public void laneWillClear() {
}
public void laneDidClear() {
}
@Override
public ValueDownlink<V> downlink(K key) {
final LaneContext laneContext = this.laneBinding.laneContext();
return new JoinValueLaneDownlink<V>(laneContext, laneContext.stage(), this.laneBinding,
this.keyForm.mold(key).toValue(), this.laneBinding.meshUri(),
Uri.empty(), Uri.empty(), Uri.empty(), 0.0f, 0.0f,
Value.absent(), this.valueForm);
}
@Override
public boolean isEmpty() {
return this.dataView.isEmpty();
}
@Override
public int size() {
return this.dataView.size();
}
@Override
public boolean containsKey(Object key) {
return this.dataView.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return this.dataView.containsValue(value);
}
@Override
public V get(Object key) {
return this.dataView.get(key);
}
@SuppressWarnings("unchecked")
@Override
public ValueDownlink<?> getDownlink(Object key) {
return this.laneBinding.getDownlink(this.keyForm.mold((K) key));
}
@Override
public V put(K key, V value) {
return this.laneBinding.put(this, key, value);
}
@Override
public void putAll(Map<? extends K, ? extends V> map) {
for (Map.Entry<? extends K, ? extends V> entry : map.entrySet()) {
this.laneBinding.put(this, entry.getKey(), entry.getValue());
}
}
@SuppressWarnings("unchecked")
@Override
public V remove(Object key) {
final Class<?> keyType = this.keyForm.type();
if (keyType == null || keyType.isInstance(key)) {
return this.laneBinding.remove(this, (K) key);
}
return this.valueForm.unit();
}
@Override
public void clear() {
this.laneBinding.clear(this);
}
@SuppressWarnings("unchecked")
@Override
public Set<Map.Entry<K, V>> entrySet() {
if (this.keyForm != Form.forValue() || this.valueForm != Form.forValue()) {
return new JoinValueLaneViewEntrySet<K, V>(this);
} else {
return (Set<Map.Entry<K, V>>) (Set<?>) this.laneBinding.entrySet();
}
}
@SuppressWarnings("unchecked")
@Override
public Set<K> keySet() {
if (this.keyForm != Form.forValue()) {
return this.dataView.keySet();
} else {
return (Set<K>) (Set<?>) this.laneBinding.keySet();
}
}
@SuppressWarnings("unchecked")
@Override
public Collection<V> values() {
if (this.valueForm != Form.forValue()) {
return new JoinValueLaneViewValues<K, V>(this);
} else {
return (Collection<V>) this.laneBinding.values();
}
}
@SuppressWarnings("unchecked")
@Override
public Iterator<Map.Entry<K, V>> iterator() {
if (this.keyForm != Form.forValue() || this.valueForm != Form.forValue()) {
return new ValueEntryIterator<K, V>(this.laneBinding.iterator(), this.keyForm, this.valueForm);
} else {
return (Iterator<Map.Entry<K, V>>) (Iterator<?>) this.laneBinding.iterator();
}
}
@Override
public Iterator<K> keyIterator() {
return this.dataView.keyIterator();
}
@SuppressWarnings("unchecked")
@Override
public Iterator<V> valueIterator() {
if (this.valueForm != Form.forValue()) {
return new ValueIterator<V>(this.laneBinding.valueIterator(), this.valueForm);
} else {
return (Iterator<V>) this.laneBinding.valueIterator();
}
}
@SuppressWarnings("unchecked")
@Override
public Iterator<Map.Entry<K, ValueDownlink<?>>> downlinkIterator() {
return (Iterator<Map.Entry<K, ValueDownlink<?>>>) (Iterator<?>) this.laneBinding.downlinks.iterator();
}
static final int RESIDENT = 1 << 0;
static final int TRANSIENT = 1 << 1;
static final int SIGNED = 1 << 2;
}
final class JoinValueLaneViewEntrySet<K, V> extends AbstractSet<Map.Entry<K, V>> {
final JoinValueLaneView<K, V> view;
JoinValueLaneViewEntrySet(JoinValueLaneView<K, V> view) {
this.view = view;
}
@Override
public int size() {
return this.view.size();
}
@Override
public Iterator<Map.Entry<K, V>> iterator() {
return this.view.iterator();
}
}
final class JoinValueLaneViewValues<K, V> extends AbstractCollection<V> {
final JoinValueLaneView<K, V> view;
JoinValueLaneViewValues(JoinValueLaneView<K, V> view) {
this.view = view;
}
@Override
public int size() {
return this.view.size();
}
@Override
public Iterator<V> iterator() {
return this.view.valueIterator();
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/ListLaneModel.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.runtime.lane;
import java.util.ListIterator;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import swim.api.Link;
import swim.api.data.ListData;
import swim.collections.FingerTrieSeq;
import swim.concurrent.Stage;
import swim.runtime.LaneRelay;
import swim.runtime.LaneView;
import swim.runtime.WarpBinding;
import swim.runtime.warp.ListLinkDelta;
import swim.runtime.warp.WarpLaneModel;
import swim.structure.Form;
import swim.structure.Value;
import swim.warp.CommandMessage;
public class ListLaneModel extends WarpLaneModel<ListLaneView<?>, ListLaneUplink> {
protected int flags;
protected ListData<Value> data;
ListLaneModel(int flags) {
this.flags = flags;
}
public ListLaneModel() {
this(0);
}
@Override
public String laneType() {
return "list";
}
@Override
protected ListLaneUplink createWarpUplink(WarpBinding link) {
return new ListLaneUplink(this, link);
}
@Override
protected void didOpenLaneView(ListLaneView<?> view) {
view.setLaneBinding(this);
}
@Override
public void onCommand(CommandMessage message) {
final Value payload = message.body();
final String tag = payload.tag();
if ("update".equals(tag)) {
final Value header = payload.header("update");
final int index = header.get("index").intValue(-1);
if (index > -1) {
final Object key;
if (header.get("key").isDistinct()) {
key = header.get("key");
} else {
key = null;
}
final Value value = payload.body();
new ListLaneRelayUpdate(this, message, index, value, key).run();
}
} else if ("move".equals(tag)) {
final Value header = payload.header("move");
final int fromIndex = header.get("from").intValue(-1);
final int toIindex = header.get("to").intValue(-1);
if (fromIndex > -1 && toIindex > -1) {
final Object key;
if (header.get("key").isDistinct()) {
key = header.get("key");
} else {
key = null;
}
new ListLaneRelayMove(this, message, fromIndex, toIindex, key).run();
}
} else if ("remove".equals(tag)) {
final Value header = payload.header("remove");
final int index = header.get("index").intValue(-1);
if (index > -1) {
final Object key;
if (header.get("key").isDistinct()) {
key = header.get("key");
} else {
key = null;
}
new ListLaneRelayRemove(this, message, index, key).run();
}
} else if ("drop".equals(tag)) {
final Value header = payload.header("drop");
final int lower = header.intValue(0);
new ListLaneRelayDrop(this, message, lower).run();
} else if ("take".equals(tag)) {
final Value header = payload.header("take");
final int upper = header.intValue(0);
new ListLaneRelayTake(this, message, upper).run();
} else if ("clear".equals(tag)) {
new ListLaneRelayClear(this, message).run();
}
}
protected void sendDown(ListLinkDelta delta) {
FingerTrieSeq<ListLaneUplink> uplinks;
FingerTrieSeq<Value> closedLinks = FingerTrieSeq.empty();
do {
uplinks = this.uplinks;
for (int i = 0, n = uplinks.size(); i < n; i += 1) {
final ListLaneUplink uplink = uplinks.get(i);
if (uplink.isConnected()) {
uplink.sendDown(delta);
} else {
closedLinks = closedLinks.appended(uplink.linkKey());
}
}
} while (uplinks != this.uplinks);
for (Value linkKey : closedLinks) {
closeUplink(linkKey);
}
}
public final boolean isResident() {
return (this.flags & RESIDENT) != 0;
}
public ListLaneModel isResident(boolean isResident) {
if (this.data != null) {
this.data.isResident(isResident);
}
if (isResident) {
this.flags |= RESIDENT;
} else {
this.flags &= ~RESIDENT;
}
final Object views = this.views;
if (views instanceof ListLaneView<?>) {
((ListLaneView<?>) views).didSetResident(isResident);
} else if (views instanceof LaneView[]) {
final LaneView[] viewArray = (LaneView[]) views;
for (int i = 0, n = viewArray.length; i < n; i += 1) {
((ListLaneView<?>) viewArray[i]).didSetResident(isResident);
}
}
return this;
}
public final boolean isTransient() {
return (this.flags & TRANSIENT) != 0;
}
public ListLaneModel isTransient(boolean isTransient) {
if (this.data != null) {
this.data.isTransient(isTransient);
}
if (isTransient) {
this.flags |= TRANSIENT;
} else {
this.flags &= ~TRANSIENT;
}
final Object views = this.views;
if (views instanceof ListLaneView<?>) {
((ListLaneView<?>) views).didSetTransient(isTransient);
} else if (views instanceof LaneView[]) {
final LaneView[] viewArray = (LaneView[]) views;
for (int i = 0, n = viewArray.length; i < n; i += 1) {
((ListLaneView<?>) viewArray[i]).didSetTransient(isTransient);
}
}
return this;
}
@SuppressWarnings("unchecked")
public <V> boolean add(ListLaneView<V> view, int index, V newObject) {
return add(view, index, newObject, null);
}
@SuppressWarnings("unchecked")
public <V> boolean add(ListLaneView<V> view, int index, V newObject, Object key) {
final Form<V> valueForm = view.valueForm;
final Value newValue = valueForm.mold(newObject).toValue();
final ListLaneRelayUpdate relay = new ListLaneRelayUpdate(this, stage(), index, newValue, key);
relay.valueForm = (Form<Object>) valueForm;
relay.newObject = newObject;
relay.run();
return relay.newObject != null; // TODO
}
@SuppressWarnings("unchecked")
public <V> V set(ListLaneView<V> view, int index, V newObject) {
return set(view, index, newObject, null);
}
@SuppressWarnings("unchecked")
public <V> V set(ListLaneView<V> view, int index, V newObject, Object key) {
final Form<V> valueForm = view.valueForm;
final Value newValue = valueForm.mold(newObject).toValue();
final ListLaneRelayUpdate relay = new ListLaneRelayUpdate(this, stage(), index, newValue, key);
relay.valueForm = (Form<Object>) valueForm;
relay.oldObject = newObject;
relay.newObject = newObject;
relay.run();
if (relay.valueForm != valueForm && valueForm != null) {
relay.oldObject = valueForm.cast(relay.oldValue);
if (relay.oldObject == null) {
relay.oldObject = valueForm.unit();
}
}
return (V) relay.oldObject;
}
public void move(int fromIndex, int toIndex) {
move(fromIndex, toIndex, null);
}
public void move(int fromIndex, int toIndex, Object key) {
final ListLaneRelayMove relay = new ListLaneRelayMove(this, stage(), fromIndex, toIndex, key);
relay.run();
}
@SuppressWarnings("unchecked")
public <V> V remove(ListLaneView<V> view, int index) {
return remove(view, index, null);
}
@SuppressWarnings("unchecked")
public <V> V remove(ListLaneView<V> view, int index, Object key) {
final Form<V> valueForm = view.valueForm;
final Map.Entry<Object, Value> entry = this.data.getEntry(index, key);
if (entry != null) {
final Object actualKey = key == null ? entry.getKey() : key;
final ListLaneRelayRemove relay = new ListLaneRelayRemove(this, stage(), index, actualKey);
relay.valueForm = (Form<Object>) valueForm;
relay.run();
if (relay.valueForm != valueForm && valueForm != null) {
relay.oldObject = valueForm.cast(relay.oldValue);
if (relay.oldObject == null) {
relay.oldObject = valueForm.unit();
}
}
return (V) relay.oldObject;
} else {
return null;
}
}
public void drop(ListLaneView<?> view, int lower) {
if (lower > 0) {
final ListLaneRelayDrop relay = new ListLaneRelayDrop(this, stage(), lower);
relay.run();
}
}
public void take(ListLaneView<?> view, int upper) {
if (upper > 0) {
final ListLaneRelayTake relay = new ListLaneRelayTake(this, stage(), upper);
relay.run();
}
}
public void clear(ListLaneView<?> view) {
final ListLaneRelayClear relay = new ListLaneRelayClear(this, stage());
relay.run();
}
public ListIterator<Map.Entry<Object, Value>> iterator() {
return this.data.entryIterator();
}
protected void openStore() {
this.data = this.laneContext.store().listData(laneUri().toString())
.isTransient(isTransient())
.isResident(isResident());
}
@Override
protected void willLoad() {
openStore();
super.willLoad();
}
static final int RESIDENT = 1 << 0;
static final int TRANSIENT = 1 << 1;
static final int SIGNED = 1 << 2;
}
final class ListLaneRelayUpdate extends LaneRelay<ListLaneModel, ListLaneView<?>> {
final Link link;
final CommandMessage message;
final int index;
Object key;
Form<Object> valueForm;
Value oldValue;
Object oldObject;
Value newValue;
Object newObject;
ListLaneRelayUpdate(ListLaneModel model, CommandMessage message, int index, Value newValue, Object key) {
super(model, 4);
this.link = null;
this.message = message;
this.index = index;
this.newValue = newValue;
this.key = key;
}
ListLaneRelayUpdate(ListLaneModel model, Link link, int index, Value newValue, Object key) {
super(model, 1, 3, null);
this.link = link;
this.message = null;
this.index = index;
this.newValue = newValue;
this.key = key;
}
ListLaneRelayUpdate(ListLaneModel model, Stage stage, int index, Value newValue, Object key) {
super(model, 1, 3, stage);
this.link = null;
this.message = null;
this.index = index;
this.newValue = newValue;
this.key = key;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
final Map.Entry<Object, Value> entry;
if (model.data.isEmpty()) {
entry = null;
} else {
entry = this.model.data.getEntry(this.index, this.key);
}
if (entry == null) {
if (this.key == null) {
final byte[] bytes = new byte[6];
ThreadLocalRandom.current().nextBytes(bytes);
this.key = Value.fromObject(bytes);
}
this.model.data.add(this.index, this.newValue, this.key);
} else {
this.oldValue = entry.getValue();
this.key = entry.getKey();
this.model.data.set(this.index, this.newValue, this.key);
}
if (this.oldValue == null) {
this.oldValue = Value.absent();
}
if (this.valueForm != null) {
this.oldObject = this.valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = this.valueForm.unit();
}
}
}
}
@SuppressWarnings("unchecked")
@Override
protected boolean runPhase(ListLaneView<?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneWillCommand(this.message);
}
return view.dispatchWillCommand(this.message.body(), preemptive);
} else if (phase == 1) {
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.oldObject = valueForm.cast(this.newValue);
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
}
if (preemptive) {
this.newObject = ((ListLaneView<Object>) view).laneWillUpdate(this.index, this.oldObject);
}
final Map.Entry<Boolean, Object> result = ((ListLaneView<Object>) view).dispatchWillUpdate(this.link, this.index, this.newObject, preemptive);
this.newObject = result.getValue();
if (this.oldObject != this.newObject) {
this.oldObject = this.newObject;
this.newValue = valueForm.mold(this.newObject).toValue();
}
return result.getKey();
} else if (phase == 2) {
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.oldObject = valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
this.newObject = valueForm.cast(this.newValue);
if (this.newObject == null) {
this.newObject = valueForm.unit();
}
}
if (preemptive) {
((ListLaneView<Object>) view).laneDidUpdate(this.index, this.newObject, this.oldObject);
}
return ((ListLaneView<Object>) view).dispatchDidUpdate(this.link, this.index, this.newObject, this.oldObject, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.laneDidCommand(this.message);
}
return view.dispatchDidCommand(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
this.model.sendDown(ListLinkDelta.update(this.index, Value.fromObject(this.key), this.newValue));
}
}
final class ListLaneRelayMove extends LaneRelay<ListLaneModel, ListLaneView<?>> {
final Link link;
final CommandMessage message;
final int fromIndex;
final int toIndex;
final Object key;
Form<Object> valueForm;
Value value;
Object object;
ListLaneRelayMove(ListLaneModel model, CommandMessage message, int fromIndex, int toIndex, Object key) {
super(model, 4);
this.link = null;
this.message = message;
this.fromIndex = fromIndex;
this.toIndex = toIndex;
this.key = key;
}
ListLaneRelayMove(ListLaneModel model, Link link, int fromIndex, int toIndex, Object key) {
super(model, 1, 3, null);
this.link = link;
this.message = null;
this.fromIndex = fromIndex;
this.toIndex = toIndex;
this.key = key;
}
ListLaneRelayMove(ListLaneModel model, Stage stage, int fromIndex, int toIndex, Object key) {
super(model, 1, 3, stage);
this.link = null;
this.message = null;
this.fromIndex = fromIndex;
this.toIndex = toIndex;
this.key = key;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
this.model.data.move(this.fromIndex, this.toIndex, this.key);
}
}
@SuppressWarnings("unchecked")
@Override
protected boolean runPhase(ListLaneView<?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneWillCommand(this.message);
}
return view.dispatchWillCommand(this.message.body(), preemptive);
} else if (phase == 1) {
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.value = this.model.data.get(this.fromIndex, this.key);
this.object = valueForm.cast(this.value);
if (this.object == null) {
this.object = valueForm.unit();
}
}
if (preemptive) {
((ListLaneView<Object>) view).laneWillMove(this.fromIndex, this.toIndex, this.object);
}
return ((ListLaneView<Object>) view).dispatchWillMove(this.link, this.fromIndex, this.toIndex, this.object, preemptive);
} else if (phase == 2) {
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.object = valueForm.cast(this.value);
if (this.object == null) {
this.object = valueForm.unit();
}
}
if (preemptive) {
((ListLaneView<Object>) view).laneDidMove(this.fromIndex, this.toIndex, this.object);
}
return ((ListLaneView<Object>) view).dispatchDidMove(this.link, this.fromIndex, this.toIndex, this.object, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.laneDidCommand(this.message);
}
return view.dispatchDidCommand(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
this.model.sendDown(ListLinkDelta.move(this.fromIndex, this.toIndex, Value.fromObject(this.key)));
}
}
final class ListLaneRelayRemove extends LaneRelay<ListLaneModel, ListLaneView<?>> {
final Link link;
final CommandMessage message;
final int index;
final Object key;
Form<Object> valueForm;
Value oldValue;
Object oldObject;
ListLaneRelayRemove(ListLaneModel model, CommandMessage message, int index, Object key) {
super(model, 4);
this.link = null;
this.message = message;
this.index = index;
this.key = key;
}
ListLaneRelayRemove(ListLaneModel model, Link link, int index, Object key) {
super(model, 1, 3, null);
this.link = link;
this.message = null;
this.index = index;
this.key = key;
}
ListLaneRelayRemove(ListLaneModel model, Stage stage, int index, Object key) {
super(model, 1, 3, stage);
this.link = null;
this.message = null;
this.index = index;
this.key = key;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
this.oldValue = this.model.data.remove(this.index, this.key);
if (this.valueForm != null) {
this.oldObject = this.valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = this.valueForm.unit();
}
}
}
}
@SuppressWarnings("unchecked")
@Override
protected boolean runPhase(ListLaneView<?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneWillCommand(this.message);
}
return view.dispatchWillCommand(this.message.body(), preemptive);
} else if (phase == 1) {
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
if (this.oldValue != null) {
this.oldObject = valueForm.cast(this.oldValue);
}
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
}
if (preemptive) {
view.laneWillRemove(this.index);
}
return view.dispatchWillRemove(this.link, this.index, preemptive);
} else if (phase == 2) {
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.oldObject = valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
}
if (preemptive) {
((ListLaneView<Object>) view).laneDidRemove(this.index, this.oldObject);
}
return ((ListLaneView<Object>) view).dispatchDidRemove(this.link, this.index, this.oldObject, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.laneDidCommand(this.message);
}
return view.dispatchDidCommand(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
this.model.sendDown(ListLinkDelta.remove(this.index, Value.fromObject(this.key)));
}
}
final class ListLaneRelayDrop extends LaneRelay<ListLaneModel, ListLaneView<?>> {
final Link link;
final CommandMessage message;
final int lower;
ListLaneRelayDrop(ListLaneModel model, CommandMessage message, int lower) {
super(model, 4);
this.link = null;
this.message = message;
this.lower = lower;
}
ListLaneRelayDrop(ListLaneModel model, Link link, int lower) {
super(model, 1, 3, null);
this.link = link;
this.message = null;
this.lower = lower;
}
ListLaneRelayDrop(ListLaneModel model, Stage stage, int lower) {
super(model, 1, 3, stage);
this.link = null;
this.message = null;
this.lower = lower;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
this.model.data.drop(this.lower);
}
}
@Override
protected boolean runPhase(ListLaneView<?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneWillCommand(this.message);
}
return view.dispatchWillCommand(this.message.body(), preemptive);
} else if (phase == 1) {
if (preemptive) {
view.laneWillDrop(this.lower);
}
return view.dispatchWillDrop(this.link, this.lower, preemptive);
} else if (phase == 2) {
if (preemptive) {
view.laneDidDrop(this.lower);
}
return view.dispatchDidDrop(this.link, this.lower, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.laneDidCommand(this.message);
}
return view.dispatchDidCommand(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
this.model.sendDown(ListLinkDelta.drop(this.lower));
}
}
final class ListLaneRelayTake extends LaneRelay<ListLaneModel, ListLaneView<?>> {
final Link link;
final CommandMessage message;
final int upper;
ListLaneRelayTake(ListLaneModel model, CommandMessage message, int upper) {
super(model, 4);
this.link = null;
this.message = message;
this.upper = upper;
}
ListLaneRelayTake(ListLaneModel model, Link link, int upper) {
super(model, 1, 3, null);
this.link = link;
this.message = null;
this.upper = upper;
}
ListLaneRelayTake(ListLaneModel model, Stage stage, int upper) {
super(model, 1, 3, stage);
this.link = null;
this.message = null;
this.upper = upper;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
this.model.data.take(this.upper);
}
}
@Override
protected boolean runPhase(ListLaneView<?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneWillCommand(this.message);
}
return view.dispatchWillCommand(this.message.body(), preemptive);
} else if (phase == 1) {
if (preemptive) {
view.laneWillTake(this.upper);
}
return view.dispatchWillTake(this.link, this.upper, preemptive);
} else if (phase == 2) {
if (preemptive) {
view.laneDidTake(this.upper);
}
return view.dispatchDidTake(this.link, this.upper, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.laneDidCommand(this.message);
}
return view.dispatchDidCommand(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
this.model.sendDown(ListLinkDelta.take(this.upper));
}
}
final class ListLaneRelayClear extends LaneRelay<ListLaneModel, ListLaneView<?>> {
final Link link;
final CommandMessage message;
ListLaneRelayClear(ListLaneModel model, CommandMessage message) {
super(model, 4);
this.link = null;
this.message = message;
}
ListLaneRelayClear(ListLaneModel model, Link link) {
super(model, 1, 3, null);
this.link = link;
this.message = null;
}
ListLaneRelayClear(ListLaneModel model, Stage stage) {
super(model, 1, 3, stage);
this.link = null;
this.message = null;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
this.model.data.clear();
}
}
@Override
protected boolean runPhase(ListLaneView<?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneWillCommand(this.message);
}
return view.dispatchWillCommand(this.message.body(), preemptive);
} else if (phase == 1) {
view.laneWillClear();
return view.dispatchWillClear(this.link, preemptive);
} else if (phase == 2) {
view.laneDidClear();
return view.dispatchDidClear(this.link, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.laneDidCommand(this.message);
}
return view.dispatchDidCommand(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
this.model.sendDown(ListLinkDelta.clear());
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/ListLaneUplink.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.runtime.lane;
import java.util.Iterator;
import java.util.Map;
import swim.concurrent.Stage;
import swim.runtime.WarpBinding;
import swim.runtime.warp.ListLinkDelta;
import swim.runtime.warp.ListUplinkModem;
import swim.structure.Value;
import swim.warp.SyncRequest;
public class ListLaneUplink extends ListUplinkModem {
final ListLaneModel laneBinding;
public ListLaneUplink(ListLaneModel laneBinding, WarpBinding linkBinding) {
super(linkBinding);
this.laneBinding = laneBinding;
}
@Override
public ListLaneModel laneBinding() {
return this.laneBinding;
}
@Override
public Stage stage() {
return this.laneBinding.stage();
}
@Override
protected void willSync(SyncRequest request) {
final Iterator<Map.Entry<Object, Value>> items = this.laneBinding.iterator();
int index = 0;
while (items.hasNext()) {
final Map.Entry<Object, Value> item = items.next();
queueDown(ListLinkDelta.update(index, Value.fromObject(item.getKey()), item.getValue()));
index += 1;
}
super.willSync(request);
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/ListLaneView.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.runtime.lane;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import swim.api.Lane;
import swim.api.Link;
import swim.api.SwimContext;
import swim.api.agent.AgentContext;
import swim.api.data.ListData;
import swim.api.lane.ListLane;
import swim.api.warp.function.DidCommand;
import swim.api.warp.function.DidEnter;
import swim.api.warp.function.DidLeave;
import swim.api.warp.function.DidUplink;
import swim.api.warp.function.WillCommand;
import swim.api.warp.function.WillEnter;
import swim.api.warp.function.WillLeave;
import swim.api.warp.function.WillUplink;
import swim.concurrent.Conts;
import swim.observable.function.DidClear;
import swim.observable.function.DidDrop;
import swim.observable.function.DidMoveIndex;
import swim.observable.function.DidRemoveIndex;
import swim.observable.function.DidTake;
import swim.observable.function.DidUpdateIndex;
import swim.observable.function.WillClear;
import swim.observable.function.WillDrop;
import swim.observable.function.WillMoveIndex;
import swim.observable.function.WillRemoveIndex;
import swim.observable.function.WillTake;
import swim.observable.function.WillUpdateIndex;
import swim.runtime.warp.WarpLaneView;
import swim.structure.Form;
import swim.util.KeyedList;
public class ListLaneView<V> extends WarpLaneView implements ListLane<V> {
protected final AgentContext agentContext;
protected Form<V> valueForm;
protected int flags;
protected ListLaneModel laneBinding;
protected ListData<V> dataView;
ListLaneView(AgentContext agentContext, Form<V> valueForm, int flags, Object observers) {
super(observers);
this.agentContext = agentContext;
this.valueForm = valueForm;
this.flags = flags;
}
public ListLaneView(AgentContext agentContext, Form<V> valueForm) {
this(agentContext, valueForm, 0, null);
}
@Override
public AgentContext agentContext() {
return this.agentContext;
}
@Override
public ListLaneModel laneBinding() {
return this.laneBinding;
}
void setLaneBinding(ListLaneModel laneBinding) {
this.laneBinding = laneBinding;
}
@Override
public ListLaneModel createLaneBinding() {
return new ListLaneModel(this.flags);
}
@Override
public final Form<V> valueForm() {
return this.valueForm;
}
@Override
public <V2> ListLaneView<V2> valueForm(Form<V2> valueForm) {
return new ListLaneView<V2>(this.agentContext, valueForm, this.flags,
typesafeObservers(this.observers));
}
@Override
public <V2> ListLaneView<V2> valueClass(Class<V2> valueClass) {
return valueForm(Form.<V2>forClass(valueClass));
}
public void setValueForm(Form<V> valueForm) {
this.valueForm = valueForm;
}
protected Object typesafeObservers(Object observers) {
// TODO: filter out WillUpdateIndex, DidUpdateIndex,
// WillMoveIndex, DidMoveIndex, WillRemoveIndex, DidRemoveIndex,
// WillDrop, DidDrop, WillTake, DidTake, WillClear, DidClear
return observers;
}
public final boolean isResident() {
return (this.flags & RESIDENT) != 0;
}
@Override
public ListLaneView<V> isResident(boolean isResident) {
if (isResident) {
this.flags |= RESIDENT;
} else {
this.flags &= ~RESIDENT;
}
final ListLaneModel laneBinding = this.laneBinding;
if (laneBinding != null) {
laneBinding.isResident(isResident);
}
return this;
}
void didSetResident(boolean isResident) {
if (isResident) {
this.flags |= RESIDENT;
} else {
this.flags &= ~RESIDENT;
}
}
public final boolean isTransient() {
return (this.flags & TRANSIENT) != 0;
}
@Override
public ListLaneView<V> isTransient(boolean isTransient) {
if (isTransient) {
this.flags |= TRANSIENT;
} else {
this.flags &= ~TRANSIENT;
}
final ListLaneModel laneBinding = this.laneBinding;
if (laneBinding != null) {
laneBinding.isTransient(isTransient);
}
return this;
}
void didSetTransient(boolean isTransient) {
if (isTransient) {
this.flags |= TRANSIENT;
} else {
this.flags &= ~TRANSIENT;
}
}
@Override
protected void willLoad() {
this.dataView = this.laneBinding.data.valueForm(this.valueForm);
super.willLoad();
}
@Override
public void close() {
this.laneBinding.closeLaneView(this);
}
@Override
public ListLaneView<V> observe(Object observer) {
super.observe(observer);
return this;
}
@Override
public ListLaneView<V> unobserve(Object observer) {
super.unobserve(observer);
return this;
}
@Override
public ListLaneView<V> willUpdate(WillUpdateIndex<V> willUpdate) {
return observe(willUpdate);
}
@Override
public ListLaneView<V> didUpdate(DidUpdateIndex<V> didUpdate) {
return observe(didUpdate);
}
@Override
public ListLaneView<V> willMove(WillMoveIndex<V> willMove) {
return observe(willMove);
}
@Override
public ListLaneView<V> didMove(DidMoveIndex<V> didMove) {
return observe(didMove);
}
@Override
public ListLaneView<V> willRemove(WillRemoveIndex willRemove) {
return observe(willRemove);
}
@Override
public ListLaneView<V> didRemove(DidRemoveIndex<V> didRemove) {
return observe(didRemove);
}
@Override
public ListLaneView<V> willDrop(WillDrop willDrop) {
return observe(willDrop);
}
@Override
public ListLaneView<V> didDrop(DidDrop didDrop) {
return observe(didDrop);
}
@Override
public ListLaneView<V> willTake(WillTake willTake) {
return observe(willTake);
}
@Override
public ListLaneView<V> didTake(DidTake didTake) {
return observe(didTake);
}
@Override
public ListLaneView<V> willClear(WillClear willClear) {
return observe(willClear);
}
@Override
public ListLaneView<V> didClear(DidClear didClear) {
return observe(didClear);
}
@Override
public ListLaneView<V> willCommand(WillCommand willCommand) {
return observe(willCommand);
}
@Override
public ListLaneView<V> didCommand(DidCommand didCommand) {
return observe(didCommand);
}
@Override
public ListLaneView<V> willUplink(WillUplink willUplink) {
return observe(willUplink);
}
@Override
public ListLaneView<V> didUplink(DidUplink didUplink) {
return observe(didUplink);
}
@Override
public ListLaneView<V> willEnter(WillEnter willEnter) {
return observe(willEnter);
}
@Override
public ListLaneView<V> didEnter(DidEnter didEnter) {
return observe(didEnter);
}
@Override
public ListLaneView<V> willLeave(WillLeave willLeave) {
return observe(willLeave);
}
@Override
public ListLaneView<V> didLeave(DidLeave didLeave) {
return observe(didLeave);
}
@SuppressWarnings("unchecked")
public Map.Entry<Boolean, V> dispatchWillUpdate(Link link, int index, V newValue, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillUpdateIndex<?>) {
if (((WillUpdateIndex<?>) observers).isPreemptive() == preemptive) {
try {
newValue = ((WillUpdateIndex<V>) observers).willUpdate(index, newValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillUpdateIndex<?>) {
if (((WillUpdateIndex<?>) observer).isPreemptive() == preemptive) {
try {
newValue = ((WillUpdateIndex<V>) observer).willUpdate(index, newValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return new AbstractMap.SimpleImmutableEntry<Boolean, V>(complete, newValue);
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
@SuppressWarnings("unchecked")
public boolean dispatchDidUpdate(Link link, int index, V newValue, V oldValue, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidUpdateIndex<?>) {
if (((DidUpdateIndex<?>) observers).isPreemptive() == preemptive) {
try {
((DidUpdateIndex<V>) observers).didUpdate(index, newValue, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidUpdateIndex<?>) {
if (((DidUpdateIndex<?>) observer).isPreemptive() == preemptive) {
try {
((DidUpdateIndex<V>) observer).didUpdate(index, newValue, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
@SuppressWarnings("unchecked")
public boolean dispatchWillMove(Link link, int fromIndex, int toIndex, V value, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillMoveIndex<?>) {
if (((WillMoveIndex<?>) observers).isPreemptive() == preemptive) {
try {
((WillMoveIndex<V>) observers).willMove(fromIndex, toIndex, value);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillMoveIndex<?>) {
if (((WillMoveIndex<?>) observer).isPreemptive() == preemptive) {
try {
((WillMoveIndex<V>) observer).willMove(fromIndex, toIndex, value);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
@SuppressWarnings("unchecked")
public boolean dispatchDidMove(Link link, int fromIndex, int toIndex, V value, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidMoveIndex<?>) {
if (((DidMoveIndex<?>) observers).isPreemptive() == preemptive) {
try {
((DidMoveIndex<V>) observers).didMove(fromIndex, toIndex, value);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidMoveIndex<?>) {
if (((DidMoveIndex<?>) observer).isPreemptive() == preemptive) {
try {
((DidMoveIndex<V>) observer).didMove(fromIndex, toIndex, value);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
public boolean dispatchWillRemove(Link link, int index, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillRemoveIndex) {
if (((WillRemoveIndex) observers).isPreemptive() == preemptive) {
try {
((WillRemoveIndex) observers).willRemove(index);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillRemoveIndex) {
if (((WillRemoveIndex) observer).isPreemptive() == preemptive) {
try {
((WillRemoveIndex) observer).willRemove(index);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
@SuppressWarnings("unchecked")
public boolean dispatchDidRemove(Link link, int index, V oldValue, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidRemoveIndex<?>) {
if (((DidRemoveIndex<?>) observers).isPreemptive() == preemptive) {
try {
((DidRemoveIndex<V>) observers).didRemove(index, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidRemoveIndex<?>) {
if (((DidRemoveIndex<?>) observer).isPreemptive() == preemptive) {
try {
((DidRemoveIndex<V>) observer).didRemove(index, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
public boolean dispatchWillDrop(Link link, int lower, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillDrop) {
if (((WillDrop) observers).isPreemptive() == preemptive) {
try {
((WillDrop) observers).willDrop(lower);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillDrop) {
if (((WillDrop) observer).isPreemptive() == preemptive) {
try {
((WillDrop) observer).willDrop(lower);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
public boolean dispatchDidDrop(Link link, int lower, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidDrop) {
if (((DidDrop) observers).isPreemptive() == preemptive) {
try {
((DidDrop) observers).didDrop(lower);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidDrop) {
if (((DidDrop) observer).isPreemptive() == preemptive) {
try {
((DidDrop) observer).didDrop(lower);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
public boolean dispatchWillTake(Link link, int upper, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillTake) {
if (((WillTake) observers).isPreemptive() == preemptive) {
try {
((WillTake) observers).willTake(upper);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillTake) {
if (((WillTake) observer).isPreemptive() == preemptive) {
try {
((WillTake) observer).willTake(upper);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
public boolean dispatchDidTake(Link link, int upper, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidTake) {
if (((DidTake) observers).isPreemptive() == preemptive) {
try {
((DidTake) observers).didTake(upper);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidTake) {
if (((DidTake) observer).isPreemptive() == preemptive) {
try {
((DidTake) observer).didTake(upper);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
public boolean dispatchWillClear(Link link, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillClear) {
if (((WillClear) observers).isPreemptive() == preemptive) {
try {
((WillClear) observers).willClear();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillClear) {
if (((WillClear) observer).isPreemptive() == preemptive) {
try {
((WillClear) observer).willClear();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
public boolean dispatchDidClear(Link link, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidClear) {
if (((DidClear) observers).isPreemptive() == preemptive) {
try {
((DidClear) observers).didClear();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidClear) {
if (((DidClear) observer).isPreemptive() == preemptive) {
try {
((DidClear) observer).didClear();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
public V laneWillInsert(int index, V newValue) {
return newValue;
}
public void laneDidInsert(int index, V newValue) {
}
public V laneWillUpdate(int index, V newValue) {
return newValue;
}
public void laneDidUpdate(int index, V newValue, V oldValue) {
}
public void laneWillMove(int fromIndex, int toIndex, V value) {
}
public void laneDidMove(int fromIndex, int toIndex, V value) {
}
public void laneWillRemove(int index) {
}
public void laneDidRemove(int index, V oldValue) {
}
public void laneWillDrop(int lower) {
}
public void laneDidDrop(int lower) {
}
public void laneWillTake(int upper) {
}
public void laneDidTake(int upper) {
}
public void laneWillClear() {
}
public void laneDidClear() {
}
@Override
public boolean isEmpty() {
return this.dataView.isEmpty();
}
@Override
public boolean contains(Object o) {
return this.dataView.contains(o);
}
@Override
public Iterator<V> iterator() {
return this.dataView.iterator();
}
@Override
public Object[] toArray() {
return this.dataView.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return this.dataView.toArray(a);
}
@Override
public boolean add(V v) {
return this.laneBinding.add(this, size(), v);
}
@Override
public boolean remove(Object o) {
final int index = indexOf(o);
if (index != -1) {
final V oldObject = this.laneBinding.remove(this, index);
return oldObject != null && oldObject != this.valueForm.unit(); // TODO
}
return false;
}
@Override
public boolean containsAll(Collection<?> elements) {
return this.dataView.containsAll(elements);
}
@Override
public boolean addAll(Collection<? extends V> elements) {
boolean added = false;
for (V element: elements) {
added = added || add(element);
}
return added;
}
@Override
public boolean addAll(int index, Collection<? extends V> elements) {
int position = index;
for (V element: elements) {
add(position++, element);
}
return elements.isEmpty();
}
@Override
public boolean removeAll(Collection<?> elements) {
boolean didRemove = false;
for (Object element: elements) {
final int index = indexOf(element);
if (index != -1) {
didRemove = didRemove || remove(element);
}
}
return didRemove;
}
@Override
public boolean retainAll(Collection<?> elements) {
boolean modified = false;
for (Object element: elements) {
if (!elements.contains(element)) {
modified = modified || remove(element);
}
}
return modified;
}
@Override
public int size() {
return this.dataView.size();
}
@Override
public void drop(int lower) {
this.laneBinding.drop(this, lower);
}
@Override
public void take(int upper) {
this.laneBinding.take(this, upper);
}
@Override
public void clear() {
this.laneBinding.clear(this);
}
@Override
public V get(int index) {
return this.dataView.get(index);
}
@Override
public V set(int index, V element) {
return this.laneBinding.set(this, index, element);
}
@Override
public void add(int index, V element) {
this.laneBinding.add(this, index, element);
}
@Override
public V remove(int index) {
return this.laneBinding.remove(this, index);
}
@Override
public int indexOf(Object o) {
return this.dataView.indexOf(o);
}
@Override
public int lastIndexOf(Object o) {
return this.dataView.lastIndexOf(o);
}
@Override
public ListIterator<V> listIterator() {
return this.dataView.listIterator();
}
@Override
public ListIterator<V> listIterator(int index) {
return this.dataView.listIterator(index);
}
@Override
public List<V> subList(int fromIndex, int toIndex) {
return this.dataView.subList(fromIndex, toIndex);
}
@Override
public KeyedList<V> snapshot() {
return this.dataView.snapshot();
}
@Override
public V get(int index, Object key) {
return this.dataView.get(index, key);
}
@Override
public Map.Entry<Object, V> getEntry(int index) {
return this.dataView.getEntry(index);
}
@Override
public Map.Entry<Object, V> getEntry(int index, Object key) {
return this.dataView.getEntry(index, key);
}
@Override
public V set(int index, V element, Object key) {
return this.laneBinding.set(this, index, element, key);
}
@Override
public boolean add(V element, Object key) {
return this.laneBinding.add(this, size(), element, key);
}
@Override
public void add(int index, V element, Object key) {
this.laneBinding.add(this, index, element, key);
}
@Override
public V remove(int index, Object key) {
return this.laneBinding.remove(this, index, key);
}
@Override
public void move(int fromIndex, int toIndex) {
this.laneBinding.move(fromIndex, toIndex);
}
@Override
public void move(int fromIndex, int toIndex, Object key) {
this.laneBinding.move(fromIndex, toIndex, key);
}
@Override
public ListIterator<Object> keyIterator() {
return this.dataView.keyIterator();
}
@Override
public ListIterator<Map.Entry<Object, V>> entryIterator() {
return this.dataView.entryIterator();
}
static final int RESIDENT = 1 << 0;
static final int TRANSIENT = 1 << 1;
static final int SIGNED = 1 << 2;
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/MapLaneModel.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.runtime.lane;
import java.util.Iterator;
import java.util.Map;
import swim.api.Link;
import swim.api.data.MapData;
import swim.collections.FingerTrieSeq;
import swim.concurrent.Stage;
import swim.runtime.LaneRelay;
import swim.runtime.LaneView;
import swim.runtime.WarpBinding;
import swim.runtime.warp.WarpLaneModel;
import swim.structure.Form;
import swim.structure.Record;
import swim.structure.Value;
import swim.warp.CommandMessage;
public class MapLaneModel extends WarpLaneModel<MapLaneView<?, ?>, MapLaneUplink> {
protected int flags;
protected MapData<Value, Value> data;
MapLaneModel(int flags) {
this.flags = flags;
}
public MapLaneModel() {
this(0);
}
@Override
public String laneType() {
return "map";
}
@Override
protected MapLaneUplink createWarpUplink(WarpBinding link) {
return new MapLaneUplink(this, link);
}
@Override
protected void didOpenLaneView(MapLaneView<?, ?> view) {
view.setLaneBinding(this);
}
@Override
public void onCommand(CommandMessage message) {
final Value payload = message.body();
final String tag = payload.tag();
if ("update".equals(tag)) {
final Value header = payload.header("update");
final Value key = header.get("key");
final Value value = payload.body();
new MapLaneRelayUpdate(this, message, key, value).run();
} else if ("remove".equals(tag)) {
final Value header = payload.header("remove");
final Value key = header.get("key");
new MapLaneRelayRemove(this, message, key).run();
} else if ("drop".equals(tag)) {
final Value header = payload.header("drop");
final int lower = header.intValue(0);
new MapLaneRelayDrop(this, message, lower).run();
} else if ("take".equals(tag)) {
final Value header = payload.header("take");
final int upper = header.intValue(0);
new MapLaneRelayTake(this, message, upper).run();
} else if ("clear".equals(tag)) {
new MapLaneRelayClear(this, message).run();
}
}
protected void cueDownKey(Value key) {
FingerTrieSeq<MapLaneUplink> uplinks;
do {
uplinks = this.uplinks;
for (int i = 0, n = uplinks.size(); i < n; i += 1) {
uplinks.get(i).cueDownKey(key);
}
} while (uplinks != this.uplinks);
}
public final boolean isResident() {
return (this.flags & RESIDENT) != 0;
}
public MapLaneModel isResident(boolean isResident) {
if (this.data != null) {
this.data.isResident(isResident);
}
if (isResident) {
this.flags |= RESIDENT;
} else {
this.flags &= ~RESIDENT;
}
final Object views = this.views;
if (views instanceof MapLaneView<?, ?>) {
((MapLaneView<?, ?>) views).didSetResident(isResident);
} else if (views instanceof LaneView[]) {
final LaneView[] viewArray = (LaneView[]) views;
for (int i = 0, n = viewArray.length; i < n; i += 1) {
((MapLaneView<?, ?>) viewArray[i]).didSetResident(isResident);
}
}
return this;
}
public final boolean isTransient() {
return (this.flags & TRANSIENT) != 0;
}
public MapLaneModel isTransient(boolean isTransient) {
if (this.data != null) {
this.data.isTransient(isTransient);
}
if (isTransient) {
this.flags |= TRANSIENT;
} else {
this.flags &= ~TRANSIENT;
}
final Object views = this.views;
if (views instanceof MapLaneView<?, ?>) {
((MapLaneView<?, ?>) views).didSetTransient(isTransient);
} else if (views instanceof LaneView[]) {
final LaneView[] viewArray = (LaneView[]) views;
for (int i = 0, n = viewArray.length; i < n; i += 1) {
((MapLaneView<?, ?>) viewArray[i]).didSetTransient(isTransient);
}
}
return this;
}
public Value get(Value key) {
if (key != null) {
return this.data.get(key);
} else {
return Value.absent();
}
}
@SuppressWarnings("unchecked")
public <K, V> V put(MapLaneView<K, V> view, K keyObject, V newObject) {
final Form<K> keyForm = view.keyForm;
final Form<V> valueForm = view.valueForm;
final Value key = keyForm.mold(keyObject).toValue();
final Value newValue = valueForm.mold(newObject).toValue();
final MapLaneRelayUpdate relay = new MapLaneRelayUpdate(this, stage(), key, newValue);
relay.keyForm = (Form<Object>) keyForm;
relay.valueForm = (Form<Object>) valueForm;
relay.keyObject = keyObject;
relay.oldObject = newObject;
relay.newObject = newObject;
relay.run();
if (relay.valueForm != valueForm && valueForm != null) {
relay.oldObject = valueForm.cast(relay.oldValue);
if (relay.oldObject == null) {
relay.oldObject = valueForm.unit();
}
}
return (V) relay.oldObject;
}
@SuppressWarnings("unchecked")
public <K, V> V remove(MapLaneView<K, V> view, K keyObject) {
final Form<K> keyForm = view.keyForm;
final Form<V> valueForm = view.valueForm;
final Value key = keyForm.mold(keyObject).toValue();
final MapLaneRelayRemove relay = new MapLaneRelayRemove(this, stage(), key);
relay.keyForm = (Form<Object>) keyForm;
relay.valueForm = (Form<Object>) valueForm;
relay.keyObject = keyObject;
relay.run();
if (relay.valueForm == valueForm || valueForm == null) {
return (V) relay.oldObject;
} else {
return valueForm.unit();
}
}
public void drop(MapLaneView<?, ?> view, int lower) {
if (lower > 0) {
final MapLaneRelayDrop relay = new MapLaneRelayDrop(this, stage(), lower);
relay.run();
}
}
public void take(MapLaneView<?, ?> view, int upper) {
if (upper > 0) {
final MapLaneRelayTake relay = new MapLaneRelayTake(this, stage(), upper);
relay.run();
}
}
public void clear(MapLaneView<?, ?> view) {
final MapLaneRelayClear relay = new MapLaneRelayClear(this, stage());
relay.run();
}
public Iterator<Map.Entry<Value, Value>> iterator() {
return this.data.iterator();
}
protected void openStore() {
this.data = this.laneContext.store().mapData(laneUri().toString())
.isTransient(isTransient())
.isResident(isResident());
}
@Override
protected void willLoad() {
openStore();
super.willLoad();
}
static final int RESIDENT = 1 << 0;
static final int TRANSIENT = 1 << 1;
static final int SIGNED = 1 << 2;
}
final class MapLaneRelayUpdate extends LaneRelay<MapLaneModel, MapLaneView<?, ?>> {
final Link link;
final CommandMessage message;
Form<Object> keyForm;
Form<Object> valueForm;
final Value key;
Object keyObject;
Value oldValue;
Object oldObject;
Value newValue;
Object newObject;
MapLaneRelayUpdate(MapLaneModel model, CommandMessage message, Value key, Value newValue) {
super(model, 4);
this.link = null;
this.message = message;
this.key = key;
this.newValue = newValue;
}
MapLaneRelayUpdate(MapLaneModel model, Link link, Value key, Value newValue) {
super(model, 1, 3, null);
this.link = link;
this.message = null;
this.key = key;
this.newValue = newValue;
}
MapLaneRelayUpdate(MapLaneModel model, Stage stage, Value key, Value newValue) {
super(model, 1, 3, stage);
this.link = null;
this.message = null;
this.key = key;
this.newValue = newValue;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
this.oldValue = this.model.data.put(this.key, this.newValue);
if (this.valueForm != null) {
this.oldObject = this.valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = this.valueForm.unit();
}
}
}
}
@SuppressWarnings("unchecked")
@Override
protected boolean runPhase(MapLaneView<?, ?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneWillCommand(this.message);
}
return view.dispatchWillCommand(this.message.body(), preemptive);
} else if (phase == 1) {
final Form<Object> keyForm = (Form<Object>) view.keyForm;
if (this.keyForm != keyForm && keyForm != null) {
this.keyForm = keyForm;
this.keyObject = keyForm.cast(this.key);
if (this.keyObject == null) {
this.keyObject = keyForm.unit();
}
}
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.oldObject = valueForm.cast(this.newValue);
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
}
if (preemptive) {
this.newObject = ((MapLaneView<Object, Object>) view).laneWillUpdate(this.keyObject, this.oldObject);
}
final Map.Entry<Boolean, Object> result = ((MapLaneView<Object, Object>) view).dispatchWillUpdate(this.link, this.keyObject, this.oldObject, preemptive);
this.newObject = result.getValue();
if (this.oldObject != this.newObject) {
this.oldObject = this.newObject;
this.newValue = valueForm.mold(this.newObject).toValue();
}
return result.getKey();
} else if (phase == 2) {
final Form<Object> keyForm = (Form<Object>) view.keyForm;
if (this.keyForm != keyForm && keyForm != null) {
this.keyForm = keyForm;
this.keyObject = keyForm.cast(this.key);
if (this.keyObject == null) {
this.keyObject = keyForm.unit();
}
}
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.oldObject = valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
this.newObject = valueForm.cast(this.newValue);
if (this.newObject == null) {
this.newObject = valueForm.unit();
}
}
if (preemptive) {
((MapLaneView<Object, Object>) view).laneDidUpdate(this.keyObject, this.newObject, this.oldObject);
}
return ((MapLaneView<Object, Object>) view).dispatchDidUpdate(this.link, this.keyObject, this.newObject, this.oldObject, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.laneDidCommand(this.message);
}
return view.dispatchDidCommand(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
this.model.cueDownKey(this.key);
}
}
final class MapLaneRelayRemove extends LaneRelay<MapLaneModel, MapLaneView<?, ?>> {
final Link link;
final CommandMessage message;
Form<Object> keyForm;
Form<Object> valueForm;
final Value key;
Object keyObject;
Value oldValue;
Object oldObject;
MapLaneRelayRemove(MapLaneModel model, CommandMessage message, Value key) {
super(model, 4);
this.link = null;
this.message = message;
this.key = key;
}
MapLaneRelayRemove(MapLaneModel model, Link link, Value key) {
super(model, 1, 3, null);
this.link = link;
this.message = null;
this.key = key;
}
MapLaneRelayRemove(MapLaneModel model, Stage stage, Value key) {
super(model, 1, 3, stage);
this.link = null;
this.message = null;
this.key = key;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
this.oldValue = this.model.data.remove(this.key);
if (this.valueForm != null) {
this.oldObject = this.valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = this.valueForm.unit();
}
}
}
}
@SuppressWarnings("unchecked")
@Override
protected boolean runPhase(MapLaneView<?, ?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneWillCommand(this.message);
}
return view.dispatchWillCommand(this.message.body(), preemptive);
} else if (phase == 1) {
final Form<Object> keyForm = (Form<Object>) view.keyForm;
if (this.keyForm != keyForm && keyForm != null) {
this.keyForm = keyForm;
this.keyObject = keyForm.cast(this.key);
if (this.keyObject == null) {
this.keyObject = keyForm.unit();
}
}
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
if (this.oldValue != null) {
this.oldObject = valueForm.cast(this.oldValue);
}
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
}
if (preemptive) {
((MapLaneView<Object, Object>) view).laneWillRemove(this.keyObject);
}
return ((MapLaneView<Object, Object>) view).dispatchWillRemove(this.link, this.keyObject, preemptive);
} else if (phase == 2) {
final Form<Object> keyForm = (Form<Object>) view.keyForm;
if (this.keyForm != keyForm && keyForm != null) {
this.keyForm = keyForm;
this.keyObject = keyForm.cast(this.key);
if (this.keyObject == null) {
this.keyObject = keyForm.unit();
}
}
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.oldObject = valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
}
if (preemptive) {
((MapLaneView<Object, Object>) view).laneDidRemove(this.keyObject, this.oldObject);
}
return ((MapLaneView<Object, Object>) view).dispatchDidRemove(this.link, this.keyObject, this.oldObject, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.laneDidCommand(this.message);
}
return view.dispatchDidCommand(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
if (this.oldValue.isDefined()) {
this.model.sendDown(Record.create(1).attr("remove", Record.create(1).slot("key", this.key)));
}
}
}
final class MapLaneRelayDrop extends LaneRelay<MapLaneModel, MapLaneView<?, ?>> {
final Link link;
final CommandMessage message;
final int lower;
MapLaneRelayDrop(MapLaneModel model, CommandMessage message, int lower) {
super(model, 4);
this.link = null;
this.message = message;
this.lower = lower;
}
MapLaneRelayDrop(MapLaneModel model, Link link, int lower) {
super(model, 1, 3, null);
this.link = link;
this.message = null;
this.lower = lower;
}
MapLaneRelayDrop(MapLaneModel model, Stage stage, int lower) {
super(model, 1, 3, stage);
this.link = null;
this.message = null;
this.lower = lower;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
this.model.data.drop(this.lower);
}
}
@Override
protected boolean runPhase(MapLaneView<?, ?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneWillCommand(this.message);
}
return view.dispatchWillCommand(this.message.body(), preemptive);
} else if (phase == 1) {
if (preemptive) {
view.laneWillDrop(this.lower);
}
return view.dispatchWillDrop(this.link, this.lower, preemptive);
} else if (phase == 2) {
if (preemptive) {
view.laneDidDrop(this.lower);
}
return view.dispatchDidDrop(this.link, this.lower, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.laneDidCommand(this.message);
}
return view.dispatchDidCommand(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
this.model.sendDown(Record.create(1).attr("drop", this.lower));
}
}
final class MapLaneRelayTake extends LaneRelay<MapLaneModel, MapLaneView<?, ?>> {
final Link link;
final CommandMessage message;
final int upper;
MapLaneRelayTake(MapLaneModel model, CommandMessage message, int upper) {
super(model, 4);
this.link = null;
this.message = message;
this.upper = upper;
}
MapLaneRelayTake(MapLaneModel model, Link link, int upper) {
super(model, 1, 3, null);
this.link = link;
this.message = null;
this.upper = upper;
}
MapLaneRelayTake(MapLaneModel model, Stage stage, int upper) {
super(model, 1, 3, stage);
this.link = null;
this.message = null;
this.upper = upper;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
this.model.data.take(this.upper);
}
}
@Override
protected boolean runPhase(MapLaneView<?, ?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneWillCommand(this.message);
}
return view.dispatchWillCommand(this.message.body(), preemptive);
} else if (phase == 1) {
if (preemptive) {
view.laneWillTake(this.upper);
}
return view.dispatchWillTake(this.link, this.upper, preemptive);
} else if (phase == 2) {
if (preemptive) {
view.laneDidTake(this.upper);
}
return view.dispatchDidTake(this.link, this.upper, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.laneDidCommand(this.message);
}
return view.dispatchDidCommand(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
this.model.sendDown(Record.create(1).attr("take", this.upper));
}
}
final class MapLaneRelayClear extends LaneRelay<MapLaneModel, MapLaneView<?, ?>> {
final Link link;
final CommandMessage message;
MapLaneRelayClear(MapLaneModel model, CommandMessage message) {
super(model, 4);
this.link = null;
this.message = message;
}
MapLaneRelayClear(MapLaneModel model, Link link) {
super(model, 1, 3, null);
this.link = link;
this.message = null;
}
MapLaneRelayClear(MapLaneModel model, Stage stage) {
super(model, 1, 3, stage);
this.link = null;
this.message = null;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
this.model.data.clear();
}
}
@Override
protected boolean runPhase(MapLaneView<?, ?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneWillCommand(this.message);
}
return view.dispatchWillCommand(this.message.body(), preemptive);
} else if (phase == 1) {
if (preemptive) {
view.laneWillClear();
}
return view.dispatchWillClear(this.link, preemptive);
} else if (phase == 2) {
if (preemptive) {
view.laneDidClear();
}
return view.dispatchDidClear(this.link, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.laneDidCommand(this.message);
}
return view.dispatchDidCommand(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
this.model.sendDown(Record.create(1).attr("clear"));
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/MapLaneUplink.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.runtime.lane;
import swim.concurrent.Stage;
import swim.runtime.WarpBinding;
import swim.runtime.warp.PartialUplinkModem;
import swim.structure.Attr;
import swim.structure.Record;
import swim.structure.Value;
import swim.warp.SyncRequest;
public class MapLaneUplink extends PartialUplinkModem {
final MapLaneModel laneBinding;
public MapLaneUplink(MapLaneModel laneBinding, WarpBinding linkBinding) {
super(linkBinding);
this.laneBinding = laneBinding;
}
@Override
public MapLaneModel laneBinding() {
return this.laneBinding;
}
@Override
public Stage stage() {
return this.laneBinding.stage();
}
@Override
protected Value nextDownKey(Value key) {
final Value value = this.laneBinding.get(key);
if (value != null) {
return Attr.of("update", Record.create(1).slot("key", key)).concat(value);
} else {
return null;
}
}
@Override
protected void willSync(SyncRequest request) {
syncDown(this.laneBinding.iterator());
super.willSync(request);
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/MapLaneView.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.runtime.lane;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import swim.api.Lane;
import swim.api.Link;
import swim.api.SwimContext;
import swim.api.agent.AgentContext;
import swim.api.data.MapData;
import swim.api.lane.MapLane;
import swim.api.warp.function.DidCommand;
import swim.api.warp.function.DidEnter;
import swim.api.warp.function.DidLeave;
import swim.api.warp.function.DidUplink;
import swim.api.warp.function.WillCommand;
import swim.api.warp.function.WillEnter;
import swim.api.warp.function.WillLeave;
import swim.api.warp.function.WillUplink;
import swim.collections.HashTrieMap;
import swim.concurrent.Conts;
import swim.observable.function.DidClear;
import swim.observable.function.DidDrop;
import swim.observable.function.DidRemoveKey;
import swim.observable.function.DidTake;
import swim.observable.function.DidUpdateKey;
import swim.observable.function.WillClear;
import swim.observable.function.WillDrop;
import swim.observable.function.WillRemoveKey;
import swim.observable.function.WillTake;
import swim.observable.function.WillUpdateKey;
import swim.runtime.warp.WarpLaneView;
import swim.streamlet.Inlet;
import swim.streamlet.KeyEffect;
import swim.streamlet.KeyOutlet;
import swim.streamlet.MapInlet;
import swim.streamlet.MapOutlet;
import swim.streamlet.Outlet;
import swim.structure.Form;
import swim.util.Cursor;
import swim.util.OrderedMap;
import swim.util.OrderedMapCursor;
public class MapLaneView<K, V> extends WarpLaneView implements MapLane<K, V> {
protected final AgentContext agentContext;
protected Form<K> keyForm;
protected Form<V> valueForm;
protected int flags;
protected MapLaneModel laneBinding;
protected MapData<K, V> dataView;
protected MapOutlet<K, V, ? extends Map<K, V>> input;
protected HashTrieMap<K, KeyEffect> effects;
protected HashTrieMap<K, KeyOutlet<K, V>> outlets;
protected Inlet<? super MapLane<K, V>>[] outputs; // TODO: unify with observers
protected int version;
MapLaneView(AgentContext agentContext, Form<K> keyForm, Form<V> valueForm,
int flags, Object observers) {
super(observers);
this.agentContext = agentContext;
this.keyForm = keyForm;
this.valueForm = valueForm;
this.flags = flags;
this.input = null;
this.effects = HashTrieMap.empty();
this.outlets = HashTrieMap.empty();
this.outputs = null;
this.version = -1;
}
public MapLaneView(AgentContext agentContext, Form<K> keyForm, Form<V> valueForm) {
this(agentContext, keyForm, valueForm, 0, null);
}
@Override
public AgentContext agentContext() {
return this.agentContext;
}
@Override
public MapLaneModel laneBinding() {
return this.laneBinding;
}
void setLaneBinding(MapLaneModel laneBinding) {
this.laneBinding = laneBinding;
}
@Override
public MapLaneModel createLaneBinding() {
return new MapLaneModel(this.flags);
}
@Override
public final Form<K> keyForm() {
return this.keyForm;
}
@Override
public <K2> MapLaneView<K2, V> keyForm(Form<K2> keyForm) {
return new MapLaneView<K2, V>(this.agentContext, keyForm, this.valueForm,
this.flags, typesafeObservers(this.observers));
}
@Override
public <K2> MapLaneView<K2, V> keyClass(Class<K2> keyClass) {
return keyForm(Form.<K2>forClass(keyClass));
}
public void setKeyForm(Form<K> keyForm) {
this.keyForm = keyForm;
}
@Override
public final Form<V> valueForm() {
return this.valueForm;
}
@Override
public <V2> MapLaneView<K, V2> valueForm(Form<V2> valueForm) {
return new MapLaneView<K, V2>(this.agentContext, this.keyForm, valueForm,
this.flags, typesafeObservers(this.observers));
}
@Override
public <V2> MapLaneView<K, V2> valueClass(Class<V2> valueClass) {
return valueForm(Form.<V2>forClass(valueClass));
}
public void setValueForm(Form<V> valueForm) {
this.valueForm = valueForm;
}
protected Object typesafeObservers(Object observers) {
// TODO: filter out WillUpdateKey, DidUpdateKey, WillRemoveKey, DidRemoveKey,
// WillDrop, DidDrop, WillTake, DidTake, WillClear, DidClear
return observers;
}
public final boolean isResident() {
return (this.flags & RESIDENT) != 0;
}
@Override
public MapLaneView<K, V> isResident(boolean isResident) {
if (isResident) {
this.flags |= RESIDENT;
} else {
this.flags &= ~RESIDENT;
}
final MapLaneModel laneBinding = this.laneBinding;
if (laneBinding != null) {
laneBinding.isResident(isResident);
}
return this;
}
void didSetResident(boolean isResident) {
if (isResident) {
this.flags |= RESIDENT;
} else {
this.flags &= ~RESIDENT;
}
}
public final boolean isTransient() {
return (this.flags & TRANSIENT) != 0;
}
@Override
public MapLaneView<K, V> isTransient(boolean isTransient) {
if (isTransient) {
this.flags |= TRANSIENT;
} else {
this.flags &= ~TRANSIENT;
}
final MapLaneModel laneBinding = this.laneBinding;
if (laneBinding != null) {
laneBinding.isTransient(isTransient);
}
return this;
}
void didSetTransient(boolean isTransient) {
if (isTransient) {
this.flags |= TRANSIENT;
} else {
this.flags &= ~TRANSIENT;
}
}
@Override
protected void willLoad() {
this.dataView = this.laneBinding.data.keyForm(this.keyForm).valueForm(this.valueForm);
super.willLoad();
}
@Override
public void close() {
this.laneBinding.closeLaneView(this);
}
@Override
public MapLaneView<K, V> observe(Object observer) {
super.observe(observer);
return this;
}
@Override
public MapLaneView<K, V> unobserve(Object observer) {
super.unobserve(observer);
return this;
}
@Override
public MapLaneView<K, V> willUpdate(WillUpdateKey<K, V> willUpdate) {
return observe(willUpdate);
}
@Override
public MapLaneView<K, V> didUpdate(DidUpdateKey<K, V> didUpdate) {
return observe(didUpdate);
}
@Override
public MapLaneView<K, V> willRemove(WillRemoveKey<K> willRemove) {
return observe(willRemove);
}
@Override
public MapLaneView<K, V> didRemove(DidRemoveKey<K, V> didRemove) {
return observe(didRemove);
}
@Override
public MapLaneView<K, V> willDrop(WillDrop willDrop) {
return observe(willDrop);
}
@Override
public MapLaneView<K, V> didDrop(DidDrop didDrop) {
return observe(didDrop);
}
@Override
public MapLaneView<K, V> willTake(WillTake willTake) {
return observe(willTake);
}
@Override
public MapLaneView<K, V> didTake(DidTake didTake) {
return observe(didTake);
}
@Override
public MapLaneView<K, V> willClear(WillClear willClear) {
return observe(willClear);
}
@Override
public MapLaneView<K, V> didClear(DidClear didClear) {
return observe(didClear);
}
@Override
public MapLaneView<K, V> willCommand(WillCommand willCommand) {
return observe(willCommand);
}
@Override
public MapLaneView<K, V> didCommand(DidCommand didCommand) {
return observe(didCommand);
}
@Override
public MapLaneView<K, V> willUplink(WillUplink willUplink) {
return observe(willUplink);
}
@Override
public MapLaneView<K, V> didUplink(DidUplink didUplink) {
return observe(didUplink);
}
@Override
public MapLaneView<K, V> willEnter(WillEnter willEnter) {
return observe(willEnter);
}
@Override
public MapLaneView<K, V> didEnter(DidEnter didEnter) {
return observe(didEnter);
}
@Override
public MapLaneView<K, V> willLeave(WillLeave willLeave) {
return observe(willLeave);
}
@Override
public MapLaneView<K, V> didLeave(DidLeave didLeave) {
return observe(didLeave);
}
@SuppressWarnings("unchecked")
public Entry<Boolean, V> dispatchWillUpdate(Link link, K key, V newValue, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillUpdateKey<?, ?>) {
if (((WillUpdateKey<?, ?>) observers).isPreemptive() == preemptive) {
try {
newValue = ((WillUpdateKey<K, V>) observers).willUpdate(key, newValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillUpdateKey<?, ?>) {
if (((WillUpdateKey<?, ?>) observer).isPreemptive() == preemptive) {
try {
newValue = ((WillUpdateKey<K, V>) observer).willUpdate(key, newValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return new AbstractMap.SimpleImmutableEntry<Boolean, V>(complete, newValue);
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
@SuppressWarnings("unchecked")
public boolean dispatchDidUpdate(Link link, K key, V newValue, V oldValue, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidUpdateKey<?, ?>) {
if (((DidUpdateKey<?, ?>) observers).isPreemptive() == preemptive) {
try {
((DidUpdateKey<K, V>) observers).didUpdate(key, newValue, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidUpdateKey<?, ?>) {
if (((DidUpdateKey<?, ?>) observer).isPreemptive() == preemptive) {
try {
((DidUpdateKey<K, V>) observer).didUpdate(key, newValue, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
@SuppressWarnings("unchecked")
public boolean dispatchWillRemove(Link link, K key, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillRemoveKey<?>) {
if (((WillRemoveKey<?>) observers).isPreemptive() == preemptive) {
try {
((WillRemoveKey<K>) observers).willRemove(key);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillRemoveKey<?>) {
if (((WillRemoveKey<?>) observer).isPreemptive() == preemptive) {
try {
((WillRemoveKey<K>) observer).willRemove(key);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
@SuppressWarnings("unchecked")
public boolean dispatchDidRemove(Link link, K key, V oldValue, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidRemoveKey<?, ?>) {
if (((DidRemoveKey<?, ?>) observers).isPreemptive() == preemptive) {
try {
((DidRemoveKey<K, V>) observers).didRemove(key, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidRemoveKey<?, ?>) {
if (((DidRemoveKey<?, ?>) observer).isPreemptive() == preemptive) {
try {
((DidRemoveKey<K, V>) observer).didRemove(key, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
public boolean dispatchWillDrop(Link link, int lower, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillDrop) {
if (((WillDrop) observers).isPreemptive() == preemptive) {
try {
((WillDrop) observers).willDrop(lower);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillDrop) {
if (((WillDrop) observer).isPreemptive() == preemptive) {
try {
((WillDrop) observer).willDrop(lower);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
public boolean dispatchDidDrop(Link link, int lower, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidDrop) {
if (((DidDrop) observers).isPreemptive() == preemptive) {
try {
((DidDrop) observers).didDrop(lower);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidDrop) {
if (((DidDrop) observer).isPreemptive() == preemptive) {
try {
((DidDrop) observer).didDrop(lower);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
public boolean dispatchWillTake(Link link, int upper, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillTake) {
if (((WillTake) observers).isPreemptive() == preemptive) {
try {
((WillTake) observers).willTake(upper);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillTake) {
if (((WillTake) observer).isPreemptive() == preemptive) {
try {
((WillTake) observer).willTake(upper);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
public boolean dispatchDidTake(Link link, int upper, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidTake) {
if (((DidTake) observers).isPreemptive() == preemptive) {
try {
((DidTake) observers).didTake(upper);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidTake) {
if (((DidTake) observer).isPreemptive() == preemptive) {
try {
((DidTake) observer).didTake(upper);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
public boolean dispatchWillClear(Link link, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillClear) {
if (((WillClear) observers).isPreemptive() == preemptive) {
try {
((WillClear) observers).willClear();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillClear) {
if (((WillClear) observer).isPreemptive() == preemptive) {
try {
((WillClear) observer).willClear();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
public boolean dispatchDidClear(Link link, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidClear) {
if (((DidClear) observers).isPreemptive() == preemptive) {
try {
((DidClear) observers).didClear();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidClear) {
if (((DidClear) observer).isPreemptive() == preemptive) {
try {
((DidClear) observer).didClear();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
public V laneWillUpdate(K key, V newValue) {
return newValue;
}
public void laneDidUpdate(K key, V newValue, V oldValue) {
invalidateInputKey(key, KeyEffect.UPDATE);
reconcileInputKey(key, 0); // TODO: debounce and track version
}
public void laneWillRemove(K key) {
}
public void laneDidRemove(K key, V oldValue) {
invalidateInputKey(key, KeyEffect.REMOVE);
reconcileInputKey(key, 0); // TODO: debounce and track version
}
public void laneWillDrop(int lower) {
}
public void laneDidDrop(int lower) {
}
public void laneWillTake(int upper) {
}
public void laneDidTake(int upper) {
}
public void laneWillClear() {
}
public void laneDidClear() {
}
@Override
public boolean isEmpty() {
return this.dataView.isEmpty();
}
@Override
public int size() {
return this.dataView.size();
}
@Override
public boolean containsKey(Object key) {
return this.dataView.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return this.dataView.containsValue(value);
}
@Override
public int indexOf(Object key) {
return this.dataView.indexOf(key);
}
@Override
public V get(Object key) {
return this.dataView.get(key);
}
@Override
public Entry<K, V> getEntry(Object key) {
return this.dataView.getEntry(key);
}
@Override
public Entry<K, V> getIndex(int index) {
return this.dataView.getIndex(index);
}
@Override
public Entry<K, V> firstEntry() {
return this.dataView.firstEntry();
}
@Override
public K firstKey() {
return this.dataView.firstKey();
}
@Override
public V firstValue() {
return this.dataView.firstValue();
}
@Override
public Entry<K, V> lastEntry() {
return this.dataView.lastEntry();
}
@Override
public K lastKey() {
return this.dataView.lastKey();
}
@Override
public V lastValue() {
return this.dataView.lastValue();
}
@Override
public Entry<K, V> nextEntry(K key) {
return this.dataView.nextEntry(key);
}
@Override
public K nextKey(K key) {
return this.dataView.nextKey(key);
}
@Override
public V nextValue(K key) {
return this.dataView.nextValue(key);
}
@Override
public Entry<K, V> previousEntry(K key) {
return this.dataView.previousEntry(key);
}
@Override
public K previousKey(K key) {
return this.dataView.previousKey(key);
}
@Override
public V previousValue(K key) {
return this.dataView.previousValue(key);
}
@Override
public V put(K key, V value) {
return this.laneBinding.put(this, key, value);
}
@Override
public void putAll(Map<? extends K, ? extends V> map) {
for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
this.laneBinding.put(this, entry.getKey(), entry.getValue());
}
}
@SuppressWarnings("unchecked")
@Override
public V remove(Object key) {
final Class<?> keyType = keyForm.type();
if (keyType == null || keyType.isInstance(key)) {
return this.laneBinding.remove(this, (K) key);
}
return valueForm.unit();
}
@Override
public void drop(int lower) {
this.laneBinding.drop(this, lower);
}
@Override
public void take(int upper) {
this.laneBinding.take(this, upper);
}
@Override
public void clear() {
this.laneBinding.clear(this);
}
@Override
public OrderedMap<K, V> headMap(K toKey) {
return this.dataView.headMap(toKey);
}
@Override
public OrderedMap<K, V> tailMap(K fromKey) {
return this.dataView.tailMap(fromKey);
}
@Override
public OrderedMap<K, V> subMap(K fromKey, K toKey) {
return this.dataView.subMap(fromKey, toKey);
}
@Override
public Set<Entry<K, V>> entrySet() {
return this.dataView.entrySet();
}
@Override
public Set<K> keySet() {
return this.dataView.keySet();
}
@Override
public Collection<V> values() {
return this.dataView.values();
}
@Override
public OrderedMapCursor<K, V> iterator() {
return this.dataView.iterator();
}
@Override
public Cursor<K> keyIterator() {
return this.dataView.keyIterator();
}
@Override
public Cursor<V> valueIterator() {
return this.dataView.valueIterator();
}
@Override
public OrderedMap<K, V> snapshot() {
return this.dataView.snapshot();
}
@Override
public Comparator<? super K> comparator() {
return this.dataView.comparator();
}
@Override
public MapLane<K, V> get() {
return this;
}
@Override
public MapOutlet<K, V, ? extends Map<K, V>> input() {
return this.input;
}
@SuppressWarnings("unchecked")
@Override
public void bindInput(Outlet<? extends Map<K, V>> input) {
if (input instanceof MapOutlet<?, ?, ?>) {
bindInput((MapOutlet<K, V, ? extends Map<K, V>>) input);
} else {
throw new IllegalArgumentException(input.toString());
}
}
public void bindInput(MapOutlet<K, V, ? extends Map<K, V>> input) {
if (this.input != null) {
this.input.unbindOutput(this);
}
this.input = input;
if (this.input != null) {
this.input.bindOutput(this);
}
}
@Override
public void unbindInput() {
if (this.input != null) {
this.input.unbindOutput(this);
}
this.input = null;
}
@Override
public void disconnectInputs() {
final MapOutlet<K, V, ? extends Map<K, V>> input = this.input;
if (input != null) {
input.unbindOutput(this);
this.input = null;
input.disconnectInputs();
}
}
@Override
public Outlet<V> outlet(K key) {
KeyOutlet<K, V> outlet = this.outlets.get(key);
if (outlet == null) {
outlet = new KeyOutlet<K, V>(this, key);
this.outlets = this.outlets.updated(key, outlet);
}
return outlet;
}
@Override
public Iterator<Inlet<? super MapLane<K, V>>> outputIterator() {
return this.outputs != null ? Cursor.array(this.outputs) : Cursor.empty();
}
@SuppressWarnings("unchecked")
@Override
public void bindOutput(Inlet<? super MapLane<K, V>> output) {
final Inlet<? super MapLane<K, V>>[] oldOutputs = this.outputs;
final int n = oldOutputs != null ? oldOutputs.length : 0;
final Inlet<? super MapLane<K, V>>[] newOutputs = (Inlet<? super MapLane<K, V>>[]) new Inlet<?>[n + 1];
if (n > 0) {
System.arraycopy(oldOutputs, 0, newOutputs, 0, n);
}
newOutputs[n] = output;
this.outputs = newOutputs;
}
@SuppressWarnings("unchecked")
@Override
public void unbindOutput(Inlet<? super MapLane<K, V>> output) {
final Inlet<? super MapLane<K, V>>[] oldOutputs = this.outputs;
final int n = oldOutputs != null ? oldOutputs.length : 0;
for (int i = 0; i < n; i += 1) {
if (oldOutputs[i] == output) {
if (n > 1) {
final Inlet<? super MapLane<K, V>>[] newOutputs = (Inlet<? super MapLane<K, V>>[]) new Inlet<?>[n - 1];
System.arraycopy(oldOutputs, 0, newOutputs, 0, i);
System.arraycopy(oldOutputs, i + 1, newOutputs, i, (n - 1) - i);
this.outputs = newOutputs;
} else {
this.outputs = null;
}
break;
}
}
}
@Override
public void unbindOutputs() {
final HashTrieMap<K, KeyOutlet<K, V>> outlets = this.outlets;
if (!outlets.isEmpty()) {
this.outlets = HashTrieMap.empty();
final Iterator<KeyOutlet<K, V>> keyOutlets = outlets.valueIterator();
while (keyOutlets.hasNext()) {
final KeyOutlet<K, V> keyOutlet = keyOutlets.next();
keyOutlet.unbindOutputs();
}
}
final Inlet<? super MapLane<K, V>>[] outputs = this.outputs;
if (outputs != null) {
this.outputs = null;
for (int i = 0, n = outputs.length; i < n; i += 1) {
final Inlet<? super MapLane<K, V>> output = outputs[i];
output.unbindInput();
}
}
}
@Override
public void disconnectOutputs() {
final HashTrieMap<K, KeyOutlet<K, V>> outlets = this.outlets;
if (!outlets.isEmpty()) {
this.outlets = HashTrieMap.empty();
final Iterator<KeyOutlet<K, V>> keyOutlets = outlets.valueIterator();
while (keyOutlets.hasNext()) {
final KeyOutlet<K, V> keyOutlet = keyOutlets.next();
keyOutlet.disconnectOutputs();
}
}
final Inlet<? super MapLane<K, V>>[] outputs = this.outputs;
if (outputs != null) {
this.outputs = null;
for (int i = 0, n = outputs.length; i < n; i += 1) {
final Inlet<? super MapLane<K, V>> output = outputs[i];
output.unbindInput();
output.disconnectOutputs();
}
}
}
@Override
public void invalidateOutputKey(K key, KeyEffect effect) {
invalidateKey(key, effect);
}
@Override
public void invalidateInputKey(K key, KeyEffect effect) {
invalidateKey(key, effect);
}
@SuppressWarnings("unchecked")
public void invalidateKey(K key, KeyEffect effect) {
final HashTrieMap<K, KeyEffect> oldEffects = this.effects;
if (oldEffects.get(key) != effect) {
willInvalidateKey(key, effect);
this.effects = oldEffects.updated(key, effect);
this.version = -1;
onInvalidateKey(key, effect);
final int n = this.outputs != null ? this.outputs.length : 0;
for (int i = 0; i < n; i += 1) {
final Inlet<?> output = this.outputs[i];
if (output instanceof MapInlet<?, ?, ?>) {
((MapInlet<K, V, ? super MapLane<K, V>>) output).invalidateOutputKey(key, effect);
} else {
output.invalidateOutput();
}
}
final KeyOutlet<K, V> outlet = this.outlets.get(key);
if (outlet != null) {
outlet.invalidateInput();
}
didInvalidateKey(key, effect);
}
}
@Override
public void invalidateOutput() {
invalidate();
}
@Override
public void invalidateInput() {
invalidate();
}
public void invalidate() {
if (this.version >= 0) {
willInvalidate();
this.version = -1;
onInvalidate();
final int n = this.outputs != null ? this.outputs.length : 0;
for (int i = 0; i < n; i += 1) {
this.outputs[i].invalidateOutput();
}
final Iterator<KeyOutlet<K, V>> outlets = this.outlets.valueIterator();
while (outlets.hasNext()) {
outlets.next().invalidateInput();
}
didInvalidate();
}
}
@Override
public void reconcileOutputKey(K key, int version) {
reconcileKey(key, version);
}
@Override
public void reconcileInputKey(K key, int version) {
reconcileKey(key, version);
}
@SuppressWarnings("unchecked")
public void reconcileKey(K key, int version) {
if (this.version < 0) {
final HashTrieMap<K, KeyEffect> oldEffects = this.effects;
final KeyEffect effect = oldEffects.get(key);
if (effect != null) {
willReconcileKey(key, effect, version);
this.effects = oldEffects.removed(key);
if (this.input != null) {
this.input.reconcileInputKey(key, version);
}
onReconcileKey(key, effect, version);
for (int i = 0, n = this.outputs != null ? this.outputs.length : 0; i < n; i += 1) {
final Inlet<?> output = this.outputs[i];
if (output instanceof MapInlet<?, ?, ?>) {
((MapInlet<K, V, ? super MapLane<K, V>>) output).reconcileOutputKey(key, version);
}
}
final KeyOutlet<K, V> outlet = this.outlets.get(key);
if (outlet != null) {
outlet.reconcileInput(version);
}
didReconcileKey(key, effect, version);
}
}
}
@Override
public void reconcileOutput(int version) {
reconcile(version);
}
@Override
public void reconcileInput(int version) {
reconcile(version);
}
public void reconcile(int version) {
if (this.version < 0) {
willReconcile(version);
final Iterator<K> keys = this.effects.keyIterator();
while (keys.hasNext()) {
reconcileKey(keys.next(), version);
}
this.version = version;
onReconcile(version);
for (int i = 0, n = this.outputs != null ? this.outputs.length : 0; i < n; i += 1) {
this.outputs[i].reconcileOutput(version);
}
didReconcile(version);
}
}
protected void willInvalidateKey(K key, KeyEffect effect) {
// stub
}
protected void onInvalidateKey(K key, KeyEffect effect) {
// stub
}
protected void didInvalidateKey(K key, KeyEffect effect) {
// stub
}
protected void willInvalidate() {
// stub
}
protected void onInvalidate() {
// stub
}
protected void didInvalidate() {
// stub
}
protected void willUpdate(int version) {
// stub
}
protected void didUpdate(int version) {
// stub
}
protected void willReconcileKey(K key, KeyEffect effect, int version) {
// stub
}
protected void onReconcileKey(K key, KeyEffect effect, int version) {
if (effect == KeyEffect.UPDATE) {
if (this.input != null) {
final V value = this.input.get(key);
if (value != null) {
put(key, value);
} else {
remove(key);
}
}
} else if (effect == KeyEffect.REMOVE) {
if (containsKey(key)) {
remove(key);
}
}
}
protected void didReconcileKey(K key, KeyEffect effect, int version) {
// stub
}
protected void willReconcile(int version) {
// stub
}
protected void onReconcile(int version) {
// stub
}
protected void didReconcile(int version) {
// stub
}
static final int RESIDENT = 1 << 0;
static final int TRANSIENT = 1 << 1;
static final int SIGNED = 1 << 2;
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/SpatialLaneModel.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.runtime.lane;
import java.util.Iterator;
import java.util.Map;
import swim.api.Link;
import swim.api.data.SpatialData;
import swim.collections.FingerTrieSeq;
import swim.concurrent.Stage;
import swim.math.Z2Form;
import swim.runtime.LaneRelay;
import swim.runtime.LaneView;
import swim.runtime.WarpBinding;
import swim.runtime.warp.WarpLaneModel;
import swim.spatial.SpatialMap;
import swim.structure.Form;
import swim.structure.Record;
import swim.structure.Value;
import swim.warp.CommandMessage;
public class SpatialLaneModel<S> extends WarpLaneModel<SpatialLaneView<?, S, ?>, SpatialLaneUplink<S>> {
protected int flags;
protected SpatialData<Value, S, Value> data;
protected final Z2Form<S> shapeForm;
SpatialLaneModel(Z2Form<S> shapeForm, int flags) {
this.shapeForm = shapeForm;
this.flags = flags;
}
public SpatialLaneModel(Z2Form<S> shapeForm) {
this(shapeForm, 0);
}
@Override
public String laneType() {
return "spatial";
}
@Override
protected SpatialLaneUplink<S> createWarpUplink(WarpBinding link) {
return new SpatialLaneUplink<S>(this, link);
}
@Override
public void onCommand(CommandMessage message) {
final Value payload = message.body();
final String tag = payload.tag();
if ("update".equals(tag)) {
final Value header = payload.header("update");
final Value key = header.get("key");
final Value shape = header.get("shape");
final S shapeObject = shapeForm.cast(shape);
final Value value = payload.body();
new SpatialLaneRelayUpdate<S>(this, message, key, shapeObject, value).run();
} else if ("move".equals(tag)) {
final Value header = payload.header("move");
final Value key = header.get("key");
final Value oldShape = header.get("from");
final Value newShape = header.get("to");
final S oldShapeObject = shapeForm.cast(oldShape);
final S newShapeObject = shapeForm.cast(newShape);
final Value value = payload.body();
new SpatialLaneRelayMove<S>(this, message, key, oldShapeObject, newShapeObject, value).run();
} else if ("remove".equals(tag)) {
final Value header = payload.header("remove");
final Value key = header.get("key");
final Value shape = header.get("shape");
final S shapeObject = shapeForm.cast(shape);
new SpatialLaneRelayRemove<S>(this, message, key, shapeObject).run();
} else if ("clear".equals(tag)) {
new SpatialLaneRelayClear<S>(this, message).run();
}
}
protected void cueDownKey(Value key) {
FingerTrieSeq<SpatialLaneUplink<S>> uplinks;
do {
uplinks = this.uplinks;
for (int i = 0, n = uplinks.size(); i < n; i += 1) {
uplinks.get(i).cueDownKey(key);
}
} while (uplinks != this.uplinks);
}
@Override
protected void didOpenLaneView(SpatialLaneView<?, S, ?> view) {
view.setLaneBinding(this);
}
public final boolean isResident() {
return (this.flags & RESIDENT) != 0;
}
public SpatialLaneModel<S> isResident(boolean isResident) {
if (this.data != null) {
this.data.isResident(isResident);
}
if (isResident) {
this.flags |= RESIDENT;
} else {
this.flags &= ~RESIDENT;
}
final Object views = this.views;
if (views instanceof SpatialLaneView<?, ?, ?>) {
((SpatialLaneView<?, ?, ?>) views).didSetResident(isResident);
} else if (views instanceof LaneView[]) {
final LaneView[] viewArray = (LaneView[]) views;
for (int i = 0, n = viewArray.length; i < n; i += 1) {
((SpatialLaneView<?, ?, ?>) viewArray[i]).didSetResident(isResident);
}
}
return this;
}
public final boolean isTransient() {
return (this.flags & TRANSIENT) != 0;
}
public SpatialLaneModel<S> isTransient(boolean isTransient) {
if (this.data != null) {
this.data.isTransient(isTransient);
}
if (isTransient) {
this.flags |= TRANSIENT;
} else {
this.flags &= ~TRANSIENT;
}
final Object views = this.views;
if (views instanceof SpatialLaneView<?, ?, ?>) {
((SpatialLaneView<?, ?, ?>) views).didSetTransient(isTransient);
} else if (views instanceof LaneView[]) {
final LaneView[] viewArray = (LaneView[]) views;
for (int i = 0, n = viewArray.length; i < n; i += 1) {
((SpatialLaneView<?, ?, ?>) viewArray[i]).didSetTransient(isTransient);
}
}
return this;
}
public Value get(Value key) {
if (key != null) {
return this.data.get(key);
} else {
return Value.absent();
}
}
@SuppressWarnings("unchecked")
public <K, V> V put(SpatialLaneView<K, S, V> view, K keyObject, S shapeObject, V newObject) {
final Form<K> keyForm = view.keyForm;
final Form<V> valueForm = view.valueForm;
final Value key = keyForm.mold(keyObject).toValue();
final Value newValue = valueForm.mold(newObject).toValue();
final SpatialLaneRelayUpdate<S> relay = new SpatialLaneRelayUpdate<S>(this, stage(), key, shapeObject, newValue);
relay.keyForm = (Form<Object>) keyForm;
relay.shapeForm = (Z2Form<Object>) shapeForm;
relay.valueForm = (Form<Object>) valueForm;
relay.keyObject = keyObject;
relay.oldObject = newObject;
relay.newObject = newObject;
relay.run();
if (relay.valueForm != valueForm && valueForm != null) {
relay.oldObject = valueForm.cast(relay.oldValue);
if (relay.oldObject == null) {
relay.oldObject = valueForm.unit();
}
}
return (V) relay.oldObject;
}
@SuppressWarnings("unchecked")
public <K, V> V move(SpatialLaneView<K, S, V> view, K keyObject,
S oldShapeObject, S newShapeObject, V newObject) {
final Form<K> keyForm = view.keyForm;
final Form<V> valueForm = view.valueForm;
final Value key = keyForm.mold(keyObject).toValue();
final Value newValue = valueForm.mold(newObject).toValue();
final SpatialLaneRelayMove<S> relay =
new SpatialLaneRelayMove<S>(this, stage(), key, oldShapeObject, newShapeObject, newValue);
relay.keyForm = (Form<Object>) keyForm;
relay.shapeForm = (Z2Form<Object>) shapeForm;
relay.valueForm = (Form<Object>) valueForm;
relay.keyObject = keyObject;
relay.oldObject = newObject;
relay.newObject = newObject;
relay.run();
if (relay.valueForm != valueForm && valueForm != null) {
relay.oldObject = valueForm.cast(relay.oldValue);
if (relay.oldObject == null) {
relay.oldObject = valueForm.unit();
}
}
return (V) relay.oldObject;
}
@SuppressWarnings("unchecked")
public <K, V> V remove(SpatialLaneView<K, S, V> view, K keyObject, S shapeObject) {
final Form<K> keyForm = view.keyForm;
final Form<V> valueForm = view.valueForm;
final Value key = keyForm.mold(keyObject).toValue();
final SpatialLaneRelayRemove<S> relay = new SpatialLaneRelayRemove<S>(this, stage(), key, shapeObject);
relay.keyForm = (Form<Object>) keyForm;
relay.shapeForm = (Z2Form<Object>) shapeForm;
relay.valueForm = (Form<Object>) valueForm;
relay.keyObject = keyObject;
relay.run();
if (relay.valueForm != valueForm && valueForm != null) {
relay.oldObject = valueForm.cast(relay.oldValue);
if (relay.oldObject == null) {
relay.oldObject = valueForm.unit();
}
}
return (V) relay.oldObject;
}
public void clear(SpatialLaneView<?, S, ?> view) {
final SpatialLaneRelayClear<S> relay = new SpatialLaneRelayClear<S>(this, stage());
relay.run();
}
public Iterator<SpatialMap.Entry<Value, S, Value>> iterator(S shape) {
return this.data.iterator(shape);
}
public Iterator<SpatialMap.Entry<Value, S, Value>> iterator() {
return this.data.iterator();
}
protected void openStore() {
this.data = this.laneContext.store().spatialData(laneUri().toString(), shapeForm)
.isTransient(isTransient())
.isResident(isResident());
}
@Override
protected void willLoad() {
openStore();
super.willLoad();
}
static final int RESIDENT = 1 << 0;
static final int TRANSIENT = 1 << 1;
static final int SIGNED = 1 << 2;
}
final class SpatialLaneRelayUpdate<S> extends LaneRelay<SpatialLaneModel<S>, SpatialLaneView<?, S, ?>> {
final Link link;
final CommandMessage message;
Form<Object> keyForm;
Z2Form<Object> shapeForm;
Form<Object> valueForm;
final Value key;
Object keyObject;
final S shapeObject;
Value oldValue;
Object oldObject;
Value newValue;
Object newObject;
SpatialLaneRelayUpdate(SpatialLaneModel<S> model, CommandMessage message, Value key, S shapeObject, Value newValue) {
super(model, 4);
this.link = null;
this.message = message;
this.key = key;
this.shapeObject = shapeObject;
this.newValue = newValue;
}
SpatialLaneRelayUpdate(SpatialLaneModel<S> model, Link link, Value key, S shapeObject, Value newValue) {
super(model, 1, 3, null);
this.link = link;
this.message = null;
this.key = key;
this.shapeObject = shapeObject;
this.newValue = newValue;
}
SpatialLaneRelayUpdate(SpatialLaneModel<S> model, Stage stage, Value key, S shapeObject, Value newValue) {
super(model, 1, 3, stage);
this.link = null;
this.message = null;
this.key = key;
this.shapeObject = shapeObject;
this.newValue = newValue;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
this.oldValue = model.data.put(key, shapeObject, newValue);
if (this.valueForm != null) {
this.oldObject = this.valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = this.valueForm.unit();
}
}
}
}
@SuppressWarnings("unchecked")
@Override
protected boolean runPhase(SpatialLaneView<?, S, ?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneWillCommand(this.message);
}
return view.dispatchWillCommand(this.message.body(), preemptive);
} else if (phase == 1) {
final Form<Object> keyForm = (Form<Object>) view.keyForm;
if (this.keyForm != keyForm && keyForm != null) {
this.keyForm = keyForm;
this.keyObject = keyForm.cast(this.key);
if (this.keyObject == null) {
this.keyObject = keyForm.unit();
}
}
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.oldObject = valueForm.cast(this.newValue);
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
}
if (preemptive) {
this.newObject = ((SpatialLaneView<Object, S, Object>) view)
.laneWillUpdate(this.keyObject, this.shapeObject, this.oldObject);
}
final Map.Entry<Boolean, Object> result = ((SpatialLaneView<Object, S, Object>) view)
.dispatchWillUpdate(this.link, this.keyObject, this.shapeObject, this.oldObject, preemptive);
this.newObject = result.getValue();
if (this.oldObject != this.newObject) {
this.oldObject = this.newObject;
this.newValue = valueForm.mold(this.newObject).toValue();
this.oldValue = this.newValue;
}
return result.getKey();
} else if (phase == 2) {
final Form<Object> keyForm = (Form<Object>) view.keyForm;
if (this.keyForm != keyForm && keyForm != null) {
this.keyForm = keyForm;
this.keyObject = keyForm.cast(this.key);
if (this.keyObject == null) {
this.keyObject = keyForm.unit();
}
}
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.oldObject = valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
this.newObject = valueForm.cast(this.newValue);
if (this.newObject == null) {
this.newObject = valueForm.unit();
}
}
if (preemptive) {
((SpatialLaneView<Object, S, Object>) view)
.laneDidUpdate(this.keyObject, this.shapeObject, this.newObject, this.oldObject);
}
return ((SpatialLaneView<Object, S, Object>) view)
.dispatchDidUpdate(this.link, this.keyObject, this.shapeObject, this.newObject, this.oldObject, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.laneDidCommand(this.message);
}
return view.dispatchDidCommand(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
this.model.cueDownKey(this.key);
}
}
final class SpatialLaneRelayMove<S> extends LaneRelay<SpatialLaneModel<S>, SpatialLaneView<?, S, ?>> {
final Link link;
final CommandMessage message;
Form<Object> keyForm;
Z2Form<Object> shapeForm;
Form<Object> valueForm;
final Value key;
Object keyObject;
final S oldShapeObject;
final S newShapeObject;
Value oldValue;
Object oldObject;
Value newValue;
Object newObject;
SpatialLaneRelayMove(SpatialLaneModel<S> model, CommandMessage message, Value key,
S oldShapeObject, S newShapeObject, Value newValue) {
super(model, 4);
this.link = null;
this.message = message;
this.key = key;
this.oldShapeObject = oldShapeObject;
this.newShapeObject = newShapeObject;
this.newValue = newValue;
}
SpatialLaneRelayMove(SpatialLaneModel<S> model, Link link, Value key,
S oldShapeObject, S newShapeObject, Value newValue) {
super(model, 1, 3, null);
this.link = link;
this.message = null;
this.key = key;
this.oldShapeObject = oldShapeObject;
this.newShapeObject = newShapeObject;
this.newValue = newValue;
}
SpatialLaneRelayMove(SpatialLaneModel<S> model, Stage stage, Value key,
S oldShapeObject, S newShapeObject, Value newValue) {
super(model, 1, 3, stage);
this.link = null;
this.message = null;
this.key = key;
this.oldShapeObject = oldShapeObject;
this.newShapeObject = newShapeObject;
this.newValue = newValue;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
this.oldValue = model.data.move(key, oldShapeObject, newShapeObject, newValue);
if (this.valueForm != null) {
this.oldObject = this.valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = this.valueForm.unit();
}
}
}
}
@SuppressWarnings("unchecked")
@Override
protected boolean runPhase(SpatialLaneView<?, S, ?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneWillCommand(this.message);
}
return view.dispatchWillCommand(this.message.body(), preemptive);
} else if (phase == 1) {
final Form<Object> keyForm = (Form<Object>) view.keyForm;
if (this.keyForm != keyForm && keyForm != null) {
this.keyForm = keyForm;
this.keyObject = keyForm.cast(this.key);
if (this.keyObject == null) {
this.keyObject = keyForm.unit();
}
}
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.oldObject = valueForm.cast(this.newValue);
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
}
if (preemptive) {
this.newObject = ((SpatialLaneView<Object, S, Object>) view)
.laneWillMove(this.keyObject, this.newShapeObject, this.oldObject, this.oldShapeObject);
}
final Map.Entry<Boolean, Object> result = ((SpatialLaneView<Object, S, Object>) view)
.dispatchWillMove(this.link, this.keyObject, this.newShapeObject, this.oldObject, this.oldShapeObject, preemptive);
this.newObject = result.getValue();
if (this.oldObject != this.newObject) {
this.oldObject = this.newObject;
this.newValue = valueForm.mold(this.newObject).toValue();
this.oldValue = this.newValue;
}
return result.getKey();
} else if (phase == 2) {
final Form<Object> keyForm = (Form<Object>) view.keyForm;
if (this.keyForm != keyForm && keyForm != null) {
this.keyForm = keyForm;
this.keyObject = keyForm.cast(this.key);
if (this.keyObject == null) {
this.keyObject = keyForm.unit();
}
}
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.oldObject = valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
this.newObject = valueForm.cast(this.newValue);
if (this.newObject == null) {
this.newObject = valueForm.unit();
}
}
if (preemptive) {
((SpatialLaneView<Object, S, Object>) view)
.laneDidMove(this.keyObject, this.newShapeObject, this.newObject, this.oldShapeObject, this.oldObject);
}
return ((SpatialLaneView<Object, S, Object>) view)
.dispatchDidMove(this.link, this.keyObject, this.newShapeObject, this.newObject, this.oldShapeObject,
this.oldObject, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.laneDidCommand(this.message);
}
return view.dispatchDidCommand(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
final Record header = Record.create(3).slot("key", key).slot("from", shapeForm.mold(this.oldShapeObject).toValue())
.slot("to", shapeForm.mold(this.newShapeObject).toValue());
this.model.sendDown(Record.create(1).attr("move", header));
}
}
final class SpatialLaneRelayRemove<S> extends LaneRelay<SpatialLaneModel<S>, SpatialLaneView<?, S, ?>> {
final Link link;
final CommandMessage message;
Form<Object> keyForm;
Z2Form<Object> shapeForm;
Form<Object> valueForm;
final Value key;
Object keyObject;
final S shapeObject;
Value oldValue;
Object oldObject;
SpatialLaneRelayRemove(SpatialLaneModel<S> model, CommandMessage message, Value key, S shapeObject) {
super(model, 4);
this.link = null;
this.message = message;
this.key = key;
this.shapeObject = shapeObject;
}
SpatialLaneRelayRemove(SpatialLaneModel<S> model, Link link, Value key, S shapeObject) {
super(model, 1, 3, null);
this.link = link;
this.message = null;
this.key = key;
this.shapeObject = shapeObject;
}
SpatialLaneRelayRemove(SpatialLaneModel<S> model, Stage stage, Value key, S shapeObject) {
super(model, 1, 3, stage);
this.link = null;
this.message = null;
this.key = key;
this.shapeObject = shapeObject;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
this.oldValue = model.data.remove(key, shapeObject);
if (this.valueForm != null) {
this.oldObject = this.valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = this.valueForm.unit();
}
}
}
}
@SuppressWarnings("unchecked")
@Override
protected boolean runPhase(SpatialLaneView<?, S, ?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneWillCommand(this.message);
}
return view.dispatchWillCommand(this.message.body(), preemptive);
} else if (phase == 1) {
final Form<Object> keyForm = (Form<Object>) view.keyForm;
if (this.keyForm != keyForm && keyForm != null) {
this.keyForm = keyForm;
this.keyObject = keyForm.cast(this.key);
if (this.keyObject == null) {
this.keyObject = keyForm.unit();
}
}
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.oldObject = valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
}
if (preemptive) {
((SpatialLaneView<Object, S, Object>) view).laneWillRemove(this.keyObject, this.shapeObject);
}
return ((SpatialLaneView<Object, S, Object>) view)
.dispatchWillRemove(this.link, this.keyObject, this.shapeObject, preemptive);
} else if (phase == 2) {
final Form<Object> keyForm = (Form<Object>) view.keyForm;
if (this.keyForm != keyForm && keyForm != null) {
this.keyForm = keyForm;
this.keyObject = keyForm.cast(this.key);
if (this.keyObject == null) {
this.keyObject = keyForm.unit();
}
}
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.oldObject = valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
}
if (preemptive) {
((SpatialLaneView<Object, S, Object>) view).laneDidRemove(this.keyObject, this.shapeObject);
}
return ((SpatialLaneView<Object, S, Object>) view)
.dispatchDidRemove(this.link, this.keyObject, this.shapeObject, this.oldObject, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.laneDidCommand(this.message);
}
return view.dispatchDidCommand(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
final Record header = Record.create(2).slot("key", key).slot("shape", shapeForm.mold(this.shapeObject).toValue());
this.model.sendDown(Record.create(1).attr("move", header));
}
}
final class SpatialLaneRelayClear<S> extends LaneRelay<SpatialLaneModel<S>, SpatialLaneView<?, S, ?>> {
final Link link;
final CommandMessage message;
SpatialLaneRelayClear(SpatialLaneModel<S> model, CommandMessage message) {
super(model, 4);
this.link = null;
this.message = message;
}
SpatialLaneRelayClear(SpatialLaneModel<S> model, Link link) {
super(model, 1, 3, null);
this.link = link;
this.message = null;
}
SpatialLaneRelayClear(SpatialLaneModel<S> model, Stage stage) {
super(model, 1, 3, stage);
this.link = null;
this.message = null;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
this.model.data.clear();
}
}
@SuppressWarnings("unchecked")
@Override
protected boolean runPhase(SpatialLaneView<?, S, ?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneWillCommand(this.message);
}
return view.dispatchWillCommand(this.message.body(), preemptive);
} else if (phase == 1) {
if (preemptive) {
view.laneWillClear();
}
return view.dispatchWillClear(this.link, preemptive);
} else if (phase == 2) {
if (preemptive) {
view.laneDidClear();
}
return view.dispatchDidClear(this.link, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.laneDidCommand(this.message);
}
return view.dispatchDidCommand(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
this.model.sendDown(Record.create(1).attr("clear"));
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/SpatialLaneUplink.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.runtime.lane;
import java.util.Iterator;
import java.util.Map;
import swim.concurrent.Stage;
import swim.runtime.WarpBinding;
import swim.runtime.warp.PartialUplinkModem;
import swim.structure.Attr;
import swim.structure.Record;
import swim.structure.Value;
import swim.warp.SyncRequest;
public class SpatialLaneUplink<S> extends PartialUplinkModem {
final SpatialLaneModel<S> laneBinding;
public SpatialLaneUplink(SpatialLaneModel<S> laneBinding, WarpBinding linkBinding) {
super(linkBinding);
this.laneBinding = laneBinding;
}
@Override
public SpatialLaneModel<S> laneBinding() {
return this.laneBinding;
}
@Override
public Stage stage() {
return this.laneBinding.stage();
}
@Override
protected Value nextDownKey(Value key) {
final Value value = this.laneBinding.get(key);
if (value != null) {
return Attr.of("update", Record.create(1).slot("key", key)).concat(value);
} else {
return null;
}
}
@SuppressWarnings("unchecked")
@Override
protected void willSync(SyncRequest request) {
syncDown((Iterator<Map.Entry<Value, Value>>) (Iterator<?>) this.laneBinding.iterator());
super.willSync(request);
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/SpatialLaneView.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.runtime.lane;
import java.util.AbstractMap;
import java.util.Iterator;
import java.util.Map;
import swim.api.Lane;
import swim.api.Link;
import swim.api.SwimContext;
import swim.api.agent.AgentContext;
import swim.api.data.SpatialData;
import swim.api.lane.SpatialLane;
import swim.api.warp.function.DidCommand;
import swim.api.warp.function.DidEnter;
import swim.api.warp.function.DidLeave;
import swim.api.warp.function.DidUplink;
import swim.api.warp.function.WillCommand;
import swim.api.warp.function.WillEnter;
import swim.api.warp.function.WillLeave;
import swim.api.warp.function.WillUplink;
import swim.concurrent.Conts;
import swim.math.Z2Form;
import swim.observable.function.DidClear;
import swim.observable.function.DidMoveShape;
import swim.observable.function.DidRemoveShape;
import swim.observable.function.DidUpdateShape;
import swim.observable.function.WillClear;
import swim.observable.function.WillMoveShape;
import swim.observable.function.WillRemoveShape;
import swim.observable.function.WillUpdateShape;
import swim.runtime.LaneBinding;
import swim.runtime.warp.WarpLaneView;
import swim.spatial.SpatialMap;
import swim.structure.Form;
public class SpatialLaneView<K, S, V> extends WarpLaneView implements SpatialLane<K, S, V> {
protected final AgentContext agentContext;
protected Form<K> keyForm;
protected Z2Form<S> shapeForm;
protected Form<V> valueForm;
protected SpatialLaneModel<S> laneBinding;
protected SpatialData<K, S, V> dataView;
protected int flags;
SpatialLaneView(AgentContext agentContext, Form<K> keyForm, Z2Form<S> shapeForm, Form<V> valueForm,
int flags, Object observers) {
super(observers);
this.agentContext = agentContext;
this.keyForm = keyForm;
this.shapeForm = shapeForm;
this.valueForm = valueForm;
this.flags = flags;
}
public SpatialLaneView(AgentContext agentContext, Form<K> keyForm, Z2Form<S> shapeForm, Form<V> valueForm) {
this(agentContext, keyForm, shapeForm, valueForm, 0, null);
}
@Override
public AgentContext agentContext() {
return this.agentContext;
}
@Override
public SpatialLaneModel<S> laneBinding() {
return this.laneBinding;
}
public void setLaneBinding(SpatialLaneModel<S> laneBinding) {
this.laneBinding = laneBinding;
}
@Override
public LaneBinding createLaneBinding() {
return new SpatialLaneModel<S>(shapeForm, flags);
}
@Override
public Form<K> keyForm() {
return this.keyForm;
}
@Override
public <K2> SpatialLane<K2, S, V> keyForm(Form<K2> keyForm) {
return new SpatialLaneView<K2, S, V>(this.agentContext, keyForm, this.shapeForm, this.valueForm,
this.flags, typesafeObservers(this.observers));
}
@Override
public <K2> SpatialLane<K2, S, V> keyClass(Class<K2> keyClass) {
return keyForm(Form.<K2>forClass(keyClass));
}
public void setKeyForm(Form<K> keyForm) {
this.keyForm = keyForm;
}
@Override
public Form<V> valueForm() {
return this.valueForm;
}
@Override
public <V2> SpatialLane<K, S, V2> valueForm(Form<V2> valueForm) {
return new SpatialLaneView<K, S, V2>(this.agentContext, keyForm, this.shapeForm, valueForm,
this.flags, typesafeObservers(this.observers));
}
@Override
public <V2> SpatialLane<K, S, V2> valueClass(Class<V2> valueClass) {
return valueForm(Form.<V2>forClass(valueClass));
}
public void setValueForm(Form<V> valueForm) {
this.valueForm = valueForm;
}
protected Object typesafeObservers(Object observers) {
// TODO: filter out WillUpdateKey, DidUpdateKey, WillRemoveKey, DidRemoveKey,
// WillDrop, DidDrop, WillTake, DidTake, WillClear, DidClear
return observers;
}
public final boolean isResident() {
return (this.flags & RESIDENT) != 0;
}
@Override
public SpatialLane<K, S, V> isResident(boolean isResident) {
if (isResident) {
this.flags |= RESIDENT;
} else {
this.flags &= ~RESIDENT;
}
final SpatialLaneModel<S> laneBinding = this.laneBinding;
if (laneBinding != null) {
laneBinding.isResident(isResident);
}
return this;
}
void didSetResident(boolean isResident) {
if (isResident) {
this.flags |= RESIDENT;
} else {
this.flags &= ~RESIDENT;
}
}
public final boolean isTransient() {
return (this.flags & TRANSIENT) != 0;
}
@Override
public SpatialLane<K, S, V> isTransient(boolean isTransient) {
if (isTransient) {
this.flags |= TRANSIENT;
} else {
this.flags &= ~TRANSIENT;
}
final SpatialLaneModel<S> laneBinding = this.laneBinding;
if (laneBinding != null) {
laneBinding.isTransient(isTransient);
}
return this;
}
void didSetTransient(boolean isTransient) {
if (isTransient) {
this.flags |= TRANSIENT;
} else {
this.flags &= ~TRANSIENT;
}
}
@Override
protected void willLoad() {
this.dataView = this.laneBinding.data.keyForm(this.keyForm).valueForm(this.valueForm);
super.willLoad();
}
@Override
public void close() {
this.laneBinding.closeLaneView(this);
}
@Override
public SpatialLaneView<K, S, V> observe(Object observer) {
super.observe(observer);
return this;
}
@Override
public SpatialLaneView<K, S, V> unobserve(Object observer) {
super.unobserve(observer);
return this;
}
@Override
public SpatialLane<K, S, V> willUpdate(WillUpdateShape<K, S, V> willUpdate) {
return observe(willUpdate);
}
@Override
public SpatialLane<K, S, V> didUpdate(DidUpdateShape<K, S, V> didUpdate) {
return observe(didUpdate);
}
@Override
public SpatialLane<K, S, V> willMove(WillMoveShape<K, S, V> willMove) {
return observe(willMove);
}
@Override
public SpatialLane<K, S, V> didMove(DidMoveShape<K, S, V> didMove) {
return observe(didMove);
}
@Override
public SpatialLane<K, S, V> willRemove(WillRemoveShape<K, S> willRemove) {
return observe(willRemove);
}
@Override
public SpatialLane<K, S, V> didRemove(DidRemoveShape<K, S, V> didRemove) {
return observe(didRemove);
}
@Override
public SpatialLane<K, S, V> willClear(WillClear willClear) {
return observe(willClear);
}
@Override
public SpatialLane<K, S, V> didClear(DidClear didClear) {
return observe(didClear);
}
@Override
public SpatialLaneView<K, S, V> willCommand(WillCommand willCommand) {
return observe(willCommand);
}
@Override
public SpatialLaneView<K, S, V> didCommand(DidCommand didCommand) {
return observe(didCommand);
}
@Override
public SpatialLaneView<K, S, V> willUplink(WillUplink willUplink) {
return observe(willUplink);
}
@Override
public SpatialLaneView<K, S, V> didUplink(DidUplink didUplink) {
return observe(didUplink);
}
@Override
public SpatialLaneView<K, S, V> willEnter(WillEnter willEnter) {
return observe(willEnter);
}
@Override
public SpatialLaneView<K, S, V> didEnter(DidEnter didEnter) {
return observe(didEnter);
}
@Override
public SpatialLaneView<K, S, V> willLeave(WillLeave willLeave) {
return observe(willLeave);
}
@Override
public SpatialLaneView<K, S, V> didLeave(DidLeave didLeave) {
return observe(didLeave);
}
@SuppressWarnings("unchecked")
public Map.Entry<Boolean, V> dispatchWillUpdate(Link link, K key, S shape, V newValue, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillUpdateShape<?, ?, ?>) {
if (((WillUpdateShape<?, ?, ?>) observers).isPreemptive() == preemptive) {
try {
newValue = ((WillUpdateShape<K, S, V>) observers).willUpdate(key, shape, newValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillUpdateShape<?, ?, ?>) {
if (((WillUpdateShape<?, ?, ?>) observer).isPreemptive() == preemptive) {
try {
newValue = ((WillUpdateShape<K, S, V>) observer).willUpdate(key, shape, newValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return new AbstractMap.SimpleImmutableEntry<Boolean, V>(complete, newValue);
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
@SuppressWarnings("unchecked")
public boolean dispatchDidUpdate(Link link, K key, S shape, V newValue, V oldValue, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidUpdateShape<?, ?, ?>) {
if (((DidUpdateShape<?, ?, ?>) observers).isPreemptive() == preemptive) {
try {
((DidUpdateShape<K, S, V>) observers).didUpdate(key, shape, newValue, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidUpdateShape<?, ?, ?>) {
if (((DidUpdateShape<?, ?, ?>) observer).isPreemptive() == preemptive) {
try {
((DidUpdateShape<K, S, V>) observer).didUpdate(key, shape, newValue, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
@SuppressWarnings("unchecked")
public Map.Entry<Boolean, V> dispatchWillMove(Link link, K key, S newShape, V newValue, S oldShape,
boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillMoveShape<?, ?, ?>) {
if (((WillMoveShape<?, ?, ?>) observers).isPreemptive() == preemptive) {
try {
newValue = ((WillMoveShape<K, S, V>) observers).willMove(key, newShape, newValue, oldShape);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillMoveShape<?, ?, ?>) {
if (((WillMoveShape<?, ?, ?>) observer).isPreemptive() == preemptive) {
try {
newValue = ((WillMoveShape<K, S, V>) observer).willMove(key, newShape, newValue, oldShape);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return new AbstractMap.SimpleImmutableEntry<Boolean, V>(complete, newValue);
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
@SuppressWarnings("unchecked")
public boolean dispatchDidMove(Link link, K key, S newShape, V newValue, S oldShape, V oldValue,
boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillMoveShape<?, ?, ?>) {
if (((DidMoveShape<?, ?, ?>) observers).isPreemptive() == preemptive) {
try {
((DidMoveShape<K, S, V>) observers).didMove(key, newShape, newValue, oldShape, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillMoveShape<?, ?, ?>) {
if (((DidMoveShape<?, ?, ?>) observer).isPreemptive() == preemptive) {
try {
((DidMoveShape<K, S, V>) observer).didMove(key, newShape, newValue, oldShape, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
@SuppressWarnings("unchecked")
public boolean dispatchWillRemove(Link link, K key, S shape, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillMoveShape<?, ?, ?>) {
if (((WillRemoveShape<?, ?>) observers).isPreemptive() == preemptive) {
try {
((WillRemoveShape<K, S>) observers).willRemove(key, shape);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillMoveShape<?, ?, ?>) {
if (((WillRemoveShape<?, ?>) observers).isPreemptive() == preemptive) {
try {
((WillRemoveShape<K, S>) observers).willRemove(key, shape);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
@SuppressWarnings("unchecked")
public boolean dispatchDidRemove(Link link, K key, S shape, V oldValue, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillMoveShape<?, ?, ?>) {
if (((DidRemoveShape<?, ?, ?>) observers).isPreemptive() == preemptive) {
try {
((DidRemoveShape<K, S, V>) observers).didRemove(key, shape, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillMoveShape<?, ?, ?>) {
if (((DidRemoveShape<?, ?, ?>) observers).isPreemptive() == preemptive) {
try {
((DidRemoveShape<K, S, V>) observers).didRemove(key, shape, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
public boolean dispatchWillClear(Link link, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillClear) {
if (((WillClear) observers).isPreemptive() == preemptive) {
try {
((WillClear) observers).willClear();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillClear) {
if (((WillClear) observer).isPreemptive() == preemptive) {
try {
((WillClear) observer).willClear();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
public boolean dispatchDidClear(Link link, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidClear) {
if (((DidClear) observers).isPreemptive() == preemptive) {
try {
((DidClear) observers).didClear();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidClear) {
if (((DidClear) observer).isPreemptive() == preemptive) {
try {
((DidClear) observer).didClear();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
public V laneWillUpdate(K key, S shape, V newValue) {
return newValue;
}
public void laneDidUpdate(K key, S shape, V newValue, V oldValue) {
}
public V laneWillMove(K key, S newShape, V newValue, S oldShape) {
return newValue;
}
public V laneDidMove(K key, S newShape, V newValue, S oldShape, V oldValue) {
return newValue;
}
public void laneWillRemove(K key, S shape) {
}
public void laneDidRemove(K key, S shape) {
}
public void laneWillClear() {
}
public void laneDidClear() {
}
@Override
public SpatialMap<K, S, V> snapshot() {
return this.dataView.snapshot();
}
@Override
public Iterator<Entry<K, S, V>> iterator() {
return this.dataView.iterator();
}
@Override
public boolean isEmpty() {
return this.dataView.isEmpty();
}
@Override
public int size() {
return this.dataView.size();
}
@Override
public boolean containsKey(K key, S shape) {
return this.dataView.containsKey(key, shape);
}
@Override
public boolean containsKey(Object key) {
return this.dataView.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return this.dataView.containsValue(value);
}
@Override
public V get(K key, S shape) {
return this.dataView.get(key, shape);
}
@Override
public V get(Object key) {
return this.dataView.get(key);
}
@Override
public V put(K key, S shape, V newValue) {
return this.dataView.put(key, shape, newValue);
}
@Override
public V move(K key, S oldShape, S newShape, V newValue) {
return this.dataView.move(key, oldShape, newShape, newValue);
}
@Override
public V remove(K key, S shape) {
return this.dataView.remove(key, shape);
}
@Override
public void clear() {
this.dataView.clear();
}
@Override
public Iterator<Entry<K, S, V>> iterator(S shape) {
return this.dataView.iterator(shape);
}
@Override
public Iterator<K> keyIterator() {
return this.dataView.keyIterator();
}
@Override
public Iterator<V> valueIterator() {
return this.dataView.valueIterator();
}
static final int RESIDENT = 1 << 0;
static final int TRANSIENT = 1 << 1;
static final int SIGNED = 1 << 2;
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/SupplyLaneModel.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.runtime.lane;
import swim.runtime.WarpBinding;
import swim.runtime.warp.WarpLaneModel;
public class SupplyLaneModel extends WarpLaneModel<SupplyLaneView<?>, SupplyLaneUplink> {
@Override
public String laneType() {
return "supply";
}
@Override
protected SupplyLaneUplink createWarpUplink(WarpBinding link) {
return new SupplyLaneUplink(this, link);
}
@Override
protected void didOpenLaneView(SupplyLaneView<?> view) {
view.setLaneBinding(this);
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/SupplyLaneUplink.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.runtime.lane;
import swim.concurrent.Stage;
import swim.runtime.WarpBinding;
import swim.runtime.warp.SupplyUplinkModem;
public class SupplyLaneUplink extends SupplyUplinkModem {
final SupplyLaneModel laneBinding;
public SupplyLaneUplink(SupplyLaneModel laneBinding, WarpBinding linkBinding) {
super(linkBinding);
this.laneBinding = laneBinding;
}
@Override
public SupplyLaneModel laneBinding() {
return this.laneBinding;
}
@Override
public Stage stage() {
return this.laneBinding.stage();
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/SupplyLaneView.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.runtime.lane;
import swim.api.agent.AgentContext;
import swim.api.lane.SupplyLane;
import swim.api.warp.function.DidCommand;
import swim.api.warp.function.DidEnter;
import swim.api.warp.function.DidLeave;
import swim.api.warp.function.DidUplink;
import swim.api.warp.function.WillCommand;
import swim.api.warp.function.WillEnter;
import swim.api.warp.function.WillLeave;
import swim.api.warp.function.WillUplink;
import swim.runtime.warp.WarpLaneView;
import swim.structure.Form;
public class SupplyLaneView<V> extends WarpLaneView implements SupplyLane<V> {
protected final AgentContext agentContext;
protected Form<V> valueForm;
protected SupplyLaneModel laneBinding;
public SupplyLaneView(AgentContext agentContext, Form<V> valueForm, Object observers) {
super(observers);
this.agentContext = agentContext;
this.valueForm = valueForm;
}
public SupplyLaneView(AgentContext agentContext, Form<V> valueForm) {
this(agentContext, valueForm, null);
}
@Override
public AgentContext agentContext() {
return this.agentContext;
}
@Override
public SupplyLaneModel laneBinding() {
return this.laneBinding;
}
void setLaneBinding(SupplyLaneModel laneBinding) {
this.laneBinding = laneBinding;
}
@Override
public SupplyLaneModel createLaneBinding() {
return new SupplyLaneModel();
}
@Override
public final Form<V> valueForm() {
return this.valueForm;
}
@Override
public <V2> SupplyLaneView<V2> valueForm(Form<V2> valueForm) {
return new SupplyLaneView<V2>(this.agentContext, valueForm, this.observers);
}
@Override
public <V2> SupplyLaneView<V2> valueClass(Class<V2> valueClass) {
return valueForm(Form.<V2>forClass(valueClass));
}
public void setValueForm(Form<V> valueForm) {
this.valueForm = valueForm;
}
@Override
public void close() {
this.laneBinding.closeLaneView(this);
}
@Override
public SupplyLaneView<V> observe(Object observer) {
super.observe(observer);
return this;
}
@Override
public SupplyLaneView<V> unobserve(Object observer) {
super.unobserve(observer);
return this;
}
@Override
public SupplyLaneView<V> willCommand(WillCommand willCommand) {
return observe(willCommand);
}
@Override
public SupplyLaneView<V> didCommand(DidCommand didCommand) {
return observe(didCommand);
}
@Override
public SupplyLaneView<V> willUplink(WillUplink willUplink) {
return observe(willUplink);
}
@Override
public SupplyLaneView<V> didUplink(DidUplink didUplink) {
return observe(didUplink);
}
@Override
public SupplyLaneView<V> willEnter(WillEnter willEnter) {
return observe(willEnter);
}
@Override
public SupplyLaneView<V> didEnter(DidEnter didEnter) {
return observe(didEnter);
}
@Override
public SupplyLaneView<V> willLeave(WillLeave willLeave) {
return observe(willLeave);
}
@Override
public SupplyLaneView<V> didLeave(DidLeave didLeave) {
return observe(didLeave);
}
@Override
public void push(V value) {
this.laneBinding.sendDown(this.valueForm.mold(value).toValue());
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/ValueLaneModel.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.runtime.lane;
import java.util.Map;
import swim.api.Link;
import swim.api.data.ValueData;
import swim.concurrent.Stage;
import swim.runtime.LaneRelay;
import swim.runtime.LaneView;
import swim.runtime.WarpBinding;
import swim.runtime.warp.WarpLaneModel;
import swim.structure.Form;
import swim.structure.Value;
import swim.warp.CommandMessage;
public class ValueLaneModel extends WarpLaneModel<ValueLaneView<?>, ValueLaneUplink> {
protected int flags;
protected ValueData<Value> data;
ValueLaneModel(int flags) {
this.flags = flags;
}
public ValueLaneModel() {
this(0);
}
@Override
public String laneType() {
return "value";
}
@Override
protected ValueLaneUplink createWarpUplink(WarpBinding link) {
return new ValueLaneUplink(this, link);
}
@Override
protected void didOpenLaneView(ValueLaneView<?> view) {
view.setLaneBinding(this);
}
@Override
public void onCommand(CommandMessage message) {
new ValueLaneRelaySet(this, message, message.body()).run();
}
public final boolean isResident() {
return (this.flags & RESIDENT) != 0;
}
public ValueLaneModel isResident(boolean isResident) {
if (this.data != null) {
this.data.isResident(isResident);
}
if (isResident) {
this.flags |= RESIDENT;
} else {
this.flags &= ~RESIDENT;
}
final Object views = this.views;
if (views instanceof ValueLaneView<?>) {
((ValueLaneView<?>) views).didSetResident(isResident);
} else if (views instanceof LaneView[]) {
for (LaneView aViewArray : (LaneView[]) views) {
((ValueLaneView<?>) aViewArray).didSetResident(isResident);
}
}
return this;
}
public final boolean isTransient() {
return (this.flags & TRANSIENT) != 0;
}
public ValueLaneModel isTransient(boolean isTransient) {
if (this.data != null) {
this.data.isTransient(isTransient);
}
if (isTransient) {
this.flags |= TRANSIENT;
} else {
this.flags &= ~TRANSIENT;
}
final Object views = this.views;
if (views instanceof ValueLaneView<?>) {
((ValueLaneView<?>) views).didSetTransient(isTransient);
} else if (views instanceof LaneView[]) {
final LaneView[] viewArray = (LaneView[]) views;
for (int i = 0, n = viewArray.length; i < n; i += 1) {
((ValueLaneView<?>) viewArray[i]).didSetTransient(isTransient);
}
}
return this;
}
public Value get() {
return this.data.get();
}
@SuppressWarnings("unchecked")
public <V> V set(ValueLaneView<V> view, V newObject) {
final Form<V> valueForm = view.valueForm;
final Value newValue = valueForm.mold(newObject).toValue();
final ValueLaneRelaySet relay = new ValueLaneRelaySet(this, stage(), newValue);
relay.valueForm = (Form<Object>) valueForm;
relay.oldObject = newObject;
relay.newObject = newObject;
relay.run();
if (relay.valueForm != valueForm && valueForm != null) {
relay.oldObject = valueForm.cast(relay.oldValue);
if (relay.oldObject == null) {
relay.oldObject = valueForm.unit();
}
}
return (V) relay.oldObject;
}
protected void openStore() {
this.data = this.laneContext.store().valueData(laneUri().toString())
.isTransient(isTransient())
.isResident(isResident());
}
@Override
protected void willLoad() {
openStore();
super.willLoad();
}
static final int RESIDENT = 1 << 0;
static final int TRANSIENT = 1 << 1;
static final int SIGNED = 1 << 2;
}
final class ValueLaneRelaySet extends LaneRelay<ValueLaneModel, ValueLaneView<?>> {
final Link link;
final CommandMessage message;
Form<Object> valueForm;
Value oldValue;
Object oldObject;
Value newValue;
Object newObject;
ValueLaneRelaySet(ValueLaneModel model, CommandMessage message, Value newValue) {
super(model, 4);
this.link = null;
this.message = message;
this.newValue = newValue;
}
ValueLaneRelaySet(ValueLaneModel model, Link link, Value newValue) {
super(model, 1, 3, null);
this.link = link;
this.message = null;
this.newValue = newValue;
}
ValueLaneRelaySet(ValueLaneModel model, Stage stage, Value newValue) {
super(model, 1, 3, stage);
this.link = null;
this.message = null;
this.newValue = newValue;
}
@Override
protected void beginPhase(int phase) {
if (phase == 2) {
this.oldValue = this.model.data.set(this.newValue);
if (this.valueForm != null) {
this.oldObject = this.valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = this.valueForm.unit();
}
}
}
}
@SuppressWarnings("unchecked")
@Override
protected boolean runPhase(ValueLaneView<?> view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneWillCommand(this.message);
}
return view.dispatchWillCommand(this.message.body(), preemptive);
} else if (phase == 1) {
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.oldObject = valueForm.cast(this.newValue);
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
}
if (preemptive) {
this.newObject = ((ValueLaneView<Object>) view).laneWillSet(this.oldObject);
}
final Map.Entry<Boolean, Object> result = ((ValueLaneView<Object>) view).dispatchWillSet(this.link, this.oldObject, preemptive);
this.newObject = result.getValue();
if (this.oldObject != this.newObject) {
this.newValue = valueForm.mold(this.newObject).toValue();
}
return result.getKey();
} else if (phase == 2) {
final Form<Object> valueForm = (Form<Object>) view.valueForm;
if (this.valueForm != valueForm && valueForm != null) {
this.valueForm = valueForm;
this.oldObject = valueForm.cast(this.oldValue);
if (this.oldObject == null) {
this.oldObject = valueForm.unit();
}
this.newObject = valueForm.cast(this.newValue);
if (this.newObject == null) {
this.newObject = valueForm.unit();
}
}
if (preemptive) {
((ValueLaneView<Object>) view).laneDidSet(this.newObject, this.oldObject);
}
return ((ValueLaneView<Object>) view).dispatchDidSet(this.link, this.newObject, this.oldObject, preemptive);
} else if (phase == 3) {
if (preemptive) {
view.laneDidCommand(this.message);
}
return view.dispatchDidCommand(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
this.model.cueDown();
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/ValueLaneUplink.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.runtime.lane;
import swim.concurrent.Stage;
import swim.runtime.WarpBinding;
import swim.runtime.warp.DemandUplinkModem;
import swim.structure.Value;
import swim.warp.SyncRequest;
public class ValueLaneUplink extends DemandUplinkModem {
final ValueLaneModel laneBinding;
public ValueLaneUplink(ValueLaneModel laneBinding, WarpBinding linkBinding) {
super(linkBinding);
this.laneBinding = laneBinding;
}
@Override
public ValueLaneModel laneBinding() {
return this.laneBinding;
}
@Override
public Stage stage() {
return this.laneBinding.stage();
}
@Override
protected Value nextDownCue() {
return this.laneBinding.get();
}
@Override
protected void willSync(SyncRequest request) {
cueDown();
super.willSync(request);
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/ValueLaneView.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.runtime.lane;
import java.util.AbstractMap;
import java.util.Iterator;
import java.util.Map;
import swim.api.Lane;
import swim.api.Link;
import swim.api.SwimContext;
import swim.api.agent.AgentContext;
import swim.api.lane.ValueLane;
import swim.api.warp.function.DidCommand;
import swim.api.warp.function.DidEnter;
import swim.api.warp.function.DidLeave;
import swim.api.warp.function.DidUplink;
import swim.api.warp.function.WillCommand;
import swim.api.warp.function.WillEnter;
import swim.api.warp.function.WillLeave;
import swim.api.warp.function.WillUplink;
import swim.concurrent.Conts;
import swim.observable.function.DidSet;
import swim.observable.function.WillSet;
import swim.runtime.warp.WarpLaneView;
import swim.streamlet.Inlet;
import swim.streamlet.Outlet;
import swim.structure.Form;
import swim.util.Cursor;
public class ValueLaneView<V> extends WarpLaneView implements ValueLane<V> {
protected final AgentContext agentContext;
protected Form<V> valueForm;
protected int flags;
protected ValueLaneModel laneBinding;
protected Outlet<? extends V> input;
protected Inlet<? super V>[] outputs; // TODO: unify with observers
protected int version;
ValueLaneView(AgentContext agentContext, Form<V> valueForm, int flags, Object observers) {
super(observers);
this.agentContext = agentContext;
this.valueForm = valueForm;
this.flags = flags;
this.input = null;
this.outputs = null;
this.version = -1;
}
public ValueLaneView(AgentContext agentContext, Form<V> valueForm) {
this(agentContext, valueForm, 0, null);
}
@Override
public AgentContext agentContext() {
return this.agentContext;
}
@Override
public ValueLaneModel laneBinding() {
return this.laneBinding;
}
void setLaneBinding(ValueLaneModel laneBinding) {
this.laneBinding = laneBinding;
}
@Override
public ValueLaneModel createLaneBinding() {
return new ValueLaneModel(this.flags);
}
@Override
public final Form<V> valueForm() {
return this.valueForm;
}
@Override
public <V2> ValueLaneView<V2> valueForm(Form<V2> valueForm) {
return new ValueLaneView<V2>(this.agentContext, valueForm, this.flags,
typesafeObservers(this.observers));
}
@Override
public <V2> ValueLaneView<V2> valueClass(Class<V2> valueClass) {
return valueForm(Form.<V2>forClass(valueClass));
}
public void setValueForm(Form<V> valueForm) {
this.valueForm = valueForm;
}
protected Object typesafeObservers(Object observers) {
// TODO: filter out WillSet, DidSet
return observers;
}
@Override
public final boolean isResident() {
return (this.flags & RESIDENT) != 0;
}
@Override
public ValueLaneView<V> isResident(boolean isResident) {
didSetResident(isResident);
// note: marked final given access of concurrently accessed volatile objects
final ValueLaneModel laneBinding = this.laneBinding;
if (laneBinding != null) {
laneBinding.isResident(isResident);
}
return this;
}
void didSetResident(boolean isResident) {
if (isResident) {
this.flags |= RESIDENT;
} else {
this.flags &= ~RESIDENT;
}
}
@Override
public final boolean isTransient() {
return (this.flags & TRANSIENT) != 0;
}
@Override
public ValueLaneView<V> isTransient(boolean isTransient) {
didSetTransient(isTransient);
// note: marked final given access of concurrently accessed volatile objects
final ValueLaneModel laneBinding = this.laneBinding;
if (laneBinding != null) {
laneBinding.isTransient(isTransient);
}
return this;
}
void didSetTransient(boolean isTransient) {
if (isTransient) {
this.flags |= TRANSIENT;
} else {
this.flags &= ~TRANSIENT;
}
}
@Override
public void close() {
this.laneBinding.closeLaneView(this);
}
@Override
public ValueLaneView<V> observe(Object observer) {
super.observe(observer);
return this;
}
@Override
public ValueLaneView<V> unobserve(Object observer) {
super.unobserve(observer);
return this;
}
@Override
public ValueLaneView<V> willSet(WillSet<V> willSet) {
return observe(willSet);
}
@Override
public ValueLaneView<V> didSet(DidSet<V> didSet) {
return observe(didSet);
}
@Override
public ValueLaneView<V> willCommand(WillCommand willCommand) {
return observe(willCommand);
}
@Override
public ValueLaneView<V> didCommand(DidCommand didCommand) {
return observe(didCommand);
}
@Override
public ValueLaneView<V> willUplink(WillUplink willUplink) {
return observe(willUplink);
}
@Override
public ValueLaneView<V> didUplink(DidUplink didUplink) {
return observe(didUplink);
}
@Override
public ValueLaneView<V> willEnter(WillEnter willEnter) {
return observe(willEnter);
}
@Override
public ValueLaneView<V> didEnter(DidEnter didEnter) {
return observe(didEnter);
}
@Override
public ValueLaneView<V> willLeave(WillLeave willLeave) {
return observe(willLeave);
}
@Override
public ValueLaneView<V> didLeave(DidLeave didLeave) {
return observe(didLeave);
}
@SuppressWarnings("unchecked")
public Map.Entry<Boolean, V> dispatchWillSet(Link link, V newValue, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillSet<?>) {
if (((WillSet<?>) observers).isPreemptive() == preemptive) {
try {
newValue = ((WillSet<V>) observers).willSet(newValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillSet<?>) {
if (((WillSet<?>) observer).isPreemptive() == preemptive) {
try {
newValue = ((WillSet<V>) observer).willSet(newValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return new AbstractMap.SimpleImmutableEntry<Boolean, V>(complete, newValue);
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
@SuppressWarnings("unchecked")
public boolean dispatchDidSet(Link link, V newValue, V oldValue, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLane(this);
SwimContext.setLink(link);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidSet<?>) {
if (((DidSet<?>) observers).isPreemptive() == preemptive) {
try {
((DidSet<V>) observers).didSet(newValue, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidSet<?>) {
if (((DidSet<?>) observer).isPreemptive() == preemptive) {
try {
((DidSet<V>) observer).didSet(newValue, oldValue);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
public V laneWillSet(V newValue) {
return newValue;
}
public void laneDidSet(V newValue, V oldValue) {
invalidate();
reconcile(0); // TODO: debounce and track version
}
@Override
public V get() {
V state = this.valueForm.cast(this.laneBinding.get());
if (state == null) {
state = this.valueForm.unit();
}
return state;
}
@Override
public V set(V newValue) {
return this.laneBinding.set(this, newValue);
}
@Override
public Outlet<? extends V> input() {
return this.input;
}
@Override
public void bindInput(Outlet<? extends V> input) {
if (this.input != null) {
this.input.unbindOutput(this);
}
this.input = input;
if (this.input != null) {
this.input.bindOutput(this);
}
}
@Override
public void unbindInput() {
if (this.input != null) {
this.input.unbindOutput(this);
}
this.input = null;
}
@Override
public void disconnectInputs() {
final Outlet<? extends V> input = this.input;
if (input != null) {
input.unbindOutput(this);
this.input = null;
input.disconnectInputs();
}
}
@Override
public Iterator<Inlet<? super V>> outputIterator() {
return this.outputs != null ? Cursor.array(this.outputs) : Cursor.empty();
}
@SuppressWarnings("unchecked")
@Override
public void bindOutput(Inlet<? super V> output) {
final Inlet<? super V>[] oldOutputs = this.outputs;
final int n = oldOutputs != null ? oldOutputs.length : 0;
final Inlet<? super V>[] newOutputs = (Inlet<? super V>[]) new Inlet<?>[n + 1];
if (n > 0) {
System.arraycopy(oldOutputs, 0, newOutputs, 0, n);
}
newOutputs[n] = output;
this.outputs = newOutputs;
}
@SuppressWarnings("unchecked")
@Override
public void unbindOutput(Inlet<? super V> output) {
final Inlet<? super V>[] oldOutputs = this.outputs;
final int n = oldOutputs != null ? oldOutputs.length : 0;
for (int i = 0; i < n; i += 1) {
if (oldOutputs[i] == output) {
if (n > 1) {
final Inlet<? super V>[] newOutputs = (Inlet<? super V>[]) new Inlet<?>[n - 1];
System.arraycopy(oldOutputs, 0, newOutputs, 0, i);
System.arraycopy(oldOutputs, i + 1, newOutputs, i, (n - 1) - i);
this.outputs = newOutputs;
} else {
this.outputs = null;
}
break;
}
}
}
@Override
public void unbindOutputs() {
final Inlet<? super V>[] outputs = this.outputs;
if (outputs != null) {
this.outputs = null;
for (int i = 0, n = outputs.length; i < n; i += 1) {
final Inlet<? super V> output = outputs[i];
output.unbindInput();
}
}
}
@Override
public void disconnectOutputs() {
final Inlet<? super V>[] outputs = this.outputs;
if (outputs != null) {
this.outputs = null;
for (int i = 0, n = outputs.length; i < n; i += 1) {
final Inlet<? super V> output = outputs[i];
output.unbindInput();
output.disconnectOutputs();
}
}
}
@Override
public void invalidateOutput() {
invalidate();
}
@Override
public void invalidateInput() {
invalidate();
}
public void invalidate() {
if (this.version >= 0) {
willInvalidate();
this.version = -1;
onInvalidate();
final int n = this.outputs != null ? this.outputs.length : 0;
for (int i = 0; i < n; i += 1) {
this.outputs[i].invalidateOutput();
}
didInvalidate();
}
}
@Override
public void reconcileOutput(int version) {
reconcile(version);
}
@Override
public void reconcileInput(int version) {
reconcile(version);
}
public void reconcile(int version) {
if (this.version < 0) {
willReconcile(version);
this.version = version;
if (this.input != null) {
this.input.reconcileInput(version);
}
onReconcile(version);
final int n = this.outputs != null ? this.outputs.length : 0;
for (int i = 0; i < n; i += 1) {
this.outputs[i].reconcileOutput(version);
}
didReconcile(version);
}
}
protected void willInvalidate() {
// stub
}
protected void onInvalidate() {
// stub
}
protected void didInvalidate() {
// stub
}
protected void willReconcile(int version) {
// stub
}
protected void onReconcile(int version) {
if (this.input != null) {
final V value = this.input.get();
set(value);
}
}
protected void didReconcile(int version) {
// stub
}
static final int RESIDENT = 1 << 0;
static final int TRANSIENT = 1 << 1;
static final int SIGNED = 1 << 2;
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/lane/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.
/**
* Lane runtime implementation.
*/
package swim.runtime.lane;
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/router/EdgeTable.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.runtime.router;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import swim.api.Downlink;
import swim.api.policy.Policy;
import swim.collections.HashTrieMap;
import swim.concurrent.Schedule;
import swim.concurrent.Stage;
import swim.runtime.AbstractTierBinding;
import swim.runtime.DownlinkView;
import swim.runtime.EdgeBinding;
import swim.runtime.EdgeContext;
import swim.runtime.LinkBinding;
import swim.runtime.MeshBinding;
import swim.runtime.MeshContext;
import swim.runtime.PushRequest;
import swim.runtime.TierContext;
import swim.runtime.UplinkError;
import swim.store.StoreBinding;
import swim.uri.Uri;
public class EdgeTable extends AbstractTierBinding implements EdgeBinding {
protected EdgeContext edgeContext;
volatile HashTrieMap<Uri, MeshBinding> meshes;
volatile MeshBinding network;
public EdgeTable() {
this.meshes = HashTrieMap.empty();
}
@Override
public final TierContext tierContext() {
return this.edgeContext;
}
@Override
public final EdgeBinding edgeWrapper() {
return this;
}
@Override
public final EdgeContext edgeContext() {
return this.edgeContext;
}
@Override
public void setEdgeContext(EdgeContext edgeContext) {
this.edgeContext = edgeContext;
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrapEdge(Class<T> edgeClass) {
if (edgeClass.isAssignableFrom(getClass())) {
return (T) this;
} else {
return this.edgeContext.unwrapEdge(edgeClass);
}
}
protected MeshContext createMeshContext(MeshBinding mesh, Uri meshUri) {
return new EdgeTableMesh(this, mesh, meshUri);
}
@Override
public final Uri meshUri() {
return Uri.empty();
}
@Override
public Policy policy() {
return this.edgeContext.policy();
}
@Override
public Schedule schedule() {
return this.edgeContext.schedule();
}
@Override
public Stage stage() {
return this.edgeContext.stage();
}
@Override
public StoreBinding store() {
return this.edgeContext.store();
}
@Override
public MeshBinding network() {
return this.network;
}
@Override
public void setNetwork(MeshBinding network) {
this.network = network;
}
@Override
public HashTrieMap<Uri, MeshBinding> meshes() {
return this.meshes;
}
@Override
public MeshBinding getMesh(Uri meshUri) {
return this.meshes.get(meshUri);
}
@Override
public MeshBinding openMesh(Uri meshUri) {
HashTrieMap<Uri, MeshBinding> oldMeshes;
HashTrieMap<Uri, MeshBinding> newMeshes;
MeshBinding meshBinding = null;
do {
oldMeshes = this.meshes;
final MeshBinding mesh = oldMeshes.get(meshUri);
if (mesh != null) {
if (meshBinding != null) {
// Lost creation race.
meshBinding.close();
}
meshBinding = mesh;
newMeshes = oldMeshes;
break;
} else if (meshBinding == null) {
meshBinding = this.edgeContext.createMesh(meshUri);
if (meshBinding != null) {
meshBinding = this.edgeContext.injectMesh(meshUri, meshBinding);
final MeshContext meshContext = createMeshContext(meshBinding, meshUri);
meshBinding.setMeshContext(meshContext);
meshBinding = meshBinding.meshWrapper();
newMeshes = oldMeshes.updated(meshUri, meshBinding);
} else {
newMeshes = oldMeshes;
break;
}
} else {
newMeshes = oldMeshes.updated(meshUri, meshBinding);
}
} while (oldMeshes != newMeshes && !MESHES.compareAndSet(this, oldMeshes, newMeshes));
if (oldMeshes != newMeshes) {
activate(meshBinding);
}
return meshBinding;
}
@Override
public MeshBinding openMesh(Uri meshUri, MeshBinding mesh) {
HashTrieMap<Uri, MeshBinding> oldMeshes;
HashTrieMap<Uri, MeshBinding> newMeshes;
MeshBinding meshBinding = null;
do {
oldMeshes = this.meshes;
if (oldMeshes.containsKey(meshUri)) {
meshBinding = null;
newMeshes = oldMeshes;
break;
} else {
if (meshBinding == null) {
meshBinding = this.edgeContext.injectMesh(meshUri, mesh);
final MeshContext meshContext = createMeshContext(meshBinding, meshUri);
meshBinding.setMeshContext(meshContext);
meshBinding = meshBinding.meshWrapper();
}
newMeshes = oldMeshes.updated(meshUri, meshBinding);
}
} while (oldMeshes != newMeshes && !MESHES.compareAndSet(this, oldMeshes, newMeshes));
if (meshBinding != null) {
activate(meshBinding);
}
return meshBinding;
}
public void closeMesh(Uri meshUri) {
HashTrieMap<Uri, MeshBinding> oldMeshes;
HashTrieMap<Uri, MeshBinding> newMeshes;
MeshBinding meshBinding = null;
do {
oldMeshes = this.meshes;
final MeshBinding mesh = oldMeshes.get(meshUri);
if (mesh != null) {
meshBinding = mesh;
newMeshes = oldMeshes.removed(meshUri);
} else {
meshBinding = null;
newMeshes = oldMeshes;
break;
}
} while (oldMeshes != newMeshes && !MESHES.compareAndSet(this, oldMeshes, newMeshes));
if (meshBinding != null) {
if (this.network == meshBinding) {
this.network = null;
}
meshBinding.didClose();
}
}
@Override
public LinkBinding bindDownlink(Downlink downlink) {
final LinkBinding link = ((DownlinkView) downlink).createDownlinkModel();
openUplink(link);
return link;
}
@Override
public void openDownlink(LinkBinding link) {
openUplink(link);
}
@Override
public void closeDownlink(LinkBinding link) {
// nop
}
@Override
public void openUplink(LinkBinding link) {
final MeshBinding meshBinding = openMesh(link.meshUri());
if (meshBinding != null) {
meshBinding.openUplink(link);
} else {
UplinkError.rejectMeshNotFound(link);
}
}
@Override
public void pushDown(PushRequest pushRequest) {
pushUp(pushRequest);
}
@Override
public void pushUp(PushRequest pushRequest) {
final MeshBinding meshBinding = openMesh(pushRequest.meshUri());
if (meshBinding != null) {
meshBinding.pushUp(pushRequest);
} else {
pushRequest.didDecline();
}
}
@Override
public void trace(Object message) {
this.edgeContext.trace(message);
}
@Override
public void debug(Object message) {
this.edgeContext.debug(message);
}
@Override
public void info(Object message) {
this.edgeContext.info(message);
}
@Override
public void warn(Object message) {
this.edgeContext.warn(message);
}
@Override
public void error(Object message) {
this.edgeContext.error(message);
}
@Override
protected void willOpen() {
super.willOpen();
final Iterator<MeshBinding> meshesIterator = this.meshes.valueIterator();
while (meshesIterator.hasNext()) {
meshesIterator.next().open();
}
}
@Override
protected void willLoad() {
super.willLoad();
final Iterator<MeshBinding> meshesIterator = this.meshes.valueIterator();
while (meshesIterator.hasNext()) {
meshesIterator.next().load();
}
}
@Override
protected void willStart() {
super.willStart();
final Iterator<MeshBinding> meshesIterator = this.meshes.valueIterator();
while (meshesIterator.hasNext()) {
meshesIterator.next().start();
}
}
@Override
protected void willStop() {
super.willStop();
final Iterator<MeshBinding> meshesIterator = this.meshes.valueIterator();
while (meshesIterator.hasNext()) {
meshesIterator.next().stop();
}
}
@Override
protected void willUnload() {
super.willUnload();
final Iterator<MeshBinding> meshesIterator = this.meshes.valueIterator();
while (meshesIterator.hasNext()) {
meshesIterator.next().unload();
}
}
@Override
protected void willClose() {
super.willClose();
final Iterator<MeshBinding> meshesIterator = this.meshes.valueIterator();
while (meshesIterator.hasNext()) {
meshesIterator.next().close();
}
}
@Override
public void didClose() {
// nop
}
@Override
public void didFail(Throwable error) {
error.printStackTrace();
}
@SuppressWarnings("unchecked")
static final AtomicReferenceFieldUpdater<EdgeTable, HashTrieMap<Uri, MeshBinding>> MESHES =
AtomicReferenceFieldUpdater.newUpdater(EdgeTable.class, (Class<HashTrieMap<Uri, MeshBinding>>) (Class<?>) HashTrieMap.class, "meshes");
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/router/EdgeTableMesh.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.runtime.router;
import swim.api.Downlink;
import swim.api.agent.Agent;
import swim.api.agent.AgentDef;
import swim.api.agent.AgentFactory;
import swim.api.auth.Credentials;
import swim.api.auth.Identity;
import swim.api.policy.Policy;
import swim.api.policy.PolicyDirective;
import swim.concurrent.Schedule;
import swim.concurrent.Stage;
import swim.runtime.EdgeBinding;
import swim.runtime.HostBinding;
import swim.runtime.LaneBinding;
import swim.runtime.LaneDef;
import swim.runtime.LinkBinding;
import swim.runtime.MeshBinding;
import swim.runtime.MeshContext;
import swim.runtime.NodeBinding;
import swim.runtime.PartBinding;
import swim.runtime.PushRequest;
import swim.store.StoreBinding;
import swim.structure.Value;
import swim.uri.Uri;
public class EdgeTableMesh implements MeshContext {
protected final EdgeTable edge;
protected final MeshBinding mesh;
protected final Uri meshUri;
public EdgeTableMesh(EdgeTable edge, MeshBinding mesh, Uri meshUri) {
this.edge = edge;
this.mesh = mesh;
this.meshUri = meshUri;
}
@Override
public final EdgeBinding edge() {
return this.edge;
}
@Override
public final MeshBinding meshWrapper() {
return this.mesh.meshWrapper();
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrapMesh(Class<T> meshClass) {
if (meshClass.isAssignableFrom(getClass())) {
return (T) this;
} else {
return null;
}
}
@Override
public final Uri meshUri() {
return this.meshUri;
}
@Override
public Policy policy() {
return this.edge.policy();
}
@Override
public Schedule schedule() {
return this.edge.schedule();
}
@Override
public Stage stage() {
return this.edge.stage();
}
@Override
public StoreBinding store() {
return this.edge.store();
}
@Override
public PartBinding createPart(Value partKey) {
return this.edge.edgeContext().createPart(this.meshUri, partKey);
}
@Override
public PartBinding injectPart(Value partKey, PartBinding part) {
return this.edge.edgeContext().injectPart(this.meshUri, partKey, part);
}
@Override
public HostBinding createHost(Value partKey, Uri hostUri) {
return this.edge.edgeContext().createHost(this.meshUri, partKey, hostUri);
}
@Override
public HostBinding injectHost(Value partKey, Uri hostUri, HostBinding host) {
return this.edge.edgeContext().injectHost(this.meshUri, partKey, hostUri, host);
}
@Override
public NodeBinding createNode(Value partKey, Uri hostUri, Uri nodeUri) {
return this.edge.edgeContext().createNode(this.meshUri, partKey, hostUri, nodeUri);
}
@Override
public NodeBinding injectNode(Value partKey, Uri hostUri, Uri nodeUri, NodeBinding node) {
return this.edge.edgeContext().injectNode(this.meshUri, partKey, hostUri, nodeUri, node);
}
@Override
public LaneBinding createLane(Value partKey, Uri hostUri, Uri nodeUri, LaneDef laneDef) {
return this.edge.edgeContext().createLane(this.meshUri, partKey, hostUri, nodeUri, laneDef);
}
@Override
public LaneBinding createLane(Value partKey, Uri hostUri, Uri nodeUri, Uri laneUri) {
return this.edge.edgeContext().createLane(this.meshUri, partKey, hostUri, nodeUri, laneUri);
}
@Override
public LaneBinding injectLane(Value partKey, Uri hostUri, Uri nodeUri, Uri laneUri, LaneBinding lane) {
return this.edge.edgeContext().injectLane(this.meshUri, partKey, hostUri, nodeUri, laneUri, lane);
}
@Override
public void openLanes(Value partKey, Uri hostUri, Uri nodeUri, NodeBinding node) {
this.edge.edgeContext().openLanes(this.meshUri, partKey, hostUri, nodeUri, node);
}
@Override
public AgentFactory<?> createAgentFactory(Value partKey, Uri hostUri, Uri nodeUri, AgentDef agentDef) {
return this.edge.edgeContext().createAgentFactory(this.meshUri, partKey, hostUri, nodeUri, agentDef);
}
@Override
public <A extends Agent> AgentFactory<A> createAgentFactory(Value partKey, Uri hostUri, Uri nodeUri,
Class<? extends A> agentClass) {
return this.edge.edgeContext().createAgentFactory(this.meshUri, partKey, hostUri, nodeUri, agentClass);
}
@Override
public void openAgents(Value partKey, Uri hostUri, Uri nodeUri, NodeBinding node) {
this.edge.edgeContext().openAgents(this.meshUri, partKey, hostUri, nodeUri, node);
}
@Override
public PolicyDirective<Identity> authenticate(Credentials credentials) {
return this.edge.edgeContext().authenticate(credentials);
}
@Override
public LinkBinding bindDownlink(Downlink downlink) {
return this.edge.bindDownlink(downlink);
}
@Override
public void openDownlink(LinkBinding link) {
this.edge.openDownlink(link);
}
@Override
public void closeDownlink(LinkBinding link) {
// nop
}
@Override
public void pushDown(PushRequest pushRequest) {
this.edge.pushDown(pushRequest);
}
@Override
public void trace(Object message) {
this.edge.trace(message);
}
@Override
public void debug(Object message) {
this.edge.debug(message);
}
@Override
public void info(Object message) {
this.edge.info(message);
}
@Override
public void warn(Object message) {
this.edge.warn(message);
}
@Override
public void error(Object message) {
this.edge.error(message);
}
@Override
public void close() {
this.edge.closeMesh(this.meshUri);
}
@Override
public void willOpen() {
// nop
}
@Override
public void didOpen() {
// nop
}
@Override
public void willLoad() {
// nop
}
@Override
public void didLoad() {
// nop
}
@Override
public void willStart() {
// nop
}
@Override
public void didStart() {
// nop
}
@Override
public void willStop() {
// nop
}
@Override
public void didStop() {
// nop
}
@Override
public void willUnload() {
// nop
}
@Override
public void didUnload() {
// nop
}
@Override
public void willClose() {
// nop
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/router/HostTable.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.runtime.router;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import swim.api.Downlink;
import swim.api.policy.Policy;
import swim.collections.HashTrieMap;
import swim.concurrent.Schedule;
import swim.concurrent.Stage;
import swim.runtime.AbstractTierBinding;
import swim.runtime.HostBinding;
import swim.runtime.HostContext;
import swim.runtime.LinkBinding;
import swim.runtime.NodeBinding;
import swim.runtime.NodeContext;
import swim.runtime.PartBinding;
import swim.runtime.PushRequest;
import swim.runtime.TierContext;
import swim.runtime.UplinkError;
import swim.store.StoreBinding;
import swim.structure.Value;
import swim.uri.Uri;
public class HostTable extends AbstractTierBinding implements HostBinding {
protected HostContext hostContext;
volatile HashTrieMap<Uri, NodeBinding> nodes;
volatile int flags;
public HostTable() {
this.nodes = HashTrieMap.empty();
}
@Override
public final TierContext tierContext() {
return this.hostContext;
}
@Override
public final PartBinding part() {
return this.hostContext.part();
}
@Override
public final HostBinding hostWrapper() {
return this;
}
@Override
public final HostContext hostContext() {
return this.hostContext;
}
@Override
public void setHostContext(HostContext hostContext) {
this.hostContext = hostContext;
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrapHost(Class<T> hostClass) {
if (hostClass.isAssignableFrom(getClass())) {
return (T) this;
} else {
return this.hostContext.unwrapHost(hostClass);
}
}
protected NodeContext createNodeContext(NodeBinding node, Uri nodeUri) {
return new HostTableNode(this, node, nodeUri);
}
@Override
public final Uri meshUri() {
return this.hostContext.meshUri();
}
@Override
public final Value partKey() {
return this.hostContext.partKey();
}
@Override
public final Uri hostUri() {
return this.hostContext.hostUri();
}
@Override
public Policy policy() {
return this.hostContext.policy();
}
@Override
public Schedule schedule() {
return this.hostContext.schedule();
}
@Override
public Stage stage() {
return this.hostContext.stage();
}
@Override
public StoreBinding store() {
return this.hostContext.store();
}
@Override
public boolean isConnected() {
return true;
}
@Override
public boolean isRemote() {
return false;
}
@Override
public boolean isSecure() {
return true;
}
@Override
public boolean isPrimary() {
return (this.flags & PRIMARY) != 0;
}
@Override
public void setPrimary(boolean isPrimary) {
int oldFlags;
int newFlags;
do {
oldFlags = this.flags;
newFlags = oldFlags | PRIMARY;
} while (oldFlags != newFlags && !FLAGS.compareAndSet(this, oldFlags, newFlags));
}
@Override
public boolean isReplica() {
return (this.flags & REPLICA) != 0;
}
@Override
public void setReplica(boolean isReplica) {
int oldFlags;
int newFlags;
do {
oldFlags = this.flags;
newFlags = oldFlags | REPLICA;
} while (oldFlags != newFlags && !FLAGS.compareAndSet(this, oldFlags, newFlags));
}
@Override
public boolean isMaster() {
return (this.flags & MASTER) != 0;
}
@Override
public boolean isSlave() {
return (this.flags & SLAVE) != 0;
}
@Override
public void didBecomeMaster() {
int oldFlags;
int newFlags;
do {
oldFlags = this.flags;
newFlags = oldFlags & ~SLAVE | MASTER;
} while (oldFlags != newFlags && !FLAGS.compareAndSet(this, oldFlags, newFlags));
}
@Override
public void didBecomeSlave() {
int oldFlags;
int newFlags;
do {
oldFlags = this.flags;
newFlags = oldFlags & ~MASTER | SLAVE;
} while (oldFlags != newFlags && !FLAGS.compareAndSet(this, oldFlags, newFlags));
if (oldFlags != newFlags) {
closeNodes();
}
}
@Override
public HashTrieMap<Uri, NodeBinding> nodes() {
return this.nodes;
}
@Override
public NodeBinding getNode(Uri nodeUri) {
return this.nodes.get(nodeUri);
}
@Override
public NodeBinding openNode(Uri nodeUri) {
HashTrieMap<Uri, NodeBinding> oldNodes;
HashTrieMap<Uri, NodeBinding> newNodes;
NodeBinding nodeBinding = null;
do {
oldNodes = this.nodes;
final NodeBinding node = oldNodes.get(nodeUri);
if (node != null) {
if (nodeBinding != null) {
// Lost creation race.
nodeBinding.close();
}
nodeBinding = node;
newNodes = oldNodes;
break;
} else if (nodeBinding == null) {
nodeBinding = this.hostContext.createNode(nodeUri);
if (nodeBinding != null) {
nodeBinding = this.hostContext.injectNode(nodeUri, nodeBinding);
final NodeContext nodeContext = createNodeContext(nodeBinding, nodeUri);
nodeBinding.setNodeContext(nodeContext);
nodeBinding = nodeBinding.nodeWrapper();
nodeBinding.openLanes(nodeBinding);
nodeBinding.openAgents(nodeBinding);
newNodes = oldNodes.updated(nodeUri, nodeBinding);
} else {
newNodes = oldNodes;
break;
}
} else {
newNodes = oldNodes.updated(nodeUri, nodeBinding);
}
} while (oldNodes != newNodes && !NODES.compareAndSet(this, oldNodes, newNodes));
if (oldNodes != newNodes) {
activate(nodeBinding);
}
return nodeBinding;
}
@Override
public NodeBinding openNode(Uri nodeUri, NodeBinding node) {
HashTrieMap<Uri, NodeBinding> oldNodes;
HashTrieMap<Uri, NodeBinding> newNodes;
NodeBinding nodeBinding = null;
do {
oldNodes = this.nodes;
if (oldNodes.containsKey(nodeUri)) {
nodeBinding = null;
newNodes = oldNodes;
break;
} else {
if (nodeBinding == null) {
nodeBinding = this.hostContext.injectNode(nodeUri, node);
final NodeContext nodeContext = createNodeContext(nodeBinding, nodeUri);
nodeBinding.setNodeContext(nodeContext);
nodeBinding = nodeBinding.nodeWrapper();
nodeBinding.openLanes(nodeBinding);
nodeBinding.openAgents(nodeBinding);
}
newNodes = oldNodes.updated(nodeUri, nodeBinding);
}
} while (oldNodes != newNodes && !NODES.compareAndSet(this, oldNodes, newNodes));
if (nodeBinding != null) {
activate(nodeBinding);
}
return nodeBinding;
}
public void closeNode(Uri nodeUri) {
HashTrieMap<Uri, NodeBinding> oldNodes;
HashTrieMap<Uri, NodeBinding> newNodes;
NodeBinding nodeBinding = null;
do {
oldNodes = this.nodes;
final NodeBinding node = oldNodes.get(nodeUri);
if (node != null) {
nodeBinding = node;
newNodes = oldNodes.removed(nodeUri);
} else {
nodeBinding = null;
newNodes = oldNodes;
break;
}
} while (oldNodes != newNodes && !NODES.compareAndSet(this, oldNodes, newNodes));
if (nodeBinding != null) {
nodeBinding.didClose();
}
}
public void closeNodes() {
HashTrieMap<Uri, NodeBinding> oldNodes;
final HashTrieMap<Uri, NodeBinding> newNodes = HashTrieMap.empty();
do {
oldNodes = this.nodes;
} while (oldNodes != newNodes && !NODES.compareAndSet(this, oldNodes, newNodes));
for (NodeBinding nodeBinding : oldNodes.values()) {
nodeBinding.close();
nodeBinding.didClose();
}
}
@Override
public LinkBinding bindDownlink(Downlink downlink) {
return this.hostContext.bindDownlink(downlink);
}
@Override
public void openDownlink(LinkBinding link) {
this.hostContext.openDownlink(link);
}
@Override
public void closeDownlink(LinkBinding link) {
this.hostContext.closeDownlink(link);
}
@Override
public void pushDown(PushRequest pushRequest) {
this.hostContext.pushDown(pushRequest);
}
@Override
public void openUplink(LinkBinding link) {
final NodeBinding nodeBinding = openNode(link.nodeUri());
if (nodeBinding != null) {
nodeBinding.openUplink(link);
} else {
UplinkError.rejectNodeNotFound(link);
}
}
@Override
public void pushUp(PushRequest pushRequest) {
final NodeBinding nodeBinding = openNode(pushRequest.envelope().nodeUri());
if (nodeBinding != null) {
nodeBinding.pushUp(pushRequest);
} else {
pushRequest.didDecline();
}
}
@Override
public void trace(Object message) {
this.hostContext.trace(message);
}
@Override
public void debug(Object message) {
this.hostContext.debug(message);
}
@Override
public void info(Object message) {
this.hostContext.info(message);
}
@Override
public void warn(Object message) {
this.hostContext.warn(message);
}
@Override
public void error(Object message) {
this.hostContext.error(message);
}
@Override
protected void willOpen() {
super.willOpen();
final Iterator<NodeBinding> nodesIterator = this.nodes.valueIterator();
while (nodesIterator.hasNext()) {
nodesIterator.next().open();
}
}
@Override
protected void willLoad() {
super.willLoad();
final Iterator<NodeBinding> nodesIterator = this.nodes.valueIterator();
while (nodesIterator.hasNext()) {
nodesIterator.next().load();
}
}
@Override
protected void willStart() {
super.willStart();
final Iterator<NodeBinding> nodesIterator = this.nodes.valueIterator();
while (nodesIterator.hasNext()) {
nodesIterator.next().start();
}
}
@Override
protected void willStop() {
super.willStop();
final Iterator<NodeBinding> nodesIterator = this.nodes.valueIterator();
while (nodesIterator.hasNext()) {
nodesIterator.next().stop();
}
}
@Override
protected void willUnload() {
super.willUnload();
final Iterator<NodeBinding> nodesIterator = this.nodes.valueIterator();
while (nodesIterator.hasNext()) {
nodesIterator.next().unload();
}
}
@Override
protected void willClose() {
super.willClose();
final Iterator<NodeBinding> nodesIterator = this.nodes.valueIterator();
while (nodesIterator.hasNext()) {
nodesIterator.next().close();
}
}
@Override
public void didClose() {
// nop
}
@Override
public void didFail(Throwable error) {
error.printStackTrace();
}
static final int PRIMARY = 1 << 0;
static final int REPLICA = 1 << 1;
static final int MASTER = 1 << 2;
static final int SLAVE = 1 << 3;
@SuppressWarnings("unchecked")
static final AtomicReferenceFieldUpdater<HostTable, HashTrieMap<Uri, NodeBinding>> NODES =
AtomicReferenceFieldUpdater.newUpdater(HostTable.class, (Class<HashTrieMap<Uri, NodeBinding>>) (Class<?>) HashTrieMap.class, "nodes");
static final AtomicIntegerFieldUpdater<HostTable> FLAGS =
AtomicIntegerFieldUpdater.newUpdater(HostTable.class, "flags");
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/router/HostTableNode.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.runtime.router;
import swim.api.Downlink;
import swim.api.agent.Agent;
import swim.api.agent.AgentDef;
import swim.api.agent.AgentFactory;
import swim.api.auth.Identity;
import swim.api.policy.Policy;
import swim.concurrent.Schedule;
import swim.concurrent.Stage;
import swim.runtime.HostBinding;
import swim.runtime.LaneBinding;
import swim.runtime.LaneDef;
import swim.runtime.LinkBinding;
import swim.runtime.NodeBinding;
import swim.runtime.NodeContext;
import swim.runtime.PushRequest;
import swim.store.StoreBinding;
import swim.structure.Value;
import swim.uri.Uri;
public class HostTableNode implements NodeContext {
protected final HostTable host;
protected final NodeBinding node;
protected final Uri nodeUri;
public HostTableNode(HostTable host, NodeBinding node, Uri nodeUri) {
this.host = host;
this.node = node;
this.nodeUri = nodeUri;
}
@Override
public final HostBinding host() {
return this.host;
}
@Override
public final NodeBinding nodeWrapper() {
return this.node.nodeWrapper();
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrapNode(Class<T> nodeClass) {
if (nodeClass.isAssignableFrom(getClass())) {
return (T) this;
} else {
return null;
}
}
@Override
public final Uri meshUri() {
return this.host.meshUri();
}
@Override
public final Value partKey() {
return this.host.partKey();
}
@Override
public final Uri hostUri() {
return this.host.hostUri();
}
@Override
public final Uri nodeUri() {
return this.nodeUri;
}
@Override
public long createdTime() {
return this.node.createdTime();
}
@Override
public final Identity identity() {
return null; // TODO
}
@Override
public Policy policy() {
return this.host.policy();
}
@Override
public Schedule schedule() {
return this.host.schedule();
}
@Override
public Stage stage() {
return this.host.stage();
}
@Override
public StoreBinding store() {
return this.host.store();
}
@Override
public LaneBinding createLane(LaneDef laneDef) {
return this.host.hostContext().createLane(this.nodeUri, laneDef);
}
@Override
public LaneBinding createLane(Uri laneUri) {
return this.host.hostContext().createLane(this.nodeUri, laneUri);
}
@Override
public LaneBinding injectLane(Uri laneUri, LaneBinding lane) {
return this.host.hostContext().injectLane(this.nodeUri, laneUri, lane);
}
@Override
public void openLanes(NodeBinding node) {
this.host.hostContext().openLanes(this.nodeUri, node);
}
@Override
public AgentFactory<?> createAgentFactory(AgentDef agentDef) {
return this.host.hostContext().createAgentFactory(this.nodeUri, agentDef);
}
@Override
public <A extends Agent> AgentFactory<A> createAgentFactory(Class<? extends A> agentClass) {
return this.host.hostContext().createAgentFactory(this.nodeUri, agentClass);
}
@Override
public void openAgents(NodeBinding node) {
this.host.hostContext().openAgents(this.nodeUri, node);
}
@Override
public LinkBinding bindDownlink(Downlink downlink) {
return this.host.bindDownlink(downlink);
}
@Override
public void openDownlink(LinkBinding link) {
this.host.openDownlink(link);
}
@Override
public void closeDownlink(LinkBinding link) {
}
@Override
public void pushDown(PushRequest pushRequest) {
this.host.pushDown(pushRequest);
}
@Override
public void trace(Object message) {
this.host.trace(message);
}
@Override
public void debug(Object message) {
this.host.debug(message);
}
@Override
public void info(Object message) {
this.host.info(message);
}
@Override
public void warn(Object message) {
this.host.warn(message);
}
@Override
public void error(Object message) {
this.host.error(message);
}
@Override
public void close() {
this.host.closeNode(this.nodeUri);
}
@Override
public void willOpen() {
// nop
}
@Override
public void didOpen() {
// nop
}
@Override
public void willLoad() {
// nop
}
@Override
public void didLoad() {
// nop
}
@Override
public void willStart() {
// nop
}
@Override
public void didStart() {
// nop
}
@Override
public void willStop() {
// nop
}
@Override
public void didStop() {
// nop
}
@Override
public void willUnload() {
// nop
}
@Override
public void didUnload() {
// nop
}
@Override
public void willClose() {
// nop
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/router/MeshTable.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.runtime.router;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import swim.api.Downlink;
import swim.api.policy.Policy;
import swim.collections.FingerTrieSeq;
import swim.concurrent.Schedule;
import swim.concurrent.Stage;
import swim.runtime.AbstractTierBinding;
import swim.runtime.EdgeBinding;
import swim.runtime.LinkBinding;
import swim.runtime.MeshBinding;
import swim.runtime.MeshContext;
import swim.runtime.PartBinding;
import swim.runtime.PartContext;
import swim.runtime.PushRequest;
import swim.runtime.TierContext;
import swim.runtime.UplinkError;
import swim.store.StoreBinding;
import swim.structure.Extant;
import swim.structure.Text;
import swim.structure.Value;
import swim.uri.Uri;
public class MeshTable extends AbstractTierBinding implements MeshBinding {
protected MeshContext meshContext;
volatile FingerTrieSeq<PartBinding> parts;
volatile PartBinding gateway;
volatile PartBinding ourself;
public MeshTable() {
this.parts = FingerTrieSeq.empty();
}
@Override
public final TierContext tierContext() {
return this.meshContext;
}
@Override
public final EdgeBinding edge() {
return this.meshContext.edge();
}
@Override
public final MeshBinding meshWrapper() {
return this;
}
@Override
public final MeshContext meshContext() {
return this.meshContext;
}
@Override
public void setMeshContext(MeshContext meshContext) {
this.meshContext = meshContext;
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrapMesh(Class<T> meshClass) {
if (meshClass.isAssignableFrom(getClass())) {
return (T) this;
} else {
return this.meshContext.unwrapMesh(meshClass);
}
}
protected PartContext createPartContext(PartBinding part, Value partKey) {
return new MeshTablePart(this, part, partKey);
}
@Override
public final Uri meshUri() {
return this.meshContext.meshUri();
}
@Override
public Policy policy() {
return this.meshContext.policy();
}
@Override
public Schedule schedule() {
return this.meshContext.schedule();
}
@Override
public Stage stage() {
return this.meshContext.stage();
}
@Override
public StoreBinding store() {
return this.meshContext.store();
}
@Override
public PartBinding gateway() {
return this.gateway;
}
@Override
public void setGateway(PartBinding gateway) {
this.gateway = gateway;
}
@Override
public PartBinding ourself() {
return this.ourself;
}
@Override
public void setOurself(PartBinding ourself) {
this.ourself = ourself;
}
@Override
public FingerTrieSeq<PartBinding> parts() {
return this.parts;
}
boolean isMetaNode(Uri nodeUri) {
return !meshUri().isDefined() && "swim".equals(nodeUri.schemeName());
}
@Override
public PartBinding getPart(Uri nodeUri) {
if (isMetaNode(nodeUri)) {
return this.ourself;
}
final FingerTrieSeq<PartBinding> parts = this.parts;
for (int i = 0, n = parts.size(); i < n; i += 1) {
final PartBinding part = parts.get(i);
if (part.predicate().test(nodeUri)) {
return part;
}
}
return this.gateway;
}
@Override
public PartBinding getPart(Value partKey) {
final FingerTrieSeq<PartBinding> parts = this.parts;
for (int i = 0, n = parts.size(); i < n; i += 1) {
final PartBinding part = parts.get(i);
if (partKey.equals(part.partKey())) {
return part;
}
}
return null;
}
@Override
public PartBinding openPart(Uri nodeUri) {
FingerTrieSeq<PartBinding> oldParts;
FingerTrieSeq<PartBinding> newParts;
PartBinding partBinding = null;
Value partKey = Value.absent();
do {
oldParts = this.parts;
PartBinding part = null;
if (isMetaNode(nodeUri)) {
part = this.ourself;
} else {
for (int i = 0, n = oldParts.size(); i < n; i += 1) {
final PartBinding oldPart = oldParts.get(i);
if (oldPart.predicate().test(nodeUri)) {
part = oldPart;
break;
}
}
}
if (part != null) {
if (partBinding != null) {
// Lost creation race.
partBinding.close();
}
partBinding = part;
newParts = oldParts;
break;
} else if (partBinding == null) {
if (isMetaNode(nodeUri)) {
partKey = Text.from("swim");
} else {
partKey = Value.absent();
}
partBinding = this.meshContext.createPart(partKey);
if (partBinding != null) {
partBinding = this.meshContext.injectPart(partKey, partBinding);
final PartContext partContext = createPartContext(partBinding, partKey);
partBinding.setPartContext(partContext);
partBinding = partBinding.partWrapper();
newParts = oldParts.appended(partBinding);
} else {
newParts = oldParts;
break;
}
} else {
newParts = oldParts.appended(partBinding);
}
} while (oldParts != newParts && !PARTS.compareAndSet(this, oldParts, newParts));
if (oldParts != newParts) {
if (partKey instanceof Extant) {
this.gateway = partBinding;
} else if (isMetaNode(nodeUri)) {
this.ourself = partBinding;
}
activate(partBinding);
}
return partBinding;
}
@Override
public PartBinding openGateway() {
FingerTrieSeq<PartBinding> oldParts;
FingerTrieSeq<PartBinding> newParts;
PartBinding partBinding = null;
do {
oldParts = this.parts;
final PartBinding part = this.gateway;
if (part != null) {
if (partBinding != null) {
// Lost creation race.
partBinding.close();
}
partBinding = part;
newParts = oldParts;
break;
} else if (partBinding == null) {
final Value partKey = Value.absent();
partBinding = this.meshContext.createPart(partKey);
if (partBinding != null) {
partBinding = this.meshContext.injectPart(partKey, partBinding);
final PartContext partContext = createPartContext(partBinding, partKey);
partBinding.setPartContext(partContext);
partBinding = partBinding.partWrapper();
newParts = oldParts.appended(partBinding);
} else {
newParts = oldParts;
break;
}
} else {
newParts = oldParts.appended(partBinding);
}
} while (oldParts != newParts && !PARTS.compareAndSet(this, oldParts, newParts));
if (oldParts != newParts) {
this.gateway = partBinding;
activate(partBinding);
}
return partBinding;
}
@Override
public PartBinding addPart(Value partKey, PartBinding part) {
FingerTrieSeq<PartBinding> oldParts;
FingerTrieSeq<PartBinding> newParts;
PartBinding partBinding = null;
do {
oldParts = this.parts;
for (int i = 0, n = oldParts.size(); i < n; i += 1) {
final PartBinding oldPart = oldParts.get(i);
if (partKey.equals(oldPart.partKey())) {
break;
}
}
if (partBinding == null) {
partBinding = this.meshContext.injectPart(partKey, part);
final PartContext partContext = createPartContext(partBinding, partKey);
partBinding.setPartContext(partContext);
partBinding = partBinding.partWrapper();
}
newParts = oldParts.appended(partBinding);
} while (oldParts != newParts && !PARTS.compareAndSet(this, oldParts, newParts));
if (partBinding != null) {
activate(partBinding);
}
return partBinding;
}
public void closePart(Value partKey) {
FingerTrieSeq<PartBinding> oldParts;
FingerTrieSeq<PartBinding> newParts;
PartBinding partBinding;
do {
oldParts = this.parts;
newParts = oldParts;
partBinding = null;
for (int i = 0, n = oldParts.size(); i < n; i += 1) {
final PartBinding part = oldParts.get(i);
if (partKey.equals(part.partKey())) {
partBinding = part;
newParts = oldParts.removed(i);
break;
}
}
} while (oldParts != newParts && !PARTS.compareAndSet(this, oldParts, newParts));
if (partBinding != null) {
if (this.gateway == partBinding) {
this.gateway = null;
} else if (this.ourself == partBinding) {
this.ourself = null;
}
partBinding.didClose();
}
}
@Override
public LinkBinding bindDownlink(Downlink downlink) {
return this.meshContext.bindDownlink(downlink);
}
@Override
public void openDownlink(LinkBinding link) {
this.meshContext.openDownlink(link);
}
@Override
public void closeDownlink(LinkBinding link) {
}
@Override
public void openUplink(LinkBinding link) {
final PartBinding partBinding = openPart(link.nodeUri());
if (partBinding != null) {
partBinding.openUplink(link);
} else {
UplinkError.rejectPartNotFound(link);
}
}
@Override
public void pushDown(PushRequest pushRequest) {
this.meshContext.pushDown(pushRequest);
}
@Override
public void pushUp(PushRequest pushRequest) {
final PartBinding partBinding = openPart(pushRequest.nodeUri());
if (partBinding != null) {
partBinding.pushUp(pushRequest);
} else {
pushRequest.didDecline();
}
}
@Override
public void trace(Object message) {
this.meshContext.trace(message);
}
@Override
public void debug(Object message) {
this.meshContext.debug(message);
}
@Override
public void info(Object message) {
this.meshContext.info(message);
}
@Override
public void warn(Object message) {
this.meshContext.warn(message);
}
@Override
public void error(Object message) {
this.meshContext.error(message);
}
@Override
protected void willOpen() {
super.willOpen();
final Iterator<PartBinding> partsIterator = this.parts.iterator();
while (partsIterator.hasNext()) {
partsIterator.next().open();
}
}
@Override
protected void willLoad() {
super.willLoad();
final Iterator<PartBinding> partsIterator = this.parts.iterator();
while (partsIterator.hasNext()) {
partsIterator.next().load();
}
}
@Override
protected void willStart() {
super.willStart();
final Iterator<PartBinding> partsIterator = this.parts.iterator();
while (partsIterator.hasNext()) {
partsIterator.next().start();
}
}
@Override
protected void willStop() {
super.willStop();
final Iterator<PartBinding> partsIterator = this.parts.iterator();
while (partsIterator.hasNext()) {
partsIterator.next().stop();
}
}
@Override
protected void willUnload() {
super.willUnload();
final Iterator<PartBinding> partsIterator = this.parts.iterator();
while (partsIterator.hasNext()) {
partsIterator.next().unload();
}
}
@Override
protected void willClose() {
super.willClose();
final Iterator<PartBinding> partsIterator = this.parts.iterator();
while (partsIterator.hasNext()) {
partsIterator.next().close();
}
}
@Override
public void didClose() {
// nop
}
@Override
public void didFail(Throwable error) {
error.printStackTrace();
}
@SuppressWarnings("unchecked")
static final AtomicReferenceFieldUpdater<MeshTable, FingerTrieSeq<PartBinding>> PARTS =
AtomicReferenceFieldUpdater.newUpdater(MeshTable.class, (Class<FingerTrieSeq<PartBinding>>) (Class<?>) FingerTrieSeq.class, "parts");
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/router/MeshTablePart.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.runtime.router;
import swim.api.Downlink;
import swim.api.agent.Agent;
import swim.api.agent.AgentDef;
import swim.api.agent.AgentFactory;
import swim.api.auth.Credentials;
import swim.api.auth.Identity;
import swim.api.policy.Policy;
import swim.api.policy.PolicyDirective;
import swim.concurrent.Schedule;
import swim.concurrent.Stage;
import swim.runtime.HostBinding;
import swim.runtime.LaneBinding;
import swim.runtime.LaneDef;
import swim.runtime.LinkBinding;
import swim.runtime.MeshBinding;
import swim.runtime.NodeBinding;
import swim.runtime.PartBinding;
import swim.runtime.PartContext;
import swim.runtime.PushRequest;
import swim.store.StoreBinding;
import swim.structure.Value;
import swim.uri.Uri;
public class MeshTablePart implements PartContext {
protected final MeshTable mesh;
protected final PartBinding part;
protected final Value partKey;
public MeshTablePart(MeshTable mesh, PartBinding part, Value partKey) {
this.mesh = mesh;
this.part = part;
this.partKey = partKey.commit();
}
@Override
public final MeshBinding mesh() {
return this.mesh;
}
@Override
public final PartBinding partWrapper() {
return this.part.partWrapper();
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrapPart(Class<T> partClass) {
if (partClass.isAssignableFrom(getClass())) {
return (T) this;
} else {
return null;
}
}
@Override
public final Uri meshUri() {
return this.mesh.meshUri();
}
@Override
public final Value partKey() {
return this.partKey;
}
@Override
public Policy policy() {
return this.mesh.policy();
}
@Override
public Schedule schedule() {
return this.mesh.schedule();
}
@Override
public Stage stage() {
return this.mesh.stage();
}
@Override
public StoreBinding store() {
return this.mesh.store();
}
@Override
public HostBinding createHost(Uri hostUri) {
return this.mesh.meshContext().createHost(this.partKey, hostUri);
}
@Override
public HostBinding injectHost(Uri hostUri, HostBinding host) {
return this.mesh.meshContext().injectHost(this.partKey, hostUri, host);
}
@Override
public NodeBinding createNode(Uri hostUri, Uri nodeUri) {
return this.mesh.meshContext().createNode(this.partKey, hostUri, nodeUri);
}
@Override
public NodeBinding injectNode(Uri hostUri, Uri nodeUri, NodeBinding node) {
return this.mesh.meshContext().injectNode(this.partKey, hostUri, nodeUri, node);
}
@Override
public LaneBinding createLane(Uri hostUri, Uri nodeUri, LaneDef laneDef) {
return this.mesh.meshContext().createLane(this.partKey, hostUri, nodeUri, laneDef);
}
@Override
public LaneBinding createLane(Uri hostUri, Uri nodeUri, Uri laneUri) {
return this.mesh.meshContext().createLane(this.partKey, hostUri, nodeUri, laneUri);
}
@Override
public LaneBinding injectLane(Uri hostUri, Uri nodeUri, Uri laneUri, LaneBinding lane) {
return this.mesh.meshContext().injectLane(this.partKey, hostUri, nodeUri, laneUri, lane);
}
@Override
public void openLanes(Uri hostUri, Uri nodeUri, NodeBinding node) {
this.mesh.meshContext().openLanes(this.partKey, hostUri, nodeUri, node);
}
@Override
public AgentFactory<?> createAgentFactory(Uri hostUri, Uri nodeUri, AgentDef agentDef) {
return this.mesh.meshContext().createAgentFactory(this.partKey, hostUri, nodeUri, agentDef);
}
@Override
public <A extends Agent> AgentFactory<A> createAgentFactory(Uri hostUri, Uri nodeUri,
Class<? extends A> agentClass) {
return this.mesh.meshContext().createAgentFactory(this.partKey, hostUri, nodeUri, agentClass);
}
@Override
public void openAgents(Uri hostUri, Uri nodeUri, NodeBinding node) {
this.mesh.meshContext().openAgents(this.partKey, hostUri, nodeUri, node);
}
@Override
public PolicyDirective<Identity> authenticate(Credentials credentials) {
return this.mesh.meshContext().authenticate(credentials);
}
@Override
public void hostDidConnect(Uri hostUri) {
// nop
}
@Override
public void hostDidDisconnect(Uri hostUri) {
// nop
}
@Override
public LinkBinding bindDownlink(Downlink downlink) {
return this.mesh.bindDownlink(downlink);
}
@Override
public void openDownlink(LinkBinding link) {
this.mesh.openDownlink(link);
}
@Override
public void closeDownlink(LinkBinding link) {
// nop
}
@Override
public void pushDown(PushRequest pushRequest) {
this.mesh.pushDown(pushRequest);
}
@Override
public void trace(Object message) {
this.mesh.trace(message);
}
@Override
public void debug(Object message) {
this.mesh.debug(message);
}
@Override
public void info(Object message) {
this.mesh.info(message);
}
@Override
public void warn(Object message) {
this.mesh.warn(message);
}
@Override
public void error(Object message) {
this.mesh.error(message);
}
@Override
public void close() {
this.mesh.closePart(this.partKey);
}
@Override
public void willOpen() {
// nop
}
@Override
public void didOpen() {
// nop
}
@Override
public void willLoad() {
// nop
}
@Override
public void didLoad() {
// nop
}
@Override
public void willStart() {
// nop
}
@Override
public void didStart() {
// nop
}
@Override
public void willStop() {
// nop
}
@Override
public void didStop() {
// nop
}
@Override
public void willUnload() {
// nop
}
@Override
public void didUnload() {
// nop
}
@Override
public void willClose() {
// nop
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/router/PartTable.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.runtime.router;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import swim.api.Downlink;
import swim.api.policy.Policy;
import swim.collections.HashTrieMap;
import swim.concurrent.Schedule;
import swim.concurrent.Stage;
import swim.runtime.AbstractTierBinding;
import swim.runtime.HostBinding;
import swim.runtime.HostContext;
import swim.runtime.HttpBinding;
import swim.runtime.LinkBinding;
import swim.runtime.MeshBinding;
import swim.runtime.PartBinding;
import swim.runtime.PartContext;
import swim.runtime.PartPredicate;
import swim.runtime.PushRequest;
import swim.runtime.TierContext;
import swim.runtime.UplinkError;
import swim.runtime.WarpBinding;
import swim.store.StoreBinding;
import swim.structure.Value;
import swim.uri.Uri;
public class PartTable extends AbstractTierBinding implements PartBinding {
final PartPredicate predicate;
protected PartContext partContext;
volatile HashTrieMap<Uri, HostBinding> hosts;
volatile HashTrieMap<Value, LinkBinding> uplinks;
volatile HostBinding master;
public PartTable(PartPredicate predicate) {
this.hosts = HashTrieMap.empty();
this.uplinks = HashTrieMap.empty();
this.predicate = predicate;
}
public PartTable() {
this(PartPredicate.any());
}
@Override
public final TierContext tierContext() {
return this.partContext;
}
@Override
public final MeshBinding mesh() {
return this.partContext.mesh();
}
@Override
public final PartBinding partWrapper() {
return this;
}
@Override
public final PartContext partContext() {
return this.partContext;
}
@Override
public void setPartContext(PartContext partContext) {
this.partContext = partContext;
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrapPart(Class<T> partClass) {
if (partClass.isAssignableFrom(getClass())) {
return (T) this;
} else {
return this.partContext.unwrapPart(partClass);
}
}
protected HostContext createHostContext(HostBinding host, Uri hostUri) {
return new PartTableHost(this, host, hostUri);
}
@Override
public final Uri meshUri() {
return this.partContext.meshUri();
}
@Override
public final Value partKey() {
return this.partContext.partKey();
}
@Override
public Policy policy() {
return this.partContext.policy();
}
@Override
public Schedule schedule() {
return this.partContext.schedule();
}
@Override
public Stage stage() {
return this.partContext.stage();
}
@Override
public StoreBinding store() {
return this.partContext.store();
}
@Override
public PartPredicate predicate() {
return this.predicate;
}
@Override
public HostBinding master() {
return this.master;
}
@Override
public void setMaster(HostBinding master) {
this.master = master;
}
@Override
public HashTrieMap<Uri, HostBinding> hosts() {
return this.hosts;
}
@Override
public HostBinding getHost(Uri hostUri) {
return this.hosts.get(hostUri);
}
@Override
public HostBinding openHost(Uri hostUri) {
HashTrieMap<Uri, HostBinding> oldHosts;
HashTrieMap<Uri, HostBinding> newHosts;
HostBinding hostBinding = null;
do {
oldHosts = this.hosts;
final HostBinding host = oldHosts.get(hostUri);
if (host != null) {
if (hostBinding != null) {
// Lost creation race.
hostBinding.close();
}
hostBinding = host;
newHosts = oldHosts;
break;
} else if (hostBinding == null) {
hostBinding = this.partContext.createHost(hostUri);
if (hostBinding != null) {
hostBinding = this.partContext.injectHost(hostUri, hostBinding);
final HostContext hostContext = createHostContext(hostBinding, hostUri);
hostBinding.setHostContext(hostContext);
hostBinding = hostBinding.hostWrapper();
newHosts = oldHosts.updated(hostUri, hostBinding);
} else {
newHosts = oldHosts;
break;
}
} else {
newHosts = oldHosts.updated(hostUri, hostBinding);
}
} while (oldHosts != newHosts && !HOSTS.compareAndSet(this, oldHosts, newHosts));
if (oldHosts != newHosts) {
activate(hostBinding);
}
return hostBinding;
}
@Override
public HostBinding openHost(Uri hostUri, HostBinding host) {
HashTrieMap<Uri, HostBinding> oldHosts;
HashTrieMap<Uri, HostBinding> newHosts;
HostBinding hostBinding = null;
do {
oldHosts = this.hosts;
if (oldHosts.containsKey(hostUri) && host.hostContext() != null) {
hostBinding = null;
newHosts = oldHosts;
break;
} else {
if (hostBinding == null) {
hostBinding = this.partContext.injectHost(hostUri, host);
final HostContext hostContext = createHostContext(hostBinding, hostUri);
hostBinding.setHostContext(hostContext);
hostBinding = hostBinding.hostWrapper();
}
newHosts = oldHosts.updated(hostUri, hostBinding);
}
} while (oldHosts != newHosts && !HOSTS.compareAndSet(this, oldHosts, newHosts));
if (hostBinding != null) {
activate(hostBinding);
}
return hostBinding;
}
public void closeHost(Uri hostUri) {
HashTrieMap<Uri, HostBinding> oldHosts;
HashTrieMap<Uri, HostBinding> newHosts;
HostBinding hostBinding = null;
do {
oldHosts = this.hosts;
final HostBinding host = oldHosts.get(hostUri);
if (host != null) {
hostBinding = host;
newHosts = oldHosts.removed(hostUri);
} else {
hostBinding = null;
newHosts = oldHosts;
break;
}
} while (oldHosts != newHosts && !HOSTS.compareAndSet(this, oldHosts, newHosts));
if (hostBinding != null) {
if (this.master == hostBinding) {
this.master = null;
}
hostBinding.didClose();
}
}
public void hostDidConnect(Uri hostUri) {
this.partContext.hostDidConnect(hostUri);
}
public void hostDidDisconnect(Uri hostUri) {
this.partContext.hostDidDisconnect(hostUri);
}
@Override
public void reopenUplinks() {
for (LinkBinding uplink : this.uplinks.values()) {
uplink.reopen();
}
}
@Override
public LinkBinding bindDownlink(Downlink downlink) {
return this.partContext.bindDownlink(downlink);
}
@Override
public void openDownlink(LinkBinding link) {
this.partContext.openDownlink(link);
}
@Override
public void closeDownlink(LinkBinding link) {
// nop
}
@Override
public void openUplink(LinkBinding link) {
final Uri hostUri = link.hostUri();
HostBinding hostBinding = null;
if (!hostUri.isDefined() || hostUri.equals(link.meshUri())) {
hostBinding = this.master;
}
if (hostBinding == null) {
hostBinding = openHost(hostUri);
}
if (hostBinding != null) {
if (link instanceof WarpBinding) {
hostBinding.openUplink(new PartTableWarpUplink(this, (WarpBinding) link));
} else if (link instanceof HttpBinding) {
hostBinding.openUplink(new PartTableHttpUplink(this, (HttpBinding) link));
} else {
UplinkError.rejectUnsupported(link);
}
} else {
UplinkError.rejectHostNotFound(link);
}
}
void didOpenUplink(LinkBinding uplink) {
HashTrieMap<Value, LinkBinding> oldUplinks;
HashTrieMap<Value, LinkBinding> newUplinks;
do {
oldUplinks = this.uplinks;
newUplinks = oldUplinks.updated(uplink.linkKey(), uplink);
} while (oldUplinks != newUplinks && !UPLINKS.compareAndSet(this, oldUplinks, newUplinks));
}
void didCloseUplink(LinkBinding uplink) {
HashTrieMap<Value, LinkBinding> oldUplinks;
HashTrieMap<Value, LinkBinding> newUplinks;
do {
oldUplinks = this.uplinks;
newUplinks = oldUplinks.removed(uplink.linkKey());
} while (oldUplinks != newUplinks && !UPLINKS.compareAndSet(this, oldUplinks, newUplinks));
}
@Override
public void pushDown(PushRequest pushRequest) {
this.partContext.pushDown(pushRequest);
}
@Override
public void pushUp(PushRequest pushRequest) {
final Uri hostUri = pushRequest.hostUri();
HostBinding hostBinding = null;
if (!hostUri.isDefined() || hostUri.equals(pushRequest.meshUri())) {
hostBinding = this.master;
}
if (hostBinding == null) {
hostBinding = openHost(hostUri);
}
if (hostBinding != null) {
hostBinding.pushUp(pushRequest);
} else {
pushRequest.didDecline();
}
}
@Override
public void trace(Object message) {
this.partContext.trace(message);
}
@Override
public void debug(Object message) {
this.partContext.debug(message);
}
@Override
public void info(Object message) {
this.partContext.info(message);
}
@Override
public void warn(Object message) {
this.partContext.warn(message);
}
@Override
public void error(Object message) {
this.partContext.error(message);
}
@Override
protected void willOpen() {
super.willOpen();
final Iterator<HostBinding> hostsIterator = this.hosts.valueIterator();
while (hostsIterator.hasNext()) {
hostsIterator.next().open();
}
}
@Override
protected void willLoad() {
super.willLoad();
final Iterator<HostBinding> hostsIterator = this.hosts.valueIterator();
while (hostsIterator.hasNext()) {
hostsIterator.next().load();
}
}
@Override
protected void willStart() {
super.willStart();
final Iterator<HostBinding> hostsIterator = this.hosts.valueIterator();
while (hostsIterator.hasNext()) {
hostsIterator.next().start();
}
}
@Override
protected void willStop() {
super.willStop();
final Iterator<HostBinding> hostsIterator = this.hosts.valueIterator();
while (hostsIterator.hasNext()) {
hostsIterator.next().stop();
}
}
@Override
protected void willUnload() {
super.willUnload();
final Iterator<HostBinding> hostsIterator = this.hosts.valueIterator();
while (hostsIterator.hasNext()) {
hostsIterator.next().unload();
}
}
@Override
protected void willClose() {
super.willClose();
final Iterator<HostBinding> hostsIterator = this.hosts.valueIterator();
while (hostsIterator.hasNext()) {
hostsIterator.next().close();
}
}
@Override
public void didClose() {
// nop
}
@Override
public void didFail(Throwable error) {
error.printStackTrace();
}
@SuppressWarnings("unchecked")
static final AtomicReferenceFieldUpdater<PartTable, HashTrieMap<Uri, HostBinding>> HOSTS =
AtomicReferenceFieldUpdater.newUpdater(PartTable.class, (Class<HashTrieMap<Uri, HostBinding>>) (Class<?>) HashTrieMap.class, "hosts");
@SuppressWarnings("unchecked")
static final AtomicReferenceFieldUpdater<PartTable, HashTrieMap<Value, LinkBinding>> UPLINKS =
AtomicReferenceFieldUpdater.newUpdater(PartTable.class, (Class<HashTrieMap<Value, LinkBinding>>) (Class<?>) HashTrieMap.class, "uplinks");
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/router/PartTableHost.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.runtime.router;
import swim.api.Downlink;
import swim.api.agent.Agent;
import swim.api.agent.AgentDef;
import swim.api.agent.AgentFactory;
import swim.api.auth.Credentials;
import swim.api.auth.Identity;
import swim.api.policy.Policy;
import swim.api.policy.PolicyDirective;
import swim.concurrent.Schedule;
import swim.concurrent.Stage;
import swim.runtime.HostBinding;
import swim.runtime.HostContext;
import swim.runtime.LaneBinding;
import swim.runtime.LaneDef;
import swim.runtime.LinkBinding;
import swim.runtime.NodeBinding;
import swim.runtime.PartBinding;
import swim.runtime.PushRequest;
import swim.store.StoreBinding;
import swim.structure.Value;
import swim.uri.Uri;
public class PartTableHost implements HostContext {
protected final PartTable part;
protected final HostBinding host;
protected final Uri hostUri;
public PartTableHost(PartTable part, HostBinding host, Uri hostUri) {
this.part = part;
this.host = host;
this.hostUri = hostUri;
}
@Override
public final PartBinding part() {
return this.part;
}
@Override
public final HostBinding hostWrapper() {
return this.host.hostWrapper();
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrapHost(Class<T> hostClass) {
if (hostClass.isAssignableFrom(getClass())) {
return (T) this;
} else {
return null;
}
}
@Override
public final Uri meshUri() {
return this.part.meshUri();
}
@Override
public final Value partKey() {
return this.part.partKey();
}
@Override
public final Uri hostUri() {
return this.hostUri;
}
@Override
public Policy policy() {
return this.part.policy();
}
@Override
public Schedule schedule() {
return this.part.schedule();
}
@Override
public Stage stage() {
return this.part.stage();
}
@Override
public StoreBinding store() {
return this.part.store();
}
@Override
public NodeBinding createNode(Uri nodeUri) {
return this.part.partContext().createNode(this.hostUri, nodeUri);
}
@Override
public NodeBinding injectNode(Uri nodeUri, NodeBinding node) {
return this.part.partContext().injectNode(this.hostUri, nodeUri, node);
}
@Override
public LaneBinding createLane(Uri nodeUri, LaneDef laneDef) {
return this.part.partContext().createLane(this.hostUri, nodeUri, laneDef);
}
@Override
public LaneBinding createLane(Uri nodeUri, Uri laneUri) {
return this.part.partContext().createLane(this.hostUri, nodeUri, laneUri);
}
@Override
public LaneBinding injectLane(Uri nodeUri, Uri laneUri, LaneBinding lane) {
return this.part.partContext().injectLane(this.hostUri, nodeUri, laneUri, lane);
}
@Override
public void openLanes(Uri nodeUri, NodeBinding node) {
this.part.partContext().openLanes(this.hostUri, nodeUri, node);
}
@Override
public AgentFactory<?> createAgentFactory(Uri nodeUri, AgentDef agentDef) {
return this.part.partContext().createAgentFactory(this.hostUri, nodeUri, agentDef);
}
@Override
public <A extends Agent> AgentFactory<A> createAgentFactory(Uri nodeUri, Class<? extends A> agentClass) {
return this.part.partContext().createAgentFactory(this.hostUri, nodeUri, agentClass);
}
@Override
public void openAgents(Uri nodeUri, NodeBinding node) {
this.part.partContext().openAgents(this.hostUri, nodeUri, node);
}
@Override
public PolicyDirective<Identity> authenticate(Credentials credentials) {
return this.part.partContext().authenticate(credentials);
}
@Override
public LinkBinding bindDownlink(Downlink downlink) {
return this.part.bindDownlink(downlink);
}
@Override
public void openDownlink(LinkBinding link) {
this.part.openDownlink(link);
}
@Override
public void closeDownlink(LinkBinding link) {
// nop
}
@Override
public void pushDown(PushRequest pushRequest) {
this.part.pushDown(pushRequest);
}
@Override
public void trace(Object message) {
this.part.trace(message);
}
@Override
public void debug(Object message) {
this.part.debug(message);
}
@Override
public void info(Object message) {
this.part.info(message);
}
@Override
public void warn(Object message) {
this.part.warn(message);
}
@Override
public void error(Object message) {
this.part.error(message);
}
@Override
public void close() {
this.part.closeHost(this.hostUri);
}
@Override
public void willOpen() {
// nop
}
@Override
public void didOpen() {
// nop
}
@Override
public void willLoad() {
// nop
}
@Override
public void didLoad() {
// nop
}
@Override
public void willStart() {
// nop
}
@Override
public void didStart() {
// nop
}
@Override
public void didConnect() {
this.part.hostDidConnect(this.hostUri);
}
@Override
public void didDisconnect() {
this.part.hostDidDisconnect(this.hostUri);
}
@Override
public void willStop() {
// nop
}
@Override
public void didStop() {
// nop
}
@Override
public void willUnload() {
// nop
}
@Override
public void didUnload() {
// nop
}
@Override
public void willClose() {
// nop
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/router/PartTableHttpUplink.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.runtime.router;
import swim.runtime.HttpBinding;
import swim.runtime.HttpProxy;
public class PartTableHttpUplink extends HttpProxy {
protected final PartTable part;
public PartTableHttpUplink(PartTable part, HttpBinding linkBinding) {
super(linkBinding);
this.part = part;
}
protected void didOpen() {
this.part.didOpenUplink(this);
}
@Override
public void didOpenDown() {
super.didOpenDown();
didOpen();
}
protected void didClose() {
this.part.didCloseUplink(this);
}
@Override
public void didCloseDown() {
super.didCloseDown();
didClose();
}
@Override
public void didCloseUp() {
super.didCloseUp();
didClose();
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/router/PartTableWarpUplink.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.runtime.router;
import swim.runtime.WarpBinding;
import swim.runtime.WarpProxy;
public class PartTableWarpUplink extends WarpProxy {
protected final PartTable part;
public PartTableWarpUplink(PartTable part, WarpBinding linkBinding) {
super(linkBinding);
this.part = part;
}
protected void didOpen() {
this.part.didOpenUplink(this);
}
@Override
public void didOpenDown() {
super.didOpenDown();
didOpen();
}
protected void didClose() {
this.part.didCloseUplink(this);
}
@Override
public void didCloseDown() {
super.didCloseDown();
didClose();
}
@Override
public void didCloseUp() {
super.didCloseUp();
didClose();
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/router/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.
/**
* Table-based router implementation.
*/
package swim.runtime.router;
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/scope/HostScope.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.runtime.scope;
import swim.api.downlink.EventDownlink;
import swim.api.downlink.ListDownlink;
import swim.api.downlink.MapDownlink;
import swim.api.downlink.ValueDownlink;
import swim.api.http.HttpDownlink;
import swim.api.ref.HostRef;
import swim.api.ref.LaneRef;
import swim.api.ref.NodeRef;
import swim.api.ws.WsDownlink;
import swim.concurrent.Stage;
import swim.runtime.CellContext;
import swim.runtime.downlink.EventDownlinkView;
import swim.runtime.downlink.MapDownlinkView;
import swim.runtime.downlink.ValueDownlinkView;
import swim.structure.Form;
import swim.structure.Value;
import swim.uri.Uri;
import swim.warp.CommandMessage;
public class HostScope extends Scope implements HostRef {
protected final Uri meshUri;
protected final Uri hostUri;
public HostScope(CellContext cellContext, Stage stage, Uri meshUri, Uri hostUri) {
super(cellContext, stage);
this.meshUri = meshUri;
this.hostUri = hostUri;
}
public final Uri meshUri() {
return this.meshUri;
}
@Override
public final Uri hostUri() {
return this.hostUri;
}
@Override
public NodeRef nodeRef(Uri nodeUri) {
return new NodeScope(cellContext, stage, this.meshUri, this.hostUri, nodeUri);
}
@Override
public NodeRef nodeRef(String nodeUri) {
return nodeRef(Uri.parse(nodeUri));
}
@Override
public LaneRef laneRef(Uri nodeUri, Uri laneUri) {
return new LaneScope(cellContext, stage, this.meshUri, this.hostUri, nodeUri, laneUri);
}
@Override
public LaneRef laneRef(String nodeUri, String laneUri) {
return laneRef(Uri.parse(nodeUri), Uri.parse(laneUri));
}
@Override
public EventDownlink<Value> downlink() {
return new EventDownlinkView<Value>(this, stage, this.meshUri, this.hostUri,
Uri.empty(), Uri.empty(), 0.0f, 0.0f, Value.absent(), Form.forValue());
}
@Override
public ListDownlink<Value> downlinkList() {
return null; // TODO
}
@Override
public MapDownlink<Value, Value> downlinkMap() {
return new MapDownlinkView<Value, Value>(this, stage, this.meshUri, this.hostUri,
Uri.empty(), Uri.empty(), 0.0f, 0.0f, Value.absent(), Form.forValue(), Form.forValue());
}
@Override
public ValueDownlink<Value> downlinkValue() {
return new ValueDownlinkView<Value>(this, stage, this.meshUri, this.hostUri,
Uri.empty(), Uri.empty(), 0.0f, 0.0f, Value.absent(), Form.forValue());
}
@Override
public <V> HttpDownlink<V> downlinkHttp() {
return null; // TODO
}
@Override
public <I, O> WsDownlink<I, O> downlinkWs() {
return null; // TODO
}
@Override
public void command(Uri nodeUri, Uri laneUri, float prio, Value body) {
final CommandMessage message = new CommandMessage(nodeUri, laneUri, body);
pushDown(new ScopePushRequest(this.meshUri, this.hostUri, null, message, prio));
}
@Override
public void command(String nodeUri, String laneUri, float prio, Value body) {
command(Uri.parse(nodeUri), Uri.parse(laneUri), prio, body);
}
@Override
public void command(Uri nodeUri, Uri laneUri, Value body) {
command(nodeUri, laneUri, 0.0f, body);
}
@Override
public void command(String nodeUri, String laneUri, Value body) {
command(Uri.parse(nodeUri), Uri.parse(laneUri), body);
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/scope/LaneScope.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.runtime.scope;
import swim.api.downlink.EventDownlink;
import swim.api.downlink.ListDownlink;
import swim.api.downlink.MapDownlink;
import swim.api.downlink.ValueDownlink;
import swim.api.http.HttpDownlink;
import swim.api.ref.LaneRef;
import swim.api.ws.WsDownlink;
import swim.concurrent.Stage;
import swim.runtime.CellContext;
import swim.runtime.downlink.EventDownlinkView;
import swim.runtime.downlink.ListDownlinkView;
import swim.runtime.downlink.MapDownlinkView;
import swim.runtime.downlink.ValueDownlinkView;
import swim.structure.Form;
import swim.structure.Value;
import swim.uri.Uri;
import swim.warp.CommandMessage;
public class LaneScope extends Scope implements LaneRef {
protected final Uri meshUri;
protected final Uri hostUri;
protected final Uri nodeUri;
protected final Uri laneUri;
public LaneScope(CellContext cellContext, Stage stage, Uri meshUri,
Uri hostUri, Uri nodeUri, Uri laneUri) {
super(cellContext, stage);
this.meshUri = meshUri;
this.hostUri = hostUri;
this.nodeUri = nodeUri;
this.laneUri = laneUri;
}
public final Uri meshUri() {
return this.meshUri;
}
@Override
public final Uri hostUri() {
return this.hostUri;
}
@Override
public final Uri nodeUri() {
return this.nodeUri;
}
@Override
public final Uri laneUri() {
return this.laneUri;
}
@Override
public EventDownlink<Value> downlink() {
return new EventDownlinkView<Value>(this, stage, this.meshUri, this.hostUri, this.nodeUri,
this.laneUri, 0.0f, 0.0f, Value.absent(), Form.forValue());
}
@Override
public ListDownlink<Value> downlinkList() {
return new ListDownlinkView<Value>(this, stage, this.meshUri, this.hostUri,
this.nodeUri, this.laneUri, 0.0f, 0.0f, Value.absent(), Form.forValue());
}
@Override
public MapDownlink<Value, Value> downlinkMap() {
return new MapDownlinkView<Value, Value>(this, stage, this.meshUri, this.hostUri,
this.nodeUri, this.laneUri, 0.0f, 0.0f, Value.absent(), Form.forValue(), Form.forValue());
}
@Override
public ValueDownlink<Value> downlinkValue() {
return new ValueDownlinkView<Value>(this, stage, this.meshUri, this.hostUri, this.nodeUri,
this.laneUri, 0.0f, 0.0f, Value.absent(), Form.forValue());
}
@Override
public <V> HttpDownlink<V> downlinkHttp() {
return null; // TODO
}
@Override
public <I, O> WsDownlink<I, O> downlinkWs() {
return null; // TODO
}
@Override
public void command(float prio, Value body) {
final CommandMessage message = new CommandMessage(this.nodeUri, this.laneUri, body);
pushDown(new ScopePushRequest(this.meshUri, this.hostUri, null, message, prio));
}
@Override
public void command(Value body) {
command(0.0f, body);
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/scope/NodeScope.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.runtime.scope;
import swim.api.downlink.EventDownlink;
import swim.api.downlink.ListDownlink;
import swim.api.downlink.MapDownlink;
import swim.api.downlink.ValueDownlink;
import swim.api.http.HttpDownlink;
import swim.api.ref.LaneRef;
import swim.api.ref.NodeRef;
import swim.api.ws.WsDownlink;
import swim.concurrent.Stage;
import swim.runtime.CellContext;
import swim.runtime.downlink.EventDownlinkView;
import swim.runtime.downlink.MapDownlinkView;
import swim.runtime.downlink.ValueDownlinkView;
import swim.structure.Form;
import swim.structure.Value;
import swim.uri.Uri;
import swim.warp.CommandMessage;
public class NodeScope extends Scope implements NodeRef {
protected final Uri meshUri;
protected final Uri hostUri;
protected final Uri nodeUri;
public NodeScope(CellContext cellContext, Stage stage, Uri meshUri,
Uri hostUri, Uri nodeUri) {
super(cellContext, stage);
this.meshUri = meshUri;
this.hostUri = hostUri;
this.nodeUri = nodeUri;
}
public final Uri meshUri() {
return this.meshUri;
}
@Override
public final Uri hostUri() {
return this.hostUri;
}
@Override
public final Uri nodeUri() {
return this.nodeUri;
}
@Override
public LaneRef laneRef(Uri laneUri) {
return new LaneScope(cellContext, stage, this.meshUri, this.hostUri, this.nodeUri, laneUri);
}
@Override
public LaneRef laneRef(String laneUri) {
return laneRef(Uri.parse(laneUri));
}
@Override
public EventDownlink<Value> downlink() {
return new EventDownlinkView<Value>(this, stage, this.meshUri, this.hostUri, this.nodeUri,
Uri.empty(), 0.0f, 0.0f, Value.absent(), Form.forValue());
}
@Override
public ListDownlink<Value> downlinkList() {
return null; // TODO
}
@Override
public MapDownlink<Value, Value> downlinkMap() {
return new MapDownlinkView<Value, Value>(this, stage, this.meshUri, this.hostUri,
this.nodeUri, Uri.empty(), 0.0f, 0.0f, Value.absent(), Form.forValue(), Form.forValue());
}
@Override
public ValueDownlink<Value> downlinkValue() {
return new ValueDownlinkView<Value>(this, stage, this.meshUri, this.hostUri, this.nodeUri,
Uri.empty(), 0.0f, 0.0f, Value.absent(), Form.forValue());
}
@Override
public <V> HttpDownlink<V> downlinkHttp() {
return null; // TODO
}
@Override
public <I, O> WsDownlink<I, O> downlinkWs() {
return null; // TODO
}
@Override
public void command(Uri laneUri, float prio, Value body) {
final CommandMessage message = new CommandMessage(this.nodeUri, laneUri, body);
pushDown(new ScopePushRequest(this.meshUri, this.hostUri, null, message, prio));
}
@Override
public void command(String laneUri, float prio, Value body) {
command(Uri.parse(laneUri), prio, body);
}
@Override
public void command(Uri laneUri, Value body) {
command(laneUri, 0.0f, body);
}
@Override
public void command(String laneUri, Value body) {
command(Uri.parse(laneUri), body);
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/scope/Scope.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.runtime.scope;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import swim.api.Downlink;
import swim.api.policy.Policy;
import swim.collections.HashTrieSet;
import swim.concurrent.Schedule;
import swim.concurrent.Stage;
import swim.runtime.CellContext;
import swim.runtime.LinkBinding;
import swim.runtime.PushRequest;
import swim.store.StoreBinding;
public abstract class Scope implements CellContext {
protected final CellContext cellContext;
protected final Stage stage;
volatile HashTrieSet<LinkBinding> links;
public Scope(CellContext cellContext, Stage stage) {
this.cellContext = cellContext;
this.stage = stage;
this.links = HashTrieSet.empty();
}
public Scope(CellContext cellContext) {
this(cellContext, cellContext.stage());
}
public final CellContext getCellContext() {
return this.cellContext;
}
@Override
public Policy policy() {
return this.cellContext.policy();
}
@Override
public Schedule schedule() {
return this.cellContext.schedule();
}
public final Stage stage() {
return this.stage;
}
@Override
public StoreBinding store() {
return this.cellContext.store();
}
@Override
public LinkBinding bindDownlink(Downlink downlink) {
final LinkBinding link = this.cellContext.bindDownlink(downlink);
link.setCellContext(this);
HashTrieSet<LinkBinding> oldLinks;
HashTrieSet<LinkBinding> newLinks;
do {
oldLinks = this.links;
newLinks = oldLinks.added(link);
} while (oldLinks != newLinks && !LINKS.compareAndSet(this, oldLinks, newLinks));
return link;
}
@Override
public void openDownlink(LinkBinding link) {
this.cellContext.openDownlink(link);
link.setCellContext(this);
HashTrieSet<LinkBinding> oldLinks;
HashTrieSet<LinkBinding> newLinks;
do {
oldLinks = this.links;
newLinks = oldLinks.added(link);
} while (oldLinks != newLinks && !LINKS.compareAndSet(this, oldLinks, newLinks));
}
@Override
public void closeDownlink(LinkBinding link) {
HashTrieSet<LinkBinding> oldLinks;
HashTrieSet<LinkBinding> newLinks;
do {
oldLinks = this.links;
newLinks = oldLinks.removed(link);
} while (oldLinks != newLinks && !LINKS.compareAndSet(this, oldLinks, newLinks));
}
@Override
public void pushDown(PushRequest pushRequest) {
this.cellContext.pushDown(pushRequest);
}
@Override
public void trace(Object message) {
this.cellContext.trace(message);
}
@Override
public void debug(Object message) {
this.cellContext.debug(message);
}
@Override
public void info(Object message) {
this.cellContext.info(message);
}
@Override
public void warn(Object message) {
this.cellContext.warn(message);
}
@Override
public void error(Object message) {
this.cellContext.error(message);
}
public void close() {
HashTrieSet<LinkBinding> oldLinks;
final HashTrieSet<LinkBinding> newLinks = HashTrieSet.empty();
do {
oldLinks = this.links;
} while (oldLinks != newLinks && !LINKS.compareAndSet(this, oldLinks, newLinks));
final Iterator<LinkBinding> linksIterator = oldLinks.iterator();
while (linksIterator.hasNext()) {
linksIterator.next().closeDown();
}
}
@SuppressWarnings("unchecked")
static final AtomicReferenceFieldUpdater<Scope, HashTrieSet<LinkBinding>> LINKS =
AtomicReferenceFieldUpdater.newUpdater(Scope.class, (Class<HashTrieSet<LinkBinding>>) (Class<?>) HashTrieSet.class, "links");
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/scope/ScopePushRequest.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.runtime.scope;
import swim.api.auth.Identity;
import swim.runtime.PushRequest;
import swim.uri.Uri;
import swim.warp.Envelope;
public class ScopePushRequest implements PushRequest {
final Uri meshUri;
final Uri hostUri;
final Identity identity;
final Envelope envelope;
final float prio;
public ScopePushRequest(Uri meshUri, Uri hostUri, Identity identity, Envelope envelope, float prio) {
this.meshUri = meshUri;
this.hostUri = hostUri;
this.identity = identity;
this.envelope = envelope;
this.prio = prio;
}
@Override
public Uri meshUri() {
return this.meshUri;
}
@Override
public Uri hostUri() {
return this.hostUri;
}
@Override
public Uri nodeUri() {
return this.envelope.nodeUri();
}
@Override
public float prio() {
return this.prio;
}
@Override
public Identity identity() {
return this.identity;
}
@Override
public Envelope envelope() {
return this.envelope;
}
@Override
public void didDeliver() {
// nop
}
@Override
public void didDecline() {
// nop
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/scope/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.
/**
* Scope runtime implementation.
*/
package swim.runtime.scope;
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/warp/DemandDownlinkModem.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.runtime.warp;
import swim.structure.Value;
import swim.uri.Uri;
public abstract class DemandDownlinkModem<View extends WarpDownlinkView> extends WarpDownlinkModel<View> {
public DemandDownlinkModem(Uri meshUri, Uri hostUri, Uri nodeUri, Uri laneUri,
float prio, float rate, Value body) {
super(meshUri, hostUri, nodeUri, laneUri, prio, rate, body);
}
@Override
protected abstract Value nextUpCue();
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/warp/DemandUplinkModem.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.runtime.warp;
import swim.runtime.WarpBinding;
import swim.structure.Value;
public abstract class DemandUplinkModem extends WarpUplinkModem {
public DemandUplinkModem(WarpBinding linkBinding) {
super(linkBinding);
}
@Override
protected abstract Value nextDownCue();
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/warp/ListDownlinkModem.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.runtime.warp;
import java.util.concurrent.ConcurrentLinkedQueue;
import swim.structure.Value;
import swim.uri.Uri;
public abstract class ListDownlinkModem<View extends WarpDownlinkView> extends WarpDownlinkModel<View> {
final ConcurrentLinkedQueue<ListLinkDelta> upQueue;
public ListDownlinkModem(Uri meshUri, Uri hostUri, Uri nodeUri, Uri laneUri,
float prio, float rate, Value body) {
super(meshUri, hostUri, nodeUri, laneUri, prio, rate, body);
this.upQueue = new ConcurrentLinkedQueue<ListLinkDelta>();
}
@Override
protected boolean upQueueIsEmpty() {
return this.upQueue.isEmpty();
}
public void queueUp(ListLinkDelta delta) {
this.upQueue.add(delta);
}
public void pushUp(ListLinkDelta delta) {
queueUp(delta);
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
newStatus = oldStatus | FEEDING_UP;
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
if (oldStatus != newStatus) {
this.linkContext.feedUp();
}
}
@Override
protected Value nextUpQueue() {
final ListLinkDelta delta = this.upQueue.poll();
return delta != null ? delta.toValue() : null;
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/warp/ListLinkDelta.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.runtime.warp;
import swim.structure.Attr;
import swim.structure.Record;
import swim.structure.Value;
public abstract class ListLinkDelta {
ListLinkDelta() {
// sealed
}
public abstract Value toValue();
public static ListLinkDelta update(int index, Value key, Value value) {
return new ListLinkDeltaUpdate(index, key, value);
}
public static ListLinkDelta remove(int index, Value key) {
return new ListLinkDeltaRemove(index, key);
}
public static ListLinkDelta move(int fromIndex, int toIndex, Value key) {
return new ListLinkDeltaMove(fromIndex, toIndex, key);
}
public static ListLinkDelta drop(int lower) {
return new ListLinkDeltaDrop(lower);
}
public static ListLinkDelta take(int upper) {
return new ListLinkDeltaTake(upper);
}
public static ListLinkDelta clear() {
return new ListLinkDeltaClear();
}
}
final class ListLinkDeltaUpdate extends ListLinkDelta {
final int index;
final Value key;
final Value value;
ListLinkDeltaUpdate(int index, Value key, Value value) {
this.index = index;
this.key = key;
this.value = value;
}
@Override
public Value toValue() {
final Record header = Record.create(2).slot("index", this.index)
.slot("key", this.key);
return Attr.of("update", header).concat(this.value);
}
}
final class ListLinkDeltaRemove extends ListLinkDelta {
final int index;
final Value key;
ListLinkDeltaRemove(int index, Value key) {
this.index = index;
this.key = key;
}
@Override
public Value toValue() {
final Record header = Record.create(2).slot("index", this.index)
.slot("key", this.key);
return Record.create(1).attr("remove", header);
}
}
final class ListLinkDeltaMove extends ListLinkDelta {
final int fromIndex;
final int toIndex;
final Value key;
ListLinkDeltaMove(int fromIndex, int toIndex, Value key) {
this.fromIndex = fromIndex;
this.toIndex = toIndex;
this.key = key;
}
@Override
public Value toValue() {
final Record header = Record.create(3).slot("from", this.fromIndex)
.slot("to", this.toIndex)
.slot("key", this.key);
return Record.create(1).attr("move", header);
}
}
final class ListLinkDeltaDrop extends ListLinkDelta {
final int lower;
ListLinkDeltaDrop(int lower) {
this.lower = lower;
}
@Override
public Value toValue() {
return Record.create(1).attr("drop", this.lower);
}
}
final class ListLinkDeltaTake extends ListLinkDelta {
final int upper;
ListLinkDeltaTake(int upper) {
this.upper = upper;
}
@Override
public Value toValue() {
return Record.create(1).attr("take", this.upper);
}
}
final class ListLinkDeltaClear extends ListLinkDelta {
@Override
public Value toValue() {
return Record.create(1).attr("clear");
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/warp/ListUplinkModem.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.runtime.warp;
import java.util.concurrent.ConcurrentLinkedQueue;
import swim.runtime.WarpBinding;
import swim.structure.Value;
public abstract class ListUplinkModem extends WarpUplinkModem {
final ConcurrentLinkedQueue<ListLinkDelta> downQueue;
public ListUplinkModem(WarpBinding linkBinding) {
super(linkBinding);
this.downQueue = new ConcurrentLinkedQueue<ListLinkDelta>();
}
@Override
protected boolean downQueueIsEmpty() {
return this.downQueue.isEmpty();
}
public void queueDown(ListLinkDelta delta) {
this.downQueue.add(delta);
}
public void sendDown(ListLinkDelta delta) {
queueDown(delta);
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
newStatus = oldStatus | FEEDING_DOWN;
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
if (oldStatus != newStatus) {
this.linkBinding.feedDown();
}
}
@Override
protected Value nextDownQueue() {
final ListLinkDelta delta = this.downQueue.poll();
return delta != null ? delta.toValue() : null;
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/warp/PartialDownlinkModem.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.runtime.warp;
import java.util.Collection;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import swim.collections.HashTrieSet;
import swim.structure.Value;
import swim.uri.Uri;
public abstract class PartialDownlinkModem<View extends WarpDownlinkView> extends WarpDownlinkModel<View> {
final ConcurrentLinkedQueue<Value> upQueue;
volatile HashTrieSet<Value> keyQueue;
volatile Value lastKey;
public PartialDownlinkModem(Uri meshUri, Uri hostUri, Uri nodeUri, Uri laneUri,
float prio, float rate, Value body) {
super(meshUri, hostUri, nodeUri, laneUri, prio, rate, body);
this.upQueue = new ConcurrentLinkedQueue<Value>();
this.keyQueue = HashTrieSet.empty();
}
@Override
protected boolean upQueueIsEmpty() {
return this.upQueue.isEmpty();
}
@Override
protected void queueUp(Value body) {
this.upQueue.add(body);
}
public void cueUpKey(Value key) {
HashTrieSet<Value> oldKeyQueue;
HashTrieSet<Value> newKeyQueue;
do {
oldKeyQueue = this.keyQueue;
if (!oldKeyQueue.contains(key)) {
newKeyQueue = oldKeyQueue.added(key);
} else {
newKeyQueue = oldKeyQueue;
break;
}
} while (!KEY_QUEUE.compareAndSet(this, oldKeyQueue, newKeyQueue));
if (oldKeyQueue != newKeyQueue) {
cueUp();
}
}
protected void cueUpKeys(Collection<? extends Value> keys) {
if (!keys.isEmpty()) {
HashTrieSet<Value> oldKeyQueue;
HashTrieSet<Value> newKeyQueue;
do {
oldKeyQueue = this.keyQueue;
newKeyQueue = oldKeyQueue.added(keys);
} while (!KEY_QUEUE.compareAndSet(this, oldKeyQueue, newKeyQueue));
cueUp();
}
}
protected abstract Value nextUpKey(Value key);
@Override
protected Value nextUpQueue() {
return this.upQueue.poll();
}
@Override
protected Value nextUpCue() {
HashTrieSet<Value> oldKeyQueue;
HashTrieSet<Value> newKeyQueue;
Value key;
do {
oldKeyQueue = this.keyQueue;
key = oldKeyQueue.next(this.lastKey);
newKeyQueue = oldKeyQueue.removed(key);
} while (oldKeyQueue != newKeyQueue && !KEY_QUEUE.compareAndSet(this, oldKeyQueue, newKeyQueue));
if (key != null) {
this.lastKey = key;
return nextUpKey(key);
} else {
return null;
}
}
@Override
protected void feedUp() {
if (!this.keyQueue.isEmpty()) {
cueUp();
}
super.feedUp();
}
@SuppressWarnings("unchecked")
static final AtomicReferenceFieldUpdater<PartialDownlinkModem<?>, HashTrieSet<Value>> KEY_QUEUE =
AtomicReferenceFieldUpdater.newUpdater((Class<PartialDownlinkModem<?>>) (Class<?>) PartialDownlinkModem.class, (Class<HashTrieSet<Value>>) (Class<?>) HashTrieSet.class, "keyQueue");
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/warp/PartialUplinkModem.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.runtime.warp;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import swim.collections.HashTrieSet;
import swim.runtime.WarpBinding;
import swim.structure.Record;
import swim.structure.Value;
public abstract class PartialUplinkModem extends WarpUplinkModem {
final ConcurrentLinkedQueue<Value> downQueue;
volatile Iterator<Map.Entry<Value, Value>> syncQueue;
volatile HashTrieSet<Value> keyQueue;
volatile Value lastKey;
public PartialUplinkModem(WarpBinding linkBinding) {
super(linkBinding);
this.downQueue = new ConcurrentLinkedQueue<Value>();
this.keyQueue = HashTrieSet.empty();
}
@Override
protected boolean downQueueIsEmpty() {
return this.downQueue.isEmpty() && this.syncQueue == null;
}
@Override
protected void queueDown(Value body) {
this.downQueue.add(body);
}
public void syncDown(Iterator<Map.Entry<Value, Value>> syncQueue) {
this.syncQueue = syncQueue;
}
public void cueDownKey(Value key) {
HashTrieSet<Value> oldKeyQueue;
HashTrieSet<Value> newKeyQueue;
do {
oldKeyQueue = this.keyQueue;
newKeyQueue = oldKeyQueue.added(key);
} while (oldKeyQueue != newKeyQueue && !KEY_QUEUE.compareAndSet(this, oldKeyQueue, newKeyQueue));
if (oldKeyQueue != newKeyQueue) {
cueDown();
}
}
protected abstract Value nextDownKey(Value key);
@Override
protected Value nextDownQueue() {
final Iterator<Map.Entry<Value, Value>> syncQueue = this.syncQueue;
if (syncQueue != null) {
if (syncQueue.hasNext()) {
final Map.Entry<Value, Value> entry = syncQueue.next();
return Record.of().attr("update", Record.of().slot("key", entry.getKey())).concat(entry.getValue());
} else {
this.syncQueue = null;
return null;
}
}
return this.downQueue.poll();
}
@Override
protected Value nextDownCue() {
HashTrieSet<Value> oldKeyQueue;
HashTrieSet<Value> newKeyQueue;
Value key;
do {
oldKeyQueue = this.keyQueue;
key = oldKeyQueue.next(this.lastKey);
newKeyQueue = oldKeyQueue.removed(key);
} while (oldKeyQueue != newKeyQueue && !KEY_QUEUE.compareAndSet(this, oldKeyQueue, newKeyQueue));
if (key != null) {
this.lastKey = key;
if (!newKeyQueue.isEmpty()) {
int oldStatus;
int newStatus;
do {
oldStatus = status;
newStatus = oldStatus | CUED_DOWN;
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
}
return nextDownKey(key);
} else {
return null;
}
}
@SuppressWarnings("unchecked")
static final AtomicReferenceFieldUpdater<PartialUplinkModem, HashTrieSet<Value>> KEY_QUEUE =
AtomicReferenceFieldUpdater.newUpdater(PartialUplinkModem.class, (Class<HashTrieSet<Value>>) (Class<?>) HashTrieSet.class, "keyQueue");
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/warp/SupplyDownlinkModem.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.runtime.warp;
import java.util.concurrent.ConcurrentLinkedQueue;
import swim.structure.Value;
import swim.uri.Uri;
public abstract class SupplyDownlinkModem<View extends WarpDownlinkView> extends WarpDownlinkModel<View> {
final ConcurrentLinkedQueue<Value> upQueue;
public SupplyDownlinkModem(Uri meshUri, Uri hostUri, Uri nodeUri, Uri laneUri,
float prio, float rate, Value body) {
super(meshUri, hostUri, nodeUri, laneUri, prio, rate, body);
this.upQueue = new ConcurrentLinkedQueue<Value>();
}
@Override
protected boolean upQueueIsEmpty() {
return this.upQueue.isEmpty();
}
@Override
protected void queueUp(Value body) {
this.upQueue.add(body);
}
@Override
protected Value nextUpQueue() {
return this.upQueue.poll();
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/warp/SupplyUplinkModem.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.runtime.warp;
import java.util.concurrent.ConcurrentLinkedQueue;
import swim.runtime.WarpBinding;
import swim.structure.Value;
public abstract class SupplyUplinkModem extends WarpUplinkModem {
final ConcurrentLinkedQueue<Value> downQueue;
public SupplyUplinkModem(WarpBinding linkBinding) {
super(linkBinding);
this.downQueue = new ConcurrentLinkedQueue<Value>();
}
@Override
protected boolean downQueueIsEmpty() {
return this.downQueue.isEmpty();
}
@Override
public void queueDown(Value body) {
this.downQueue.add(body);
}
@Override
protected Value nextDownQueue() {
return this.downQueue.poll();
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/warp/WarpDownlinkModel.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.runtime.warp;
import swim.runtime.DownlinkRelay;
import swim.runtime.DownlinkView;
import swim.structure.Value;
import swim.uri.Uri;
import swim.warp.CommandMessage;
import swim.warp.EventMessage;
import swim.warp.LinkRequest;
import swim.warp.LinkedResponse;
import swim.warp.SyncRequest;
import swim.warp.SyncedResponse;
import swim.warp.UnlinkRequest;
import swim.warp.UnlinkedResponse;
public abstract class WarpDownlinkModel<View extends WarpDownlinkView> extends WarpDownlinkModem<View> {
public WarpDownlinkModel(Uri meshUri, Uri hostUri, Uri nodeUri, Uri laneUri,
float prio, float rate, Value body) {
super(meshUri, hostUri, nodeUri, laneUri, prio, rate, body);
}
@Override
public final boolean keepLinked() {
final Object views = this.views;
if (views instanceof WarpDownlinkView) {
return ((WarpDownlinkView) views).keepLinked();
} else if (views instanceof DownlinkView[]) {
final DownlinkView[] viewArray = (DownlinkView[]) views;
for (int i = 0, n = viewArray.length; i < n; i += 1) {
if (((WarpDownlinkView) viewArray[i]).keepLinked()) {
return true;
}
}
}
return false;
}
@Override
public final boolean keepSynced() {
final Object views = this.views;
if (views instanceof WarpDownlinkView) {
return ((WarpDownlinkView) views).keepSynced();
} else if (views instanceof DownlinkView[]) {
final DownlinkView[] viewArray = (DownlinkView[]) views;
for (int i = 0, n = viewArray.length; i < n; i += 1) {
if (((WarpDownlinkView) viewArray[i]).keepSynced()) {
return true;
}
}
}
return false;
}
@Override
protected void pushDownEvent(EventMessage message) {
onEvent(message);
new WarpDownlinkRelayOnEvent<View>(this, message).run();
}
@Override
protected void pushDownLinked(LinkedResponse response) {
didLink(response);
new WarpDownlinkRelayDidLink<View>(this, response).run();
}
@Override
protected void pushDownSynced(SyncedResponse response) {
didSync(response);
new WarpDownlinkRelayDidSync<View>(this, response).run();
}
@Override
protected void pushDownUnlinked(UnlinkedResponse response) {
didUnlink(response);
new WarpDownlinkRelayDidUnlink<View>(this, response).run();
}
@Override
protected void pullUpCommand(CommandMessage message) {
onCommand(message);
new WarpDownlinkRelayWillCommand<View>(this, message).run();
}
@Override
protected void pullUpLink(LinkRequest request) {
willLink(request);
new WarpDownlinkRelayWillLink<View>(this, request).run();
}
@Override
protected void pullUpSync(SyncRequest request) {
willSync(request);
new WarpDownlinkRelayWillSync<View>(this, request).run();
}
@Override
protected void pullUpUnlink(UnlinkRequest request) {
willUnlink(request);
new WarpDownlinkRelayWillUnlink<View>(this, request).run();
}
}
final class WarpDownlinkRelayOnEvent<View extends WarpDownlinkView> extends DownlinkRelay<WarpDownlinkModel<View>, View> {
final EventMessage message;
WarpDownlinkRelayOnEvent(WarpDownlinkModel<View> model, EventMessage message) {
super(model, 2);
this.message = message;
}
@Override
protected boolean runPhase(View view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.downlinkWillReceive(this.message);
}
return view.dispatchWillReceive(this.message.body(), preemptive);
} else if (phase == 1) {
if (preemptive) {
view.downlinkDidReceive(this.message);
}
return view.dispatchDidReceive(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
this.model.cueDown();
}
}
final class WarpDownlinkRelayWillCommand<View extends WarpDownlinkView> extends DownlinkRelay<WarpDownlinkModel<View>, View> {
final CommandMessage message;
WarpDownlinkRelayWillCommand(WarpDownlinkModel<View> model, CommandMessage message) {
super(model);
this.message = message;
}
@Override
protected boolean runPhase(View view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.downlinkWillCommand(this.message);
}
return view.dispatchWillCommand(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
}
final class WarpDownlinkRelayWillLink<View extends WarpDownlinkView> extends DownlinkRelay<WarpDownlinkModel<View>, View> {
final LinkRequest request;
WarpDownlinkRelayWillLink(WarpDownlinkModel<View> model, LinkRequest request) {
super(model);
this.request = request;
}
@Override
protected boolean runPhase(View view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.downlinkWillLink(this.request);
}
return view.dispatchWillLink(preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
}
final class WarpDownlinkRelayDidLink<View extends WarpDownlinkView> extends DownlinkRelay<WarpDownlinkModel<View>, View> {
final LinkedResponse response;
WarpDownlinkRelayDidLink(WarpDownlinkModel<View> model, LinkedResponse response) {
super(model);
this.response = response;
}
@Override
protected boolean runPhase(View view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.downlinkDidLink(this.response);
}
return view.dispatchDidLink(preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
this.model.cueDown();
}
}
final class WarpDownlinkRelayWillSync<View extends WarpDownlinkView> extends DownlinkRelay<WarpDownlinkModel<View>, View> {
final SyncRequest request;
WarpDownlinkRelayWillSync(WarpDownlinkModel<View> model, SyncRequest request) {
super(model);
this.request = request;
}
@Override
protected boolean runPhase(View view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.downlinkWillSync(this.request);
}
return view.dispatchWillSync(preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
}
final class WarpDownlinkRelayDidSync<View extends WarpDownlinkView> extends DownlinkRelay<WarpDownlinkModel<View>, View> {
final SyncedResponse response;
WarpDownlinkRelayDidSync(WarpDownlinkModel<View> model, SyncedResponse response) {
super(model);
this.response = response;
}
@Override
protected boolean runPhase(View view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.downlinkDidSync(this.response);
}
return view.dispatchDidSync(preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
this.model.cueDown();
}
}
final class WarpDownlinkRelayWillUnlink<View extends WarpDownlinkView> extends DownlinkRelay<WarpDownlinkModel<View>, View> {
final UnlinkRequest request;
WarpDownlinkRelayWillUnlink(WarpDownlinkModel<View> model, UnlinkRequest request) {
super(model);
this.request = request;
}
@Override
protected boolean runPhase(View view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.downlinkWillUnlink(this.request);
}
return view.dispatchWillUnlink(preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
}
final class WarpDownlinkRelayDidUnlink<View extends WarpDownlinkView> extends DownlinkRelay<WarpDownlinkModel<View>, View> {
final UnlinkedResponse response;
WarpDownlinkRelayDidUnlink(WarpDownlinkModel<View> model, UnlinkedResponse response) {
super(model);
this.response = response;
}
@Override
protected boolean runPhase(View view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.downlinkDidUnlink(this.response);
}
return view.dispatchDidUnlink(preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
@Override
protected void done() {
// Don't cueDown model after unlinked.
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/warp/WarpDownlinkModem.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.runtime.warp;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import swim.runtime.CellContext;
import swim.runtime.DownlinkModel;
import swim.runtime.DownlinkView;
import swim.runtime.LinkContext;
import swim.runtime.WarpBinding;
import swim.runtime.WarpContext;
import swim.structure.Value;
import swim.uri.Uri;
import swim.warp.CommandMessage;
import swim.warp.Envelope;
import swim.warp.EventMessage;
import swim.warp.LinkRequest;
import swim.warp.LinkedResponse;
import swim.warp.SyncRequest;
import swim.warp.SyncedResponse;
import swim.warp.UnlinkRequest;
import swim.warp.UnlinkedResponse;
public abstract class WarpDownlinkModem<View extends DownlinkView> extends DownlinkModel<View> implements WarpBinding {
protected final float prio;
protected final float rate;
protected final Value body;
protected WarpContext linkContext;
protected CellContext cellContext;
protected volatile int status;
public WarpDownlinkModem(Uri meshUri, Uri hostUri, Uri nodeUri, Uri laneUri,
float prio, float rate, Value body) {
super(meshUri, hostUri, nodeUri, laneUri);
this.prio = prio;
this.rate = rate;
this.body = body;
}
@Override
public final WarpBinding linkWrapper() {
return this;
}
@Override
public final WarpContext linkContext() {
return this.linkContext;
}
@Override
public void setLinkContext(LinkContext linkContext) {
this.linkContext = (WarpContext) linkContext;
}
@Override
public final CellContext cellContext() {
return this.cellContext;
}
@Override
public void setCellContext(CellContext cellContext) {
this.cellContext = cellContext;
}
@Override
public final float prio() {
return this.prio;
}
@Override
public final float rate() {
return this.rate;
}
@Override
public final Value body() {
return this.body;
}
@Override
public abstract boolean keepLinked();
@Override
public abstract boolean keepSynced();
public void cueDown() {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
if ((oldStatus & FEEDING_DOWN) != 0) {
newStatus = oldStatus & ~FEEDING_DOWN | PULLING_DOWN;
} else {
newStatus = oldStatus & ~PULLING_DOWN;
}
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
if ((oldStatus & FEEDING_DOWN) != 0) {
this.linkContext.pullDown();
}
}
@Override
public void feedDown() {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
if ((oldStatus & PULLING_DOWN) == 0) {
newStatus = oldStatus & ~FEEDING_DOWN | PULLING_DOWN;
} else {
newStatus = oldStatus | FEEDING_DOWN;
}
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
if ((oldStatus & PULLING_DOWN) == 0) {
this.linkContext.pullDown();
}
}
@Override
public void pushDown(Envelope envelope) {
if (envelope instanceof EventMessage) {
pushDownEvent((EventMessage) envelope);
} else if (envelope instanceof LinkedResponse) {
pushDownLinked((LinkedResponse) envelope);
} else if (envelope instanceof SyncedResponse) {
pushDownSynced((SyncedResponse) envelope);
} else if (envelope instanceof UnlinkedResponse) {
pushDownUnlinked((UnlinkedResponse) envelope);
} else {
pushDownEnvelope(envelope);
}
}
protected void pushDownEvent(EventMessage message) {
try {
onEvent(message);
} finally {
cueDown();
}
}
protected void pushDownLinked(LinkedResponse response) {
try {
didLink(response);
} finally {
cueDown();
}
}
protected void pushDownSynced(SyncedResponse response) {
try {
didSync(response);
} finally {
cueDown();
}
}
protected void pushDownUnlinked(UnlinkedResponse response) {
didUnlink(response);
// Don't cueDown
}
protected void pushDownEnvelope(Envelope envelope) {
// nop
}
@Override
public void skipDown() {
cueDown();
}
protected boolean upQueueIsEmpty() {
return true;
}
protected void queueUp(Value body) {
throw new UnsupportedOperationException();
}
protected Value nextUpQueue() {
return null;
}
protected CommandMessage nextUpQueueCommand() {
final Value body = nextUpQueue();
if (body != null) {
return new CommandMessage(this.nodeUri, this.laneUri, body);
} else {
return null;
}
}
protected Value nextUpCue() {
return null;
}
protected CommandMessage nextUpCueCommand() {
final Value body = nextUpCue();
if (body != null) {
return new CommandMessage(this.nodeUri, this.laneUri, body);
} else {
return null;
}
}
public void pushUp(Value body) {
queueUp(body);
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
newStatus = oldStatus | FEEDING_UP;
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
if (oldStatus != newStatus) {
this.linkContext.feedUp();
}
}
public void cueUp() {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
newStatus = oldStatus | FEEDING_UP | CUED_UP;
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
if ((oldStatus & FEEDING_UP) == 0) {
this.linkContext.feedUp();
}
}
protected void feedUp() {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
if ((oldStatus & CUED_UP) != 0 || !upQueueIsEmpty()) {
newStatus = oldStatus | FEEDING_UP;
} else {
newStatus = oldStatus;
break;
}
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
if (oldStatus != newStatus) {
this.linkContext.feedUp();
}
}
@Override
public void pullUp() {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
if ((oldStatus & UNLINK) != 0) {
newStatus = oldStatus & ~(UNLINK | FEEDING_UP);
} else if ((oldStatus & SYNC) != 0) {
newStatus = oldStatus & ~(LINK | SYNC | FEEDING_UP);
} else if ((oldStatus & LINK) != 0) {
newStatus = oldStatus & ~(LINK | FEEDING_UP);
} else {
newStatus = oldStatus & ~(CUED_UP | FEEDING_UP);
}
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
if ((oldStatus & UNLINK) != 0) {
final UnlinkRequest request = unlinkRequest();
pullUpUnlink(request);
this.linkContext.pushUp(request);
} else if ((oldStatus & SYNC) != 0) {
final SyncRequest request = syncRequest();
pullUpSync(request);
this.linkContext.pushUp(request);
feedUp();
} else if ((oldStatus & LINK) != 0) {
final LinkRequest request = linkRequest();
pullUpLink(request);
this.linkContext.pushUp(request);
feedUp();
} else {
CommandMessage message = nextUpQueueCommand();
if (message == null && (oldStatus & CUED_UP) != 0) {
message = nextUpCueCommand();
}
if (message != null) {
pullUpCommand(message);
this.linkContext.pushUp(message);
feedUp();
} else {
this.linkContext.skipUp();
}
}
}
protected void pullUpCommand(CommandMessage message) {
onCommand(message);
}
protected void pullUpLink(LinkRequest request) {
willLink(request);
}
protected void pullUpSync(SyncRequest request) {
willSync(request);
}
protected void pullUpUnlink(UnlinkRequest request) {
willUnlink(request);
}
public void link() {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
if ((oldStatus & (LINKED | OPENED)) == OPENED) {
newStatus = oldStatus | FEEDING_UP | LINKING | LINK | LINKED;
} else {
newStatus = oldStatus;
break;
}
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
if ((oldStatus & FEEDING_UP) == 0 && (newStatus & FEEDING_UP) != 0 && this.linkContext != null) {
this.linkContext.feedUp();
}
}
public void sync() {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
if ((oldStatus & (LINKED | OPENED)) == OPENED) {
newStatus = oldStatus | FEEDING_UP | SYNCING | SYNC | LINKING | LINK | LINKED;
} else {
newStatus = oldStatus;
break;
}
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
if ((oldStatus & FEEDING_UP) == 0 && (newStatus & FEEDING_UP) != 0 && this.linkContext != null) {
this.linkContext.feedUp();
}
}
public void unlink() {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
if ((oldStatus & LINK) != 0) {
newStatus = oldStatus & ~(FEEDING_UP | SYNCING | SYNC | LINKING | LINK | LINKED);
} else if ((oldStatus & (UNLINKING | LINKED)) == LINKED) {
newStatus = (oldStatus | FEEDING_UP | UNLINKING | UNLINK) & ~(SYNCING | SYNC | LINKING | LINK);
} else {
newStatus = oldStatus;
break;
}
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
if ((oldStatus & FEEDING_UP) == 0 && (newStatus & FEEDING_UP) != 0 && this.linkContext != null) {
this.linkContext.feedUp();
}
}
public void command(float prio, Value body) {
queueUp(body);
}
public void command(Value body) {
queueUp(body);
}
protected LinkRequest linkRequest() {
return new LinkRequest(this.nodeUri, this.laneUri, this.prio, this.rate, this.body);
}
protected SyncRequest syncRequest() {
return new SyncRequest(this.nodeUri, this.laneUri, this.prio, this.rate, this.body);
}
protected UnlinkRequest unlinkRequest() {
return new UnlinkRequest(this.nodeUri, this.laneUri, this.body);
}
@Override
public void reopen() {
// nop
}
@Override
public void openDown() {
didOpen();
this.linkContext.didOpenDown();
if ((this.status & FEEDING_UP) != 0) {
this.linkContext.feedUp();
}
}
protected void didOpen() {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
newStatus = oldStatus | OPENED;
} while (oldStatus != newStatus & !STATUS.compareAndSet(this, oldStatus, newStatus));
if (keepLinked()) {
if (keepSynced()) {
sync();
} else {
link();
}
}
}
@Override
public void closeDown() {
final CellContext cellContext = this.cellContext;
if (cellContext != null) {
cellContext.closeDownlink(this);
}
didClose();
this.linkContext.didCloseDown();
}
protected void didClose() {
STATUS.set(this, 0);
}
protected void onEvent(EventMessage message) {
// stub
}
protected void onCommand(CommandMessage message) {
// stub
}
protected void willLink(LinkRequest request) {
// stub
}
protected void didLink(LinkedResponse response) {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
newStatus = oldStatus & ~LINKING;
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
}
protected void willSync(SyncRequest request) {
// stub
}
protected void didSync(SyncedResponse response) {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
newStatus = oldStatus & ~SYNCING;
} while (oldStatus != newStatus & !STATUS.compareAndSet(this, oldStatus, newStatus));
}
protected void willUnlink(UnlinkRequest request) {
// stub
}
protected void didUnlink(UnlinkedResponse response) {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
newStatus = oldStatus & ~(PULLING_DOWN | UNLINKING | UNLINK | SYNCING | SYNC | LINKING | LINK | LINKED);
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
}
@Override
public void didConnect() {
if (keepLinked()) {
if (keepSynced()) {
sync();
} else {
link();
}
}
super.didConnect();
}
@Override
public void didDisconnect() {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
newStatus = oldStatus & ~(FEEDING_UP | UNLINKING | UNLINK | SYNCING | SYNC | LINKING | LINK | LINKED);
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
super.didDisconnect();
}
@Override
public void didCloseUp() {
didClose();
super.didCloseUp();
}
@Override
public void didFail(Throwable error) {
error.printStackTrace();
super.didFail(error);
}
static final int OPENED = 1 << 0;
static final int LINKED = 1 << 1;
static final int LINK = 1 << 2;
static final int LINKING = 1 << 3;
static final int SYNC = 1 << 4;
static final int SYNCING = 1 << 5;
static final int UNLINK = 1 << 6;
static final int UNLINKING = 1 << 7;
static final int FEEDING_DOWN = 1 << 8;
static final int PULLING_DOWN = 1 << 9;
static final int CUED_UP = 1 << 10;
static final int FEEDING_UP = 1 << 11;
@SuppressWarnings("unchecked")
static final AtomicIntegerFieldUpdater<WarpDownlinkModem<?>> STATUS =
AtomicIntegerFieldUpdater.newUpdater((Class<WarpDownlinkModem<?>>) (Class<?>) WarpDownlinkModem.class, "status");
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/warp/WarpDownlinkView.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.runtime.warp;
import swim.api.Link;
import swim.api.SwimContext;
import swim.api.function.DidClose;
import swim.api.function.DidConnect;
import swim.api.function.DidDisconnect;
import swim.api.function.DidFail;
import swim.api.warp.WarpDownlink;
import swim.api.warp.function.DidLink;
import swim.api.warp.function.DidReceive;
import swim.api.warp.function.DidSync;
import swim.api.warp.function.DidUnlink;
import swim.api.warp.function.WillCommand;
import swim.api.warp.function.WillLink;
import swim.api.warp.function.WillReceive;
import swim.api.warp.function.WillSync;
import swim.api.warp.function.WillUnlink;
import swim.concurrent.Conts;
import swim.concurrent.Stage;
import swim.runtime.CellContext;
import swim.runtime.DownlinkView;
import swim.structure.Value;
import swim.uri.Uri;
import swim.warp.CommandMessage;
import swim.warp.EventMessage;
import swim.warp.LinkRequest;
import swim.warp.LinkedResponse;
import swim.warp.SyncRequest;
import swim.warp.SyncedResponse;
import swim.warp.UnlinkRequest;
import swim.warp.UnlinkedResponse;
public abstract class WarpDownlinkView extends DownlinkView implements WarpDownlink {
protected final Uri meshUri;
protected final Uri hostUri;
protected final Uri nodeUri;
protected final Uri laneUri;
protected final float prio;
protected final float rate;
protected final Value body;
protected volatile int flags;
public WarpDownlinkView(CellContext cellContext, Stage stage, Uri meshUri,
Uri hostUri, Uri nodeUri, Uri laneUri, float prio,
float rate, Value body, int flags, Object observers) {
super(cellContext, stage, observers);
this.meshUri = meshUri.isDefined() ? meshUri : hostUri;
this.hostUri = hostUri;
this.nodeUri = nodeUri;
this.laneUri = laneUri;
this.prio = prio;
this.rate = rate;
this.body = body;
this.flags = flags;
}
@Override
public abstract WarpDownlinkModel<?> downlinkModel();
public final Uri meshUri() {
return this.meshUri;
}
@Override
public final Uri hostUri() {
return this.hostUri;
}
@Override
public abstract WarpDownlinkView hostUri(Uri hostUri);
@Override
public abstract WarpDownlinkView hostUri(String hostUri);
@Override
public final Uri nodeUri() {
return this.nodeUri;
}
@Override
public abstract WarpDownlinkView nodeUri(Uri nodeUri);
@Override
public abstract WarpDownlinkView nodeUri(String nodeUri);
@Override
public final Uri laneUri() {
return this.laneUri;
}
@Override
public abstract WarpDownlinkView laneUri(Uri laneUri);
@Override
public abstract WarpDownlinkView laneUri(String laneUri);
@Override
public final float prio() {
return this.prio;
}
@Override
public abstract WarpDownlinkView prio(float prio);
@Override
public final float rate() {
return this.rate;
}
@Override
public abstract WarpDownlinkView rate(float rate);
@Override
public final Value body() {
return this.body;
}
@Override
public abstract WarpDownlinkView body(Value body);
@Override
public final boolean keepLinked() {
return (this.flags & KEEP_LINKED) != 0;
}
@Override
public abstract WarpDownlinkView keepLinked(boolean keepLinked);
@Override
public final boolean keepSynced() {
return (this.flags & KEEP_SYNCED) != 0;
}
@Override
public abstract WarpDownlinkView keepSynced(boolean keepSynced);
@Override
public WarpDownlinkView observe(Object observer) {
super.observe(observer);
return this;
}
@Override
public WarpDownlinkView unobserve(Object observer) {
super.unobserve(observer);
return this;
}
@Override
public abstract WarpDownlinkView willReceive(WillReceive willReceive);
@Override
public abstract WarpDownlinkView didReceive(DidReceive didReceive);
@Override
public abstract WarpDownlinkView willCommand(WillCommand willCommand);
@Override
public abstract WarpDownlinkView willLink(WillLink willLink);
@Override
public abstract WarpDownlinkView didLink(DidLink didLink);
@Override
public abstract WarpDownlinkView willSync(WillSync willSync);
@Override
public abstract WarpDownlinkView didSync(DidSync didSync);
@Override
public abstract WarpDownlinkView willUnlink(WillUnlink willUnlink);
@Override
public abstract WarpDownlinkView didUnlink(DidUnlink didUnlink);
@Override
public abstract WarpDownlinkView didConnect(DidConnect didConnect);
@Override
public abstract WarpDownlinkView didDisconnect(DidDisconnect didDisconnect);
@Override
public abstract WarpDownlinkView didClose(DidClose didClose);
@Override
public abstract WarpDownlinkView didFail(DidFail didFail);
public boolean dispatchWillReceive(Value body, boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillReceive) {
if (((WillReceive) observers).isPreemptive() == preemptive) {
try {
((WillReceive) observers).willReceive(body);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillReceive) {
if (((WillReceive) observer).isPreemptive() == preemptive) {
try {
((WillReceive) observer).willReceive(body);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
public boolean dispatchDidReceive(Value body, boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidReceive) {
if (((DidReceive) observers).isPreemptive() == preemptive) {
try {
((DidReceive) observers).didReceive(body);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidReceive) {
if (((DidReceive) observer).isPreemptive() == preemptive) {
try {
((DidReceive) observer).didReceive(body);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
public boolean dispatchWillCommand(Value body, boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillCommand) {
if (((WillCommand) observers).isPreemptive() == preemptive) {
try {
((WillCommand) observers).willCommand(body);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillCommand) {
if (((WillCommand) observer).isPreemptive() == preemptive) {
try {
((WillCommand) observer).willCommand(body);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
public boolean dispatchWillLink(boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillLink) {
if (((WillLink) observers).isPreemptive() == preemptive) {
try {
((WillLink) observers).willLink();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillLink) {
if (((WillLink) observer).isPreemptive() == preemptive) {
try {
((WillLink) observer).willLink();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
public boolean dispatchDidLink(boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidLink) {
if (((DidLink) observers).isPreemptive() == preemptive) {
try {
((DidLink) observers).didLink();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidLink) {
if (((DidLink) observer).isPreemptive() == preemptive) {
try {
((DidLink) observer).didLink();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
public boolean dispatchWillSync(boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillSync) {
if (((WillSync) observers).isPreemptive() == preemptive) {
try {
((WillSync) observers).willSync();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillSync) {
if (((WillSync) observer).isPreemptive() == preemptive) {
try {
((WillSync) observer).willSync();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
public boolean dispatchDidSync(boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidSync) {
if (((DidSync) observers).isPreemptive() == preemptive) {
try {
((DidSync) observers).didSync();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidSync) {
if (((DidSync) observer).isPreemptive() == preemptive) {
try {
((DidSync) observer).didSync();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
public boolean dispatchWillUnlink(boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillUnlink) {
if (((WillUnlink) observers).isPreemptive() == preemptive) {
try {
((WillUnlink) observers).willUnlink();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillUnlink) {
if (((WillUnlink) observer).isPreemptive() == preemptive) {
try {
((WillUnlink) observer).willUnlink();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
public boolean dispatchDidUnlink(boolean preemptive) {
final Link oldLink = SwimContext.getLink();
try {
SwimContext.setLink(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidUnlink) {
if (((DidUnlink) observers).isPreemptive() == preemptive) {
try {
((DidUnlink) observers).didUnlink();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidUnlink) {
if (((DidUnlink) observer).isPreemptive() == preemptive) {
try {
((DidUnlink) observer).didUnlink();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
downlinkDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
public void downlinkWillReceive(EventMessage message) {
// stub
}
public void downlinkDidReceive(EventMessage message) {
// stub
}
public void downlinkWillCommand(CommandMessage message) {
// stub
}
public void downlinkWillLink(LinkRequest request) {
// stub
}
public void downlinkDidLink(LinkedResponse response) {
// stub
}
public void downlinkWillSync(SyncRequest request) {
// stub
}
public void downlinkDidSync(SyncedResponse response) {
// stub
}
public void downlinkWillUnlink(UnlinkRequest request) {
// stub
}
public void downlinkDidUnlink(UnlinkedResponse response) {
// stub
}
@Override
public abstract WarpDownlinkModel<?> createDownlinkModel();
@Override
public abstract WarpDownlinkView open();
@Override
public void command(float prio, Value body) {
downlinkModel().command(prio, body);
}
@Override
public void command(Value body) {
downlinkModel().command(body);
}
protected static final int KEEP_LINKED = 1 << 0;
protected static final int KEEP_SYNCED = 1 << 1;
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/warp/WarpErrorUplinkModem.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.runtime.warp;
import java.net.InetSocketAddress;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import swim.api.auth.Identity;
import swim.collections.FingerTrieSeq;
import swim.runtime.WarpBinding;
import swim.runtime.WarpContext;
import swim.structure.Value;
import swim.warp.Envelope;
import swim.warp.UnlinkedResponse;
public class WarpErrorUplinkModem implements WarpContext {
protected final WarpBinding linkBinding;
protected final Value body;
volatile int status;
public WarpErrorUplinkModem(WarpBinding linkBinding, Value body) {
this.linkBinding = linkBinding;
this.body = body;
}
@Override
public final WarpBinding linkWrapper() {
return this.linkBinding.linkWrapper();
}
public final WarpBinding linkBinding() {
return this.linkBinding;
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrapLink(Class<T> linkClass) {
if (linkClass.isAssignableFrom(getClass())) {
return (T) this;
} else {
return null;
}
}
@Override
public Value linkKey() {
return Value.absent(); // never opened
}
@Override
public boolean isConnectedUp() {
return true;
}
@Override
public boolean isRemoteUp() {
return false;
}
@Override
public boolean isSecureUp() {
return true;
}
@Override
public String securityProtocolUp() {
return null;
}
@Override
public String cipherSuiteUp() {
return null;
}
@Override
public InetSocketAddress localAddressUp() {
return null;
}
@Override
public Identity localIdentityUp() {
return null;
}
@Override
public Principal localPrincipalUp() {
return null;
}
@Override
public Collection<Certificate> localCertificatesUp() {
return FingerTrieSeq.empty();
}
@Override
public InetSocketAddress remoteAddressUp() {
return null;
}
@Override
public Identity remoteIdentityUp() {
return null;
}
@Override
public Principal remotePrincipalUp() {
return null;
}
@Override
public Collection<Certificate> remoteCertificatesUp() {
return FingerTrieSeq.empty();
}
public void cueDown() {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
newStatus = oldStatus | FEEDING_DOWN;
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
if (oldStatus != newStatus) {
this.linkBinding.feedDown();
}
}
@Override
public void pullDown() {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
newStatus = oldStatus & ~FEEDING_DOWN;
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
if (oldStatus != newStatus) {
final UnlinkedResponse response = getUnlinkedResponse();
this.linkBinding.pushDown(response);
} else {
this.linkBinding.skipDown();
}
}
@Override
public void feedUp() {
// nop
}
@Override
public void pushUp(Envelope envelope) {
// nop
}
@Override
public void skipUp() {
// nop
}
@Override
public void closeUp() {
// nop
}
@Override
public void didOpenDown() {
// nop
}
@Override
public void didCloseDown() {
// nop
}
protected UnlinkedResponse getUnlinkedResponse() {
return new UnlinkedResponse(this.linkBinding.nodeUri(), this.linkBinding.laneUri(), this.body);
}
@Override
public void traceUp(Object message) {
// nop
}
@Override
public void debugUp(Object message) {
// nop
}
@Override
public void infoUp(Object message) {
// nop
}
@Override
public void warnUp(Object message) {
// nop
}
@Override
public void errorUp(Object message) {
// nop
}
static final int FEEDING_DOWN = 1 << 0;
static final AtomicIntegerFieldUpdater<WarpErrorUplinkModem> STATUS =
AtomicIntegerFieldUpdater.newUpdater(WarpErrorUplinkModem.class, "status");
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/warp/WarpLaneModel.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.runtime.warp;
import swim.api.auth.Identity;
import swim.api.warp.WarpUplink;
import swim.collections.FingerTrieSeq;
import swim.runtime.LaneModel;
import swim.runtime.LaneRelay;
import swim.runtime.LinkBinding;
import swim.runtime.PushRequest;
import swim.runtime.WarpBinding;
import swim.structure.Value;
import swim.warp.CommandMessage;
import swim.warp.Envelope;
public abstract class WarpLaneModel<View extends WarpLaneView, U extends WarpUplinkModem> extends LaneModel<View, U> {
@Override
protected U createUplink(LinkBinding link) {
if (link instanceof WarpBinding) {
return createWarpUplink((WarpBinding) link);
}
return null;
}
protected abstract U createWarpUplink(WarpBinding link);
@SuppressWarnings("unchecked")
public void cueDown() {
FingerTrieSeq<U> uplinks;
FingerTrieSeq<Value> closedLinks = FingerTrieSeq.empty();
do {
uplinks = (FingerTrieSeq<U>) (FingerTrieSeq<?>) this.uplinks;
for (int i = 0, n = uplinks.size(); i < n; i += 1) {
final U uplink = uplinks.get(i);
if (uplink.isConnected()) {
uplink.cueDown();
} else {
closedLinks = closedLinks.appended(uplink.linkKey());
}
}
} while (uplinks != this.uplinks);
for (Value linkKey: closedLinks) {
closeUplink(linkKey);
}
}
@SuppressWarnings("unchecked")
public void sendDown(Value body) {
FingerTrieSeq<U> uplinks;
FingerTrieSeq<Value> closedLinks = FingerTrieSeq.empty();
do {
uplinks = (FingerTrieSeq<U>) (FingerTrieSeq<?>) this.uplinks;
for (int i = 0, n = uplinks.size(); i < n; i += 1) {
final U uplink = uplinks.get(i);
if (uplink.isConnected()) {
uplink.sendDown(body);
} else {
closedLinks = closedLinks.appended(uplink.linkKey());
}
}
} while (uplinks != this.uplinks);
for (Value linkKey : closedLinks) {
closeUplink(linkKey);
}
}
@Override
public void pushUp(PushRequest pushRequest) {
final Envelope envelope = pushRequest.envelope();
if (envelope instanceof CommandMessage) {
onCommand((CommandMessage) envelope);
pushRequest.didDeliver();
} else {
pushRequest.didDecline();
}
}
@Override
public void pushUpCommand(CommandMessage message) {
onCommand(message);
}
protected void onCommand(CommandMessage message) {
new WarpLaneRelayOnCommand<View>(this, message).run();
}
@Override
protected void didUplink(U uplink) {
new WarpLaneRelayDidUplink<View>(this, uplink).run();
}
protected void didEnter(Identity identity) {
new WarpLaneRelayDidEnter<View>(this, identity).run();
}
protected void didLeave(Identity identity) {
new WarpLaneRelayDidLeave<View>(this, identity).run();
}
}
final class WarpLaneRelayOnCommand<View extends WarpLaneView> extends LaneRelay<WarpLaneModel<View, ?>, View> {
final CommandMessage message;
WarpLaneRelayOnCommand(WarpLaneModel<View, ?> model, CommandMessage message) {
super(model, 2);
this.message = message;
}
@Override
protected boolean runPhase(View view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneWillCommand(this.message);
}
return view.dispatchWillCommand(this.message.body(), preemptive);
} else if (phase == 1) {
if (preemptive) {
view.laneDidCommand(this.message);
}
return view.dispatchDidCommand(this.message.body(), preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
}
final class WarpLaneRelayDidUplink<View extends WarpLaneView> extends LaneRelay<LaneModel<View, ?>, View> {
final WarpUplink uplink;
WarpLaneRelayDidUplink(LaneModel<View, ?> model, WarpUplink uplink) {
super(model);
this.uplink = uplink;
}
@Override
protected boolean runPhase(View view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneDidUplink(this.uplink);
}
return view.dispatchDidUplink(this.uplink, preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
}
final class WarpLaneRelayDidEnter<View extends WarpLaneView> extends LaneRelay<WarpLaneModel<View, ?>, View> {
final Identity identity;
WarpLaneRelayDidEnter(WarpLaneModel<View, ?> model, Identity identity) {
super(model);
this.identity = identity;
}
@Override
protected boolean runPhase(View view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneDidEnter(this.identity);
}
return view.dispatchDidEnter(this.identity, preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
}
final class WarpLaneRelayDidLeave<View extends WarpLaneView> extends LaneRelay<WarpLaneModel<View, ?>, View> {
final Identity identity;
WarpLaneRelayDidLeave(WarpLaneModel<View, ?> model, Identity identity) {
super(model);
this.identity = identity;
}
@Override
protected boolean runPhase(View view, int phase, boolean preemptive) {
if (phase == 0) {
if (preemptive) {
view.laneDidLeave(this.identity);
}
return view.dispatchDidLeave(this.identity, preemptive);
} else {
throw new AssertionError(); // unreachable
}
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/warp/WarpLaneView.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.runtime.warp;
import swim.api.Lane;
import swim.api.Link;
import swim.api.SwimContext;
import swim.api.auth.Identity;
import swim.api.warp.WarpLane;
import swim.api.warp.WarpUplink;
import swim.api.warp.function.DidCommand;
import swim.api.warp.function.DidEnter;
import swim.api.warp.function.DidLeave;
import swim.api.warp.function.DidUplink;
import swim.api.warp.function.WillCommand;
import swim.api.warp.function.WillEnter;
import swim.api.warp.function.WillLeave;
import swim.api.warp.function.WillUplink;
import swim.concurrent.Conts;
import swim.runtime.LaneView;
import swim.structure.Value;
import swim.warp.CommandMessage;
public abstract class WarpLaneView extends LaneView implements WarpLane {
public WarpLaneView(Object observers) {
super(observers);
}
@Override
public WarpLaneView observe(Object observer) {
super.observe(observer);
return this;
}
@Override
public WarpLaneView unobserve(Object observer) {
super.unobserve(observer);
return this;
}
@Override
public abstract WarpLaneView willCommand(WillCommand willCommand);
@Override
public abstract WarpLaneView didCommand(DidCommand didCommand);
@Override
public abstract WarpLaneView willUplink(WillUplink willUplink);
@Override
public abstract WarpLaneView didUplink(DidUplink didUplink);
@Override
public abstract WarpLaneView willEnter(WillEnter willEnter);
@Override
public abstract WarpLaneView didEnter(DidEnter didEnter);
@Override
public abstract WarpLaneView willLeave(WillLeave willLeave);
@Override
public abstract WarpLaneView didLeave(DidLeave didLeave);
public boolean dispatchWillCommand(Value body, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
try {
SwimContext.setLane(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillCommand) {
if (((WillCommand) observers).isPreemptive() == preemptive) {
try {
((WillCommand) observers).willCommand(body);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillCommand) {
if (((WillCommand) observer).isPreemptive() == preemptive) {
try {
((WillCommand) observer).willCommand(body);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLane(oldLane);
}
}
public boolean dispatchDidCommand(Value body, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
try {
SwimContext.setLane(this);
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidCommand) {
if (((DidCommand) observers).isPreemptive() == preemptive) {
try {
((DidCommand) observers).didCommand(body);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidCommand) {
if (((DidCommand) observer).isPreemptive() == preemptive) {
try {
((DidCommand) observer).didCommand(body);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLane(oldLane);
}
}
public boolean dispatchWillUplink(WarpUplink uplink, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
SwimContext.setLane(this);
SwimContext.setLink(uplink);
try {
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillUplink) {
if (((WillUplink) observers).isPreemptive() == preemptive) {
try {
((WillUplink) observers).willUplink(uplink);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillUplink) {
if (((WillUplink) observer).isPreemptive() == preemptive) {
try {
((WillUplink) observer).willUplink(uplink);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
public boolean dispatchDidUplink(WarpUplink uplink, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
final Link oldLink = SwimContext.getLink();
SwimContext.setLane(this);
SwimContext.setLink(uplink);
try {
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidUplink) {
if (((DidUplink) observers).isPreemptive() == preemptive) {
try {
((DidUplink) observers).didUplink(uplink);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidUplink) {
if (((DidUplink) observer).isPreemptive() == preemptive) {
try {
((DidUplink) observer).didUplink(uplink);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
SwimContext.setLane(oldLane);
}
}
public boolean dispatchWillEnter(Identity identity, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
SwimContext.setLane(this);
try {
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillEnter) {
if (((WillEnter) observers).isPreemptive() == preemptive) {
try {
((WillEnter) observers).willEnter(identity);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillEnter) {
if (((WillEnter) observer).isPreemptive() == preemptive) {
try {
((WillEnter) observer).willEnter(identity);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLane(oldLane);
}
}
public boolean dispatchDidEnter(Identity identity, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
SwimContext.setLane(this);
try {
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidEnter) {
if (((DidEnter) observers).isPreemptive() == preemptive) {
try {
((DidEnter) observers).didEnter(identity);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidEnter) {
if (((DidEnter) observer).isPreemptive() == preemptive) {
try {
((DidEnter) observer).didEnter(identity);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLane(oldLane);
}
}
public boolean dispatchWillLeave(Identity identity, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
SwimContext.setLane(this);
try {
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof WillLeave) {
if (((WillLeave) observers).isPreemptive() == preemptive) {
try {
((WillLeave) observers).willLeave(identity);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof WillLeave) {
if (((WillLeave) observer).isPreemptive() == preemptive) {
try {
((WillLeave) observer).willLeave(identity);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLane(oldLane);
}
}
public boolean dispatchDidLeave(Identity identity, boolean preemptive) {
final Lane oldLane = SwimContext.getLane();
SwimContext.setLane(this);
try {
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof DidLeave) {
if (((DidLeave) observers).isPreemptive() == preemptive) {
try {
((DidLeave) observers).didLeave(identity);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidLeave) {
if (((DidLeave) observer).isPreemptive() == preemptive) {
try {
((DidLeave) observer).didLeave(identity);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
laneDidFail(error);
}
throw error;
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLane(oldLane);
}
}
public void laneWillCommand(CommandMessage message) {
// stub
}
public void laneDidCommand(CommandMessage message) {
// stub
}
public void laneWillUplink(WarpUplink uplink) {
// stub
}
public void laneDidUplink(WarpUplink uplink) {
// stub
}
public void laneWillEnter(Identity identity) {
// stub
}
public void laneDidEnter(Identity identity) {
// stub
}
public void laneWillLeave(Identity identity) {
// stub
}
public void laneDidLeave(Identity identity) {
// stub
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/warp/WarpUplinkModem.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.runtime.warp;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import swim.api.Link;
import swim.api.SwimContext;
import swim.api.function.DidClose;
import swim.api.warp.WarpUplink;
import swim.api.warp.function.OnCommandMessage;
import swim.api.warp.function.OnEventMessage;
import swim.api.warp.function.OnLinkRequest;
import swim.api.warp.function.OnLinkedResponse;
import swim.api.warp.function.OnSyncRequest;
import swim.api.warp.function.OnSyncedResponse;
import swim.api.warp.function.OnUnlinkRequest;
import swim.api.warp.function.OnUnlinkedResponse;
import swim.concurrent.Conts;
import swim.runtime.AbstractUplinkContext;
import swim.runtime.LinkKeys;
import swim.runtime.WarpBinding;
import swim.runtime.WarpContext;
import swim.structure.Value;
import swim.uri.Uri;
import swim.warp.CommandMessage;
import swim.warp.Envelope;
import swim.warp.EventMessage;
import swim.warp.LinkRequest;
import swim.warp.LinkedResponse;
import swim.warp.SyncRequest;
import swim.warp.SyncedResponse;
import swim.warp.UnlinkRequest;
import swim.warp.UnlinkedResponse;
public abstract class WarpUplinkModem extends AbstractUplinkContext implements WarpContext, WarpUplink {
protected final WarpBinding linkBinding;
protected final Value linkKey;
protected volatile int status;
protected WarpUplinkModem(WarpBinding linkBinding, Value linkKey) {
this.linkBinding = linkBinding;
this.linkKey = linkKey.commit();
}
protected WarpUplinkModem(WarpBinding linkBinding) {
this(linkBinding, LinkKeys.generateLinkKey());
}
@Override
public final WarpBinding linkWrapper() {
return this.linkBinding.linkWrapper();
}
@Override
public final WarpBinding linkBinding() {
return this.linkBinding;
}
@Override
public final Uri hostUri() {
return this.linkBinding.hostUri();
}
@Override
public final Uri nodeUri() {
return this.linkBinding.nodeUri();
}
@Override
public final Uri laneUri() {
return this.linkBinding.laneUri();
}
@Override
public final Value linkKey() {
return this.linkKey;
}
@Override
public final float prio() {
return this.linkBinding.prio();
}
@Override
public final float rate() {
return this.linkBinding.rate();
}
@Override
public final Value body() {
return this.linkBinding.body();
}
@Override
public WarpUplinkModem observe(Object observer) {
super.observe(observer);
return this;
}
@Override
public WarpUplinkModem unobserve(Object observer) {
super.unobserve(observer);
return this;
}
@Override
public WarpUplinkModem onEvent(OnEventMessage onEvent) {
observe(onEvent);
return this;
}
@Override
public WarpUplinkModem onCommand(OnCommandMessage onCommand) {
observe(onCommand);
return this;
}
@Override
public WarpUplinkModem onLink(OnLinkRequest onLink) {
observe(onLink);
return this;
}
@Override
public WarpUplinkModem onLinked(OnLinkedResponse onLinked) {
observe(onLinked);
return this;
}
@Override
public WarpUplinkModem onSync(OnSyncRequest onSync) {
observe(onSync);
return this;
}
@Override
public WarpUplinkModem onSynced(OnSyncedResponse onSynced) {
observe(onSynced);
return this;
}
@Override
public WarpUplinkModem onUnlink(OnUnlinkRequest onUnlink) {
observe(onUnlink);
return this;
}
@Override
public WarpUplinkModem onUnlinked(OnUnlinkedResponse onUnlinked) {
observe(onUnlinked);
return this;
}
@Override
public WarpUplinkModem didClose(DidClose didClose) {
observe(didClose);
return this;
}
protected void dispatchOnEvent(EventMessage message) {
final Link oldLink = SwimContext.getLink();
SwimContext.setLink(this);
try {
final Object observers = this.observers;
if (observers instanceof OnEventMessage) {
try {
((OnEventMessage) observers).onEvent(message);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
didFail(error);
} else {
throw error;
}
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof OnEventMessage) {
try {
((OnEventMessage) observer).onEvent(message);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
didFail(error);
} else {
throw error;
}
}
}
}
}
} finally {
SwimContext.setLink(oldLink);
}
}
protected boolean dispatchOnCommand(CommandMessage message, boolean preemptive) {
final Link oldLink = SwimContext.getLink();
SwimContext.setLink(this);
try {
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof OnCommandMessage) {
if (((OnCommandMessage) observers).isPreemptive() == preemptive) {
try {
((OnCommandMessage) observers).onCommand(message);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
didFail(error);
} else {
throw error;
}
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof OnCommandMessage) {
if (((OnCommandMessage) observer).isPreemptive() == preemptive) {
try {
((OnCommandMessage) observer).onCommand(message);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
didFail(error);
} else {
throw error;
}
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
protected boolean dispatchOnLink(LinkRequest request, boolean preemptive) {
final Link oldLink = SwimContext.getLink();
SwimContext.setLink(this);
try {
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof OnLinkRequest) {
if (((OnLinkRequest) observers).isPreemptive() == preemptive) {
try {
((OnLinkRequest) observers).onLink(request);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
didFail(error);
} else {
throw error;
}
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof OnLinkRequest) {
if (((OnLinkRequest) observer).isPreemptive() == preemptive) {
try {
((OnLinkRequest) observer).onLink(request);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
didFail(error);
} else {
throw error;
}
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
protected void dispatchOnLinked(LinkedResponse response) {
final Link oldLink = SwimContext.getLink();
SwimContext.setLink(this);
try {
final Object observers = this.observers;
if (observers instanceof OnLinkedResponse) {
try {
((OnLinkedResponse) observers).onLinked(response);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
didFail(error);
} else {
throw error;
}
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof OnLinkedResponse) {
try {
((OnLinkedResponse) observer).onLinked(response);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
didFail(error);
} else {
throw error;
}
}
}
}
}
} finally {
SwimContext.setLink(oldLink);
}
}
protected boolean dispatchOnSync(SyncRequest request, boolean preemptive) {
final Link oldLink = SwimContext.getLink();
SwimContext.setLink(this);
try {
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof OnSyncRequest) {
if (((OnSyncRequest) observers).isPreemptive() == preemptive) {
try {
((OnSyncRequest) observers).onSync(request);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
didFail(error);
} else {
throw error;
}
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof OnSyncRequest) {
if (((OnSyncRequest) observer).isPreemptive() == preemptive) {
try {
((OnSyncRequest) observer).onSync(request);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
didFail(error);
} else {
throw error;
}
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
protected void dispatchOnSynced(SyncedResponse response) {
final Link oldLink = SwimContext.getLink();
SwimContext.setLink(this);
try {
final Object observers = this.observers;
if (observers instanceof OnSyncedResponse) {
try {
((OnSyncedResponse) observers).onSynced(response);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
didFail(error);
} else {
throw error;
}
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof OnSyncedResponse) {
try {
((OnSyncedResponse) observer).onSynced(response);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
didFail(error);
} else {
throw error;
}
}
}
}
}
} finally {
SwimContext.setLink(oldLink);
}
}
protected boolean dispatchOnUnlink(UnlinkRequest request, boolean preemptive) {
final Link oldLink = SwimContext.getLink();
SwimContext.setLink(this);
try {
final Object observers = this.observers;
boolean complete = true;
if (observers instanceof OnUnlinkRequest) {
if (((OnUnlinkRequest) observers).isPreemptive() == preemptive) {
try {
((OnUnlinkRequest) observers).onUnlink(request);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
didFail(error);
} else {
throw error;
}
}
} else if (preemptive) {
complete = false;
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof OnUnlinkRequest) {
if (((OnUnlinkRequest) observer).isPreemptive() == preemptive) {
try {
((OnUnlinkRequest) observer).onUnlink(request);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
didFail(error);
} else {
throw error;
}
}
} else if (preemptive) {
complete = false;
}
}
}
}
return complete;
} finally {
SwimContext.setLink(oldLink);
}
}
protected void dispatchOnUnlinked(UnlinkedResponse response) {
final Link oldLink = SwimContext.getLink();
SwimContext.setLink(this);
try {
final Object observers = this.observers;
if (observers instanceof OnUnlinkedResponse) {
try {
((OnUnlinkedResponse) observers).onUnlinked(response);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
didFail(error);
} else {
throw error;
}
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof OnUnlinkedResponse) {
try {
((OnUnlinkedResponse) observer).onUnlinked(response);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
didFail(error);
} else {
throw error;
}
}
}
}
}
} finally {
SwimContext.setLink(oldLink);
}
}
protected void dispatchDidClose() {
final Link oldLink = SwimContext.getLink();
SwimContext.setLink(this);
try {
final Object observers = this.observers;
if (observers instanceof DidClose) {
try {
((DidClose) observers).didClose();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
didFail(error);
} else {
throw error;
}
}
} else if (observers instanceof Object[]) {
final Object[] array = (Object[]) observers;
for (int i = 0, n = array.length; i < n; i += 1) {
final Object observer = array[i];
if (observer instanceof DidClose) {
try {
((DidClose) observer).didClose();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
didFail(error);
} else {
throw error;
}
}
}
}
}
} finally {
SwimContext.setLink(oldLink);
}
}
protected boolean downQueueIsEmpty() {
return true;
}
protected void queueDown(Value body) {
throw new UnsupportedOperationException();
}
protected Value nextDownQueue() {
return null;
}
protected EventMessage nextDownQueueEvent() {
final Value body = nextDownQueue();
if (body != null) {
return new EventMessage(nodeUri(), laneUri(), body);
} else {
return null;
}
}
protected Value nextDownCue() {
return null;
}
protected EventMessage nextDownCueEvent() {
final Value body = nextDownCue();
if (body != null) {
return new EventMessage(nodeUri(), laneUri(), body);
} else {
return null;
}
}
public void sendDown(Value body) {
queueDown(body);
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
newStatus = oldStatus | FEEDING_DOWN;
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
if (oldStatus != newStatus) {
this.linkBinding.feedDown();
}
}
public void cueDown() {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
if ((oldStatus & LINKED) != 0) {
newStatus = oldStatus | FEEDING_DOWN | CUED_DOWN;
} else {
newStatus = oldStatus | CUED_DOWN;
}
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
if ((oldStatus & FEEDING_DOWN) != (newStatus & FEEDING_DOWN)) {
this.linkBinding.feedDown();
}
}
@Override
public void pullDown() {
stage().execute(new WarpUplinkModemPullDown(this));
}
protected void runPullDown() {
try {
pullDownEnvelope();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
didFail(error);
} else {
throw error;
}
}
}
protected void pullDownEnvelope() {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
if ((oldStatus & UNLINKING) != 0) {
newStatus = oldStatus & ~UNLINKING;
} else if ((oldStatus & LINKING) != 0) {
newStatus = oldStatus & ~LINKING;
} else {
newStatus = oldStatus;
break;
}
} while (!STATUS.compareAndSet(this, oldStatus, newStatus));
if ((oldStatus & UNLINKING) != (newStatus & UNLINKING)) {
final UnlinkedResponse response = unlinkedResponse();
pullDownUnlinked(response);
this.linkBinding.pushDown(response);
} else if ((oldStatus & LINKING) != (newStatus & LINKING)) {
final LinkedResponse response = linkedResponse();
pullDownLinked(response);
this.linkBinding.pushDown(response);
if ((newStatus & SYNCING) != 0) {
this.linkBinding.feedDown();
} else {
do {
oldStatus = this.status;
if ((oldStatus & CUED_DOWN) == 0 && downQueueIsEmpty()) {
newStatus = oldStatus & ~FEEDING_DOWN;
} else {
newStatus = oldStatus;
break;
}
} while (!STATUS.compareAndSet(this, oldStatus, newStatus));
if (oldStatus == newStatus) {
this.linkBinding.feedDown();
}
}
} else {
EventMessage message = nextDownQueueEvent();
if (message == null && (oldStatus & CUED_DOWN) != 0) {
do {
oldStatus = this.status;
newStatus = oldStatus & ~CUED_DOWN;
} while (!STATUS.compareAndSet(this, oldStatus, newStatus));
message = nextDownCueEvent();
}
if (message != null) {
pullDownEvent(message);
this.linkBinding.pushDown(message);
do {
oldStatus = this.status;
if ((oldStatus & (SYNCING | CUED_DOWN)) == 0 && downQueueIsEmpty()) {
newStatus = oldStatus & ~FEEDING_DOWN;
} else {
newStatus = oldStatus | FEEDING_DOWN;
}
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
if ((newStatus & FEEDING_DOWN) != 0) {
this.linkBinding.feedDown();
}
} else if ((oldStatus & SYNCING) != 0) {
final SyncedResponse response = syncedResponse();
pullDownSynced(response);
this.linkBinding.pushDown(response);
do {
oldStatus = this.status;
if ((oldStatus & CUED_DOWN) == 0 && downQueueIsEmpty()) {
newStatus = oldStatus & ~(SYNCING | FEEDING_DOWN);
} else {
newStatus = oldStatus & ~SYNCING;
}
} while (!STATUS.compareAndSet(this, oldStatus, newStatus));
if ((newStatus & FEEDING_DOWN) != 0) {
this.linkBinding.feedDown();
}
} else {
this.linkBinding.skipDown();
do {
oldStatus = this.status;
if ((oldStatus & CUED_DOWN) == 0 && downQueueIsEmpty()) {
newStatus = oldStatus & ~FEEDING_DOWN;
} else {
newStatus = oldStatus;
break;
}
} while (!STATUS.compareAndSet(this, oldStatus, newStatus));
if ((newStatus & FEEDING_DOWN) != 0) {
this.linkBinding.feedDown();
}
}
}
}
protected void pullDownEvent(EventMessage message) {
onEvent(message);
dispatchOnEvent(message);
}
protected void pullDownLinked(LinkedResponse response) {
didLink(response);
dispatchOnLinked(response);
}
protected void pullDownSynced(SyncedResponse response) {
didSync(response);
dispatchOnSynced(response);
}
protected void pullDownUnlinked(UnlinkedResponse response) {
didUnlink(response);
dispatchOnUnlinked(response);
}
public void cueUp() {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
if ((oldStatus & FEEDING_UP) != 0) {
newStatus = oldStatus & ~FEEDING_UP | PULLING_UP;
} else {
newStatus = oldStatus & ~PULLING_UP;
}
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
if ((oldStatus & FEEDING_UP) != 0) {
this.linkBinding.pullUp();
}
}
@Override
public void feedUp() {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
if ((oldStatus & PULLING_UP) == 0) {
newStatus = oldStatus & ~FEEDING_UP | PULLING_UP;
} else {
newStatus = oldStatus | FEEDING_UP;
}
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
if ((oldStatus & PULLING_UP) == 0) {
this.linkBinding.pullUp();
}
}
@Override
public void pushUp(Envelope envelope) {
if (envelope instanceof CommandMessage) {
pushUpCommand((CommandMessage) envelope);
} else if (envelope instanceof LinkRequest) {
pushUpLink((LinkRequest) envelope);
} else if (envelope instanceof SyncRequest) {
pushUpSync((SyncRequest) envelope);
} else if (envelope instanceof UnlinkRequest) {
pushUpUnlink((UnlinkRequest) envelope);
} else {
pushUpEnvelope(envelope);
}
}
protected void pushUpCommand(CommandMessage message) {
onCommand(message);
laneBinding().pushUpCommand(message);
if (!dispatchOnCommand(message, true)) {
stage().execute(new WarpUplinkModemOnCommand(this, message));
} else {
cueUp();
}
}
protected void runOnCommand(CommandMessage message) {
try {
dispatchOnCommand(message, false);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
didFail(error);
} else {
throw error;
}
} finally {
cueUp();
}
}
protected void pushUpLink(LinkRequest request) {
willLink(request);
if (!dispatchOnLink(request, true)) {
stage().execute(new WarpUplinkModemOnLink(this, request));
} else {
cueUp();
}
}
protected void runOnLink(LinkRequest request) {
try {
dispatchOnLink(request, false);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
didFail(error);
} else {
throw error;
}
} finally {
cueUp();
}
}
protected void pushUpSync(SyncRequest request) {
willSync(request);
if (!dispatchOnSync(request, true)) {
stage().execute(new WarpUplinkModemOnSync(this, request));
} else {
cueUp();
}
}
protected void runOnSync(SyncRequest request) {
try {
dispatchOnSync(request, false);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
didFail(error);
} else {
throw error;
}
} finally {
cueUp();
}
}
protected void pushUpUnlink(UnlinkRequest request) {
willUnlink(request);
if (!dispatchOnUnlink(request, true)) {
stage().execute(new WarpUplinkModemOnUnlink(this, request));
}
}
protected void runOnUnlink(UnlinkRequest request) {
try {
dispatchOnUnlink(request, false);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
didFail(error);
} else {
throw error;
}
}
}
protected void pushUpEnvelope(Envelope envelope) {
cueUp();
}
@Override
public void skipUp() {
cueUp();
}
public void unlink() {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
newStatus = oldStatus & ~(SYNCING | LINKING | LINKED) | FEEDING_DOWN | UNLINKING;
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
if ((oldStatus & FEEDING_DOWN) == 0) {
this.linkBinding.feedDown();
}
if ((oldStatus & FEEDING_UP) != 0) {
this.linkBinding.pullUp();
}
}
protected void onEvent(EventMessage message) {
// stub
}
protected void onCommand(CommandMessage message) {
// stub
}
protected void willLink(LinkRequest request) {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
if ((oldStatus & FEEDING_UP) == 0) {
newStatus = oldStatus & ~PULLING_UP | FEEDING_DOWN | LINKING | LINKED;
} else {
newStatus = oldStatus | FEEDING_DOWN | LINKING | LINKED;
}
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
if ((oldStatus & FEEDING_DOWN) == 0) {
this.linkBinding.feedDown();
}
if ((oldStatus & FEEDING_UP) != 0) {
this.linkBinding.pullUp();
}
}
protected void didLink(LinkedResponse response) {
// stub
}
protected void willSync(SyncRequest request) {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
if ((oldStatus & LINKED) == 0) {
if ((oldStatus & FEEDING_UP) == 0) {
newStatus = oldStatus & ~PULLING_UP | FEEDING_DOWN | SYNCING | LINKING | LINKED;
} else {
newStatus = oldStatus | FEEDING_DOWN | SYNCING | LINKING | LINKED;
}
} else {
if ((oldStatus & FEEDING_UP) == 0) {
newStatus = oldStatus & ~PULLING_UP | FEEDING_DOWN | SYNCING;
} else {
newStatus = oldStatus | FEEDING_DOWN | SYNCING;
}
}
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
if ((oldStatus & FEEDING_DOWN) == 0) {
this.linkBinding.feedDown();
}
if ((oldStatus & FEEDING_UP) != 0) {
this.linkBinding.pullUp();
}
}
protected void didSync(SyncedResponse response) {
// stub
}
protected void willUnlink(UnlinkRequest request) {
int oldStatus;
int newStatus;
do {
oldStatus = this.status;
if ((oldStatus & FEEDING_UP) == 0) {
newStatus = oldStatus & ~(PULLING_UP | SYNCING | LINKING | LINKED) | FEEDING_DOWN | UNLINKING;
} else {
newStatus = oldStatus & ~(SYNCING | LINKING | LINKED) | FEEDING_DOWN | UNLINKING;
}
} while (oldStatus != newStatus && !STATUS.compareAndSet(this, oldStatus, newStatus));
if ((oldStatus & FEEDING_DOWN) == 0) {
this.linkBinding.feedDown();
}
if ((oldStatus & FEEDING_UP) != 0) {
this.linkBinding.pullUp();
}
}
protected void didUnlink(UnlinkedResponse response) {
close();
}
protected LinkedResponse linkedResponse() {
return new LinkedResponse(nodeUri(), laneUri(), prio(), rate(), body());
}
protected SyncedResponse syncedResponse() {
return new SyncedResponse(nodeUri(), laneUri());
}
protected UnlinkedResponse unlinkedResponse() {
return new UnlinkedResponse(nodeUri(), laneUri());
}
static final int LINKED = 1 << 0;
static final int LINKING = 1 << 1;
static final int SYNCING = 1 << 2;
static final int UNLINKING = 1 << 3;
static final int CUED_DOWN = 1 << 4;
static final int FEEDING_DOWN = 1 << 5;
static final int FEEDING_UP = 1 << 6;
static final int PULLING_UP = 1 << 7;
static final AtomicIntegerFieldUpdater<WarpUplinkModem> STATUS =
AtomicIntegerFieldUpdater.newUpdater(WarpUplinkModem.class, "status");
}
final class WarpUplinkModemPullDown implements Runnable {
final WarpUplinkModem uplink;
WarpUplinkModemPullDown(WarpUplinkModem uplink) {
this.uplink = uplink;
}
@Override
public void run() {
uplink.runPullDown();
}
}
final class WarpUplinkModemOnCommand implements Runnable {
final WarpUplinkModem uplink;
final CommandMessage message;
WarpUplinkModemOnCommand(WarpUplinkModem uplink, CommandMessage message) {
this.uplink = uplink;
this.message = message;
}
@Override
public void run() {
uplink.runOnCommand(message);
}
}
final class WarpUplinkModemOnLink implements Runnable {
final WarpUplinkModem uplink;
final LinkRequest request;
WarpUplinkModemOnLink(WarpUplinkModem uplink, LinkRequest request) {
this.uplink = uplink;
this.request = request;
}
@Override
public void run() {
uplink.runOnLink(request);
}
}
final class WarpUplinkModemOnSync implements Runnable {
final WarpUplinkModem uplink;
final SyncRequest request;
WarpUplinkModemOnSync(WarpUplinkModem uplink, SyncRequest request) {
this.uplink = uplink;
this.request = request;
}
@Override
public void run() {
uplink.runOnSync(request);
}
}
final class WarpUplinkModemOnUnlink implements Runnable {
final WarpUplinkModem uplink;
final UnlinkRequest request;
WarpUplinkModemOnUnlink(WarpUplinkModem uplink, UnlinkRequest request) {
this.uplink = uplink;
this.request = request;
}
@Override
public void run() {
uplink.runOnUnlink(request);
}
}
|
0 | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime | java-sources/ai/swim/swim-runtime/3.10.0/swim/runtime/warp/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.
/**
* WARP lane and downlink runtime implementations.
*/
package swim.runtime.warp;
|
0 | java-sources/ai/swim/swim-security | java-sources/ai/swim/swim-security/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.
/**
* Cryptographic security model.
*/
module swim.security {
requires swim.util;
requires transitive swim.codec;
requires transitive swim.structure;
requires transitive swim.recon;
requires transitive swim.json;
requires transitive swim.collections;
exports swim.security;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.