index int64 | repo_id string | file_path string | content string |
|---|---|---|---|
0 | java-sources/ai/swim/swim-http/3.10.0/swim/http | java-sources/ai/swim/swim-http/3.10.0/swim/http/header/UserAgentParser.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.http.header;
import swim.codec.Input;
import swim.codec.Parser;
import swim.collections.FingerTrieSeq;
import swim.http.Http;
import swim.http.HttpParser;
import swim.http.Product;
import swim.util.Builder;
final class UserAgentParser extends Parser<UserAgent> {
final HttpParser http;
final Parser<Product> product;
final Builder<Product, FingerTrieSeq<Product>> products;
final int step;
UserAgentParser(HttpParser http, Parser<Product> product,
Builder<Product, FingerTrieSeq<Product>> products, int step) {
this.http = http;
this.product = product;
this.products = products;
this.step = step;
}
UserAgentParser(HttpParser http) {
this(http, null, null, 1);
}
@Override
public Parser<UserAgent> feed(Input input) {
return parse(input, this.http, this.product, this.products, this.step);
}
static Parser<UserAgent> parse(Input input, HttpParser http, Parser<Product> product,
Builder<Product, FingerTrieSeq<Product>> products, int step) {
int c = 0;
if (step == 1) {
if (product == null) {
product = http.parseProduct(input);
} else {
product = product.feed(input);
}
if (product.isDone()) {
if (products == null) {
products = FingerTrieSeq.builder();
}
products.add(product.bind());
product = null;
step = 2;
} else if (product.isError()) {
return product.asError();
}
}
do {
if (step == 2) {
while (input.isCont()) {
c = input.head();
if (Http.isSpace(c)) {
input = input.step();
} else {
break;
}
}
if (input.isCont() && Http.isTokenChar(c)) {
step = 3;
} else if (!input.isEmpty()) {
return done(UserAgent.from(products.bind()));
}
}
if (step == 3) {
if (product == null) {
product = http.parseProduct(input);
} else {
product = product.feed(input);
}
if (product.isDone()) {
products.add(product.bind());
product = null;
step = 2;
continue;
} else if (product.isError()) {
return product.asError();
}
}
break;
} while (true);
if (input.isError()) {
return error(input.trap());
}
return new UserAgentParser(http, product, products, step);
}
static Parser<UserAgent> parse(Input input, HttpParser http) {
return parse(input, http, null, null, 1);
}
}
|
0 | java-sources/ai/swim/swim-http/3.10.0/swim/http | java-sources/ai/swim/swim-http/3.10.0/swim/http/header/UserAgentWriter.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.http.header;
import java.util.Iterator;
import swim.codec.Output;
import swim.codec.Writer;
import swim.codec.WriterException;
import swim.http.HttpWriter;
import swim.http.Product;
final class UserAgentWriter extends Writer<Object, Object> {
final HttpWriter http;
final Iterator<Product> products;
final Writer<?, ?> part;
final int step;
UserAgentWriter(HttpWriter http, Iterator<Product> products, Writer<?, ?> part, int step) {
this.http = http;
this.products = products;
this.part = part;
this.step = step;
}
@Override
public Writer<Object, Object> pull(Output<?> output) {
return write(output, this.http, this.products, this.part, this.step);
}
static Writer<Object, Object> write(Output<?> output, HttpWriter http, Iterator<Product> products,
Writer<?, ?> part, int step) {
do {
if (step == 1) {
if (part == null) {
if (!products.hasNext()) {
return done();
} else {
part = products.next().writeHttp(output, http);
}
} else {
part = part.pull(output);
}
if (part.isDone()) {
part = null;
if (!products.hasNext()) {
return done();
} else {
step = 2;
}
} else if (part.isError()) {
return part.asError();
}
}
if (step == 2 && output.isCont()) {
output = output.write(' ');
step = 1;
continue;
}
break;
} while (true);
if (output.isDone()) {
return error(new WriterException("truncated"));
} else if (output.isError()) {
return error(output.trap());
}
return new UserAgentWriter(http, products, part, step);
}
static Writer<Object, Object> write(Output<?> output, HttpWriter http, Iterator<Product> products) {
return write(output, http, products, null, 1);
}
}
|
0 | java-sources/ai/swim/swim-http/3.10.0/swim/http | java-sources/ai/swim/swim-http/3.10.0/swim/http/header/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 header models.
*/
package swim.http.header;
|
0 | java-sources/ai/swim/swim-io | java-sources/ai/swim/swim-io/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.
/**
* Flow-controlled input/output library.
*/
module swim.io {
requires swim.util;
requires transitive swim.codec;
requires transitive swim.structure;
requires transitive swim.concurrent;
exports swim.io;
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/AbstractIpModem.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.io;
import java.net.InetSocketAddress;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.Collection;
import swim.codec.Decoder;
import swim.codec.Encoder;
public abstract class AbstractIpModem<I, O> implements IpModem<I, O>, IpContext, FlowContext {
protected IpModemContext<I, O> context;
@Override
public IpModemContext<I, O> ipModemContext() {
return this.context;
}
@Override
public void setIpModemContext(IpModemContext<I, O> context) {
this.context = context;
}
@Override
public long idleTimeout() {
return -1L; // default timeout
}
@Override
public void doRead() {
// stub
}
@Override
public void didRead(I input) {
// stub
}
@Override
public void doWrite() {
// stub
}
@Override
public void didWrite(O output) {
// stub
}
@Override
public void willConnect() {
// stub
}
@Override
public void didConnect() {
// stub
}
@Override
public void willSecure() {
// stub
}
@Override
public void didSecure() {
// stub
}
@Override
public void willBecome(IpSocket socket) {
// stub
}
@Override
public void didBecome(IpSocket socket) {
// stub
}
@Override
public void didTimeout() {
// stub
}
@Override
public void didDisconnect() {
// stub
}
@Override
public void didFail(Throwable error) {
error.printStackTrace();
}
@Override
public boolean isConnected() {
return this.context.isConnected();
}
@Override
public boolean isClient() {
return this.context.isClient();
}
@Override
public boolean isServer() {
return this.context.isServer();
}
@Override
public boolean isSecure() {
return this.context.isSecure();
}
@Override
public String securityProtocol() {
return this.context.securityProtocol();
}
@Override
public String cipherSuite() {
return this.context.cipherSuite();
}
@Override
public InetSocketAddress localAddress() {
return this.context.localAddress();
}
@Override
public Principal localPrincipal() {
return this.context.localPrincipal();
}
@Override
public Collection<Certificate> localCertificates() {
return this.context.localCertificates();
}
@Override
public InetSocketAddress remoteAddress() {
return this.context.remoteAddress();
}
@Override
public Principal remotePrincipal() {
return this.context.remotePrincipal();
}
@Override
public Collection<Certificate> remoteCertificates() {
return this.context.remoteCertificates();
}
@Override
public FlowControl flowControl() {
return this.context.flowControl();
}
@Override
public void flowControl(FlowControl flowControl) {
this.context.flowControl(flowControl);
}
@Override
public FlowControl flowControl(FlowModifier flowModifier) {
return this.context.flowControl(flowModifier);
}
public IpSettings ipSettings() {
return this.context.ipSettings();
}
public <I2 extends I> void read(Decoder<I2> decoder) {
this.context.read(decoder);
}
public <O2 extends O> void write(Encoder<?, O2> encoder) {
this.context.write(encoder);
}
public void become(IpSocket socket) {
this.context.become(socket);
}
public void close() {
this.context.close();
}
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/AbstractIpService.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.io;
import java.net.InetSocketAddress;
public abstract class AbstractIpService implements IpService, FlowContext {
protected IpServiceContext context;
@Override
public IpServiceContext ipServiceContext() {
return this.context;
}
@Override
public void setIpServiceContext(IpServiceContext context) {
this.context = context;
}
@SuppressWarnings("unchecked")
@Override
public IpSocket createSocket() {
final IpModem<?, ?> modem = createModem();
if (modem != null) {
return new IpSocketModem<Object, Object>((IpModem<Object, Object>) modem);
} else {
throw new UnsupportedOperationException();
}
}
public IpModem<?, ?> createModem() {
return null;
}
@Override
public void didBind() {
// stub
}
@Override
public void didAccept(IpSocket socket) {
// stub
}
@Override
public void didUnbind() {
// stub
}
@Override
public void didFail(Throwable error) {
error.printStackTrace();
}
@Override
public FlowControl flowControl() {
return this.context.flowControl();
}
@Override
public void flowControl(FlowControl flowControl) {
this.context.flowControl(flowControl);
}
@Override
public FlowControl flowControl(FlowModifier flowModifier) {
return this.context.flowControl(flowModifier);
}
public IpSettings ipSettings() {
return this.context.ipSettings();
}
public InetSocketAddress localAddress() {
return this.context.localAddress();
}
public void unbind() {
this.context.unbind();
}
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/AbstractIpSocket.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.io;
import java.net.InetSocketAddress;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.Collection;
import swim.codec.InputBuffer;
import swim.codec.OutputBuffer;
public abstract class AbstractIpSocket implements IpSocket, IpContext, FlowContext {
protected IpSocketContext context;
@Override
public IpSocketContext ipSocketContext() {
return this.context;
}
@Override
public void setIpSocketContext(IpSocketContext context) {
this.context = context;
}
@Override
public long idleTimeout() {
return -1L; // default timeout
}
@Override
public void doRead() {
// stub
}
@Override
public void doWrite() {
// stub
}
@Override
public void didWrite() {
// stub
}
@Override
public void willConnect() {
// stub
}
@Override
public void didConnect() {
// stub
}
@Override
public void willSecure() {
// stub
}
@Override
public void didSecure() {
// stub
}
@Override
public void willBecome(IpSocket socket) {
// stub
}
@Override
public void didBecome(IpSocket socket) {
// stub
}
@Override
public void didTimeout() {
// stub
}
@Override
public void didDisconnect() {
// stub
}
@Override
public void didFail(Throwable error) {
error.printStackTrace();
}
@Override
public boolean isConnected() {
return this.context.isConnected();
}
@Override
public boolean isClient() {
return this.context.isClient();
}
@Override
public boolean isServer() {
return this.context.isServer();
}
@Override
public boolean isSecure() {
return this.context.isSecure();
}
@Override
public String securityProtocol() {
return this.context.securityProtocol();
}
@Override
public String cipherSuite() {
return this.context.cipherSuite();
}
@Override
public InetSocketAddress localAddress() {
return this.context.localAddress();
}
@Override
public Principal localPrincipal() {
return this.context.localPrincipal();
}
@Override
public Collection<Certificate> localCertificates() {
return this.context.localCertificates();
}
@Override
public InetSocketAddress remoteAddress() {
return this.context.remoteAddress();
}
@Override
public Principal remotePrincipal() {
return this.context.remotePrincipal();
}
@Override
public Collection<Certificate> remoteCertificates() {
return this.context.remoteCertificates();
}
@Override
public FlowControl flowControl() {
return this.context.flowControl();
}
@Override
public void flowControl(FlowControl flowControl) {
this.context.flowControl(flowControl);
}
@Override
public FlowControl flowControl(FlowModifier flowModifier) {
return this.context.flowControl(flowModifier);
}
public IpSettings ipSettings() {
return this.context.ipSettings();
}
public InputBuffer inputBuffer() {
return this.context.inputBuffer();
}
public OutputBuffer<?> outputBuffer() {
return this.context.outputBuffer();
}
public void become(IpSocket socket) {
this.context.become(socket);
}
public void close() {
this.context.close();
}
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/ClientAuth.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.io;
import swim.codec.Debug;
import swim.codec.Output;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Text;
import swim.structure.Value;
/**
* Transport-layer security client authentication configuration.
*/
public enum ClientAuth implements Debug {
/**
* Client authentication disabled.
*/
NONE,
/**
* Client authentication requested.
*/
WANT,
/**
* Client authentication required.
*/
NEED;
@Override
public void debug(Output<?> output) {
output = output.write("ClientAuth").write('.').write(name());
}
private static Form<ClientAuth> form = new ClientAuthForm();
/**
* Returns the {@code ClientAuth} with the given case-insensitive {@code
* name}, one of <em>none</em>, <em>want</em>, or <em>need</em>.
*
* @throws IllegalArgumentException if {@code name} is not a valid {@code
* ClientAuth} token.
*/
public static ClientAuth from(String name) {
if ("none".equalsIgnoreCase(name)) {
return NONE;
} else if ("want".equalsIgnoreCase(name)) {
return WANT;
} else if ("need".equalsIgnoreCase(name)) {
return NEED;
} else {
throw new IllegalArgumentException(name);
}
}
/**
* Returns the structural {@code Form} of {@code ClientAuth}.
*/
@Kind
public static Form<ClientAuth> form() {
if (form == null) {
form = new ClientAuthForm();
}
return form;
}
}
final class ClientAuthForm extends Form<ClientAuth> {
@Override
public Class<?> type() {
return ClientAuth.class;
}
@Override
public ClientAuth unit() {
return ClientAuth.NONE;
}
@Override
public Item mold(ClientAuth clientAuth) {
if (clientAuth != null) {
switch (clientAuth) {
case NONE: return Text.from("none");
case WANT: return Text.from("want");
case NEED: return Text.from("need");
default: return Item.absent();
}
} else {
return Item.extant();
}
}
@Override
public ClientAuth cast(Item item) {
final Value value = item.target();
final String string = value.stringValue(null);
if ("none".equalsIgnoreCase(string)) {
return ClientAuth.NONE;
} else if ("want".equalsIgnoreCase(string)) {
return ClientAuth.WANT;
} else if ("need".equalsIgnoreCase(string)) {
return ClientAuth.NEED;
} else {
return null;
}
}
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/FlowContext.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.io;
/**
* Flow-controlled network channel context.
*
* @see FlowControl
* @see FlowModifier
*/
public interface FlowContext {
/**
* Returns the current {@code FlowControl} state of the underlying network
* channel.
*/
FlowControl flowControl();
/**
* Enqueues an atomic replacement of the underlying network channel's flow
* control state with a new {@code flowControl}.
*/
void flowControl(FlowControl flowControl);
/**
* Enqueues an atomic modification to the underlying network channel's flow
* control state by applying a {@code flowModifier} delta.
*/
FlowControl flowControl(FlowModifier flowModifier);
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/FlowControl.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.io;
import java.nio.channels.SelectionKey;
import swim.codec.Debug;
import swim.codec.Output;
/**
* Network channel flow state, controlling <em>accept</em>, <em>connect</em>,
* <em>read</em>, and <em>write</em> operations.
*
* @see FlowModifier
* @see FlowContext
*/
public enum FlowControl implements Debug {
/**
* <em>accept</em>, <em>connect</em>, <em>read</em>, and <em>write</em> disabled.
*/
WAIT(0x0),
/**
* <em>accept</em> enabled; <em>connect</em>, <em>read</em>, and <em>write</em> disabled.
*/
ACCEPT(0x1),
/**
* <em>connect</em> enabled; <em>accept</em>, <em>read</em>, and <em>write</em> disabled.
*/
CONNECT(0x2),
/**
* <em>accept</em> and <em>connect</em> enabled; <em>read</em> and <em>write</em> disabled.
*/
ACCEPT_CONNECT(0x3),
/**
* <em>read</em> enabled; <em>accept</em>, <em>connect</em>, and <em>write</em> disabled.
*/
READ(0x4),
/**
* <em>accept</em> and <em>read</em> enabled; <em>connect</em> and <em>write</em> disabled.
*/
ACCEPT_READ(0x5),
/**
* <em>connect</em> and <em>read</em> enabled; <em>accept</em> and <em>write</em> disabled.
*/
CONNECT_READ(0x6),
/**
* <em>accept</em>, <em>connect</em>, and <em>read</em> enabled; <em>write</em> disabled.
*/
ACCEPT_CONNECT_READ(0x7),
/**
* <em>write</em> enabled; <em>accept</em>, <em>connect</em>, and <em>read</em> disabled.
*/
WRITE(0x8),
/**
* <em>accept</em> and <em>write</em> enabled; <em>connect</em> and <em>read</em> disabled.
*/
ACCEPT_WRITE(0x9),
/**
* <em>connect</em> and <em>write</em> enabled; <em>accept</em> and <em>read</em> disabled.
*/
CONNECT_WRITE(0xa),
/**
* <em>accept</em>, <em>connect</em>, and <em>write</em> enabled; <em>read</em> disabled.
*/
ACCEPT_CONNECT_WRITE(0xb),
/**
* <em>read</em> and <em>write</em> enabled; <em>accept</em> and <em>connect</em> disabled.
*/
READ_WRITE(0xc),
/**
* <em>accept</em>, <em>read</em>, and <em>write</em> enabled; <em>connect</em> disabled.
*/
ACCEPT_READ_WRITE(0xd),
/**
* <em>connect</em>, <em>read</em>, and <em>write</em> enabled; <em>accept</em> disabled.
*/
CONNECT_READ_WRITE(0xe),
/**
* <em>accept</em>, <em>connect</em>, <em>read</em>, and <em>write</em> enabled.
*/
ACCEPT_CONNECT_READ_WRITE(0xf);
private final int flags;
FlowControl(int flags) {
this.flags = flags;
}
/**
* Returns {@code true} if the <em>accept</em> operation is enabled.
*/
public boolean isAcceptEnabled() {
return (this.flags & 0x1) != 0;
}
/**
* Returns {@code true} if the <em>connect</em> operation is enabled.
*/
public boolean isConnectEnabled() {
return (this.flags & 0x2) != 0;
}
/**
* Returns {@code true} if the <em>read</em> operation is enabled.
*/
public boolean isReadEnabled() {
return (this.flags & 0x4) != 0;
}
/**
* Returns {@code true} if the <em>write</em> operation is enabled.
*/
public boolean isWriteEnabled() {
return (this.flags & 0x8) != 0;
}
/**
* Returns an updated {@code FlowControl} with its <em>accept</em> operation disabled.
*/
public FlowControl acceptDisabled() {
return fromFlags(this.flags & ~0x1);
}
/**
* Returns an updated {@code FlowControl} with its <em>accept</em> operation enabled.
*/
public FlowControl acceptEnabled() {
return fromFlags(this.flags | 0x1);
}
/**
* Returns an updated {@code FlowControl} with its <em>connect</em> operation disabled.
*/
public FlowControl connectDisabled() {
return fromFlags(this.flags & ~0x2);
}
/**
* Returns an updated {@code FlowControl} with its <em>connect</em> operation enabled.
*/
public FlowControl connectEnabled() {
return fromFlags(this.flags | 0x2);
}
/**
* Returns an updated {@code FlowControl} with its <em>read</em> operation disabled.
*/
public FlowControl readDisabled() {
return fromFlags(this.flags & ~0x4);
}
/**
* Returns an updated {@code FlowControl} with its <em>read</em> operation enabled.
*/
public FlowControl readEnabled() {
return fromFlags(this.flags | 0x4);
}
/**
* Returns an updated {@code FlowControl} with its <em>write</em> operation disabled.
*/
public FlowControl writeDisabled() {
return fromFlags(this.flags & ~0x8);
}
/**
* Returns an updated {@code FlowControl} with its <em>write</em> operation enabled.
*/
public FlowControl writeEnabled() {
return fromFlags(this.flags | 0x8);
}
/**
* Returns an updated {@code FlowControl} with its <em>read</em> and
* <em>write</em> operations patched by a {@code flowModifier} delta.
*/
public FlowControl modify(FlowModifier flowModifier) {
int flags = this.flags;
if (flowModifier.isReadDisabled()) {
flags &= ~0x4;
}
if (flowModifier.isWriteDisabled()) {
flags &= ~0x8;
}
if (flowModifier.isReadEnabled()) {
flags |= 0x4;
}
if (flowModifier.isWriteEnabled()) {
flags |= 0x8;
}
return fromFlags(flags);
}
/**
* Returns the {@code FlowControl} with all operations enabled in {@code
* this} or {@code that} enabled.
*/
public FlowControl or(FlowControl that) {
return fromFlags(this.flags | that.flags);
}
/**
* Returns the {@code FlowControl} with all operations enabled in {@code
* this} or {@code that}—but not both—enabled.
*/
public FlowControl xor(FlowControl that) {
return fromFlags(this.flags ^ that.flags);
}
/**
* Returns the {@code FlowControl} with all operations enabled in {@code
* this} and {@code that} enabled.
*/
public FlowControl and(FlowControl that) {
return fromFlags(this.flags & that.flags);
}
/**
* Returns the {@code FlowControl} with all operations enabled in {@code
* this} disabled, and all operations disabled in {@code this} enabled.
*/
public FlowControl not() {
return fromFlags(~this.flags & 0xf);
}
/**
* Returns the {@link SelectionKey} interest set corresponding to this
* {@code FlowControl}.
*/
public int toSelectorOps() {
final int flags = this.flags;
int selectorOps = 0;
if ((flags & 0x1) != 0) {
selectorOps |= SelectionKey.OP_ACCEPT;
}
if ((flags & 0x2) != 0) {
selectorOps |= SelectionKey.OP_CONNECT;
}
if ((flags & 0x4) != 0) {
selectorOps |= SelectionKey.OP_READ;
}
if ((flags & 0x8) != 0) {
selectorOps |= SelectionKey.OP_WRITE;
}
return selectorOps;
}
@Override
public void debug(Output<?> output) {
output = output.write("FlowControl").write('.').write(name());
}
private static FlowControl fromFlags(int flags) {
switch (flags) {
case 0x0: return WAIT;
case 0x1: return ACCEPT;
case 0x2: return CONNECT;
case 0x3: return ACCEPT_CONNECT;
case 0x4: return READ;
case 0x5: return ACCEPT_READ;
case 0x6: return CONNECT_READ;
case 0x7: return ACCEPT_CONNECT_READ;
case 0x8: return WRITE;
case 0x9: return ACCEPT_WRITE;
case 0xa: return CONNECT_WRITE;
case 0xb: return ACCEPT_CONNECT_WRITE;
case 0xc: return READ_WRITE;
case 0xd: return ACCEPT_READ_WRITE;
case 0xe: return CONNECT_READ_WRITE;
case 0xf: return ACCEPT_CONNECT_READ_WRITE;
default: throw new IllegalArgumentException("0x" + Integer.toHexString(flags));
}
}
/**
* Returns the {@code FlowControl} corresponding to the given {@link
* SelectionKey} interest set.
*/
public static FlowControl fromSelectorOps(int selectorOps) {
int flags = 0;
if ((selectorOps & SelectionKey.OP_ACCEPT) != 0) {
flags |= 0x1;
}
if ((selectorOps & SelectionKey.OP_CONNECT) != 0) {
flags |= 0x2;
}
if ((selectorOps & SelectionKey.OP_READ) != 0) {
flags |= 0x4;
}
if ((selectorOps & SelectionKey.OP_WRITE) != 0) {
flags |= 0x8;
}
return fromFlags(flags);
}
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/FlowModifier.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.io;
import swim.codec.Debug;
import swim.codec.Output;
/**
* Network channel flow delta, modifying <em>read</em> and <em>write</em>
* operations. Represents an atomic change to a {@code FlowControl} state.
*
* @see FlowControl
* @see FlowContext
*/
public enum FlowModifier implements Debug {
/**
* <em>read</em> and <em>write</em> operations should not be modified.
*/
RESELECT(0x0),
/**
* <em>read</em> operation should be disabled; <em>write</em> operation
* should not be modified.
*/
DISABLE_READ(0x1),
/**
* <em>write</em> operation should be disabled; <em>read</em> operation
* should not be modified.
*/
DISABLE_WRITE(0x2),
/**
* <em>read</em> and <em>write</em> operations should be disabled.
*/
DISABLE_READ_WRITE(0x3),
/**
* <em>read</em> operation should be enabled; <em>write</em> operation
* should not be modified.
*/
ENABLE_READ(0x4),
/**
* <em>write</em> operation should be disabled; <em>read</em> operation
* should be enabled.
*/
DISABLE_WRITE_ENABLE_READ(0x6),
/**
* <em>write</em> operation should be enabled; <em>read</em> operation
* should not be modified.
*/
ENABLE_WRITE(0x8),
/**
* <em>read</em> operation should be disabled; <em>write</em> operation
* should be enabled.
*/
DISABLE_READ_ENABLE_WRITE(0x9),
/**
* <em>read</em> and <em>write</em> operations should be enabled.
*/
ENABLE_READ_WRITE(0xc);
private final int flags;
FlowModifier(int flags) {
this.flags = flags;
}
/**
* Returns {@code true} if the <em>read</em> operation should be disabled.
*/
public boolean isReadDisabled() {
return (this.flags & 0x1) != 0;
}
/**
* Returns {@code true} if the <em>write</em> operation should be disabled.
*/
public boolean isWriteDisabled() {
return (this.flags & 0x2) != 0;
}
/**
* Returns {@code true} if the <em>read</em> operation should be enabled.
*/
public boolean isReadEnabled() {
return (this.flags & 0x4) != 0;
}
/**
* Returns {@code true} if the <em>write</em> operation should be enabled.
*/
public boolean isWriteEnabled() {
return (this.flags & 0x8) != 0;
}
/**
* Returns the {@code FlowModifier} with all modifications applied in {@code
* this} or {@code that} applied, with enable instructions taking precedence
* over conflicting disable instructions.
*/
public FlowModifier or(FlowModifier that) {
return fromFlags(this.flags | that.flags);
}
/**
* Returns the {@code FlowModifier} with all modifications applied in {@code
* this} or {@code that}—but not both—applied, with enable instructions
* taking precedence over conflicting disable instructions.
*/
public FlowModifier xor(FlowModifier that) {
return fromFlags(this.flags ^ that.flags);
}
/**
* Returns the {@code FlowModifier} with all modifications applied in {@code
* this} and {@code that} applied, with enable instructions taking precedence
* over conflicting disable instructions.
*/
public FlowModifier and(FlowModifier that) {
return fromFlags(this.flags & that.flags);
}
/**
* Returns the {@code FlowModifier} with all applied modifications in {@code
* this} unapplied, and all unapplied operations in {@code this} applied,
* with enable instructions taking precedence over conflicting disable
* instructions.
*/
public FlowModifier not() {
return fromFlags(~this.flags & 0xf);
}
@Override
public void debug(Output<?> output) {
output = output.write("FlowModifier").write('.').write(name());
}
private static FlowModifier fromFlags(int flags) {
if ((flags ^ 0x5) == 0) {
flags &= ~0x1; // ENABLE_READ takes precedence over DISABLE_READ
}
if ((flags ^ 0xa) == 0) {
flags &= ~0x2; // ENABLE_WRITE takes precedence over DISABLE_WRITE
}
switch (flags) {
case 0x0: return RESELECT;
case 0x1: return DISABLE_READ;
case 0x2: return DISABLE_WRITE;
case 0x3: return DISABLE_READ_WRITE;
case 0x4: return ENABLE_READ;
case 0x6: return DISABLE_WRITE_ENABLE_READ;
case 0x8: return ENABLE_WRITE;
case 0x9: return DISABLE_READ_ENABLE_WRITE;
case 0xc: return ENABLE_READ_WRITE;
default: throw new IllegalArgumentException("0x" + Integer.toHexString(flags));
}
}
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/IpContext.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.io;
import java.net.InetSocketAddress;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.Collection;
/**
* IP network connection context.
*/
public interface IpContext {
/**
* Returns {@code true} if the underlying network channel is currently
* connected.
*/
boolean isConnected();
/**
* Returns {@code true} if the underlying network channel initiated an
* outgoing connection.
*/
boolean isClient();
/**
* Returns {@code true} if the underlying network channel accepted an
* incoming connection.
*/
boolean isServer();
/**
* Returns {@code true} if the underlying network transport is encrypted.
*/
boolean isSecure();
/**
* Returns the name of the transport-layer security protocol used by the
* underlying network connection. Returns {@code null} if the underlying
* network channel is not currently connected, or if the underlying network
* connection is not secure.
*/
String securityProtocol();
/**
* Returns the cryptographic cipher suite used by the underlying network
* connection. Returns {@code null} if the underlying network channel is not
* currently connected, or if the underlying network connection is not secure.
*/
String cipherSuite();
/**
* Returns the IP address and port of the local endpoint of the underlying
* network connection. Returns {@code null} if the underlying network
* channel is not currently connected.
*/
InetSocketAddress localAddress();
/**
* Returns the authenticated identity of the local endpoint of the
* underlying network connection. Returns {@code null} if the underlying
* network channel is not currently connected, or if the underlying network
* connection is not authenticated.
*/
Principal localPrincipal();
/**
* Returns the certificate chain used to authenticate the local endpoint of
* the underlying network connection. Returns {@code null} if the underlying
* network channel is not currently connected, or if the underlying network
* connection is not authenticated.
*/
Collection<Certificate> localCertificates();
/**
* Returns the IP address and port of the remote endpoint of the underlying
* network connection. Returns {@code null} if the underlying network
* channel is not currently connected.
*/
InetSocketAddress remoteAddress();
/**
* Returns the authenticated identity of the remote endpoint of the
* underlying network connection. Returns {@code null} if the underlying
* network channel is not currently connected, or if the underlying network
* connection is not authenticated.
*/
Principal remotePrincipal();
/**
* Returns the certificate chain used to authenticate the remote endpoint of
* the underlying network connection. Returns {@code null} if the underlying
* network channel is not currently connected, or if the underlying network
* connection is not authenticated.
*/
Collection<Certificate> remoteCertificates();
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/IpEndpoint.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.io;
import swim.concurrent.Stage;
/**
* Network interface for binding and connecting IP sockets and modems.
*/
public class IpEndpoint implements IpStation {
protected final Station station;
protected IpSettings ipSettings;
public IpEndpoint(Station station, IpSettings ipSettings) {
this.station = station;
this.ipSettings = ipSettings;
}
public IpEndpoint(Station station) {
this(station, IpSettings.standard());
}
public IpEndpoint(Stage stage, IpSettings ipSettings) {
this(new Station(stage), ipSettings);
}
public IpEndpoint(Stage stage) {
this(new Station(stage), IpSettings.standard());
}
public final Stage stage() {
return this.station.stage();
}
@Override
public final Station station() {
return this.station;
}
@Override
public final IpSettings ipSettings() {
return this.ipSettings;
}
public void start() {
this.station.start();
}
public void stop() {
this.station.stop();
}
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/IpException.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.io;
public class IpException extends RuntimeException {
private static final long serialVersionUID = 1L;
public IpException(String message, Throwable cause) {
super(message, cause);
}
public IpException(String message) {
super(message);
}
public IpException(Throwable cause) {
super(cause);
}
public IpException() {
super();
}
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/IpInterface.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.io;
import java.net.InetSocketAddress;
public interface IpInterface {
IpSettings ipSettings();
IpServiceRef bindTcp(InetSocketAddress localAddress, IpService service, IpSettings ipSettings);
default IpServiceRef bindTcp(InetSocketAddress localAddress, IpService service) {
return bindTcp(localAddress, service, ipSettings());
}
default IpServiceRef bindTcp(String address, int port, IpService service, IpSettings ipSettings) {
return bindTcp(new InetSocketAddress(address, port), service, ipSettings);
}
default IpServiceRef bindTcp(String address, int port, IpService service) {
return bindTcp(new InetSocketAddress(address, port), service, ipSettings());
}
IpServiceRef bindTls(InetSocketAddress localAddress, IpService service, IpSettings ipSettings);
default IpServiceRef bindTls(InetSocketAddress localAddress, IpService service) {
return bindTls(localAddress, service, ipSettings());
}
default IpServiceRef bindTls(String address, int port, IpService service, IpSettings ipSettings) {
return bindTls(new InetSocketAddress(address, port), service, ipSettings);
}
default IpServiceRef bindTls(String address, int port, IpService service) {
return bindTls(new InetSocketAddress(address, port), service, ipSettings());
}
IpSocketRef connectTcp(InetSocketAddress remoteAddress, IpSocket socket, IpSettings ipSettings);
default IpSocketRef connectTcp(InetSocketAddress remoteAddress, IpSocket socket) {
return connectTcp(remoteAddress, socket, ipSettings());
}
default IpSocketRef connectTcp(String address, int port, IpSocket socket, IpSettings ipSettings) {
return connectTcp(new InetSocketAddress(address, port), socket, ipSettings);
}
default IpSocketRef connectTcp(String address, int port, IpSocket socket) {
return connectTcp(new InetSocketAddress(address, port), socket, ipSettings());
}
default <I, O> IpSocketRef connectTcp(InetSocketAddress remoteAddress, IpModem<I, O> modem, IpSettings ipSettings) {
final IpSocket socket = new IpSocketModem<I, O>(modem);
return connectTcp(remoteAddress, socket, ipSettings);
}
default <I, O> IpSocketRef connectTcp(InetSocketAddress remoteAddress, IpModem<I, O> modem) {
final IpSocket socket = new IpSocketModem<I, O>(modem);
return connectTcp(remoteAddress, socket, ipSettings());
}
default <I, O> IpSocketRef connectTcp(String address, int port, IpModem<I, O> modem, IpSettings ipSettings) {
final IpSocket socket = new IpSocketModem<I, O>(modem);
return connectTcp(new InetSocketAddress(address, port), socket, ipSettings);
}
default <I, O> IpSocketRef connectTcp(String address, int port, IpModem<I, O> modem) {
final IpSocket socket = new IpSocketModem<I, O>(modem);
return connectTcp(new InetSocketAddress(address, port), socket, ipSettings());
}
IpSocketRef connectTls(InetSocketAddress remoteAddress, IpSocket socket, IpSettings ipSettings);
default IpSocketRef connectTls(InetSocketAddress remoteAddress, IpSocket socket) {
return connectTls(remoteAddress, socket, ipSettings());
}
default IpSocketRef connectTls(String address, int port, IpSocket socket, IpSettings ipSettings) {
return connectTls(new InetSocketAddress(address, port), socket, ipSettings);
}
default IpSocketRef connectTls(String address, int port, IpSocket socket) {
return connectTls(new InetSocketAddress(address, port), socket, ipSettings());
}
default <I, O> IpSocketRef connectTls(InetSocketAddress remoteAddress, IpModem<I, O> modem, IpSettings ipSettings) {
final IpSocket socket = new IpSocketModem<I, O>(modem);
return connectTls(remoteAddress, socket, ipSettings);
}
default <I, O> IpSocketRef connectTls(InetSocketAddress remoteAddress, IpModem<I, O> modem) {
final IpSocket socket = new IpSocketModem<I, O>(modem);
return connectTls(remoteAddress, socket, ipSettings());
}
default <I, O> IpSocketRef connectTls(String address, int port, IpModem<I, O> modem, IpSettings ipSettings) {
final IpSocket socket = new IpSocketModem<I, O>(modem);
return connectTls(new InetSocketAddress(address, port), socket, ipSettings);
}
default <I, O> IpSocketRef connectTls(String address, int port, IpModem<I, O> modem) {
final IpSocket socket = new IpSocketModem<I, O>(modem);
return connectTls(new InetSocketAddress(address, port), socket, ipSettings());
}
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/IpModem.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.io;
import swim.codec.Decoder;
import swim.codec.Encoder;
/**
* Network socket binding that provides asynchronous I/O decoders and encoders
* for a non-blocking NIO network channel.
*
* An {@code IpModem} interfaces with the underlying asynchronous networking
* system via an {@link IpModemContext}. The modem context invokes I/O
* callbacks on the {@code IpModem} when the underlying network socket is
* ready to perform I/O operations permitted by the socket context's {@link
* FlowControl}.
*/
public interface IpModem<I, O> {
/**
* Returns the socket modem context to which this {@code IpModem} is bound;
* returns {@code null} if this {@code IpModem} is unbound.
*/
IpModemContext<I, O> ipModemContext();
/**
* Sets the socket modem context to which this {@code IpModem} is bound.
*/
void setIpModemContext(IpModemContext<I, O> context);
/**
* Returns the number of idle milliseconds after which this {@code IpModem}
* should be closed due to inactivity. Returns {@code -1} if a default idle
* timeout should be used. Returns {@code 0} if the underlying network
* socket should not time out.
*/
long idleTimeout();
/**
* I/O callback invoked by the modem context asking this {@code IpModem} to
* provide an input {@link Decoder} by invoking the modem context's {@link
* IpModemContext#read(Decoder) read} method. The modem context will
* asynchronously feed input data to the provided read {@code Decoder} until
* it transitions out of the <em>cont</em> state. The read flow control of
* the underlying network socket is automatically managed by the modem
* context using the state of the read {@code Decoder}. May be invoked
* concurrently to other I/O callbacks, but never concurrently with other
* {@code doRead} or {@code didRead} calls.
*/
void doRead();
/**
* I/O callback invoked by the modem context with the completed value of the
* current read {@code Decoder} after it has transitioned to the
* <em>done</em> state. May be invoked concurrently to other I/O callbacks,
* but never concurrently with other {@code doRead} or {@code didRead} calls.
*/
void didRead(I input);
/**
* I/O callback invoked by the modem context asking this {@code IpModem} to
* provide an output {@link Encoder} by invoking the modem context's {@link
* IpModemContext#write(Encoder) write} method. The modem context will
* asynchronously pull output data from the provided write {@code Encoder}
* until it transitions out of the <em>cont</em> state. The write flow
* control of the underlying network socket is automatically managed by the
* modem context using the state of the write {@code Encoder}. May be
* invoked concurrently to other I/O callbacks, but never concurrently with
* other {@code doWrite} or {@code didWrite} calls.
*/
void doWrite();
/**
* I/O callback invoked by the modem context with the completed value of the
* current write {@code Encoder} after it has transitioned to the
* <em>done</em> state. May be invoked concurrently to other I/O callbacks,
* but never concurrently with other {@code dodWrite} or {@code didWrite}
* calls.
*/
void didWrite(O output);
/**
* Lifecycle callback invoked by the modem context before the underlying
* network socket attempts to open a connection.
*/
void willConnect();
/**
* Lifecycle callback invoked by the modem context after the underlying
* network socket has opened a connection.
*/
void didConnect();
/**
* Lifecycle callback invoked by the modem context before the underlying
* network socket establishes a secure connection.
*/
void willSecure();
/**
* Lifecycle callback invoked by the modem context after the underlying
* network socket has established a secure connection.
*/
void didSecure();
/**
* Lifecycle callback invoked by the modem context before it has {@link
* IpModemContext#become(IpSocket) become} a new {@code socket}
* implementation.
*/
void willBecome(IpSocket socket);
/**
* Lifecycle callback invoked by the modem context after it has {@link
* IpModemContext#become(IpSocket) become} a new {@code socket}
* implementation.
*/
void didBecome(IpSocket socket);
/**
* Lifecycle callback invoked by the modem context after the underlying
* network connection has timed out. The modem will automatically be closed.
*/
void didTimeout();
/**
* Lifecycle callback invoked by the socket context after the underlying
* network connection has disconnected.
*/
void didDisconnect();
/**
* Lifecycle callback invoked by the modem context when the underlying
* network socket fails by throwing an {@code error}. The modem will
* automatically be closed.
*/
void didFail(Throwable error);
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/IpModemContext.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.io;
import swim.codec.Decoder;
import swim.codec.Encoder;
/**
* Network socket context that manages asynchronous I/O decoders and encoders
* for a non-blocking NIO network channel. An {@code IpModemContext} is
* implicitly bound to a {@link IpModem}, providing the {@code IpModem} with
* the ability to modify its {@link FlowControl} state, enqueue read decoders
* and write encoders, to {@link #become(IpSocket) become} a different kind of
* {@code IpSocket}, and to close the socket.
*/
public interface IpModemContext<I, O> extends IpContext, FlowContext {
/**
* Returns the configuration parameters that govern the underlying network
* socket.
*/
IpSettings ipSettings();
/**
* Enqueues a read {@code decoder} to which input data will be asynchronously
* fed. The read flow control of the underlying network socket is
* automatically managed using the state of the read {@code decoder}. When
* the read {@code decoder} transitions into the <em>done</em> state, the
* {@link IpModem#didRead(Object) didRead} callback of the bound {@code
* IpModem} will be invoked with the decoded result. If the read {@code
* decoder} transitions into the <em>error</em> state, then the {@link
* IpModem#didFail(Throwable) didFail} callback of the bound {@code IpModem}
* will be invoked with the decode error.
*/
<I2 extends I> void read(Decoder<I2> decoder);
/**
* Enqueues a write {@code encoder} from which output data will be
* asynchronously pulled. The write flow control of the underlying network
* socket is automatically managed using the state of the write {@code
* encoder}. When the write {@code encoder} transitions into the
* <em>done</em> state, the {@link IpModem#didWrite(Object) didWrite}
* callback of the bound {@code IpModem} will be invoked with the encoded
* result. If the write {@code encoder} transitions into the <em>error</em>
* state, then the {@link IpModem#didFail(Throwable) didFail} callback of
* the bound {@code IpModem} will be invoked with the encode error.
*/
<O2 extends O> void write(Encoder<?, O2> encoder);
/**
* Rebinds the underlying {@code IpSocketContext} to a new {@code socket}
* implementation, thereby changing the {@code IpSocket} handler that
* receives network I/O callbacks.
*/
void become(IpSocket socket);
/**
* Closes the underlying network socket.
*/
void close();
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/IpService.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.io;
/**
* Network service listener that handles asynchronous I/O operations for a
* non-blocking NIO server socket channel.
*
* An {@code IpService} interfaces with the underlying asynchronous networking
* system via an {@link IpServiceContext}. The service context invokes I/O
* callbacks on the {@code IpService} when the underlying server socket is
* ready to perform I/O operations permitted by the service context's {@link
* FlowControl}.
*/
public interface IpService {
/**
* Returns the network listener context to which this {@code IpService} is
* bound; returns {@code null} if this {@code IpService} is unbound.
*/
IpServiceContext ipServiceContext();
/**
* Sets the network listener context to which this {@code IpService} is bound.
*/
void setIpServiceContext(IpServiceContext context);
/**
* Returns a new {@code IpSocket} binding to handle an incoming network
* connection.
*/
IpSocket createSocket();
/**
* Lifecycle callback invoked by the service context after the underlying
* network listener has bound to a port.
*/
void didBind();
/**
* Lifecycle callback invoked by the service context after the underlying
* network listener has accepted a new {@code socket} connection.
*/
void didAccept(IpSocket socket);
/**
* Lifecycle callback invoked by the service context after the underlying
* network listener has been unbound.
*/
void didUnbind();
/**
* Lifecycle callback invoked by the service context when the underlying
* network listener fails by throwing an {@code error}. The listener will
* automatically be closed.
*/
void didFail(Throwable error);
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/IpServiceContext.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.io;
/**
* Network listener context that manages asynchronous I/O operations for a
* non-blocking NIO server socket channel. An {@code IpServiceContext} is
* implicitly bound to an {@link IpService}, providing the {@code IpService}
* with the ability to modify its {@link FlowControl} state, and to unbind
* the network listener.
*/
public interface IpServiceContext extends IpServiceRef, FlowContext {
/**
* Returns the configuration parameters that govern the underlying network
* listener.
*/
IpSettings ipSettings();
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/IpServiceRef.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.io;
import java.net.InetSocketAddress;
/**
* External handle to a network {@link IpService} listener.
*/
public interface IpServiceRef {
/**
* Returns the IP address and port to which the underlying network listener
* is bound. Returns {@code null} if the underlying network listener is not
* currently bound.
*/
InetSocketAddress localAddress();
/**
* Unbinds the underlying network listener.
*/
void unbind();
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/IpSettings.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.io;
import java.net.Socket;
import java.net.SocketException;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Record;
import swim.structure.Value;
import swim.util.Murmur3;
/**
* IP Socket configuration parameters.
*/
public class IpSettings implements Debug {
protected final TcpSettings tcpSettings;
protected final TlsSettings tlsSettings;
public IpSettings(TcpSettings tcpSettings, TlsSettings tlsSettings) {
this.tcpSettings = tcpSettings;
this.tlsSettings = tlsSettings;
}
/**
* Returns the TCP socket configuration.
*/
public TcpSettings tcpSettings() {
return this.tcpSettings;
}
/**
* Returns a copy of these {@code IpSettings} configured with the given
* {@code tcpSettings}.
*/
public IpSettings tcpSettings(TcpSettings tcpSettings) {
return copy(tcpSettings, this.tlsSettings);
}
/**
* Returns the TLS socket configuration.
*/
public TlsSettings tlsSettings() {
return this.tlsSettings;
}
/**
* Returns a copy of these {@code IpSettings} configured with the given
* {@code tlsSettings}.
*/
public IpSettings tlsSettings(TlsSettings tlsSettings) {
return copy(this.tcpSettings, tlsSettings);
}
/**
* Returns a new {@code IpSettings} instance with the given options.
* Subclasses may override this method to ensure the proper class is
* instantiated when updating settings.
*/
protected IpSettings copy(TcpSettings tcpSettings, TlsSettings tlsSettings) {
return new IpSettings(tcpSettings, tlsSettings);
}
/**
* Configures the {@code socket} with these {@code IpSettings}.
*/
public void configure(Socket socket) throws SocketException {
this.tcpSettings.configure(socket);
}
/**
* Returns a structural {@code Value} representing these {@code IpSettings}.
*/
public Value toValue() {
return form().mold(this).toValue();
}
/**
* Returns {@code true} if these {@code IpSettings} can possibly equal some
* {@code other} object.
*/
public boolean canEqual(Object other) {
return other instanceof IpSettings;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof IpSettings) {
final IpSettings that = (IpSettings) other;
return that.canEqual(this) && this.tcpSettings.equals(that.tcpSettings)
&& this.tlsSettings.equals(that.tlsSettings);
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(IpSettings.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(hashSeed,
this.tcpSettings.hashCode()), this.tlsSettings.hashCode()));
}
@Override
public void debug(Output<?> output) {
output = output.write("IpSettings").write('.').write("standard").write('(').write(')')
.write('.').write("tcpSettings").write('(').debug(this.tcpSettings).write(')')
.write('.').write("tlsSettings").write('(').debug(this.tlsSettings).write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static IpSettings standard;
private static Form<IpSettings> form;
/**
* Returns the default {@code IpSettings} instance.
*/
public static IpSettings standard() {
if (standard == null) {
standard = new IpSettings(TcpSettings.standard(), TlsSettings.standard());
}
return standard;
}
public static IpSettings from(TcpSettings tcpSettings) {
return new IpSettings(tcpSettings, TlsSettings.standard());
}
public static IpSettings from(TlsSettings tlsSettings) {
return new IpSettings(TcpSettings.standard(), tlsSettings);
}
/**
* Returns the structural {@code Form} of {@code IpSettings}.
*/
@Kind
public static Form<IpSettings> form() {
if (form == null) {
form = new IpSettingsForm();
}
return form;
}
}
final class IpSettingsForm extends Form<IpSettings> {
@Override
public IpSettings unit() {
return IpSettings.standard();
}
@Override
public Class<?> type() {
return IpSettings.class;
}
@Override
public Item mold(IpSettings settings) {
if (settings != null) {
final Record record = Record.create(2);
record.add(TcpSettings.form().mold(settings.tcpSettings));
record.add(TlsSettings.form().mold(settings.tlsSettings));
return record;
} else {
return Item.extant();
}
}
@Override
public IpSettings cast(Item item) {
final Value value = item.toValue();
TcpSettings tcpSettings = null;
TlsSettings tlsSettings = null;
for (Item member : value) {
final TcpSettings newTcpSettings = TcpSettings.form().cast(member);
if (newTcpSettings != null) {
tcpSettings = newTcpSettings;
}
final TlsSettings newTlsSettings = TlsSettings.form().cast(member);
if (newTlsSettings != null) {
tlsSettings = newTlsSettings;
}
}
if (tcpSettings == null) {
tcpSettings = TcpSettings.standard();
}
if (tlsSettings == null) {
tlsSettings = TlsSettings.standard();
}
return new IpSettings(tcpSettings, tlsSettings);
}
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/IpSocket.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.io;
/**
* Network socket binding that handles asynchronous I/O operations for a
* non-blocking NIO network channel.
*
* An {@code IpSocket} interfaces with the underlying asynchronous networking
* system via an {@link IpSocketContext}. The socket context invokes I/O
* callbacks on the {@code IpSocket} when the underlying network socket is
* ready to perform I/O operations permitted by the socket context's {@link
* FlowControl}.
*/
public interface IpSocket {
/**
* Returns the network socket context to which this {@code IpSocket} is
* bound; returns {@code null} if this {@code IpSocket} is unbound.
*/
IpSocketContext ipSocketContext();
/**
* Sets the network socket context to which this {@code IpSocket} is bound.
*/
void setIpSocketContext(IpSocketContext context);
/**
* Returns the number of idle milliseconds after which this {@code IpSocket}
* should be closed due to inactivity. Returns {@code -1} if a default idle
* timeout should be used. Returns {@code 0} if the underlying network
* socket should not time out.
*/
long idleTimeout();
/**
* I/O callback invoked by the socket context asking this {@code IpSocket}
* to read input data out of the socket context's {@link
* IpSocketContext#inputBuffer() inputBuffer}. May be invoked concurrently
* to other I/O callbacks, but never concurrently with other {@code doRead}
* calls.
*/
void doRead();
/**
* I/O callback invoked by the socket context asking this {@code IpSocket}
* to write output data into the socket context's {@link
* IpSocketContext#outputBuffer() outputBuffer}. May be invoked concurrently
* to other I/O callbacks, but never concurrently with other {@code doWrite}
* or {@code didWrite} calls.
*/
void doWrite();
/**
* I/O callback invoked by the socket context after the underlying network
* socket has completed writing all data in its {@code outputBuffer}. May be
* invoked concurrently to other I/O callbacks, but never concurrently with
* other {@code doWrite} or {@code didWrite} calls.
*/
void didWrite();
/**
* Lifecycle callback invoked by the socket context before the underlying
* network socket attempts to open a connection.
*/
void willConnect();
/**
* Lifecycle callback invoked by the socket context after the underlying
* network socket has opened a connection.
*/
void didConnect();
/**
* Lifecycle callback invoked by the socket context before the underlying
* network socket establishes a secure connection.
*/
void willSecure();
/**
* Lifecycle callback invoked by the socket context after the underlying
* network socket has established a secure connection.
*/
void didSecure();
/**
* Lifecycle callback invoked by the socket context before it has {@link
* IpSocketContext#become(IpSocket) become} a new {@code socket}
* implementation.
*/
void willBecome(IpSocket socket);
/**
* Lifecycle callback invoked by the socket context after it has {@link
* IpSocketContext#become(IpSocket) become} a new {@code socket}
* implementation.
*/
void didBecome(IpSocket socket);
/**
* Lifecycle callback invoked by the socket context after the underlying
* network connection has timed out. The socket will automatically be closed.
*/
void didTimeout();
/**
* Lifecycle callback invoked by the socket context after the underlying
* network connection has disconnected.
*/
void didDisconnect();
/**
* Lifecycle callback invoked by the socket context when the underlying
* network socket fails by throwing an {@code error}. The socket will
* automatically be closed.
*/
void didFail(Throwable error);
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/IpSocketContext.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.io;
import swim.codec.InputBuffer;
import swim.codec.OutputBuffer;
/**
* Network socket context that manages asynchronous I/O operations for a
* non-blocking NIO network channel. An {@code IpSocketContext} is implicitly
* bound to an {@link IpSocket}, providing the {@code IpSocket} with the
* ability to modify its {@link FlowControl} state, access its read and write
* buffers, to {@link #become(IpSocket) become} a different kind of {@code
* IpSocket}, and to close the socket.
*/
public interface IpSocketContext extends IpSocketRef, FlowContext {
/**
* Returns the configuration parameters that govern the underlying network
* socket.
*/
IpSettings ipSettings();
/**
* Returns the buffer into which input data is read by the underlying network
* socket. The bound {@code IpSocket} reads from this buffer in response to
* {@link IpSocket#doRead() doRead} callbacks.
*/
InputBuffer inputBuffer();
/**
* Returns the buffer from which output data is written by the underlying
* network socket. The bound {@code IpSocket} writes to this buffer in
* repsonse to {@link IpSocket#doWrite() doWrite} callbacks.
*/
OutputBuffer<?> outputBuffer();
/**
* Rebinds this {@code IpSocketContext} to a new {@code socket}
* implementation, thereby changing the {@code IpSocket} handler that
* receives network I/O callbacks.
*/
void become(IpSocket socket);
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/IpSocketModem.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.io;
import java.net.InetSocketAddress;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.Collection;
import java.util.concurrent.ConcurrentLinkedQueue;
import swim.codec.Decoder;
import swim.codec.Encoder;
import swim.codec.InputBuffer;
import swim.codec.OutputBuffer;
import swim.concurrent.Conts;
/**
* Adapter from a flow-controlled {@link IpSocket} to a decoder/encoder
* controlled {@link IpModem}.
*/
public class IpSocketModem<I, O> implements IpSocket, IpModemContext<I, O> {
final IpModem<I, O> modem;
final ConcurrentLinkedQueue<Decoder<? extends I>> readerQueue;
final ConcurrentLinkedQueue<Encoder<?, ? extends O>> writerQueue;
volatile Decoder<? extends I> reading;
volatile Encoder<?, ? extends O> writing;
protected volatile IpSocketContext context;
public IpSocketModem(IpModem<I, O> modem) {
this.modem = modem;
this.readerQueue = new ConcurrentLinkedQueue<Decoder<? extends I>>();
this.writerQueue = new ConcurrentLinkedQueue<Encoder<?, ? extends O>>();
}
@Override
public IpSocketContext ipSocketContext() {
return this.context;
}
@Override
public void setIpSocketContext(IpSocketContext context) {
this.context = context;
this.modem.setIpModemContext(this);
}
@Override
public boolean isConnected() {
return this.context.isConnected();
}
@Override
public boolean isClient() {
return this.context.isClient();
}
@Override
public boolean isServer() {
return this.context.isServer();
}
@Override
public boolean isSecure() {
return this.context.isSecure();
}
@Override
public String securityProtocol() {
return this.context.securityProtocol();
}
@Override
public String cipherSuite() {
return this.context.cipherSuite();
}
@Override
public InetSocketAddress localAddress() {
return this.context.localAddress();
}
@Override
public Principal localPrincipal() {
return this.context.localPrincipal();
}
@Override
public Collection<Certificate> localCertificates() {
return this.context.localCertificates();
}
@Override
public InetSocketAddress remoteAddress() {
return this.context.remoteAddress();
}
@Override
public Principal remotePrincipal() {
return this.context.remotePrincipal();
}
@Override
public Collection<Certificate> remoteCertificates() {
return this.context.remoteCertificates();
}
@Override
public IpSettings ipSettings() {
return this.context.ipSettings();
}
@Override
public <I2 extends I> void read(Decoder<I2> reader) {
this.readerQueue.add(reader);
if (this.reading == null) {
final IpSocketContext context = this.context;
if (context != null) {
context.flowControl(FlowModifier.ENABLE_READ);
}
}
}
@Override
public <O2 extends O> void write(Encoder<?, O2> writer) {
this.writerQueue.add(writer);
if (this.writing == null) {
final IpSocketContext context = this.context;
if (context != null) {
context.flowControl(FlowModifier.ENABLE_WRITE);
}
}
}
@Override
public long idleTimeout() {
return this.modem.idleTimeout();
}
@Override
public void doRead() {
IpSocketContext context = this.context;
if (context == null) {
return;
}
InputBuffer inputBuffer = context.inputBuffer();
Decoder<? extends I> reader = this.reading;
int oldIndex;
int newIndex;
do {
if (reader != null) {
do {
oldIndex = inputBuffer.index();
inputBuffer = inputBuffer.isPart(true);
reader = reader.feed(inputBuffer);
newIndex = inputBuffer.index();
} while (oldIndex != newIndex && inputBuffer.isCont() && reader.isCont());
if (reader.isCont()) {
this.reading = reader;
break;
} else if (reader.isDone()) {
this.modem.didRead(reader.bind());
} else if (reader.isError()) {
this.modem.didFail(reader.trap());
}
}
reader = this.readerQueue.poll();
if (reader != null) {
this.reading = reader;
} else {
this.modem.doRead();
reader = this.readerQueue.poll();
this.reading = reader;
if (reader == null) {
context = this.context;
if (context != null) {
context.flowControl(FlowModifier.DISABLE_READ);
// Reconcile read flow control race.
reader = this.readerQueue.poll();
this.reading = reader;
if (reader != null) {
context.flowControl(FlowModifier.ENABLE_READ);
} else {
break;
}
} else {
break;
}
}
}
} while (inputBuffer.isCont());
}
@Override
public void doWrite() {
Encoder<?, ? extends O> writer = this.writing;
if (writer == null) {
writer = this.writerQueue.poll();
if (writer == null) {
final IpSocketContext context = this.context;
if (context != null) {
context.flowControl(FlowModifier.DISABLE_WRITE);
// Reconcile write flow control race.
writer = this.writerQueue.poll();
this.writing = writer;
if (writer != null) {
context.flowControl(FlowModifier.ENABLE_WRITE);
} else {
return;
}
} else {
return;
}
}
}
OutputBuffer<?> outputBuffer = this.context.outputBuffer();
int oldIndex;
int newIndex;
do {
oldIndex = outputBuffer.index();
outputBuffer = outputBuffer.isPart(true);
writer = writer.pull(outputBuffer);
newIndex = outputBuffer.index();
} while (oldIndex != newIndex && outputBuffer.isCont() && writer.isCont());
this.writing = writer;
if (newIndex == 0) {
didWrite();
}
}
@Override
public void didWrite() {
Encoder<?, ? extends O> writer = this.writing;
if (!writer.isCont()) {
if (writer.isDone()) {
this.modem.didWrite(writer.bind());
} else if (writer.isError()) {
this.modem.didFail(writer.trap());
}
writer = this.writerQueue.poll();
if (writer != null) {
this.writing = writer;
} else {
this.modem.doWrite();
writer = this.writerQueue.poll();
this.writing = writer;
if (writer == null) {
final IpSocketContext context = this.context;
if (context != null) {
context.flowControl(FlowModifier.DISABLE_WRITE);
// Reconcile write flow control race.
writer = this.writerQueue.poll();
this.writing = writer;
if (writer != null) {
context.flowControl(FlowModifier.ENABLE_WRITE);
}
}
}
}
}
}
@Override
public void willConnect() {
this.modem.willConnect();
}
@Override
public void didConnect() {
if (this.reading != null) {
if (this.writing != null) {
this.context.flowControl(FlowModifier.ENABLE_READ_WRITE);
} else {
this.context.flowControl(FlowModifier.ENABLE_READ);
}
} else if (this.writing != null) {
this.context.flowControl(FlowModifier.ENABLE_WRITE);
}
this.modem.didConnect();
}
@Override
public void willSecure() {
this.modem.willSecure();
}
@Override
public void didSecure() {
this.modem.didSecure();
}
@Override
public void willBecome(IpSocket socket) {
this.modem.willBecome(socket);
}
@Override
public void didBecome(IpSocket socket) {
this.modem.didBecome(socket);
}
@Override
public void didTimeout() {
this.modem.didTimeout();
}
@Override
public void didDisconnect() {
Decoder<? extends I> reader = this.reading;
do {
if (reader != null) {
try {
reader.feed(InputBuffer.done());
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
// swallow
} else {
// Rethrow fatal exception.
throw error;
}
}
}
reader = this.readerQueue.poll();
} while (reader != null);
Encoder<?, ? extends O> writer = this.writing;
do {
if (writer != null) {
try {
writer.pull(OutputBuffer.done());
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
// swallow
} else {
// Rethrow fatal exception.
throw error;
}
}
}
writer = this.writerQueue.poll();
} while (writer != null);
this.modem.didDisconnect();
close();
}
@Override
public void didFail(Throwable error) {
this.modem.didFail(error);
}
@Override
public FlowControl flowControl() {
return this.context.flowControl();
}
@Override
public void flowControl(FlowControl flowControl) {
this.context.flowControl(flowControl);
}
@Override
public FlowControl flowControl(FlowModifier flowModifier) {
return this.context.flowControl(flowModifier);
}
@Override
public void become(IpSocket socket) {
final IpSocketContext context = this.context;
this.context = null;
context.become(socket);
}
@Override
public void close() {
this.context.close();
}
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/IpSocketRef.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.io;
/**
* External handle to a network {@link IpSocket}.
*/
public interface IpSocketRef extends IpContext {
/**
* Closes the underlying network socket.
*/
void close();
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/IpStation.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.io;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Collection;
import javax.net.ssl.SSLEngine;
public interface IpStation extends IpInterface {
Station station();
@Override
default IpServiceRef bindTcp(InetSocketAddress localAddress, IpService service, IpSettings ipSettings) {
try {
final Station station = station();
final ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking(false);
serverChannel.socket().setReuseAddress(true);
serverChannel.socket().bind(localAddress, station().transportSettings.backlog);
final TcpService context = new TcpService(station(), localAddress, serverChannel, service, ipSettings);
service.setIpServiceContext(context);
station().transport(context, FlowControl.ACCEPT);
context.didBind();
return context;
} catch (IOException error) {
throw new StationException(error);
}
}
@Override
default IpServiceRef bindTls(InetSocketAddress localAddress, IpService service, IpSettings ipSettings) {
try {
final Station station = station();
final ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking(false);
serverChannel.socket().setReuseAddress(true);
serverChannel.socket().bind(localAddress, station.transportSettings.backlog);
final TlsService context = new TlsService(station, localAddress, serverChannel, service, ipSettings);
service.setIpServiceContext(context);
station.transport(context, FlowControl.ACCEPT);
context.didBind();
return context;
} catch (IOException error) {
throw new StationException(error);
}
}
@Override
default IpSocketRef connectTcp(InetSocketAddress remoteAddress, IpSocket socket, IpSettings ipSettings) {
try {
final Station station = station();
final SocketChannel channel = SocketChannel.open();
channel.configureBlocking(false);
ipSettings.configure(channel.socket());
final boolean connected = channel.connect(remoteAddress);
final InetSocketAddress localAddress = (InetSocketAddress) channel.socket().getLocalSocketAddress();
final TcpSocket context = new TcpSocket(localAddress, remoteAddress, channel, ipSettings, true);
context.become(socket);
if (connected) {
station.transport(context, FlowControl.WAIT);
context.didConnect();
} else {
context.willConnect();
station.transport(context, FlowControl.CONNECT);
}
return context;
} catch (IOException error) {
throw new StationException(error);
}
}
@Override
default IpSocketRef connectTls(InetSocketAddress remoteAddress, IpSocket socket, IpSettings ipSettings) {
try {
final Station station = station();
final SocketChannel channel = SocketChannel.open();
channel.configureBlocking(false);
ipSettings.configure(channel.socket());
final TlsSettings tlsSettings = ipSettings.tlsSettings();
final SSLEngine sslEngine = tlsSettings.sslContext().createSSLEngine();
sslEngine.setUseClientMode(true);
switch (tlsSettings.clientAuth()) {
case NEED: sslEngine.setNeedClientAuth(true); break;
case WANT: sslEngine.setWantClientAuth(true); break;
case NONE: sslEngine.setWantClientAuth(false); break;
default:
}
final Collection<String> cipherSuites = tlsSettings.cipherSuites();
if (cipherSuites != null) {
sslEngine.setEnabledCipherSuites(cipherSuites.toArray(new String[cipherSuites.size()]));
}
final Collection<String> protocols = tlsSettings.protocols();
if (protocols != null) {
sslEngine.setEnabledProtocols(protocols.toArray(new String[protocols.size()]));
}
final boolean connected = channel.connect(remoteAddress);
final InetSocketAddress localAddress = (InetSocketAddress) channel.socket().getLocalSocketAddress();
final TlsSocket context = new TlsSocket(localAddress, remoteAddress, channel, sslEngine, ipSettings, true);
context.become(socket);
if (connected) {
station.transport(context, FlowControl.WAIT);
context.didConnect();
} else {
context.willConnect();
station.transport(context, FlowControl.CONNECT);
}
return context;
} catch (IOException error) {
throw new StationException(error);
}
}
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/Station.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.io;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.WritableByteChannel;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import swim.concurrent.AbstractTask;
import swim.concurrent.Conts;
import swim.concurrent.MainStage;
import swim.concurrent.Stage;
/**
* Asynchronous I/O multiplexor.
*/
public class Station {
/**
* Stage on which to execute I/O tasks.
*/
protected final Stage stage;
/**
* Transport configuration parameters.
*/
protected TransportSettings transportSettings;
/**
* Barrier used to sequence station startup.
*/
final CountDownLatch startLatch;
/**
* Barrier used to sequence station shutdown.
*/
final CountDownLatch stopLatch;
/**
* Thread that waits on and dispatches I/O readiness events.
*/
final StationThread thread;
/**
* Atomic bit field with {@link #STARTED} and {@link #STOPPED} flags.
*/
volatile int status;
public Station(Stage stage, TransportSettings transportSettings) {
// Assign the I/O task execution stage.
this.stage = stage;
// Assign the initial transport configuration parameters.
this.transportSettings = transportSettings != null ? transportSettings : TransportSettings.standard();
// Initialize the barrier used to sequence station startup.
this.startLatch = new CountDownLatch(1);
// Initialize the barrier used to sequence station shutdown.
this.stopLatch = new CountDownLatch(1);
// Initialize--but don't start--the station thread.
this.thread = new StationThread(this);
}
public Station(Stage stage) {
this(stage, null);
}
/**
* Returns the {@code Stage} on which this {@code Station} executes I/O tasks.
*/
public final Stage stage() {
return this.stage;
}
/**
* Returns the transport configuration parameters that govern this {@code
* Station}'s regsitered transports.
*/
public final TransportSettings transportSettings() {
return this.transportSettings;
}
/**
* Updates the transport configuration parameters that govern this {@code
* Station}'s registered transports, and returns {@code this}.
*/
public Station transportSettings(TransportSettings transportSettings) {
this.transportSettings = transportSettings;
return this;
}
/**
* Ensures that this {@code Station} is up and running, starting up the
* selector thread if it has not yet been started.
*
* @throws StationException if this {@code Station} has been stopped.
*/
public void start() {
do {
final int oldStatus = STATUS.get(this);
if ((oldStatus & STOPPED) == 0) {
// Station hasn't yet stopped; make sure it has started.
if ((oldStatus & STARTED) == 0) {
final int newStatus = oldStatus | STARTED;
// Try to set the STARTED flag; linearization point for station startup.
if (STATUS.compareAndSet(this, oldStatus, newStatus)) {
// Initaite selector thread startup.
willStart();
this.thread.start();
break;
}
} else {
// Selector thread already started.
break;
}
} else {
throw new StationException("Can't restart stopped station");
}
} while (true);
// Loop while the selector thread is not yet up and running.
boolean interrupted = false;
while (this.startLatch.getCount() != 0) {
try {
// Wait for selector thread startup to complete.
this.startLatch.await();
} catch (InterruptedException error) {
interrupted = true;
}
}
if (interrupted) {
Thread.currentThread().interrupt();
}
}
/**
* Ensures that this {@code Station} has been permanently stopped, shutting
* down the selector thread, if it's currently running. Upon return, this
* {@code Station} is guaranteed to be in the <em>stopped</em> state.
*/
public void stop() {
boolean interrupted = false;
do {
final int oldStatus = STATUS.get(this);
if ((oldStatus & STOPPED) == 0) {
// Station hasn't yet stopped; try to stop it.
final int newStatus = oldStatus | STOPPED;
// Try to set the STOPPED flag; linearization point for station shutdown.
if (STATUS.compareAndSet(this, oldStatus, newStatus)) {
// Loop while the selector thread is still running.
while (this.thread.isAlive()) {
// Interrupt the selector thread so it will wakeup and die.
this.thread.interrupt();
try {
// Wait for the selector thread to exit.
this.thread.join(100);
} catch (InterruptedException error) {
interrupted = true;
}
}
}
} else {
// Selector thread already stopped.
break;
}
} while (true);
// Loop while the selector thread is still running.
while (this.stopLatch.getCount() != 0) {
try {
// Wait for selector thread shutdown to complete.
this.stopLatch.await();
} catch (InterruptedException e) {
interrupted = true;
}
}
if (this.stage instanceof MainStage) {
((MainStage) this.stage).stop();
}
if (interrupted) {
Thread.currentThread().interrupt();
}
}
/**
* Binds the given {@code transport} to this {@code Station}, initializing
* the {@code transport}'s context with the given {@code flowControl} state.
* The {@code Station} thereafter asynchronously executes I/O tasks on behalf
* of the {@code transport} when the underlying physical transport is ready
* for I/O operations permitted by the {@code transport}'s current flow
* control state. Returns a {@code TransportRef}, which can be used to
* modify the flow control of the {@code transport}, and to close the {@code
* transport}.
*/
public TransportRef transport(Transport transport, FlowControl flowControl) {
// Ensure that the station has started.
start();
// Create the context that binds the transport to this station.
final StationTransport context = new StationTransport(this, transport, flowControl);
transport.setTransportContext(context);
// Initialize the transport's flow control.
reselect(context);
// Return the transport context.
return context;
}
/**
* Informs the selector thread of a possible change to the given transport
* {@code context}'s flow control state.
*/
void reselect(StationTransport context) {
this.thread.reselect(context);
}
/**
* Lifecycle callback invoked before the selector thread starts.
*/
protected void willStart() {
// stub
}
/**
* Lifecycle callback invoked after the selector thread starts.
*/
protected void didStart() {
// stub
}
/**
* Lifecycle callback invoked before the selector thread stops.
*/
protected void willStop() {
// stub
}
/**
* Lifecycle callback invoked after the selector thread stops.
*/
protected void didStop() {
// stub
}
/**
* Lifecycle callback invoked if the selector thread throws a fatal {@code
* error}. The selector thread will stop after invoking {@code didFail}.
*/
protected void didFail(Throwable error) {
error.printStackTrace();
}
/**
* Introspection callback invoked after a {@code transport} completes an
* accept operation.
*/
protected void transportDidAccept(Transport transport) {
// stub
}
/**
* Introspection callback invoked after a {@code transport} completes a
* connect operation.
*/
protected void transportDidConnect(Transport transport) {
// stub
}
/**
* Introspection callback invoked after a {@code transport} times out.
*/
protected void transportDidTimeout(Transport transport) {
// stub
}
/**
* Introspection callback invoked after a {@code transport} closes.
*/
protected void transportDidClose(Transport transport) {
// stub
}
/**
* Introspection callback invoked after a {@code transport} operation fails
* by throwing an {@code error}.
*/
protected void transportDidFail(Transport transport, Throwable error) {
if (!(error instanceof IOException)) {
error.printStackTrace();
}
}
/**
* Atomic {@link #status} bit flag indicating that the station has started,
* and is currently running.
*/
static final int STARTED = 1 << 0;
/**
* Atomic {@link #status} bit flag indicating that the station had previously
* started, but is now permanently stopped.
*/
static final int STOPPED = 1 << 1;
/**
* Atomic {@link #status} field updater, used to linearize station startup
* and shutdown.
*/
static final AtomicIntegerFieldUpdater<Station> STATUS =
AtomicIntegerFieldUpdater.newUpdater(Station.class, "status");
}
/**
* Context that binds a {@code Transport} to a {@code Station}, manages the
* execution of I/O tasks, and maintains consistency of the transport's flow
* control, with respoect to the station's selector.
*/
final class StationTransport implements TransportContext, TransportRef {
/**
* {@code Station} to which the {@code transport} is bound.
*/
final Station station;
/**
* {@code Transport} binding on which to invoke I/O callbacks.
*/
final Transport transport;
/**
* Atomic reference to the current flow control state of the transport.
*/
volatile FlowControl flowControl;
/**
* Sequential {@code Task} that invokes transport read callbacks.
*/
StationReader reader;
/**
* Sequential {@code Task} that invokes transport write callbacks.
*/
StationWriter writer;
/**
* Registration of the transport channel with the station's selector.
*/
SelectionKey selectionKey;
/**
* Monotonic timestamp of the most recent transport I/O operation.
*/
volatile long lastSelectTime;
StationTransport(Station station, Transport transport, FlowControl flowControl) {
this.station = station;
this.transport = transport;
this.flowControl = flowControl;
}
/**
* Informs the station's selector thread of a possible change to the
* transport's flow control state.
*/
void reselect() {
this.station.reselect(this);
}
/**
* Returns the number of idle milliseconds after which the transport should
* be closed due to lack of activity.
*/
long idleTimeout() {
return this.transport.idleTimeout();
}
@Override
public TransportSettings transportSettings() {
return this.station.transportSettings;
}
@Override
public FlowControl flowControl() {
return FLOW_CONTROL.get(this);
}
@Override
public void flowControl(FlowControl newFlow) {
final FlowControl oldFlow = FLOW_CONTROL.getAndSet(this, newFlow);
if (!oldFlow.equals(newFlow)) {
reselect();
}
}
@Override
public FlowControl flowControl(FlowModifier flowModifier) {
do {
final FlowControl oldFlow = FLOW_CONTROL.get(this);
final FlowControl newFlow = oldFlow.modify(flowModifier);
if (!oldFlow.equals(newFlow)) {
// Flow control changed; atomically update the transport's state.
if (FLOW_CONTROL.compareAndSet(this, oldFlow, newFlow)) {
// Inform the station's selector of the change.
reselect();
return newFlow;
}
} else {
// No change to flow control state.
return newFlow;
}
} while (true);
}
@Override
public void close() {
try {
// Close the transport's NIO channel.
this.transport.channel().close();
} catch (IOException error) {
// Report close failure to the station, but not to the transport binding.
this.station.transportDidFail(this.transport, error);
}
// Complete the transport close.
didClose();
}
/**
* I/O callback invoked by the station's selector thread when the transport
* is ready to complete an <em>accept</em> operation.
*/
void doAccept() {
try {
// Tell the transport binding to complete the accept operation.
this.transport.doAccept();
// Inform the station that the transport completed the accept operation.
this.station.transportDidAccept(this.transport);
} catch (ClosedChannelException error) {
// Channel closed during the accept operation; complete the close.
didClose();
} catch (IOException error) {
// Report the transport I/O exception.
didFail(error);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
// Report the non-fatal transport exception.
didFail(error);
} else {
// Rethrow the fatal exception.
throw error;
}
}
}
/**
* I/O callback invoked by the station's selector thread when the transport
* is ready to complete a <em>connect</em> operation. Disables the
* <em>connect</em> operation on the transport's flow control state.
*/
void doConnect() {
do {
final FlowControl oldFlowControl = FLOW_CONTROL.get(this);
if (oldFlowControl.isConnectEnabled()) {
// Connect operation is enabled; disable it.
final FlowControl newFlowControl = oldFlowControl.connectDisabled();
if (FLOW_CONTROL.compareAndSet(this, oldFlowControl, newFlowControl)) {
break;
}
} else {
// Connect operation already disabled.
break;
}
} while (true);
try {
// Tell the transport binding to complete the connect operation.
this.transport.doConnect();
// Inform the station that the transport completed the connect operation.
this.station.transportDidConnect(this.transport);
} catch (ClosedChannelException error) {
// Channel closed during the connect operation; complete the close.
didClose();
} catch (IOException error) {
// Report the transport I/O exception.
didFail(error);
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
// Report the non-fatal transport exception.
didFail(error);
} else {
// Rethrow the fatal exception.
throw error;
}
}
}
/**
* Schedules the transport's asynchronous reader task for execution on the
* station's stage.
*/
void cueRead() {
StationReader reader = this.reader;
if (reader == null) {
// Lazily instantiate the reader task, and bind it to the station's stage.
reader = new StationReader(this);
this.station.stage.task(reader);
this.reader = reader;
}
// Schedule the reader task to run.
reader.cue();
}
/**
* I/O callback invoked by the station's selector thread when the transport
* is ready to perform a <em>read</em> operation.
*/
void doRead() {
final ByteBuffer readBuffer = this.transport.readBuffer();
final ReadableByteChannel channel = (ReadableByteChannel) this.transport.channel();
// Loop while reading is permitted.
while (FLOW_CONTROL.get(this).isReadEnabled()) {
final int count;
try {
// Try to read input bytes from the transport channel.
count = channel.read(readBuffer);
} catch (ClosedChannelException error) {
// Channel closed during the read operation; complete the close.
didClose();
break;
} catch (IOException error) {
// Report the transport I/O exception.
didFail(error);
break;
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
// Report the non-fatal transport exception.
didFail(error);
break;
} else {
// Rethrow the fatal exception.
throw error;
}
}
if (count < 0) {
// The transport channel has reached the end of the stream; close the
// transport.
close();
break;
} else if (readBuffer.position() > 0) {
// The input buffer has available input data; prepare the input buffer
// to be read by the transport binding.
((Buffer) readBuffer).flip();
try {
// Tell the transport binding to read input bytes from the input
// buffer.
this.transport.doRead();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
// Report the non-fatal transport exception.
didFail(error);
break;
} else {
// Rethrow the fatal exception.
throw error;
}
}
if (readBuffer.hasRemaining()) {
// The transport binding didn't read all the input bytes from the
// input buffer; compact the input buffer to make room to read more
// input data.
readBuffer.compact();
} else {
// The transport binding read all bytes from the input buffer; reset
// the input buffer.
((Buffer) readBuffer).clear();
}
// Continue trying to read from the transport channel.
continue;
} else {
// The input buffer is empty; synchronize the transport's flow control
// state with the station's selector to ensure that doRead gets called
// again, when ready and permitted.
reselect();
break;
}
}
}
/**
* Schedules the transport's asynchronous write task for execution on the
* station's stage.
*/
void cueWrite() {
StationWriter writer = this.writer;
if (writer == null) {
// Lazily instantiate the writer task, and bind it to the station's stage.
writer = new StationWriter(this);
this.station.stage.task(writer);
this.writer = writer;
}
// Schedule the writer task to run.
writer.cue();
}
/**
* I/O callback invoked by the station's selector thread when the transport
* is ready to perform a <em>write</em> operation.
*/
void doWrite() {
final ByteBuffer writeBuffer = this.transport.writeBuffer();
final WritableByteChannel channel = (WritableByteChannel) this.transport.channel();
// Loop while the output buffer has bytes remaining to be written, and
// writing is permitted.
do {
if (writeBuffer.hasRemaining()) {
// The output buffer has bytes remaining to be written.
final int count;
try {
// Try to write the remaining output bytes to the transport channel.
count = channel.write(writeBuffer);
} catch (ClosedChannelException error) {
// Channel closed during the write operation; complete the close.
didClose();
break;
} catch (IOException error) {
// Report the transport I/O exception.
didFail(error);
break;
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
// Report the non-fatal transport exception.
didFail(error);
break;
} else {
// Rethrow the fatal exception.
throw error;
}
}
if (count > 0) {
// Output bytes were successfully written to the transport channel.
if (!writeBuffer.hasRemaining()) {
// The output buffer has no more bytes to be written.
try {
// Inform the transport binding that the write completed.
this.transport.didWrite();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
// Report the non-fatal transport exception.
didFail(error);
return;
} else {
// Rethrow the fatal exception.
throw error;
}
}
continue;
} else {
// The output buffer still has bytes remaining to be written;
// synchronize the transport's flow control state with the
// station's selector to ensure that doWrite gets called again,
// when ready and permitted.
reselect();
break;
}
} else {
// No output bytes were written to the transport channel; synchronize
// the transport's flow control state with the station's selector to
// ensure that doWrite gets called again, when ready and permitted.
reselect();
break;
}
} else if (FLOW_CONTROL.get(this).isWriteEnabled()) {
// The output buffer is empty, and writing is permitted.
// Clear the output buffer to prepare it for new output data.
((Buffer) writeBuffer).clear();
try {
// Tell the transport binding to write more output bytes to the
// output buffer.
this.transport.doWrite();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
// Report the non-fatal transport exception.
didFail(error);
return;
} else {
// Rethrow the fatal exception.
throw error;
}
}
// Prepare the output buffer to be written to the transport channel.
((Buffer) writeBuffer).flip();
if (writeBuffer.hasRemaining()) {
// New output bytes were written by the transport binding to the
// output buffer; continue writing the output buffer to the transport
// channel.
continue;
} else {
// No new output bytes were written by the transport binding to the
// output buffer; synchronize the transport's flow control state with
// the station's selector to ensure that doWrite gets called again,
// when ready and permitted.
reselect();
break;
}
} else {
// The output buffer is empty, and writing is not permitted;
// synchronize the transport's flow control state with the station's
// selector to ensure that doWrite gets called again, when ready and
// permitted.
reselect();
break;
}
} while (true);
}
void didTimeout() {
// Inform the transport binding that the transport has timed out.
this.transport.didTimeout();
// Inform the station that the transport has timed out.
this.station.transportDidTimeout(this.transport);
}
/**
* Clean up the transport after it has closed.
*/
void didClose() {
final StationReader reader = this.reader;
if (reader != null) {
// Best effort to prevent the reader task from running post-close.
reader.cancel();
}
final StationWriter writer = this.writer;
if (writer != null) {
// Best effort to prevent the writer task from running post-close.
writer.cancel();
}
// Inform the transport binding that the transport has closed.
this.transport.didClose();
// Inform the station that the transport has closed.
this.station.transportDidClose(this.transport);
}
/**
* Report a—possibly non-fatal—transport error.
*/
void didFail(Throwable error) {
// Inform the transport binding that the transport failed.
this.transport.didFail(error);
// Inform the station that the transport failed.
this.station.transportDidFail(this.transport, error);
}
/**
* Atomic {@link #flowControl} field updater, used to linearize transport
* flow control modifications.
*/
static final AtomicReferenceFieldUpdater<StationTransport, FlowControl> FLOW_CONTROL =
AtomicReferenceFieldUpdater.newUpdater(StationTransport.class, FlowControl.class, "flowControl");
}
/**
* Sequential task from which all transport read operations are performed.
*/
final class StationReader extends AbstractTask {
final StationTransport context;
StationReader(StationTransport context) {
this.context = context;
}
@Override
public void runTask() {
this.context.doRead();
}
}
/**
* Sequential task from which all transport write operations are performed.
*/
final class StationWriter extends AbstractTask {
final StationTransport context;
StationWriter(StationTransport context) {
this.context = context;
}
@Override
public void runTask() {
this.context.doWrite();
}
}
/**
* Thread of execution that waits on and dispatches I/O readiness events.
*/
final class StationThread extends Thread {
/**
* {@code Station} whose I/O transports this {@code StationThread} manages.
*/
final Station station;
/**
* I/O selector used to wait on I/O readiness events.
*/
final Selector selector;
/**
* Submission queue used to sequence transport flow control modifications;
* needed because {@code SelectionKey}'s cannot be atomically mutated by
* concurrent threads.
*/
final ConcurrentLinkedQueue<StationTransport> reselectQueue;
/**
* Monotonic timestamp of most recent timeout check.
*/
long lastIdleCheck;
StationThread(Station station) {
setName("SwimStation" + THREAD_COUNT.getAndIncrement());
this.station = station;
try {
this.selector = Selector.open();
} catch (IOException cause) {
throw new RuntimeException(cause);
}
this.reselectQueue = new ConcurrentLinkedQueue<StationTransport>();
this.lastIdleCheck = System.currentTimeMillis();
}
@Override
public void run() {
final Station station = this.station;
try {
// Linearization point for station start.
station.startLatch.countDown();
station.didStart();
// Loop while the station has not been stopped.
do {
// Drain the reselect submission queue, synchronizing the flow
// control state of all modified transports with their corresponding
// selection keys.
reflow();
// Wait on and then dispatch I/O readines events.
select();
// Check for idle transport timeouts.
checkIdle();
} while ((Station.STATUS.get(station) & Station.STOPPED) == 0);
station.willStop();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
// Report internal station error.
station.didFail(error);
} else {
// Rethrow fatal exception.
throw error;
}
} finally {
// Close all registered transports.
closeAll();
try {
// Close the I/O selector.
this.selector.close();
} catch (IOException error) {
// Report I/O selector close failure.
station.didFail(error);
}
// Force the station into the stopped state.
Station.STATUS.set(station, Station.STOPPED);
// Linearization point for station stop.
station.stopLatch.countDown();
station.didStop();
}
}
/**
* Enqueues the transport {@code context} to have its flow control state
* synchronized with the I/O selector, and wakes up the selector thread to
* have it account for the flow control change.
*/
void reselect(StationTransport context) {
this.reselectQueue.add(context);
this.selector.wakeup();
}
/**
* Synchronizes the flow control state of all transports in the reselect
* queue with the I/O selector.
*/
void reflow() {
// Loop until the reselect queue is empty.
do {
// Dequeue the next transport from the reselect queue.
final StationTransport context = this.reselectQueue.poll();
if (context != null) {
// Synchronize the transport's flow control state with the I/O selector.
reflow(context);
} else {
// No more transports to reselect.
break;
}
} while (true);
}
/**
* Synchronizes the flow control state of the given transport {@code context}
* with the I/O interest ops of the transport channel's selection key.
*/
void reflow(StationTransport context) {
final SelectionKey selectionKey = context.selectionKey;
// Get the selection key interest ops corresponding to the transport's
// current flow control state.
final int interestOps = StationTransport.FLOW_CONTROL.get(context).toSelectorOps();
if (selectionKey != null) {
// Transport channel is registered with the I/O selector.
try {
// Update the selection key's permitted I/O operations.
selectionKey.interestOps(interestOps);
} catch (CancelledKeyException error) {
// Transport channel closed during the I/O operation update; complete
// the close.
context.didClose();
}
} else {
// Transport channel not yet registered with the I/O selector.
try {
// Try to register the transport channel with the I/O selector.
context.selectionKey = context.transport.channel().register(this.selector, interestOps, context);
} catch (CancelledKeyException | ClosedChannelException error) {
// Transport channel closed during registration; complete the close.
context.didClose();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
// Report transport channel registration exception.
context.didFail(error);
} else {
// Rethrhrow fatal exception.
throw error;
}
}
}
}
/**
* Waits on and dispatches I/O readiness events for all transports registered
* with the I/O selector.
*/
void select() {
try {
// Wait for I/O readiness events, or for timeout check time to elapse.
final int selectedCount = this.selector.select(this.station.transportSettings.idleInterval);
if (selectedCount > 0) {
final Iterator<SelectionKey> selectedKeys = this.selector.selectedKeys().iterator();
while (selectedKeys.hasNext()) {
// Get the next ready selection key.
final SelectionKey selectionKey = selectedKeys.next();
// Remove the key from the selected set.
selectedKeys.remove();
// Get the transport context attached to the selection key.
final StationTransport context = (StationTransport) selectionKey.attachment();
try {
// Get the set of ready I/O operations for the transport channel.
final int readyOps = selectionKey.readyOps();
if ((readyOps & SelectionKey.OP_ACCEPT) != 0) {
// Dispatch the ready transport accept operation.
doAccept(selectionKey, context);
}
if ((readyOps & SelectionKey.OP_CONNECT) != 0) {
// Dispatch the ready transport connect operation.
doConnect(selectionKey, context);
}
if ((readyOps & SelectionKey.OP_READ) != 0) {
// Dispatch the ready transport read operation.
doRead(selectionKey, context);
}
if ((readyOps & SelectionKey.OP_WRITE) != 0) {
// Dispatch the ready transport write operation.
doWrite(selectionKey, context);
}
} catch (CancelledKeyException error) {
// Transport closed during select operation; complete the close.
context.didClose();
}
}
}
} catch (IOException error) {
// Report the selector I/O exception.
this.station.didFail(error);
}
}
/**
* Checks all transports registered with the I/O selector for idle timeouts.
*/
void checkIdle() {
final TransportSettings transportSettings = this.station.transportSettings;
final long now = System.currentTimeMillis();
if (now - this.lastIdleCheck >= transportSettings.idleInterval) {
// Idle interval has elapsed since last timeout check.
final Iterator<SelectionKey> keys = this.selector.keys().iterator();
// Loop over all selection keys registered with the I/O selector.
while (keys.hasNext()) {
final SelectionKey key = keys.next();
final StationTransport context = (StationTransport) key.attachment();
if (context != null) {
// Ask the transport for its desired idle timeout.
long idleTimeout = context.idleTimeout();
if (idleTimeout < 0L) {
// Negative idle timeout means use the default idle timeout.
idleTimeout = transportSettings.idleTimeout;
}
// Zero indicates no idle timeout.
if (idleTimeout > 0L && now - context.lastSelectTime > idleTimeout) {
// Idle timeout has elapsed.
try {
// Close the transport channel.
key.channel().close();
// Timeout the transport.
context.didTimeout();
} catch (IOException error) {
// Report the transport I/O exception.
this.station.transportDidFail(context.transport, error);
}
// Close the transport.
context.didClose();
}
}
}
// Update last timeout check time.
this.lastIdleCheck = now;
}
}
/**
* Dispatches a ready accept operation on the transport {@code context} in
* response to a selection on its {@code selectionKey}.
*/
void doAccept(SelectionKey selectionKey, StationTransport context) {
context.lastSelectTime = System.currentTimeMillis();
context.doAccept();
}
/**
* Dispatches a ready connect operation on the transport {@code context} in
* response to a selection on its {@code selectionKey}. Clears the {@code
* selectionKey}'s {@code OP_CONNECT} interest op to prevent the connect
* operation from being redispatched until reselected by the transport.
*/
void doConnect(SelectionKey selectionKey, StationTransport context) {
selectionKey.interestOps(selectionKey.interestOps() & ~SelectionKey.OP_CONNECT);
context.lastSelectTime = System.currentTimeMillis();
context.doConnect();
}
/**
* Dispatches a ready read operation on the transport {@code context} in
* response to a selection on its {@code selectionKey}. Clears the {@code
* selectionKey}'s {@code OP_READ} interest op to prevent the read operation
* operation from being redispatched until reselected by the transport.
*/
void doRead(SelectionKey selectionKey, StationTransport context) {
selectionKey.interestOps(selectionKey.interestOps() & ~SelectionKey.OP_READ);
context.lastSelectTime = System.currentTimeMillis();
context.cueRead();
}
/**
* Dispatches a ready write operation on the transport {@code context} in
* response to a selection on its {@code selectionKey}. Clears the {@code
* selectionKey}'s {@code OP_WRITE} interest op to prevent the write
* operation from being retriggered until reselected by the transport.
*/
void doWrite(SelectionKey selectionKey, StationTransport context) {
selectionKey.interestOps(selectionKey.interestOps() & ~SelectionKey.OP_WRITE);
context.lastSelectTime = System.currentTimeMillis();
context.cueWrite();
}
/**
* Closes all transports registered with the I/O selector.
*/
void closeAll() {
for (SelectionKey selectionKey : this.selector.keys()) {
final StationTransport context = (StationTransport) selectionKey.attachment();
if (context != null) {
try {
context.close();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
// Report transport close error.
this.station.transportDidFail(context.transport, error);
} else {
// Rethrow fatal exception.
throw error;
}
}
}
}
}
/**
* Total number of selector threads that have ever been instantiated. Used
* to uniquely name selector threads.
*/
static final AtomicInteger THREAD_COUNT = new AtomicInteger(0);
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/StationException.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.io;
/**
* Thrown when a {@link Station} encounters an error.
*/
public class StationException extends RuntimeException {
private static final long serialVersionUID = 1L;
public StationException(String message, Throwable cause) {
super(message, cause);
}
public StationException(String message) {
super(message);
}
public StationException(Throwable cause) {
super(cause);
}
public StationException() {
super();
}
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/TcpService.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.io;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
class TcpService implements Transport, IpServiceContext {
final Station station;
final InetSocketAddress localAddress;
final ServerSocketChannel serverChannel;
final IpService service;
final IpSettings ipSettings;
TransportContext context;
TcpService(Station station, InetSocketAddress localAddress,
ServerSocketChannel serverChannel, IpService service,
IpSettings ipSettings) {
this.station = station;
this.localAddress = localAddress;
this.serverChannel = serverChannel;
this.service = service;
this.ipSettings = ipSettings;
}
@Override
public TransportContext transportContext() {
return this.context;
}
@Override
public void setTransportContext(TransportContext context) {
this.context = context;
}
@Override
public ServerSocketChannel channel() {
return this.serverChannel;
}
@Override
public ByteBuffer readBuffer() {
throw new UnsupportedOperationException();
}
@Override
public ByteBuffer writeBuffer() {
throw new UnsupportedOperationException();
}
@Override
public long idleTimeout() {
return 0L; // never timeout
}
@Override
public InetSocketAddress localAddress() {
return this.localAddress;
}
@Override
public IpSettings ipSettings() {
return this.ipSettings;
}
@Override
public FlowControl flowControl() {
return this.context.flowControl();
}
@Override
public void flowControl(FlowControl flowControl) {
this.context.flowControl(flowControl);
}
@Override
public FlowControl flowControl(FlowModifier flowModifier) {
return this.context.flowControl(flowModifier);
}
@Override
public void unbind() {
this.context.close();
}
@Override
public void doAccept() throws IOException {
final SocketChannel channel;
try {
channel = this.serverChannel.accept();
} catch (ClosedChannelException error) {
return;
}
if (channel == null) {
return;
}
channel.configureBlocking(false);
this.ipSettings.configure(channel.socket());
final IpSocket socket = this.service.createSocket();
final InetSocketAddress remoteAddress = (InetSocketAddress) channel.socket().getRemoteSocketAddress();
final TcpSocket transport = new TcpSocket(this.localAddress, remoteAddress, channel, this.ipSettings, false);
transport.become(socket);
this.station.transport(transport, FlowControl.WAIT);
this.service.didAccept(socket);
transport.didConnect();
}
@Override
public void doConnect() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public void doRead() {
throw new UnsupportedOperationException();
}
@Override
public void doWrite() {
throw new UnsupportedOperationException();
}
@Override
public void didWrite() {
throw new UnsupportedOperationException();
}
void didBind() {
this.service.didBind();
}
void didAccept(IpSocket socket) {
this.service.didAccept(socket);
}
void didUnbind() {
this.service.didUnbind();
}
@Override
public void didTimeout() {
// stub
}
@Override
public void didClose() {
didUnbind();
}
@Override
public void didFail(Throwable error) {
this.service.didFail(error);
}
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/TcpSettings.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.io;
import java.net.Socket;
import java.net.SocketException;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Record;
import swim.structure.Value;
import swim.util.Murmur3;
/**
* TCP configuration parameters.
*/
public class TcpSettings implements Debug {
protected final boolean keepAlive;
protected final boolean noDelay;
protected final int receiveBufferSize;
protected final int sendBufferSize;
protected final int readBufferSize;
protected final int writeBufferSize;
public TcpSettings(boolean keepAlive, boolean noDelay, int receiveBufferSize,
int sendBufferSize, int readBufferSize, int writeBufferSize) {
this.keepAlive = keepAlive;
this.noDelay = noDelay;
this.receiveBufferSize = receiveBufferSize;
this.sendBufferSize = sendBufferSize;
this.readBufferSize = readBufferSize;
this.writeBufferSize = writeBufferSize;
}
/**
* Returns {@code true} if TCP should be configured with the {@code
* SO_KEEPALIVE} socket option to send keepalive probes to prevent idle
* connections from timing out.
*/
public final boolean keepAlive() {
return this.keepAlive;
}
/**
* Returns a copy of these {@code TcpSettings} configured with the given
* {@code keepAlive} value for the {@code SO_KEEPALIVE} socket option.
*/
public TcpSettings keepAlive(boolean keepAlive) {
return copy(keepAlive, this.noDelay, this.receiveBufferSize,
this.sendBufferSize, this.readBufferSize, this.writeBufferSize);
}
/**
* Returns {@code true} if TCP should be configured with the {@code
* TCP_NODELAY} socket option to disable Nagle's algorithm.
*/
public final boolean noDelay() {
return this.noDelay;
}
/**
* Returns a copy of these {@code TcpSettings} configured with the given
* {@code noDelay} value for the {@code TCP_NODELAY} socket option.
*/
public TcpSettings noDelay(boolean noDelay) {
return copy(this.keepAlive, noDelay, this.receiveBufferSize,
this.sendBufferSize, this.readBufferSize, this.writeBufferSize);
}
/**
* Returns the value of the {@code SO_RCVBUF} socket option with which TCP
* should be configured to control the size of receive buffers.
*/
public final int receiveBufferSize() {
return this.receiveBufferSize;
}
/**
* Returns a copy of these {@code TcpSettings} configured with the given
* {@code receiveBufferSize} value for the {@code SO_RCVBUF} socket option.
*/
public TcpSettings receiveBufferSize(int receiveBufferSize) {
return copy(this.keepAlive, this.noDelay, receiveBufferSize,
this.sendBufferSize, this.readBufferSize, this.writeBufferSize);
}
/**
* Returns the value of the {@code SO_SNDBUF} socket option with which TCP
* should be configured to control the size of send buffers.
*/
public final int sendBufferSize() {
return this.sendBufferSize;
}
/**
* Returns a copy of these {@code TcpSettings} configured with the given
* {@code sendBufferSize} value for the {@code SO_SNDBUF} socket option.
*/
public TcpSettings sendBufferSize(int sendBufferSize) {
return copy(this.keepAlive, this.noDelay, this.receiveBufferSize,
sendBufferSize, this.readBufferSize, this.writeBufferSize);
}
/**
* Returns the size in bytes of the per-socket userspace buffers into which
* data is received.
*/
public final int readBufferSize() {
return this.readBufferSize;
}
/**
* Returns a copy of these {@code TcpSettings} configured with the given
* {@code readBufferSize} for per-socket userspace read buffers.
*/
public TcpSettings readBufferSize(int readBufferSize) {
return copy(this.keepAlive, this.noDelay, this.receiveBufferSize,
this.sendBufferSize, readBufferSize, this.writeBufferSize);
}
/**
* Returns the size in bytes of the per-socket userspace buffers from which
* data is sent.
*/
public final int writeBufferSize() {
return this.writeBufferSize;
}
/**
* Returns a copy of these {@code TcpSettings} configured with the given
* {@code writeBufferSize} for per-socket userspace write buffers.
*/
public TcpSettings writeBufferSize(int writeBufferSize) {
return copy(this.keepAlive, this.noDelay, this.receiveBufferSize,
this.sendBufferSize, this.readBufferSize, writeBufferSize);
}
/**
* Returns a new {@code TcpSettings} instance with the given options.
* Subclasses may override this method to ensure the proper class is
* instantiated when updating settings.
*/
protected TcpSettings copy(boolean keepAlive, boolean noDelay, int receiveBufferSize,
int sendBufferSize, int readBufferSize, int writeBufferSize) {
return new TcpSettings(keepAlive, noDelay, receiveBufferSize,
sendBufferSize, readBufferSize, writeBufferSize);
}
/**
* Configures the {@code socket} with these {@code TcpSettings}.
*/
public void configure(Socket socket) throws SocketException {
socket.setKeepAlive(this.keepAlive);
socket.setTcpNoDelay(this.noDelay);
if (this.receiveBufferSize != 0) {
socket.setReceiveBufferSize(this.receiveBufferSize);
}
if (this.sendBufferSize != 0) {
socket.setSendBufferSize(this.sendBufferSize);
}
}
/**
* Returns a structural {@code Value} representing these {@code TcpSettings}.
*/
public Value toValue() {
return form().mold(this).toValue();
}
/**
* Returns {@code true} if these {@code TcpSettings} can possibly equal some
* {@code other} object.
*/
public boolean canEqual(Object other) {
return other instanceof TcpSettings;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof TcpSettings) {
final TcpSettings that = (TcpSettings) other;
return that.canEqual(this) && this.keepAlive == that.keepAlive && this.noDelay == that.noDelay
&& this.receiveBufferSize == that.receiveBufferSize && this.sendBufferSize == that.sendBufferSize
&& this.readBufferSize == that.readBufferSize && this.writeBufferSize == that.writeBufferSize;
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(TcpSettings.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(Murmur3.mix(Murmur3.mix(Murmur3.mix(
hashSeed, Murmur3.hash(this.keepAlive)), Murmur3.hash(this.noDelay)), this.receiveBufferSize),
this.sendBufferSize), this.readBufferSize), this.writeBufferSize));
}
@Override
public void debug(Output<?> output) {
output = output.write("TcpSettings").write('.').write("standard").write('(').write(')')
.write('.').write("noDelay").write('(').debug(this.noDelay).write(')')
.write('.').write("keepAlive").write('(').debug(this.keepAlive).write(')')
.write('.').write("receiveBufferSize").write('(').debug(this.receiveBufferSize).write(')')
.write('.').write("sendBufferSize").write('(').debug(this.sendBufferSize).write(')')
.write('.').write("readBufferSize").write('(').debug(this.readBufferSize).write(')')
.write('.').write("writeBufferSize").write('(').debug(this.writeBufferSize).write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static TcpSettings standard;
private static Form<TcpSettings> form;
/**
* Returns the default {@code TcpSettings} instance.
*/
public static TcpSettings standard() {
if (standard == null) {
final boolean keepAlive = Boolean.parseBoolean(System.getProperty("swim.tcp.keepalive"));
final boolean noDelay = Boolean.parseBoolean(System.getProperty("swim.tcp.nodelay"));
int receiveBufferSize;
try {
receiveBufferSize = Integer.parseInt(System.getProperty("swim.tcp.receive.buffer.size"));
} catch (NumberFormatException error) {
receiveBufferSize = 0;
}
int sendBufferSize;
try {
sendBufferSize = Integer.parseInt(System.getProperty("swim.tcp.send.buffer.size"));
} catch (NumberFormatException error) {
sendBufferSize = 0;
}
int readBufferSize;
try {
readBufferSize = Integer.parseInt(System.getProperty("swim.tcp.read.buffer.size"));
} catch (NumberFormatException error) {
readBufferSize = 4096;
}
int writeBufferSize;
try {
writeBufferSize = Integer.parseInt(System.getProperty("swim.tcp.write.buffer.size"));
} catch (NumberFormatException error) {
writeBufferSize = 4096;
}
standard = new TcpSettings(keepAlive, noDelay, receiveBufferSize,
sendBufferSize, readBufferSize, writeBufferSize);
}
return standard;
}
/**
* Returns the structural {@code Form} of {@code TcpSettings}.
*/
@Kind
public static Form<TcpSettings> form() {
if (form == null) {
form = new TcpSettingsForm();
}
return form;
}
}
final class TcpSettingsForm extends Form<TcpSettings> {
@Override
public String tag() {
return "tcp";
}
@Override
public TcpSettings unit() {
return TcpSettings.standard();
}
@Override
public Class<?> type() {
return TcpSettings.class;
}
@Override
public Item mold(TcpSettings settings) {
if (settings != null) {
final TcpSettings standard = TcpSettings.standard();
final Record record = Record.create(7).attr(tag());
if (settings.keepAlive != standard.keepAlive) {
record.slot("keepAlive", true);
}
if (settings.noDelay != standard.noDelay) {
record.slot("noDelay", true);
}
if (settings.receiveBufferSize != standard.receiveBufferSize) {
record.slot("receiveBufferSize", settings.receiveBufferSize);
}
if (settings.sendBufferSize != standard.sendBufferSize) {
record.slot("sendBufferSize", settings.sendBufferSize);
}
if (settings.readBufferSize != standard.readBufferSize) {
record.slot("readBufferSize", settings.readBufferSize);
}
if (settings.writeBufferSize != standard.writeBufferSize) {
record.slot("writeBufferSize", settings.writeBufferSize);
}
return record;
} else {
return Item.extant();
}
}
@Override
public TcpSettings cast(Item item) {
final Value value = item.toValue();
if (value.getAttr(tag()).isDefined()) {
final TcpSettings standard = TcpSettings.standard();
final boolean keepAlive = value.get("keepAlive").booleanValue(standard.keepAlive);
final boolean noDelay = value.get("noDelay").booleanValue(standard.noDelay);
final int receiveBufferSize = value.get("receiveBufferSize").intValue(standard.receiveBufferSize);
final int sendBufferSize = value.get("sendBufferSize").intValue(standard.sendBufferSize);
final int readBufferSize = value.get("readBufferSize").intValue(standard.readBufferSize);
final int writeBufferSize = value.get("writeBufferSize").intValue(standard.writeBufferSize);
return new TcpSettings(keepAlive, noDelay, receiveBufferSize,
sendBufferSize, readBufferSize, writeBufferSize);
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/TcpSocket.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.io;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import swim.codec.Binary;
import swim.codec.InputBuffer;
import swim.codec.OutputBuffer;
import swim.concurrent.Conts;
class TcpSocket implements Transport, IpSocketContext {
final InetSocketAddress localAddress;
final InetSocketAddress remoteAddress;
final ByteBuffer readBuffer;
final ByteBuffer writeBuffer;
final InputBuffer inputBuffer;
final OutputBuffer<?> outputBuffer;
final SocketChannel channel;
final IpSettings ipSettings;
TransportContext context;
volatile IpSocket socket;
volatile int status;
TcpSocket(InetSocketAddress localAddress, InetSocketAddress remoteAddress,
SocketChannel channel, IpSettings ipSettings, boolean isClient) {
this.localAddress = localAddress;
this.remoteAddress = remoteAddress;
this.channel = channel;
this.ipSettings = ipSettings;
this.status = isClient ? CLIENT : SERVER;
final TcpSettings tcpSettings = ipSettings.tcpSettings();
this.readBuffer = ByteBuffer.allocate(tcpSettings.readBufferSize());
this.writeBuffer = ByteBuffer.allocate(tcpSettings.writeBufferSize());
((Buffer) this.writeBuffer).position(this.writeBuffer.capacity());
this.inputBuffer = Binary.inputBuffer(this.readBuffer);
this.outputBuffer = Binary.outputBuffer(this.writeBuffer);
}
@Override
public TransportContext transportContext() {
return this.context;
}
@Override
public void setTransportContext(TransportContext context) {
this.context = context;
}
@Override
public SocketChannel channel() {
return this.channel;
}
@Override
public ByteBuffer readBuffer() {
return this.readBuffer;
}
@Override
public ByteBuffer writeBuffer() {
return this.writeBuffer;
}
@Override
public long idleTimeout() {
return this.socket.idleTimeout();
}
@Override
public IpSettings ipSettings() {
return this.ipSettings;
}
@Override
public InputBuffer inputBuffer() {
return this.inputBuffer;
}
@Override
public OutputBuffer<?> outputBuffer() {
return this.outputBuffer;
}
@Override
public boolean isConnected() {
return (STATUS.get(this) & CONNECTED) != 0;
}
@Override
public boolean isClient() {
return (STATUS.get(this) & CLIENT) != 0;
}
@Override
public boolean isServer() {
return (STATUS.get(this) & SERVER) != 0;
}
@Override
public boolean isSecure() {
return false;
}
@Override
public String securityProtocol() {
return null;
}
@Override
public String cipherSuite() {
return null;
}
@Override
public InetSocketAddress localAddress() {
return this.localAddress;
}
@Override
public Principal localPrincipal() {
return null;
}
@Override
public Collection<Certificate> localCertificates() {
return Collections.emptyList();
}
@Override
public InetSocketAddress remoteAddress() {
return this.remoteAddress;
}
@Override
public Principal remotePrincipal() {
return null;
}
@Override
public Collection<Certificate> remoteCertificates() {
return Collections.emptyList();
}
@Override
public FlowControl flowControl() {
return this.context.flowControl();
}
@Override
public void flowControl(FlowControl flowControl) {
this.context.flowControl(flowControl);
}
@Override
public FlowControl flowControl(FlowModifier flowModifier) {
return this.context.flowControl(flowModifier);
}
@Override
public void become(IpSocket newSocket) {
final IpSocket oldSocket = this.socket;
if (oldSocket != null) {
oldSocket.willBecome(newSocket);
}
final int status = STATUS.get(this);
newSocket.setIpSocketContext(this);
this.socket = newSocket;
if ((status & CONNECTED) != 0) {
newSocket.didConnect();
} else if ((status & CONNECTING) != 0) {
newSocket.willConnect();
}
if (oldSocket != null) {
oldSocket.didBecome(newSocket);
}
}
@Override
public void close() {
this.context.close();
}
@Override
public void doAccept() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public void doConnect() throws IOException {
try {
this.channel.finishConnect();
didConnect();
} catch (ConnectException error) {
didClose();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
didFail(error);
} else {
throw error;
}
}
}
@Override
public void doRead() {
this.socket.doRead();
}
@Override
public void doWrite() {
this.socket.doWrite();
}
@Override
public void didWrite() {
this.socket.didWrite();
}
void willConnect() {
do {
final int oldStatus = STATUS.get(this);
if ((status & CONNECTING) == 0) {
final int newStatus = oldStatus | CONNECTING;
if (STATUS.compareAndSet(this, oldStatus, newStatus)) {
this.socket.willConnect();
break;
}
} else {
break;
}
} while (true);
}
void didConnect() {
do {
final int oldStatus = STATUS.get(this);
if ((oldStatus & (CONNECTING | CONNECTED)) != CONNECTED) {
final int newStatus = oldStatus & ~CONNECTING | CONNECTED;
if (STATUS.compareAndSet(this, oldStatus, newStatus)) {
this.socket.didConnect();
break;
}
} else {
break;
}
} while (true);
}
@Override
public void didClose() {
do {
final int oldStatus = STATUS.get(this);
if ((status & (CONNECTING | CONNECTED)) != 0) {
final int newStatus = oldStatus & ~(CONNECTING | CONNECTED);
if (STATUS.compareAndSet(this, oldStatus, newStatus)) {
this.socket.didDisconnect();
break;
}
} else {
break;
}
} while (true);
}
@Override
public void didTimeout() {
this.socket.didTimeout();
}
@Override
public void didFail(Throwable error) {
if (!(error instanceof IOException)) {
this.socket.didFail(error);
}
close();
}
static final int CLIENT = 1 << 0;
static final int SERVER = 1 << 1;
static final int CONNECTING = 1 << 2;
static final int CONNECTED = 1 << 3;
static final AtomicIntegerFieldUpdater<TcpSocket> STATUS =
AtomicIntegerFieldUpdater.newUpdater(TcpSocket.class, "status");
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/TlsService.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.io;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Collection;
import javax.net.ssl.SSLEngine;
class TlsService implements Transport, IpServiceContext {
final Station station;
final InetSocketAddress localAddress;
final ServerSocketChannel serverChannel;
final IpService service;
final IpSettings ipSettings;
TransportContext context;
TlsService(Station station, InetSocketAddress localAddress,
ServerSocketChannel serverChannel, IpService service,
IpSettings ipSettings) {
this.station = station;
this.localAddress = localAddress;
this.serverChannel = serverChannel;
this.service = service;
this.ipSettings = ipSettings;
}
@Override
public TransportContext transportContext() {
return this.context;
}
@Override
public void setTransportContext(TransportContext context) {
this.context = context;
}
@Override
public ServerSocketChannel channel() {
return this.serverChannel;
}
@Override
public ByteBuffer readBuffer() {
throw new UnsupportedOperationException();
}
@Override
public ByteBuffer writeBuffer() {
throw new UnsupportedOperationException();
}
@Override
public long idleTimeout() {
return 0L; // never timeout
}
@Override
public InetSocketAddress localAddress() {
return this.localAddress;
}
@Override
public IpSettings ipSettings() {
return this.ipSettings;
}
@Override
public FlowControl flowControl() {
return this.context.flowControl();
}
@Override
public void flowControl(FlowControl flowControl) {
this.context.flowControl(flowControl);
}
@Override
public FlowControl flowControl(FlowModifier flowModifier) {
return this.context.flowControl(flowModifier);
}
@Override
public void unbind() {
this.context.close();
}
@Override
public void doAccept() throws IOException {
final SocketChannel channel;
try {
channel = this.serverChannel.accept();
} catch (ClosedChannelException error) {
return;
}
if (channel == null) {
return;
}
channel.configureBlocking(false);
this.ipSettings.configure(channel.socket());
final InetSocketAddress remoteAddress = (InetSocketAddress) channel.socket().getRemoteSocketAddress();
final TlsSettings tlsSettings = this.ipSettings.tlsSettings();
// Passing host and port to createSSLEngine causes SSLSession reuse problems with TLS 1.3.
final SSLEngine sslEngine = tlsSettings.sslContext().createSSLEngine(/*remoteAddress.getHostString(), remoteAddress.getPort()*/);
sslEngine.setUseClientMode(false);
switch (tlsSettings.clientAuth()) {
case NEED: sslEngine.setNeedClientAuth(true); break;
case WANT: sslEngine.setWantClientAuth(true); break;
case NONE: sslEngine.setWantClientAuth(false); break;
default:
}
final Collection<String> cipherSuites = tlsSettings.cipherSuites();
if (cipherSuites != null) {
sslEngine.setEnabledCipherSuites(cipherSuites.toArray(new String[cipherSuites.size()]));
}
final Collection<String> protocols = tlsSettings.protocols();
if (protocols != null) {
sslEngine.setEnabledProtocols(protocols.toArray(new String[protocols.size()]));
}
final IpSocket socket = this.service.createSocket();
final TlsSocket transport = new TlsSocket(this.localAddress, remoteAddress, channel, sslEngine, this.ipSettings, false);
transport.become(socket);
this.station.transport(transport, FlowControl.WAIT);
this.service.didAccept(socket);
transport.didConnect();
}
@Override
public void doConnect() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public void doRead() {
throw new UnsupportedOperationException();
}
@Override
public void doWrite() {
throw new UnsupportedOperationException();
}
@Override
public void didWrite() {
throw new UnsupportedOperationException();
}
void didBind() {
this.service.didBind();
}
void didAccept(IpSocket socket) {
this.service.didAccept(socket);
}
void didUnbind() {
this.service.didUnbind();
}
@Override
public void didTimeout() {
// stub
}
@Override
public void didClose() {
didUnbind();
}
@Override
public void didFail(Throwable error) {
this.service.didFail(error);
}
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/TlsSettings.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.io;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.Collection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.collections.FingerTrieSeq;
import swim.structure.Form;
import swim.structure.FormException;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Record;
import swim.structure.Value;
import swim.util.Murmur3;
/**
* TLS configuration parameters.
*/
public class TlsSettings implements Debug {
protected final SSLContext sslContext;
protected final ClientAuth clientAuth;
protected final Collection<String> cipherSuites;
protected final Collection<String> protocols;
public TlsSettings(SSLContext sslContext, ClientAuth clientAuth,
Collection<String> cipherSuites,
Collection<String> protocols) {
this.sslContext = sslContext;
this.clientAuth = clientAuth;
this.cipherSuites = cipherSuites;
this.protocols = protocols;
}
/**
* Returns the factory used to create secure sockets.
*/
public final SSLContext sslContext() {
return this.sslContext;
}
/**
* Returns a copy of these {@code TlsSettings} configured with the given
* {@code sslContext} for creating secure sockets.
*/
public TlsSettings sslContext(SSLContext sslContext) {
return copy(sslContext, this.clientAuth, this.cipherSuites, this.protocols);
}
/**
* Returns the authentication requirement for incoming connections.
*/
public final ClientAuth clientAuth() {
return this.clientAuth;
}
/**
* Returns a copy of these {@code TlsSettings} configured with the given
* {@code clientAuth} authentication requirement for incoming connections.
*/
public TlsSettings clientAuth(ClientAuth clientAuth) {
return copy(this.sslContext, clientAuth, this.cipherSuites, this.protocols);
}
/**
* Returns the set of permitted cipher suites for secure socket connections,
* or {@code null} if the system defaults should be used.
*/
public final Collection<String> cipherSuites() {
return this.cipherSuites;
}
/**
* Returns a copy of these {@code TlsSettings} configured with the given set
* of {@code cipherSuites}; {@code cipherSuites} may be {@code null} if the
* system defaults should be used.
*/
public TlsSettings cipherSuites(Collection<String> cipherSuites) {
return copy(this.sslContext, this.clientAuth, cipherSuites, this.protocols);
}
/**
* Returns the set of permitted secure socket layer protocols, or {@code
* null} if the system defaults should be used.
*/
public final Collection<String> protocols() {
return this.protocols;
}
/**
* Returns a copy of these {@code TlsSettings} configured with the given set
* of {@code protocols}; {@code protocols} may be {@code null} if the system
* defaults should be used.
*/
public TlsSettings protocols(Collection<String> protocols) {
return copy(this.sslContext, this.clientAuth, this.cipherSuites, protocols);
}
/**
* Returns a new {@code TlsSettings} instance with the given options.
* Subclasses may override this method to ensure the proper class is
* instantiated when updating settings.
*/
protected TlsSettings copy(SSLContext sslContext, ClientAuth clientAuth,
Collection<String> cipherSuites,
Collection<String> protocols) {
return new TlsSettings(sslContext, clientAuth, cipherSuites, protocols);
}
/**
* Returns a structural {@code Value} representing these {@code TlsSettings}.
*/
public Value toValue() {
return form().mold(this).toValue();
}
/**
* Returns {@code true} if these {@code TlsSettings} can possibly equal some
* {@code other} object.
*/
public boolean canEqual(Object other) {
return other instanceof TlsSettings;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof TlsSettings) {
final TlsSettings that = (TlsSettings) other;
return that.canEqual(this)
&& (this.sslContext == null ? that.sslContext == null : this.sslContext.equals(that.sslContext))
&& this.clientAuth.equals(that.clientAuth)
&& (this.cipherSuites == null ? that.cipherSuites == null : this.cipherSuites.equals(that.cipherSuites))
&& (this.protocols == null ? that.protocols == null : this.protocols.equals(that.protocols));
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(TlsSettings.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed,
Murmur3.hash(this.sslContext)), this.clientAuth.hashCode()),
Murmur3.hash(this.cipherSuites)), Murmur3.hash(this.protocols)));
}
@Override
public void debug(Output<?> output) {
output = output.write("TlsSettings").write('.').write("standard").write('(').write(')')
.write('.').write("sslContext").write('(').debug(this.sslContext).write(')')
.write('.').write("clientAuth").write('(').debug(this.clientAuth).write(')')
.write('.').write("cipherSuites").write('(').debug(this.cipherSuites).write(')')
.write('.').write("protocols").write('(').debug(this.protocols).write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static TlsSettings standard;
private static Form<TlsSettings> form;
public static TlsSettings create(ClientAuth clientAuth,
Collection<String> cipherSuites,
Collection<String> protocols) {
try {
final String tlsProtocol = System.getProperty("swim.tls.protocol", "TLS");
final String tlsProvider = System.getProperty("swim.tls.provider");
final String tlsRandom = System.getProperty("swim.tls.random");
final SecureRandom random;
if (tlsRandom != null) {
random = SecureRandom.getInstance(tlsRandom);
} else {
random = new SecureRandom();
}
final SSLContext sslContext;
if (tlsProvider != null) {
sslContext = SSLContext.getInstance(tlsProtocol, tlsProvider);
} else {
sslContext = SSLContext.getInstance(tlsProtocol);
}
final KeyManager[] keyManagers = loadKeyManagers();
final TrustManager[] trustManagers = loadTrustManagers();
sslContext.init(keyManagers, trustManagers, random);
return new TlsSettings(sslContext, clientAuth, cipherSuites, protocols);
} catch (GeneralSecurityException cause) {
return null;
}
}
/**
* Returns the default {@code TlsSettings} instance.
*/
public static TlsSettings standard() {
if (standard == null) {
ClientAuth clientAuth;
try {
clientAuth = ClientAuth.from(System.getProperty("swim.tls.client.auth"));
} catch (IllegalArgumentException swallow) {
clientAuth = ClientAuth.NONE;
}
FingerTrieSeq<String> cipherSuites;
try {
cipherSuites = FingerTrieSeq.of(System.getProperty("swim.tls.ciphersuites").split(","));
} catch (NullPointerException cause) {
cipherSuites = null;
}
FingerTrieSeq<String> protocols;
try {
protocols = FingerTrieSeq.of(System.getProperty("swim.tls.protocols").split(","));
} catch (NullPointerException cause) {
protocols = null;
}
standard = create(clientAuth, cipherSuites, protocols);
}
return standard;
}
/**
* Returns the structural {@code Form} of {@code TlsSettings}.
*/
@Kind
public static Form<TlsSettings> form() {
if (form == null) {
form = new TlsSettingsForm();
}
return form;
}
static KeyManager[] loadKeyManagers() {
final String path = System.getProperty("swim.tls.keystore.path");
final String resource = System.getProperty("swim.tls.keystore.resource");
if (path != null || resource != null) {
final String type = System.getProperty("swim.tls.keystore.type", KeyStore.getDefaultType());
final String provider = System.getProperty("swim.tls.keystore.provider");
final String password = System.getProperty("swim.tls.keystore.password");
final char[] passwordChars = password != null ? password.toCharArray() : null;
InputStream inputStream = null;
try {
final KeyStore keyStore;
final KeyManagerFactory keyManagerFactory;
if (provider != null) {
keyStore = KeyStore.getInstance(type, provider);
keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm(), provider);
} else {
keyStore = KeyStore.getInstance(type);
keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
}
if (path != null) {
inputStream = new FileInputStream(path);
} else if (resource != null) {
inputStream = ClassLoader.getSystemResourceAsStream(resource);
if (inputStream == null) {
throw new RuntimeException("Missing swim.tls.keystore.resource: " + resource);
}
}
keyStore.load(inputStream, passwordChars);
keyManagerFactory.init(keyStore, passwordChars);
return keyManagerFactory.getKeyManagers();
} catch (GeneralSecurityException | IOException cause) {
throw new RuntimeException(cause);
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException cause) {
throw new RuntimeException(cause);
}
}
}
return null;
}
static TrustManager[] loadTrustManagers() {
final String path = System.getProperty("swim.tls.truststore.path");
final String resource = System.getProperty("swim.tls.truststore.resource");
if (path != null || resource != null) {
final String type = System.getProperty("swim.tls.truststore.type", KeyStore.getDefaultType());
final String provider = System.getProperty("swim.tls.truststore.provider");
final String password = System.getProperty("swim.tls.truststore.password");
final char[] passwordChars = password != null ? password.toCharArray() : null;
InputStream inputStream = null;
try {
final KeyStore trustStore;
final TrustManagerFactory trustManagerFactory;
if (provider != null) {
trustStore = KeyStore.getInstance(type, provider);
trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm(), provider);
} else {
trustStore = KeyStore.getInstance(type);
trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
}
if (path != null) {
inputStream = new FileInputStream(path);
} else if (resource != null) {
inputStream = ClassLoader.getSystemResourceAsStream(resource);
if (inputStream == null) {
throw new RuntimeException("Missing swim.tls.truststore.resource: " + resource);
}
}
trustStore.load(inputStream, passwordChars);
trustManagerFactory.init(trustStore);
return trustManagerFactory.getTrustManagers();
} catch (GeneralSecurityException | IOException cause) {
throw new RuntimeException(cause);
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException cause) {
throw new RuntimeException(cause);
}
}
}
return null;
}
}
final class TlsSettingsForm extends Form<TlsSettings> {
@Override
public String tag() {
return "tls";
}
@Override
public Class<?> type() {
return TlsSettings.class;
}
@Override
public Item mold(TlsSettings settings) {
if (settings != null) {
final Record header = Record.create(2)
.slot("protocol", settings.sslContext.getProtocol())
.slot("provider", settings.sslContext.getProvider().getName());
final Record record = Record.create(4).attr(tag(), header);
if (settings.clientAuth != ClientAuth.NONE) {
record.slot("clientAuth", ClientAuth.form().mold(settings.clientAuth).toValue());
}
if (settings.cipherSuites != null) {
final Record cipherSuites = Record.create(settings.cipherSuites.size());
for (String cipherSuite : settings.cipherSuites) {
cipherSuites.item(cipherSuite);
}
record.slot("cipherSuites", cipherSuites);
}
if (settings.protocols != null) {
final Record protocols = Record.create(settings.protocols.size());
for (String protocol : settings.protocols) {
protocols.item(protocol);
}
record.slot("protocols", protocols);
}
return record;
} else {
return Item.extant();
}
}
@Override
public TlsSettings cast(Item item) {
final Value value = item.toValue();
final Value header = value.getAttr(tag());
if (header.isDefined()) {
final String tlsProtocol = header.get("protocol").stringValue(System.getProperty("swim.tls.protocol", "TLS"));
final String tlsProvider = header.get("provider").stringValue(System.getProperty("swim.tls.provider"));
final String tlsRandom = header.get("random").stringValue(System.getProperty("swim.tls.random"));
KeyManager[] keyManagers = TlsSettings.loadKeyManagers();
TrustManager[] trustManagers = TlsSettings.loadTrustManagers();
for (Item member : value) {
final KeyManagerFactory keyManagerFactory = castKeyManagerFactory(member.toValue());
if (keyManagerFactory != null) {
if (keyManagers == null) {
keyManagers = keyManagerFactory.getKeyManagers();
} else {
final KeyManager[] newKeyManagers = keyManagerFactory.getKeyManagers();
if (newKeyManagers != null && newKeyManagers.length > 0) {
final KeyManager[] oldKeyManagers = keyManagers;
keyManagers = new KeyManager[oldKeyManagers.length + newKeyManagers.length];
System.arraycopy(oldKeyManagers, 0, keyManagers, 0, oldKeyManagers.length);
System.arraycopy(newKeyManagers, 0, keyManagers, oldKeyManagers.length, newKeyManagers.length);
}
}
}
final TrustManagerFactory trustManagerFactory = castTrustManagerFactory(member.toValue());
if (trustManagerFactory != null) {
if (trustManagers == null) {
trustManagers = trustManagerFactory.getTrustManagers();
} else {
final TrustManager[] newTrustManagers = trustManagerFactory.getTrustManagers();
if (newTrustManagers != null && newTrustManagers.length > 0) {
final TrustManager[] oldTrustManagers = trustManagers;
trustManagers = new TrustManager[oldTrustManagers.length + newTrustManagers.length];
System.arraycopy(oldTrustManagers, 0, trustManagers, 0, oldTrustManagers.length);
System.arraycopy(newTrustManagers, 0, trustManagers, oldTrustManagers.length, newTrustManagers.length);
}
}
}
}
final SSLContext sslContext;
try {
final SecureRandom random;
if (tlsRandom != null) {
random = SecureRandom.getInstance(tlsRandom);
} else {
random = new SecureRandom();
}
if (tlsProvider != null) {
sslContext = SSLContext.getInstance(tlsProtocol, tlsProvider);
} else {
sslContext = SSLContext.getInstance(tlsProtocol);
}
sslContext.init(keyManagers, trustManagers, random);
} catch (GeneralSecurityException cause) {
throw new IpException(cause);
}
ClientAuth clientAuth = ClientAuth.form().cast(value.get("clientAuth"));
if (clientAuth == null) {
try {
clientAuth = ClientAuth.from(System.getProperty("swim.tls.client.auth"));
} catch (IllegalArgumentException swallow) {
clientAuth = ClientAuth.NONE;
}
}
FingerTrieSeq<String> cipherSuites;
if (value.containsKey("cipherSuites")) {
cipherSuites = FingerTrieSeq.empty();
for (Item cipherSuite : value.get("cipherSuites")) {
cipherSuites = cipherSuites.appended(cipherSuite.stringValue());
}
} else {
try {
cipherSuites = FingerTrieSeq.of(System.getProperty("swim.tls.ciphersuites").split(","));
} catch (NullPointerException cause) {
cipherSuites = null;
}
}
FingerTrieSeq<String> protocols;
if (value.containsKey("protocols")) {
protocols = FingerTrieSeq.empty();
for (Item protocol : value.get("protocols")) {
protocols = protocols.appended(protocol.stringValue());
}
} else {
try {
protocols = FingerTrieSeq.of(System.getProperty("swim.tls.protocols").split(","));
} catch (NullPointerException cause) {
protocols = null;
}
}
return new TlsSettings(sslContext, clientAuth, cipherSuites, protocols);
}
return null;
}
private KeyManagerFactory castKeyManagerFactory(Value value) {
final Value header = value.getAttr("keyStore");
if (header.isDefined()) {
final String type = header.get("type").stringValue(KeyStore.getDefaultType());
final String provider = header.get("provider").stringValue(null);
final KeyStore keyStore;
final KeyManagerFactory keyManagerFactory;
try {
if (provider != null) {
keyStore = KeyStore.getInstance(type, provider);
keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm(), provider);
} else {
keyStore = KeyStore.getInstance(type);
keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
}
} catch (GeneralSecurityException cause) {
throw new IpException(cause);
}
final String path = value.get("path").stringValue(null);
final String resource = value.get("resource").stringValue(null);
final String password = value.get("password").stringValue(null);
final char[] passwordChars = password != null ? password.toCharArray() : null;
InputStream inputStream = null;
try {
if (path != null) {
inputStream = new FileInputStream(path);
} else if (resource != null) {
inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
if (inputStream == null) {
throw new FormException("Missing keystore resource: " + resource);
}
}
keyStore.load(inputStream, passwordChars);
keyManagerFactory.init(keyStore, passwordChars);
return keyManagerFactory;
} catch (GeneralSecurityException cause) {
throw new IpException(cause);
} catch (IOException cause) {
throw new FormException(cause);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException cause) {
throw new FormException(cause);
}
}
}
}
return null;
}
private TrustManagerFactory castTrustManagerFactory(Value value) {
final Value header = value.getAttr("trustStore");
if (header.isDefined()) {
final String type = header.get("type").stringValue(KeyStore.getDefaultType());
final String provider = header.get("provider").stringValue(null);
final KeyStore trustStore;
final TrustManagerFactory trustManagerFactory;
try {
if (provider != null) {
trustStore = KeyStore.getInstance(type, provider);
trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm(), provider);
} else {
trustStore = KeyStore.getInstance(type);
trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
}
} catch (GeneralSecurityException cause) {
throw new IpException(cause);
}
final String path = value.get("path").stringValue(null);
final String resource = value.get("resource").stringValue(null);
final String password = value.get("password").stringValue(null);
final char[] passwordChars = password != null ? password.toCharArray() : null;
InputStream inputStream = null;
try {
if (path != null) {
inputStream = new FileInputStream(path);
} else if (resource != null) {
inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
if (inputStream == null) {
throw new FormException("Missing truststore resource: " + resource);
}
}
trustStore.load(inputStream, passwordChars);
trustManagerFactory.init(trustStore);
return trustManagerFactory;
} catch (GeneralSecurityException cause) {
throw new IpException(cause);
} catch (IOException cause) {
throw new FormException(cause);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException cause) {
throw new FormException(cause);
}
}
}
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/TlsSocket.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.io;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import swim.codec.Binary;
import swim.codec.InputBuffer;
import swim.codec.OutputBuffer;
import swim.concurrent.Conts;
class TlsSocket implements Transport, IpSocketContext {
final InetSocketAddress localAddress;
final InetSocketAddress remoteAddress;
final ByteBuffer readBuffer;
final ByteBuffer writeBuffer;
final ByteBuffer inputBuffer;
final ByteBuffer outputBuffer;
final InputBuffer reader;
final OutputBuffer<?> writer;
final SocketChannel channel;
final SSLEngine sslEngine;
final IpSettings ipSettings;
TransportContext context;
volatile IpSocket socket;
volatile FlowControl flowControl;
volatile int status;
TlsSocket(InetSocketAddress localAddress, InetSocketAddress remoteAddress, SocketChannel channel,
SSLEngine sslEngine, IpSettings ipSettings, boolean isClient) {
this.localAddress = localAddress;
this.remoteAddress = remoteAddress;
this.channel = channel;
this.sslEngine = sslEngine;
this.ipSettings = ipSettings;
this.flowControl = FlowControl.WAIT;
this.status = isClient ? CLIENT : SERVER;
final SSLSession sslSession = this.sslEngine.getSession();
final TcpSettings tcpSettings = this.ipSettings.tcpSettings();
final int readBufferSize = Math.max(tcpSettings.readBufferSize(), sslSession.getApplicationBufferSize());
final int writeBufferSize = Math.max(tcpSettings.writeBufferSize(), sslSession.getPacketBufferSize());
this.readBuffer = ByteBuffer.allocate(readBufferSize);
this.writeBuffer = ByteBuffer.allocate(writeBufferSize);
((Buffer) this.writeBuffer).position(this.writeBuffer.capacity());
this.inputBuffer = ByteBuffer.allocate(readBufferSize);
this.outputBuffer = ByteBuffer.allocate(writeBufferSize);
((Buffer) this.outputBuffer).position(this.outputBuffer.capacity());
this.reader = Binary.inputBuffer(inputBuffer);
this.writer = Binary.outputBuffer(outputBuffer);
}
@Override
public TransportContext transportContext() {
return this.context;
}
@Override
public void setTransportContext(TransportContext context) {
this.context = context;
}
@Override
public SocketChannel channel() {
return this.channel;
}
@Override
public ByteBuffer readBuffer() {
return this.readBuffer;
}
@Override
public ByteBuffer writeBuffer() {
return this.writeBuffer;
}
@Override
public long idleTimeout() {
return this.socket.idleTimeout();
}
@Override
public IpSettings ipSettings() {
return this.ipSettings;
}
@Override
public InputBuffer inputBuffer() {
return this.reader;
}
@Override
public OutputBuffer<?> outputBuffer() {
return this.writer;
}
@Override
public boolean isConnected() {
return (this.status & CONNECTED) != 0;
}
@Override
public boolean isClient() {
return (this.status & CLIENT) != 0;
}
@Override
public boolean isServer() {
return (this.status & SERVER) != 0;
}
@Override
public boolean isSecure() {
return true;
}
@Override
public String securityProtocol() {
return this.sslEngine.getSession().getProtocol();
}
@Override
public String cipherSuite() {
return this.sslEngine.getSession().getCipherSuite();
}
@Override
public InetSocketAddress localAddress() {
return this.localAddress;
}
@Override
public Principal localPrincipal() {
return this.sslEngine.getSession().getLocalPrincipal();
}
@Override
public Collection<Certificate> localCertificates() {
final Certificate[] certificates = this.sslEngine.getSession().getLocalCertificates();
if (certificates != null) {
return Arrays.asList(certificates);
} else {
return Collections.emptyList();
}
}
@Override
public InetSocketAddress remoteAddress() {
return this.remoteAddress;
}
@Override
public Principal remotePrincipal() {
try {
return this.sslEngine.getSession().getPeerPrincipal();
} catch (SSLException error) {
return null;
}
}
@Override
public Collection<Certificate> remoteCertificates() {
try {
final Certificate[] certificates = this.sslEngine.getSession().getPeerCertificates();
if (certificates != null) {
return Arrays.asList(certificates);
}
} catch (SSLException error) {
// ignore
}
return Collections.emptyList();
}
@Override
public FlowControl flowControl() {
return this.flowControl;
}
@Override
public void flowControl(FlowControl flowControl) {
FLOW_CONTROL.set(this, flowControl);
if ((this.status & HANDSHAKING) == 0) {
this.context.flowControl(flowControl);
}
}
@Override
public FlowControl flowControl(FlowModifier flowModifier) {
FlowControl oldFlow;
FlowControl newFlow;
do {
oldFlow = this.flowControl;
newFlow = oldFlow.modify(flowModifier);
if (!oldFlow.equals(newFlow)) {
if (FLOW_CONTROL.compareAndSet(this, oldFlow, newFlow)) {
break;
}
} else {
break;
}
} while (true);
if ((this.status & HANDSHAKING) == 0) {
return this.context.flowControl(flowModifier);
} else {
return newFlow;
}
}
@Override
public void become(IpSocket newSocket) {
final IpSocket oldSocket = this.socket;
if (oldSocket != null) {
oldSocket.willBecome(newSocket);
}
final int status = this.status;
newSocket.setIpSocketContext(this);
this.socket = newSocket;
if ((status & CONNECTED) != 0) {
newSocket.didConnect();
} else if ((status & CONNECTING) != 0) {
newSocket.willConnect();
}
if (oldSocket != null) {
oldSocket.didBecome(newSocket);
}
}
@Override
public void close() {
this.context.close();
}
@Override
public void doAccept() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public void doConnect() throws IOException {
try {
this.channel.finishConnect();
didConnect();
} catch (ConnectException error) {
didClose();
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
didFail(error);
} else {
throw error;
}
}
}
@Override
public void doRead() {
read: do {
final SSLEngineResult result;
try {
result = this.sslEngine.unwrap(this.readBuffer, this.inputBuffer);
} catch (SSLException error) {
this.socket.didFail(error);
close();
return;
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
this.socket.didFail(error);
close();
return;
} else {
throw error;
}
}
final SSLEngineResult.Status sslStatus = result.getStatus();
final SSLEngineResult.HandshakeStatus handshakeStatus;
switch (sslStatus) {
case OK:
if (this.inputBuffer.position() > 0) {
((Buffer) this.inputBuffer).flip();
this.socket.doRead();
if (this.inputBuffer.hasRemaining()) {
this.inputBuffer.compact();
} else {
((Buffer) this.inputBuffer).clear();
}
}
handshakeStatus = result.getHandshakeStatus();
switch (handshakeStatus) {
case NEED_UNWRAP:
this.context.flowControl(FlowModifier.ENABLE_READ);
if (this.readBuffer.hasRemaining()) {
continue read;
} else {
break read;
}
case NEED_WRAP:
this.context.flowControl(FlowModifier.ENABLE_READ_WRITE);
break read;
case NEED_TASK:
this.sslEngine.getDelegatedTask().run();
continue read;
case FINISHED:
handshakeAcknowledged();
break read;
case NOT_HANDSHAKING:
break read;
default:
throw new AssertionError(handshakeStatus); // unreachable
}
case CLOSED:
receivedClose();
break read;
case BUFFER_UNDERFLOW:
handshakeStatus = result.getHandshakeStatus();
switch (handshakeStatus) {
case NEED_UNWRAP:
this.context.flowControl(FlowModifier.ENABLE_READ);
break read;
case NEED_WRAP:
this.context.flowControl(FlowModifier.ENABLE_WRITE);
break read;
case NOT_HANDSHAKING:
break read;
default:
throw new AssertionError(handshakeStatus); // unreachable
}
case BUFFER_OVERFLOW:
close();
break read;
default:
throw new AssertionError(sslStatus); // unreachable
}
} while (true);
}
@Override
public void doWrite() {
if ((this.status & (HANDSHAKING | CLOSING)) == 0 && !this.outputBuffer.hasRemaining()) {
((Buffer) this.outputBuffer).clear();
this.socket.doWrite();
((Buffer) this.outputBuffer).flip();
}
final SSLEngineResult result;
try {
result = this.sslEngine.wrap(this.outputBuffer, this.writeBuffer);
} catch (SSLException error) {
this.socket.didFail(error);
close();
return;
} catch (Throwable error) {
if (Conts.isNonFatal(error)) {
this.socket.didFail(error);
close();
return;
} else {
throw error;
}
}
final SSLEngineResult.Status sslStatus = result.getStatus();
switch (sslStatus) {
case OK:
SSLEngineResult.HandshakeStatus handshakeStatus = result.getHandshakeStatus();
switch (handshakeStatus) {
case NEED_UNWRAP:
this.context.flowControl(FlowModifier.ENABLE_READ);
break;
case NEED_WRAP:
this.context.flowControl(FlowModifier.ENABLE_WRITE);
break;
case FINISHED:
handshakeFinished();
break;
case NEED_TASK:
this.sslEngine.getDelegatedTask().run();
handshakeStatus = this.sslEngine.getHandshakeStatus();
switch (handshakeStatus) {
case FINISHED:
handshakeFinished();
break;
default:
throw new AssertionError(handshakeStatus); // unreachable
}
break;
case NOT_HANDSHAKING:
break;
default:
throw new AssertionError(handshakeStatus); // unreachable
}
break;
case CLOSED:
close();
break;
case BUFFER_UNDERFLOW:
close();
break;
case BUFFER_OVERFLOW:
close();
break;
default:
throw new AssertionError(sslStatus); // unreachable
}
}
@Override
public void didWrite() {
final int status = this.status;
if ((status & HANDSHAKING) != 0) {
SSLEngineResult.HandshakeStatus handshakeStatus = this.sslEngine.getHandshakeStatus();
switch (handshakeStatus) {
case NEED_UNWRAP:
this.context.flowControl(FlowModifier.DISABLE_WRITE_ENABLE_READ);
break;
case NEED_WRAP:
this.context.flowControl(FlowModifier.ENABLE_READ_WRITE);
break;
case NEED_TASK:
final Runnable task = this.sslEngine.getDelegatedTask();
if (task != null) {
task.run();
handshakeStatus = this.sslEngine.getHandshakeStatus();
switch (handshakeStatus) {
case FINISHED:
handshakeAcknowledged();
break;
default:
throw new AssertionError(handshakeStatus); // unreachable
}
}
break;
default:
throw new AssertionError(handshakeStatus); // unreachable
}
} else if ((status & HANDSHAKED) != 0) {
handshakeAcknowledged();
} else {
this.socket.didWrite();
}
}
void handshakeFinished() {
do {
final int oldStatus = this.status;
if ((oldStatus & (HANDSHAKING | HANDSHAKED)) != HANDSHAKED) {
final int newStatus = oldStatus & ~HANDSHAKING | HANDSHAKED;
if (STATUS.compareAndSet(this, oldStatus, newStatus)) {
this.socket.didSecure();
break;
}
} else {
break;
}
} while (true);
}
void handshakeAcknowledged() {
do {
final int oldStatus = this.status;
if ((oldStatus & (HANDSHAKING | HANDSHAKED)) != 0) {
final int newStatus = oldStatus & ~(HANDSHAKING | HANDSHAKED);
if (STATUS.compareAndSet(this, oldStatus, newStatus)) {
this.socket.didSecure();
this.context.flowControl(this.flowControl);
break;
}
} else {
break;
}
} while (true);
}
void receivedClose() {
do {
final int oldStatus = this.status;
if ((status & CLOSING) == 0) {
final int newStatus = oldStatus & CLOSING;
if (STATUS.compareAndSet(this, oldStatus, newStatus)) {
this.context.flowControl(FlowControl.READ_WRITE);
break;
}
} else {
break;
}
} while (true);
}
void willConnect() {
do {
final int oldStatus = this.status;
if ((status & CONNECTING) == 0) {
final int newStatus = oldStatus | CONNECTING;
if (STATUS.compareAndSet(this, oldStatus, newStatus)) {
this.socket.willConnect();
break;
}
} else {
break;
}
} while (true);
}
void didConnect() throws SSLException {
do {
final int oldStatus = this.status;
if ((status & (CONNECTING | CONNECTED | HANDSHAKING)) != (CONNECTED | HANDSHAKING)) {
final int newStatus = oldStatus & ~CONNECTING | CONNECTED | HANDSHAKING;
if (STATUS.compareAndSet(this, oldStatus, newStatus)) {
if ((oldStatus & CONNECTED) != (newStatus & CONNECTED)) {
this.socket.didConnect();
}
if ((oldStatus & HANDSHAKING) != (newStatus & HANDSHAKING)) {
this.socket.willSecure();
}
this.sslEngine.beginHandshake();
final SSLEngineResult.HandshakeStatus handshakeStatus = this.sslEngine.getHandshakeStatus();
switch (handshakeStatus) {
case NEED_UNWRAP:
this.context.flowControl(FlowModifier.ENABLE_READ);
break;
case NEED_WRAP:
this.context.flowControl(FlowModifier.ENABLE_READ_WRITE);
break;
default:
throw new AssertionError(handshakeStatus); // unreachable
}
break;
}
} else {
break;
}
} while (true);
}
@Override
public void didClose() {
do {
final int oldStatus = this.status;
if ((status & (CONNECTING | CONNECTED)) != 0) {
final int newStatus = oldStatus & ~(CONNECTING | CONNECTED);
if (STATUS.compareAndSet(this, oldStatus, newStatus)) {
this.socket.didDisconnect();
break;
}
} else {
break;
}
} while (true);
}
@Override
public void didTimeout() {
this.socket.didTimeout();
}
@Override
public void didFail(Throwable error) {
if (!(error instanceof IOException)) {
this.socket.didFail(error);
}
close();
}
static final int CLIENT = 1 << 0;
static final int SERVER = 1 << 1;
static final int CONNECTING = 1 << 2;
static final int CONNECTED = 1 << 3;
static final int HANDSHAKING = 1 << 4;
static final int HANDSHAKED = 1 << 5;
static final int CLOSING = 1 << 6;
static final AtomicReferenceFieldUpdater<TlsSocket, FlowControl> FLOW_CONTROL =
AtomicReferenceFieldUpdater.newUpdater(TlsSocket.class, FlowControl.class, "flowControl");
static final AtomicIntegerFieldUpdater<TlsSocket> STATUS =
AtomicIntegerFieldUpdater.newUpdater(TlsSocket.class, "status");
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/Transport.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.io;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
/**
* I/O transport binding that handles asynchronous I/O operations for a
* non-blocking NIO channel. A {@code Transport} provides a selectable {@link
* #channel()} on which to perform asynchronous I/O operations, along with an
* {@link #readBuffer()} into which input data will be read, and an {@link
* #writeBuffer()} from which data will be written.
*
* A {@code Transport} interfaces with the underlying asynchronous I/O system
* via a {@link TransportContext}. The transport context invokes I/O callbacks
* on the {@code Transport} when the underlying NIO channel is ready to perform
* I/O operations permitted by the transport context's {@link FlowControl}.
*/
public interface Transport {
/**
* Returns the I/O transport context to which this {@code Transport} is bound;
* returns {@code null} if this {@code Transport} is unbound.
*/
TransportContext transportContext();
/**
* Sets the I/O transport context to which this {@code Transport} is bound.
*/
void setTransportContext(TransportContext context);
/**
* Returns the NIO channel that this {@code Transport} manages.
*/
SelectableChannel channel();
/**
* Returns the buffer into which input data should be read by the underlying
* I/O transport.
*/
ByteBuffer readBuffer();
/**
* Returns the buffer from which output data should be written by the
* underlying I/O transport.
*/
ByteBuffer writeBuffer();
/**
* Returns the number of idle milliseconds after which this {@code Transport}
* should be closed due to inactivity. Returns {@code -1} if a default idle
* timeout should be used. Returns {@code 0} if the underlying I/O transport
* should not time out.
*/
long idleTimeout();
/**
* I/O callback invoked by the transport context when the underlying
* transport is ready to complete an <em>accept</em> operation.
*/
void doAccept() throws IOException;
/**
* I/O callback invoked by the transport context when the underlying
* transport is ready to complete a <em>connect</em> operation.
*/
void doConnect() throws IOException;
/**
* I/O callback invoked by the transport context asking this {@code Transport}
* to read input data out of the {@code readBuffer}, thereby completing a
* <em>read</em> operation from the underlying I/O transport. May be invoked
* concurrently to other I/O callbacks, but never concurrently with other
* {@code doRead} calls.
*/
void doRead();
/**
* I/O callback invoked by the transport context asking this {@code Transport}
* to write output data into the {@code writeBuffer}, thereby initiating a
* <em>write</em> operation to the underlying I/O transport. May be invoked
* concurrently to other I/O callbacks, but never concurrently with other
* {@code doWrite} or {@code didWrite} calls.
*/
void doWrite();
/**
* I/O callback invoked by the transport context after the underlying
* transport has completed writing all data in its {@code writeBuffer},
* thereby completing the current <em>write</em> operation. May be invoked
* concurrently to other I/O callbacks, but never concurrently with other
* {@code doWrite} or {@code didWrite} calls.
*/
void didWrite();
/**
* Lifecycle callback invoked by the transport context after the underlying
* transport has timed out. The transport will automatically be closed.
*/
void didTimeout();
/**
* Lifecycle callback invoked by the transport context after the underlying
* transport has closed.
*/
void didClose();
/**
* Lifecycle callback invoked by the transport context when the underlying
* transport fails by throwing an {@code error}. The transport will
* automatically be closed.
*/
void didFail(Throwable error);
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/TransportContext.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.io;
/**
* I/O transport context that manages asynchronous I/O operations for a
* non-blocking NIO channel. A {@code TransportContext} is implicitly bound to
* a {@link Transport}, providing the {@code Transport} with the ability to
* modify its {@link FlowControl} state, and to close the transport.
*/
public interface TransportContext extends TransportRef {
/**
* Returns the configuration parameters that govern the underlying I/O
* transport.
*/
TransportSettings transportSettings();
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/TransportRef.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.io;
/**
* External handle to an I/O {@link Transport}.
*/
public interface TransportRef extends FlowContext {
/**
* Closes the underlying I/O transport.
*/
void close();
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/TransportSettings.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.io;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Record;
import swim.structure.Value;
import swim.util.Murmur3;
/**
* {@link Transport} configuration parameters.
*/
public class TransportSettings implements Debug {
protected final int backlog;
protected final long idleInterval;
protected final long idleTimeout;
public TransportSettings(int backlog, long idleInterval, long idleTimeout) {
this.backlog = backlog;
this.idleInterval = idleInterval;
this.idleTimeout = idleTimeout;
}
/**
* Returns the maximum length of the queue of incoming connections.
*/
public final int backlog() {
return this.backlog;
}
/**
* Returns a copy of these {@code TransportSettings} configured with the
* given {@code backlog} for the maximum length of the queue of incoming
* connections.
*/
public TransportSettings backlog(int backlog) {
return copy(backlog, this.idleInterval, this.idleTimeout);
}
/**
* Returns the number of milliseconds between transport idle checks.
*/
public final long idleInterval() {
return this.idleInterval;
}
/**
* Returns a copy of these {@code TransportSettings} configured with the
* given {@code idleInterval} for transport idle checks.
*/
public TransportSettings idleInterval(long idleInterval) {
return copy(this.backlog, idleInterval, this.idleTimeout);
}
/**
* Returns the default number of idle milliseconds after which a transport
* should be timed out due to inactivity.
*/
public final long idleTimeout() {
return this.idleTimeout;
}
/**
* Returns a copy of these {@code TransportSettings} configured with the
* given {@code idleTimeout} for transport idle timeouts
*/
public TransportSettings idleTimeout(long idleTimeout) {
return copy(this.backlog, this.idleInterval, idleTimeout);
}
/**
* Returns a new {@code TransportSettings} instance with the given options.
* Subclasses may override this method to ensure the proper class is
* instantiated when updating settings.
*/
protected TransportSettings copy(int backlog, long idleInterval, long idleTimeout) {
return new TransportSettings(backlog, idleInterval, idleTimeout);
}
/**
* Returns a structural {@code Value} representing these {@code
* TransportSettings}.
*/
public Value toValue() {
return form().mold(this).toValue();
}
/**
* Returns {@code true} if these {@code TransportSettings} can possibly equal
* some {@code other} object.
*/
public boolean canEqual(Object other) {
return other instanceof TransportSettings;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof TransportSettings) {
final TransportSettings that = (TransportSettings) other;
return that.canEqual(this) && this.backlog == that.backlog
&& this.idleInterval == that.idleInterval
&& this.idleTimeout == that.idleTimeout;
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(TransportSettings.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed, backlog),
Murmur3.hash(this.idleInterval)), Murmur3.hash(this.idleTimeout)));
}
@Override
public void debug(Output<?> output) {
output = output.write("TransportSettings").write('.').write("standard").write('(').write(')')
.write('.').write("backlog").write('(').debug(this.backlog).write(')')
.write('.').write("idleInterval").write('(').debug(this.idleInterval).write(')')
.write('.').write("idleTimeout").write('(').debug(this.idleTimeout).write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static TransportSettings standard;
private static Form<TransportSettings> form;
/**
* Returns the default {@code TransportSettings} instance.
*/
public static TransportSettings standard() {
if (standard == null) {
int backlog;
try {
backlog = Integer.parseInt(System.getProperty("swim.transport.backlog"));
} catch (NumberFormatException error) {
backlog = 0;
}
long idleInterval;
try {
idleInterval = Long.parseLong(System.getProperty("swim.transport.idle.interval"));
} catch (NumberFormatException error) {
idleInterval = 30000L; // 30 seconds
}
long idleTimeout;
try {
idleTimeout = Long.parseLong(System.getProperty("swim.transport.idle.timeout"));
} catch (NumberFormatException error) {
idleTimeout = 90000L; // 90 seconds
}
standard = new TransportSettings(backlog, idleInterval, idleTimeout);
}
return standard;
}
/**
* Returns the structural {@code Form} of {@code TransportSettings}.
*/
@Kind
public static Form<TransportSettings> form() {
if (form == null) {
form = new TransportSettingsForm();
}
return form;
}
}
final class TransportSettingsForm extends Form<TransportSettings> {
@Override
public String tag() {
return "transport";
}
@Override
public TransportSettings unit() {
return TransportSettings.standard();
}
@Override
public Class<?> type() {
return TransportSettings.class;
}
@Override
public Item mold(TransportSettings settings) {
if (settings != null) {
final TransportSettings standard = TransportSettings.standard();
final Record record = Record.create(4).attr(tag());
if (settings.backlog != standard.backlog) {
record.slot("backlog", settings.backlog);
}
if (settings.idleInterval != standard.idleInterval) {
record.slot("idleInterval", settings.idleInterval);
}
if (settings.idleTimeout != standard.idleTimeout) {
record.slot("idleTimeout", settings.idleTimeout);
}
return record;
} else {
return Item.extant();
}
}
@Override
public TransportSettings cast(Item item) {
final Value value = item.toValue();
if (value.getAttr(tag()).isDefined()) {
final TransportSettings standard = TransportSettings.standard();
final int backlog = value.get("backlog").intValue(standard.backlog);
final long idleInterval = value.get("idleInterval").longValue(standard.idleInterval);
final long idleTimeout = value.get("idleTimeout").longValue(standard.idleTimeout);
return new TransportSettings(backlog, idleInterval, idleTimeout);
}
return null;
}
}
|
0 | java-sources/ai/swim/swim-io/3.10.0/swim | java-sources/ai/swim/swim-io/3.10.0/swim/io/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.
/**
* Flow-controlled input/output library.
*/
package swim.io;
|
0 | java-sources/ai/swim/swim-io-http | java-sources/ai/swim/swim-io-http/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.
/**
* Flow-controlled HTTP I/O library.
*/
module swim.io.http {
requires swim.util;
requires transitive swim.codec;
requires swim.collections;
requires transitive swim.http;
requires transitive swim.io;
exports swim.io.http;
}
|
0 | java-sources/ai/swim/swim-io-http/3.10.0/swim/io | java-sources/ai/swim/swim-io-http/3.10.0/swim/io/http/AbstractHttpClient.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.io.http;
import java.net.InetSocketAddress;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.Collection;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
import swim.http.header.Connection;
import swim.io.FlowContext;
import swim.io.FlowControl;
import swim.io.FlowModifier;
import swim.io.IpContext;
import swim.io.IpSocket;
public abstract class AbstractHttpClient implements HttpClient, IpContext, FlowContext {
protected HttpClientContext context;
@Override
public HttpClientContext httpClientContext() {
return this.context;
}
@Override
public void setHttpClientContext(HttpClientContext context) {
this.context = context;
}
@Override
public long idleTimeout() {
return -1L; // default timeout
}
@Override
public void willRequest(HttpRequest<?> request) {
// stub
}
@Override
public void didRequest(HttpRequest<?> request) {
// stub
}
@Override
public void willRespond(HttpResponse<?> response) {
// stub
}
@Override
public void didRespond(HttpResponse<?> response) {
final Connection connection = response.getHeader(Connection.class);
if (connection != null) {
if (connection.contains("close")) {
close();
return;
} else if (connection.contains("Upgrade")) {
return;
}
}
context.readResponse();
}
@Override
public void willConnect() {
// stub
}
@Override
public void didConnect() {
context.readResponse();
}
@Override
public void willSecure() {
// stub
}
@Override
public void didSecure() {
// stub
}
@Override
public void willBecome(IpSocket socket) {
// stub
}
@Override
public void didBecome(IpSocket socket) {
// stub
}
@Override
public void didTimeout() {
// stub
}
@Override
public void didDisconnect() {
// stub
}
@Override
public void didFail(Throwable error) {
error.printStackTrace();
}
@Override
public boolean isConnected() {
return this.context.isConnected();
}
@Override
public boolean isClient() {
return this.context.isClient();
}
@Override
public boolean isServer() {
return this.context.isServer();
}
@Override
public boolean isSecure() {
return this.context.isSecure();
}
@Override
public String securityProtocol() {
return this.context.securityProtocol();
}
@Override
public String cipherSuite() {
return this.context.cipherSuite();
}
@Override
public InetSocketAddress localAddress() {
return this.context.localAddress();
}
@Override
public Principal localPrincipal() {
return this.context.localPrincipal();
}
@Override
public Collection<Certificate> localCertificates() {
return this.context.localCertificates();
}
@Override
public InetSocketAddress remoteAddress() {
return this.context.remoteAddress();
}
@Override
public Principal remotePrincipal() {
return this.context.remotePrincipal();
}
@Override
public Collection<Certificate> remoteCertificates() {
return this.context.remoteCertificates();
}
@Override
public FlowControl flowControl() {
return this.context.flowControl();
}
@Override
public void flowControl(FlowControl flowControl) {
this.context.flowControl(flowControl);
}
@Override
public FlowControl flowControl(FlowModifier flowModifier) {
return this.context.flowControl(flowModifier);
}
public HttpSettings httpSettings() {
return this.context.httpSettings();
}
public void doRequest(HttpRequester<?> requester) {
this.context.doRequest(requester);
}
public void readResponse() {
this.context.readResponse();
}
public void become(IpSocket socket) {
this.context.become(socket);
}
public void close() {
this.context.close();
}
}
|
0 | java-sources/ai/swim/swim-io-http/3.10.0/swim/io | java-sources/ai/swim/swim-io-http/3.10.0/swim/io/http/AbstractHttpRequester.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.io.http;
import java.net.InetSocketAddress;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.Collection;
import swim.codec.Decoder;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
import swim.io.FlowContext;
import swim.io.FlowControl;
import swim.io.FlowModifier;
import swim.io.IpContext;
import swim.io.IpSocket;
public abstract class AbstractHttpRequester<T> implements HttpRequester<T>, IpContext, FlowContext {
protected HttpRequesterContext context;
@Override
public HttpRequesterContext httpRequesterContext() {
return this.context;
}
@Override
public void setHttpRequesterContext(HttpRequesterContext context) {
this.context = context;
}
@Override
public abstract void doRequest();
@SuppressWarnings("unchecked")
@Override
public Decoder<T> contentDecoder(HttpResponse<?> response) {
return (Decoder<T>) response.contentDecoder();
}
@Override
public void willRequest(HttpRequest<?> request) {
// stub
}
@Override
public void didRequest(HttpRequest<?> request) {
// stub
}
@Override
public void willRespond(HttpResponse<?> response) {
// stub
}
@Override
public void didRespond(HttpResponse<T> response) {
// stub
}
@Override
public void willBecome(IpSocket socket) {
// stub
}
@Override
public void didBecome(IpSocket socket) {
// stub
}
@Override
public void didTimeout() {
// stub
}
@Override
public void didDisconnect() {
// stub
}
@Override
public void didFail(Throwable error) {
error.printStackTrace();
}
@Override
public boolean isConnected() {
return this.context.isConnected();
}
@Override
public boolean isClient() {
return this.context.isClient();
}
@Override
public boolean isServer() {
return this.context.isServer();
}
@Override
public boolean isSecure() {
return this.context.isSecure();
}
@Override
public String securityProtocol() {
return this.context.securityProtocol();
}
@Override
public String cipherSuite() {
return this.context.cipherSuite();
}
@Override
public InetSocketAddress localAddress() {
return this.context.localAddress();
}
@Override
public Principal localPrincipal() {
return this.context.localPrincipal();
}
@Override
public Collection<Certificate> localCertificates() {
return this.context.localCertificates();
}
@Override
public InetSocketAddress remoteAddress() {
return this.context.remoteAddress();
}
@Override
public Principal remotePrincipal() {
return this.context.remotePrincipal();
}
@Override
public Collection<Certificate> remoteCertificates() {
return this.context.remoteCertificates();
}
@Override
public FlowControl flowControl() {
return this.context.flowControl();
}
@Override
public void flowControl(FlowControl flowControl) {
this.context.flowControl(flowControl);
}
@Override
public FlowControl flowControl(FlowModifier flowModifier) {
return this.context.flowControl(flowModifier);
}
public HttpSettings httpSettings() {
return this.context.httpSettings();
}
public void writeRequest(HttpRequest<?> request) {
this.context.writeRequest(request);
}
public void become(IpSocket socket) {
this.context.become(socket);
}
public void close() {
this.context.close();
}
}
|
0 | java-sources/ai/swim/swim-io-http/3.10.0/swim/io | java-sources/ai/swim/swim-io-http/3.10.0/swim/io/http/AbstractHttpResponder.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.io.http;
import java.net.InetSocketAddress;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.Collection;
import swim.codec.Decoder;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
import swim.io.FlowContext;
import swim.io.FlowControl;
import swim.io.FlowModifier;
import swim.io.IpContext;
import swim.io.IpSocket;
public abstract class AbstractHttpResponder<T> implements HttpResponder<T>, IpContext, FlowContext {
protected HttpResponderContext context;
@Override
public HttpResponderContext httpResponderContext() {
return this.context;
}
@Override
public void setHttpResponderContext(HttpResponderContext context) {
this.context = context;
}
@SuppressWarnings("unchecked")
@Override
public Decoder<T> contentDecoder(HttpRequest<?> request) {
return (Decoder<T>) request.contentDecoder();
}
@Override
public void willRequest(HttpRequest<?> request) {
// stub
}
@Override
public void didRequest(HttpRequest<T> request) {
// stub
}
@Override
public void doRespond(HttpRequest<T> request) {
// stub
}
@Override
public void willRespond(HttpResponse<?> response) {
// stub
}
@Override
public void didRespond(HttpResponse<?> response) {
// stub
}
@Override
public void willBecome(IpSocket socket) {
// stub
}
@Override
public void didBecome(IpSocket socket) {
// stub
}
@Override
public void didTimeout() {
// stub
}
@Override
public void didDisconnect() {
// stub
}
@Override
public void didFail(Throwable error) {
error.printStackTrace();
}
@Override
public boolean isConnected() {
return this.context.isConnected();
}
@Override
public boolean isClient() {
return this.context.isClient();
}
@Override
public boolean isServer() {
return this.context.isServer();
}
@Override
public boolean isSecure() {
return this.context.isSecure();
}
@Override
public String securityProtocol() {
return this.context.securityProtocol();
}
@Override
public String cipherSuite() {
return this.context.cipherSuite();
}
@Override
public InetSocketAddress localAddress() {
return this.context.localAddress();
}
@Override
public Principal localPrincipal() {
return this.context.localPrincipal();
}
@Override
public Collection<Certificate> localCertificates() {
return this.context.localCertificates();
}
@Override
public InetSocketAddress remoteAddress() {
return this.context.remoteAddress();
}
@Override
public Principal remotePrincipal() {
return this.context.remotePrincipal();
}
@Override
public Collection<Certificate> remoteCertificates() {
return this.context.remoteCertificates();
}
@Override
public FlowControl flowControl() {
return this.context.flowControl();
}
@Override
public void flowControl(FlowControl flowControl) {
this.context.flowControl(flowControl);
}
@Override
public FlowControl flowControl(FlowModifier flowModifier) {
return this.context.flowControl(flowModifier);
}
public HttpSettings httpSettings() {
return this.context.httpSettings();
}
public void writeResponse(HttpResponse<?> response) {
this.context.writeResponse(response);
}
public void become(IpSocket socket) {
this.context.become(socket);
}
public void close() {
this.context.close();
}
}
|
0 | java-sources/ai/swim/swim-io-http/3.10.0/swim/io | java-sources/ai/swim/swim-io-http/3.10.0/swim/io/http/AbstractHttpServer.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.io.http;
import java.net.InetSocketAddress;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.Collection;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
import swim.http.header.Connection;
import swim.io.FlowContext;
import swim.io.FlowControl;
import swim.io.FlowModifier;
import swim.io.IpContext;
import swim.io.IpSocket;
public abstract class AbstractHttpServer implements HttpServer, IpContext, FlowContext {
protected HttpServerContext context;
@Override
public HttpServerContext httpServerContext() {
return this.context;
}
@Override
public void setHttpServerContext(HttpServerContext context) {
this.context = context;
}
@Override
public long idleTimeout() {
return -1L; // default timeout
}
@Override
public abstract HttpResponder<?> doRequest(HttpRequest<?> request);
@Override
public void willRequest(HttpRequest<?> request) {
// stub
}
@Override
public void didRequest(HttpRequest<?> request) {
final Connection connection = request.getHeader(Connection.class);
if (connection != null) {
if (connection.contains("close")) {
close();
return;
} else if (connection.contains("Upgrade")) {
return;
}
}
context.readRequest();
}
@Override
public void willRespond(HttpResponse<?> response) {
// stub
}
@Override
public void didRespond(HttpResponse<?> response) {
// stub
}
@Override
public void didConnect() {
this.context.readRequest();
}
@Override
public void willSecure() {
// stub
}
@Override
public void didSecure() {
// stub
}
@Override
public void willBecome(IpSocket socket) {
// stub
}
@Override
public void didBecome(IpSocket socket) {
// stub
}
@Override
public void didTimeout() {
// stub
}
@Override
public void didDisconnect() {
// stub
}
@Override
public void didFail(Throwable error) {
error.printStackTrace();
}
@Override
public boolean isConnected() {
return this.context.isConnected();
}
@Override
public boolean isClient() {
return this.context.isClient();
}
@Override
public boolean isServer() {
return this.context.isServer();
}
@Override
public boolean isSecure() {
return this.context.isSecure();
}
@Override
public String securityProtocol() {
return this.context.securityProtocol();
}
@Override
public String cipherSuite() {
return this.context.cipherSuite();
}
@Override
public InetSocketAddress localAddress() {
return this.context.localAddress();
}
@Override
public Principal localPrincipal() {
return this.context.localPrincipal();
}
@Override
public Collection<Certificate> localCertificates() {
return this.context.localCertificates();
}
@Override
public InetSocketAddress remoteAddress() {
return this.context.remoteAddress();
}
@Override
public Principal remotePrincipal() {
return this.context.remotePrincipal();
}
@Override
public Collection<Certificate> remoteCertificates() {
return this.context.remoteCertificates();
}
@Override
public FlowControl flowControl() {
return this.context.flowControl();
}
@Override
public void flowControl(FlowControl flowControl) {
this.context.flowControl(flowControl);
}
@Override
public FlowControl flowControl(FlowModifier flowModifier) {
return this.context.flowControl(flowModifier);
}
public HttpSettings httpSettings() {
return this.context.httpSettings();
}
public void readRequest() {
this.context.readRequest();
}
public void become(IpSocket socket) {
this.context.become(socket);
}
public void close() {
this.context.close();
}
}
|
0 | java-sources/ai/swim/swim-io-http/3.10.0/swim/io | java-sources/ai/swim/swim-io-http/3.10.0/swim/io/http/AbstractHttpService.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.io.http;
import java.net.InetSocketAddress;
import swim.io.FlowContext;
import swim.io.FlowControl;
import swim.io.FlowModifier;
public abstract class AbstractHttpService implements HttpService, FlowContext {
protected HttpServiceContext context;
@Override
public HttpServiceContext httpServiceContext() {
return this.context;
}
@Override
public void setHttpServiceContext(HttpServiceContext context) {
this.context = context;
}
@Override
public abstract HttpServer createServer();
@Override
public void didBind() {
// stub
}
@Override
public void didAccept(HttpServer server) {
// stub
}
@Override
public void didUnbind() {
// stub
}
@Override
public void didFail(Throwable error) {
error.printStackTrace();
}
@Override
public FlowControl flowControl() {
return this.context.flowControl();
}
@Override
public void flowControl(FlowControl flowControl) {
this.context.flowControl(flowControl);
}
@Override
public FlowControl flowControl(FlowModifier flowModifier) {
return this.context.flowControl(flowModifier);
}
public HttpSettings httpSettings() {
return this.context.httpSettings();
}
public InetSocketAddress localAddress() {
return this.context.localAddress();
}
public void unbind() {
this.context.unbind();
}
}
|
0 | java-sources/ai/swim/swim-io-http/3.10.0/swim/io | java-sources/ai/swim/swim-io-http/3.10.0/swim/io/http/HttpClient.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.io.http;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
import swim.io.IpSocket;
public interface HttpClient {
HttpClientContext httpClientContext();
void setHttpClientContext(HttpClientContext context);
long idleTimeout();
void willRequest(HttpRequest<?> request);
void didRequest(HttpRequest<?> request);
void willRespond(HttpResponse<?> response);
void didRespond(HttpResponse<?> response);
void willConnect();
void didConnect();
void willSecure();
void didSecure();
void willBecome(IpSocket socket);
void didBecome(IpSocket socket);
void didTimeout();
void didDisconnect();
void didFail(Throwable error);
}
|
0 | java-sources/ai/swim/swim-io-http/3.10.0/swim/io | java-sources/ai/swim/swim-io-http/3.10.0/swim/io/http/HttpClientContext.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.io.http;
import swim.io.FlowContext;
import swim.io.IpContext;
import swim.io.IpSocket;
public interface HttpClientContext extends IpContext, FlowContext {
HttpSettings httpSettings();
void doRequest(HttpRequester<?> requester);
void readResponse();
void become(IpSocket socket);
void close();
}
|
0 | java-sources/ai/swim/swim-io-http/3.10.0/swim/io | java-sources/ai/swim/swim-io-http/3.10.0/swim/io/http/HttpClientModem.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.io.http;
import java.net.InetSocketAddress;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import swim.codec.Decoder;
import swim.codec.Utf8;
import swim.collections.FingerTrieSeq;
import swim.http.Http;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
import swim.io.FlowControl;
import swim.io.FlowModifier;
import swim.io.IpModem;
import swim.io.IpModemContext;
import swim.io.IpSocket;
public class HttpClientModem implements IpModem<HttpResponse<?>, HttpRequest<?>>, HttpClientContext {
protected final HttpClient client;
protected final HttpSettings httpSettings;
volatile FingerTrieSeq<HttpClientRequester<?>> requesters;
volatile FingerTrieSeq<HttpClientRequester<?>> responders;
volatile HttpClientRequester<?> responding;
protected IpModemContext<HttpResponse<?>, HttpRequest<?>> context;
public HttpClientModem(HttpClient client, HttpSettings httpSettings) {
this.client = client;
this.httpSettings = httpSettings;
this.requesters = FingerTrieSeq.empty();
this.responders = FingerTrieSeq.empty();
}
@Override
public IpModemContext<HttpResponse<?>, HttpRequest<?>> ipModemContext() {
return this.context;
}
@Override
public void setIpModemContext(IpModemContext<HttpResponse<?>, HttpRequest<?>> context) {
this.context = context;
this.client.setHttpClientContext(this);
}
@Override
public long idleTimeout() {
return this.client.idleTimeout();
}
@Override
public void doRead() {
// nop
}
@Override
public void didRead(HttpResponse<?> response) {
if (RESPONDING.get(this) == null) {
willRespond(response);
} else {
didRespond(response);
}
}
@Override
public void doWrite() {
// nop
}
@Override
public void didWrite(HttpRequest<?> request) {
didRequest(request);
}
@Override
public void willConnect() {
this.client.willConnect();
}
@Override
public void didConnect() {
this.client.didConnect();
}
@Override
public void willSecure() {
this.client.willSecure();
}
@Override
public void didSecure() {
this.client.didSecure();
}
@Override
public void willBecome(IpSocket socket) {
this.client.willBecome(socket);
}
@Override
public void didBecome(IpSocket socket) {
this.client.didBecome(socket);
}
@Override
public void didTimeout() {
for (HttpClientRequester<?> responderContext : RESPONDERS.get(this)) {
responderContext.didTimeout();
}
this.client.didTimeout();
}
@Override
public void didDisconnect() {
REQUESTERS.set(this, FingerTrieSeq.<HttpClientRequester<?>>empty());
do {
final FingerTrieSeq<HttpClientRequester<?>> oldResponders = RESPONDERS.get(this);
final FingerTrieSeq<HttpClientRequester<?>> newResponders = FingerTrieSeq.empty();
if (oldResponders != newResponders) {
if (RESPONDERS.compareAndSet(this, oldResponders, newResponders)) {
for (HttpClientRequester<?> responderContext : oldResponders) {
responderContext.didDisconnect();
}
break;
}
} else {
break;
}
} while (true);
this.client.didDisconnect();
close();
}
@Override
public void didFail(Throwable error) {
REQUESTERS.set(this, FingerTrieSeq.<HttpClientRequester<?>>empty());
do {
final FingerTrieSeq<HttpClientRequester<?>> oldResponders = RESPONDERS.get(this);
final FingerTrieSeq<HttpClientRequester<?>> newResponders = FingerTrieSeq.empty();
if (oldResponders != newResponders) {
if (RESPONDERS.compareAndSet(this, oldResponders, newResponders)) {
for (HttpClientRequester<?> responderContext : oldResponders) {
responderContext.didFail(error);
}
break;
}
} else {
break;
}
} while (true);
this.client.didFail(error);
close();
}
@Override
public boolean isConnected() {
final IpModemContext<HttpResponse<?>, HttpRequest<?>> context = this.context;
return context != null && context.isConnected();
}
@Override
public boolean isClient() {
return true;
}
@Override
public boolean isServer() {
return false;
}
@Override
public boolean isSecure() {
final IpModemContext<HttpResponse<?>, HttpRequest<?>> context = this.context;
return context != null && context.isSecure();
}
@Override
public String securityProtocol() {
return this.context.securityProtocol();
}
@Override
public String cipherSuite() {
return this.context.cipherSuite();
}
@Override
public InetSocketAddress localAddress() {
return this.context.localAddress();
}
@Override
public Principal localPrincipal() {
return this.context.localPrincipal();
}
@Override
public Collection<Certificate> localCertificates() {
return this.context.localCertificates();
}
@Override
public InetSocketAddress remoteAddress() {
return this.context.remoteAddress();
}
@Override
public Principal remotePrincipal() {
return this.context.remotePrincipal();
}
@Override
public Collection<Certificate> remoteCertificates() {
return this.context.remoteCertificates();
}
@Override
public FlowControl flowControl() {
return this.context.flowControl();
}
@Override
public void flowControl(FlowControl flowControl) {
this.context.flowControl(flowControl);
}
@Override
public FlowControl flowControl(FlowModifier flowModifier) {
return this.context.flowControl(flowModifier);
}
@Override
public HttpSettings httpSettings() {
return this.httpSettings;
}
@SuppressWarnings("unchecked")
@Override
public void doRequest(HttpRequester<?> requester) {
final HttpClientRequester<?> requesterContext = new HttpClientRequester<Object>(this, (HttpRequester<Object>) requester);
requester.setHttpRequesterContext(requesterContext);
outer: do {
final FingerTrieSeq<HttpClientRequester<?>> oldRequesters = REQUESTERS.get(this);
final FingerTrieSeq<HttpClientRequester<?>> newRequesters = oldRequesters.appended(requesterContext);
if (REQUESTERS.compareAndSet(this, oldRequesters, newRequesters)) {
do {
final FingerTrieSeq<HttpClientRequester<?>> oldResponders = RESPONDERS.get(this);
final FingerTrieSeq<HttpClientRequester<?>> newResponders = oldResponders.appended(requesterContext);
if (RESPONDERS.compareAndSet(this, oldResponders, newResponders)) {
if (oldRequesters.isEmpty()) {
requesterContext.doRequest();
}
break outer;
}
} while (true);
}
} while (true);
}
@Override
public void readResponse() {
doReadResponseMessage();
}
@Override
public void become(IpSocket socket) {
this.context.become(socket);
}
@Override
public void close() {
this.context.close();
}
void doWriteRequest(HttpRequest<?> request) {
willRequest(request);
this.context.write(request.httpEncoder());
}
void willRequest(HttpRequest<?> request) {
this.client.willRequest(request);
RESPONDERS.get(this).head().willRequest(request);
}
void didRequest(HttpRequest<?> request) {
do {
final FingerTrieSeq<HttpClientRequester<?>> oldRequesters = REQUESTERS.get(this);
final FingerTrieSeq<HttpClientRequester<?>> newRequesters = oldRequesters.tail();
if (REQUESTERS.compareAndSet(this, oldRequesters, newRequesters)) {
final HttpClientRequester<?> requesterContext = oldRequesters.head();
requesterContext.didRequest(request);
this.client.didRequest(request);
if (!newRequesters.isEmpty()) {
newRequesters.head().doRequest();
}
break;
}
} while (true);
}
void doReadResponseMessage() {
this.context.read(Utf8.decodedParser(Http.standardParser().responseParser()));
}
void doReadResponseEntity(Decoder<HttpResponse<?>> entityDecoder) {
if (entityDecoder.isCont()) {
this.context.read(entityDecoder);
} else {
didRead(entityDecoder.bind());
}
}
void willRespond(HttpResponse<?> response) {
do {
final FingerTrieSeq<HttpClientRequester<?>> oldResponders = RESPONDERS.get(this);
final FingerTrieSeq<HttpClientRequester<?>> newResponders = oldResponders.tail();
if (RESPONDERS.compareAndSet(this, oldResponders, newResponders)) {
final HttpClientRequester<?> requesterContext = oldResponders.head();
if (!RESPONDING.compareAndSet(this, null, requesterContext)) {
throw new AssertionError();
}
requesterContext.willRespond(response);
this.client.willRespond(response);
break;
}
} while (true);
}
void didRespond(HttpResponse<?> response) {
final HttpClientRequester<?> requesterContext = RESPONDING.getAndSet(this, null);
requesterContext.didRespond(response);
this.client.didRespond(response);
}
@SuppressWarnings("unchecked")
static final AtomicReferenceFieldUpdater<HttpClientModem, FingerTrieSeq<HttpClientRequester<?>>> REQUESTERS =
AtomicReferenceFieldUpdater.newUpdater(HttpClientModem.class, (Class<FingerTrieSeq<HttpClientRequester<?>>>) (Class<?>) FingerTrieSeq.class, "requesters");
@SuppressWarnings("unchecked")
static final AtomicReferenceFieldUpdater<HttpClientModem, FingerTrieSeq<HttpClientRequester<?>>> RESPONDERS =
AtomicReferenceFieldUpdater.newUpdater(HttpClientModem.class, (Class<FingerTrieSeq<HttpClientRequester<?>>>) (Class<?>) FingerTrieSeq.class, "responders");
@SuppressWarnings("unchecked")
static final AtomicReferenceFieldUpdater<HttpClientModem, HttpClientRequester<?>> RESPONDING =
AtomicReferenceFieldUpdater.newUpdater(HttpClientModem.class, (Class<HttpClientRequester<?>>) (Class<?>) HttpClientRequester.class, "responding");
}
|
0 | java-sources/ai/swim/swim-io-http/3.10.0/swim/io | java-sources/ai/swim/swim-io-http/3.10.0/swim/io/http/HttpClientRequester.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.io.http;
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.codec.Decoder;
import swim.http.HttpException;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
import swim.io.FlowControl;
import swim.io.FlowModifier;
import swim.io.IpSocket;
public class HttpClientRequester<T> implements HttpRequesterContext {
protected final HttpClientModem modem;
protected final HttpRequester<T> requester;
volatile HttpRequest<?> request;
volatile int status;
public HttpClientRequester(HttpClientModem modem, HttpRequester<T> requester) {
this.modem = modem;
this.requester = requester;
}
@Override
public boolean isConnected() {
return this.modem.isConnected();
}
@Override
public boolean isClient() {
return this.modem.isClient();
}
@Override
public boolean isServer() {
return this.modem.isServer();
}
@Override
public boolean isSecure() {
return this.modem.isSecure();
}
@Override
public String securityProtocol() {
return this.modem.securityProtocol();
}
@Override
public String cipherSuite() {
return this.modem.cipherSuite();
}
@Override
public InetSocketAddress localAddress() {
return this.modem.localAddress();
}
@Override
public Principal localPrincipal() {
return this.modem.localPrincipal();
}
@Override
public Collection<Certificate> localCertificates() {
return this.modem.localCertificates();
}
@Override
public InetSocketAddress remoteAddress() {
return this.modem.remoteAddress();
}
@Override
public Principal remotePrincipal() {
return this.modem.remotePrincipal();
}
@Override
public Collection<Certificate> remoteCertificates() {
return this.modem.remoteCertificates();
}
@Override
public FlowControl flowControl() {
return this.modem.flowControl();
}
@Override
public void flowControl(FlowControl flowControl) {
this.modem.flowControl(flowControl);
}
@Override
public FlowControl flowControl(FlowModifier flowModifier) {
return this.modem.flowControl(flowModifier);
}
@Override
public HttpSettings httpSettings() {
return this.modem.httpSettings();
}
@Override
public void writeRequest(HttpRequest<?> request) {
this.request = request;
do {
final int oldStatus = STATUS.get(this);
if ((oldStatus & REQUESTED) == 0) {
final int newStatus = oldStatus | REQUESTED;
if (STATUS.compareAndSet(this, oldStatus, newStatus)) {
if ((newStatus & REQUESTING) != 0) {
this.modem.doWriteRequest(request);
}
break;
}
} else {
throw new HttpException("already requested");
}
} while (true);
}
@SuppressWarnings("unchecked")
void willRespond(HttpResponse<?> response) {
this.requester.willRespond(response);
final Decoder<?> contentDecoder = this.requester.contentDecoder(response);
final Decoder<HttpResponse<?>> entityDecoder = (Decoder<HttpResponse<?>>) response.entityDecoder(contentDecoder);
this.modem.doReadResponseEntity(entityDecoder);
}
@SuppressWarnings("unchecked")
void didRespond(HttpResponse<?> response) {
this.requester.didRespond((HttpResponse<T>) response);
}
@Override
public void become(IpSocket socket) {
this.modem.become(socket);
}
@Override
public void close() {
this.modem.close();
}
void doRequest() {
this.requester.doRequest();
do {
final int oldStatus = STATUS.get(this);
if ((oldStatus & REQUESTING) == 0) {
final int newStatus = oldStatus | REQUESTING;
if (STATUS.compareAndSet(this, oldStatus, newStatus)) {
if ((newStatus & REQUESTED) != 0) {
this.modem.doWriteRequest(this.request);
}
break;
}
} else {
throw new AssertionError();
}
} while (true);
}
void willRequest(HttpRequest<?> request) {
this.requester.willRequest(request);
}
void didRequest(HttpRequest<?> request) {
this.requester.didRequest(request);
}
void willBecome(IpSocket socket) {
this.requester.willBecome(socket);
}
void didBecome(IpSocket socket) {
this.requester.didBecome(socket);
}
void didDisconnect() {
this.requester.didDisconnect();
}
void didTimeout() {
this.requester.didTimeout();
}
void didFail(Throwable error) {
this.requester.didFail(error);
}
static final int REQUESTING = 1 << 0;
static final int REQUESTED = 1 << 1;
@SuppressWarnings("unchecked")
static final AtomicIntegerFieldUpdater<HttpClientRequester<?>> STATUS =
AtomicIntegerFieldUpdater.newUpdater((Class<HttpClientRequester<?>>) (Class<?>) HttpClientRequester.class, "status");
}
|
0 | java-sources/ai/swim/swim-io-http/3.10.0/swim/io | java-sources/ai/swim/swim-io-http/3.10.0/swim/io/http/HttpEndpoint.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.io.http;
import swim.concurrent.Stage;
import swim.io.IpSettings;
import swim.io.IpStation;
import swim.io.Station;
public class HttpEndpoint implements IpStation, HttpInterface {
protected final Station station;
protected HttpSettings httpSettings;
public HttpEndpoint(Station station, HttpSettings httpSettings) {
this.station = station;
this.httpSettings = httpSettings;
}
public HttpEndpoint(Station station) {
this(station, HttpSettings.standard());
}
public HttpEndpoint(Stage stage, HttpSettings httpSettings) {
this(new Station(stage), httpSettings);
}
public HttpEndpoint(Stage stage) {
this(new Station(stage), HttpSettings.standard());
}
public final Stage stage() {
return this.station.stage();
}
@Override
public final Station station() {
return this.station;
}
@Override
public final IpSettings ipSettings() {
return this.httpSettings.ipSettings();
}
@Override
public final HttpSettings httpSettings() {
return this.httpSettings;
}
public void start() {
this.station.start();
}
public void stop() {
this.station.stop();
}
}
|
0 | java-sources/ai/swim/swim-io-http/3.10.0/swim/io | java-sources/ai/swim/swim-io-http/3.10.0/swim/io/http/HttpInterface.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.io.http;
import java.net.InetSocketAddress;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
import swim.io.IpInterface;
import swim.io.IpServiceRef;
import swim.io.IpSocketModem;
import swim.io.IpSocketRef;
public interface HttpInterface extends IpInterface {
HttpSettings httpSettings();
default IpServiceRef bindHttp(InetSocketAddress localAddress, HttpService service, HttpSettings httpSettings) {
final HttpSocketService tcpService = new HttpSocketService(service, httpSettings);
return bindTcp(localAddress, tcpService, httpSettings.ipSettings());
}
default IpServiceRef bindHttp(InetSocketAddress localAddress, HttpService service) {
return bindHttp(localAddress, service, httpSettings());
}
default IpServiceRef bindHttp(String address, int port, HttpService service, HttpSettings httpSettings) {
return bindHttp(new InetSocketAddress(address, port), service, httpSettings);
}
default IpServiceRef bindHttp(String address, int port, HttpService service) {
return bindHttp(new InetSocketAddress(address, port), service, httpSettings());
}
default IpServiceRef bindHttps(InetSocketAddress localAddress, HttpService service, HttpSettings httpSettings) {
final HttpSocketService tlsService = new HttpSocketService(service, httpSettings);
return bindTls(localAddress, tlsService, httpSettings.ipSettings());
}
default IpServiceRef bindHttps(InetSocketAddress localAddress, HttpService service) {
return bindHttps(localAddress, service, httpSettings());
}
default IpServiceRef bindHttps(String address, int port, HttpService service, HttpSettings httpSettings) {
return bindHttps(new InetSocketAddress(address, port), service, httpSettings);
}
default IpServiceRef bindHttps(String address, int port, HttpService service) {
return bindHttps(new InetSocketAddress(address, port), service, httpSettings());
}
default IpSocketRef connectHttp(InetSocketAddress remoteAddress, HttpClient client, HttpSettings httpSettings) {
final HttpClientModem modem = new HttpClientModem(client, httpSettings);
final IpSocketModem<HttpResponse<?>, HttpRequest<?>> socket = new IpSocketModem<HttpResponse<?>, HttpRequest<?>>(modem);
return connectTcp(remoteAddress, socket, httpSettings.ipSettings());
}
default IpSocketRef connectHttp(InetSocketAddress remoteAddress, HttpClient client) {
return connectHttp(remoteAddress, client, httpSettings());
}
default IpSocketRef connectHttp(String address, int port, HttpClient client, HttpSettings httpSettings) {
return connectHttp(new InetSocketAddress(address, port), client, httpSettings);
}
default IpSocketRef connectHttp(String address, int port, HttpClient client) {
return connectHttp(new InetSocketAddress(address, port), client, httpSettings());
}
default IpSocketRef connectHttps(InetSocketAddress remoteAddress, HttpClient client, HttpSettings httpSettings) {
final HttpClientModem modem = new HttpClientModem(client, httpSettings);
final IpSocketModem<HttpResponse<?>, HttpRequest<?>> socket = new IpSocketModem<HttpResponse<?>, HttpRequest<?>>(modem);
return connectTls(remoteAddress, socket, httpSettings.ipSettings());
}
default IpSocketRef connectHttps(InetSocketAddress remoteAddress, HttpClient client) {
return connectHttps(remoteAddress, client, httpSettings());
}
default IpSocketRef connectHttps(String address, int port, HttpClient client, HttpSettings httpSettings) {
return connectHttps(new InetSocketAddress(address, port), client, httpSettings);
}
default IpSocketRef connectHttps(String address, int port, HttpClient client) {
return connectHttps(new InetSocketAddress(address, port), client, httpSettings());
}
}
|
0 | java-sources/ai/swim/swim-io-http/3.10.0/swim/io | java-sources/ai/swim/swim-io-http/3.10.0/swim/io/http/HttpRequester.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.io.http;
import swim.codec.Decoder;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
import swim.io.IpSocket;
public interface HttpRequester<T> {
HttpRequesterContext httpRequesterContext();
void setHttpRequesterContext(HttpRequesterContext context);
void doRequest();
Decoder<T> contentDecoder(HttpResponse<?> response);
void willRequest(HttpRequest<?> request);
void didRequest(HttpRequest<?> request);
void willRespond(HttpResponse<?> response);
void didRespond(HttpResponse<T> response);
void willBecome(IpSocket socket);
void didBecome(IpSocket socket);
void didTimeout();
void didDisconnect();
void didFail(Throwable error);
}
|
0 | java-sources/ai/swim/swim-io-http/3.10.0/swim/io | java-sources/ai/swim/swim-io-http/3.10.0/swim/io/http/HttpRequesterContext.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.io.http;
import swim.http.HttpRequest;
import swim.io.FlowContext;
import swim.io.IpContext;
import swim.io.IpSocket;
public interface HttpRequesterContext extends IpContext, FlowContext {
HttpSettings httpSettings();
void writeRequest(HttpRequest<?> request);
void become(IpSocket socket);
void close();
}
|
0 | java-sources/ai/swim/swim-io-http/3.10.0/swim/io | java-sources/ai/swim/swim-io-http/3.10.0/swim/io/http/HttpResponder.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.io.http;
import swim.codec.Decoder;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
import swim.io.IpSocket;
public interface HttpResponder<T> {
HttpResponderContext httpResponderContext();
void setHttpResponderContext(HttpResponderContext context);
Decoder<T> contentDecoder(HttpRequest<?> request);
void willRequest(HttpRequest<?> request);
void didRequest(HttpRequest<T> request);
void doRespond(HttpRequest<T> request);
void willRespond(HttpResponse<?> response);
void didRespond(HttpResponse<?> response);
void willBecome(IpSocket socket);
void didBecome(IpSocket socket);
void didTimeout();
void didDisconnect();
void didFail(Throwable error);
}
|
0 | java-sources/ai/swim/swim-io-http/3.10.0/swim/io | java-sources/ai/swim/swim-io-http/3.10.0/swim/io/http/HttpResponderContext.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.io.http;
import swim.http.HttpResponse;
import swim.io.FlowContext;
import swim.io.IpContext;
import swim.io.IpSocket;
public interface HttpResponderContext extends IpContext, FlowContext {
HttpSettings httpSettings();
void writeResponse(HttpResponse<?> response);
void become(IpSocket socket);
void close();
}
|
0 | java-sources/ai/swim/swim-io-http/3.10.0/swim/io | java-sources/ai/swim/swim-io-http/3.10.0/swim/io/http/HttpServer.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.io.http;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
import swim.io.IpSocket;
public interface HttpServer {
HttpServerContext httpServerContext();
void setHttpServerContext(HttpServerContext context);
long idleTimeout();
HttpResponder<?> doRequest(HttpRequest<?> request);
void willRequest(HttpRequest<?> request);
void didRequest(HttpRequest<?> request);
void willRespond(HttpResponse<?> response);
void didRespond(HttpResponse<?> response);
void didConnect();
void willSecure();
void didSecure();
void willBecome(IpSocket socket);
void didBecome(IpSocket socket);
void didTimeout();
void didDisconnect();
void didFail(Throwable error);
}
|
0 | java-sources/ai/swim/swim-io-http/3.10.0/swim/io | java-sources/ai/swim/swim-io-http/3.10.0/swim/io/http/HttpServerContext.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.io.http;
import swim.io.FlowContext;
import swim.io.IpContext;
import swim.io.IpSocket;
public interface HttpServerContext extends IpContext, FlowContext {
HttpSettings httpSettings();
void readRequest();
void become(IpSocket socket);
void close();
}
|
0 | java-sources/ai/swim/swim-io-http/3.10.0/swim/io | java-sources/ai/swim/swim-io-http/3.10.0/swim/io/http/HttpServerModem.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.io.http;
import java.net.InetSocketAddress;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import swim.codec.Decoder;
import swim.codec.Utf8;
import swim.collections.FingerTrieSeq;
import swim.http.Http;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
import swim.io.FlowControl;
import swim.io.FlowModifier;
import swim.io.IpModem;
import swim.io.IpModemContext;
import swim.io.IpSocket;
public class HttpServerModem implements IpModem<HttpRequest<?>, HttpResponse<?>>, HttpServerContext {
protected final HttpServer server;
protected final HttpSettings httpSettings;
volatile HttpServerResponder<?> requesting;
volatile FingerTrieSeq<HttpServerResponder<?>> responders;
protected IpModemContext<HttpRequest<?>, HttpResponse<?>> context;
public HttpServerModem(HttpServer server, HttpSettings httpSettings) {
this.server = server;
this.httpSettings = httpSettings;
this.responders = FingerTrieSeq.empty();
}
@Override
public IpModemContext<HttpRequest<?>, HttpResponse<?>> ipModemContext() {
return this.context;
}
@Override
public void setIpModemContext(IpModemContext<HttpRequest<?>, HttpResponse<?>> context) {
this.context = context;
this.server.setHttpServerContext(this);
}
@Override
public long idleTimeout() {
return this.server.idleTimeout();
}
@Override
public void doRead() {
// nop
}
@Override
public void didRead(HttpRequest<?> request) {
if (REQUESTING.get(this) == null) {
willRequest(request);
} else {
didRequest(request);
}
}
@Override
public void doWrite() {
// nop
}
@Override
public void didWrite(HttpResponse<?> response) {
didRespond(response);
}
@Override
public void willConnect() {
// nop
}
@Override
public void didConnect() {
this.server.didConnect();
}
@Override
public void willSecure() {
this.server.willSecure();
}
@Override
public void didSecure() {
this.server.didSecure();
}
@Override
public void willBecome(IpSocket socket) {
this.server.willBecome(socket);
}
@Override
public void didBecome(IpSocket socket) {
this.server.didBecome(socket);
}
@Override
public void didTimeout() {
for (HttpServerResponder<?> responderContext : RESPONDERS.get(this)) {
responderContext.didTimeout();
}
this.server.didTimeout();
}
@Override
public void didDisconnect() {
do {
final FingerTrieSeq<HttpServerResponder<?>> oldResponders = RESPONDERS.get(this);
final FingerTrieSeq<HttpServerResponder<?>> newResponders = FingerTrieSeq.empty();
if (oldResponders != newResponders) {
if (RESPONDERS.compareAndSet(this, oldResponders, newResponders)) {
for (HttpServerResponder<?> responderContext : oldResponders) {
responderContext.didDisconnect();
}
break;
}
} else {
break;
}
} while (true);
server.didDisconnect();
close();
}
@Override
public void didFail(Throwable error) {
do {
final FingerTrieSeq<HttpServerResponder<?>> oldResponders = RESPONDERS.get(this);
final FingerTrieSeq<HttpServerResponder<?>> newResponders = FingerTrieSeq.empty();
if (oldResponders != newResponders) {
if (RESPONDERS.compareAndSet(this, oldResponders, newResponders)) {
for (HttpServerResponder<?> responderContext : oldResponders) {
responderContext.didFail(error);
}
break;
}
} else {
break;
}
} while (true);
server.didFail(error);
close();
}
@Override
public boolean isConnected() {
final IpModemContext<HttpRequest<?>, HttpResponse<?>> context = this.context;
return context != null && context.isConnected();
}
@Override
public boolean isClient() {
return false;
}
@Override
public boolean isServer() {
return true;
}
@Override
public boolean isSecure() {
final IpModemContext<HttpRequest<?>, HttpResponse<?>> context = this.context;
return context != null && context.isSecure();
}
@Override
public String securityProtocol() {
return this.context.securityProtocol();
}
@Override
public String cipherSuite() {
return this.context.cipherSuite();
}
@Override
public InetSocketAddress localAddress() {
return this.context.localAddress();
}
@Override
public Principal localPrincipal() {
return this.context.localPrincipal();
}
@Override
public Collection<Certificate> localCertificates() {
return this.context.localCertificates();
}
@Override
public InetSocketAddress remoteAddress() {
return this.context.remoteAddress();
}
@Override
public Principal remotePrincipal() {
return this.context.remotePrincipal();
}
@Override
public Collection<Certificate> remoteCertificates() {
return this.context.remoteCertificates();
}
@Override
public FlowControl flowControl() {
return this.context.flowControl();
}
@Override
public void flowControl(FlowControl flowControl) {
this.context.flowControl(flowControl);
}
@Override
public FlowControl flowControl(FlowModifier flowModifier) {
return this.context.flowControl(flowModifier);
}
@Override
public HttpSettings httpSettings() {
return this.httpSettings;
}
@Override
public void readRequest() {
doReadRequestMessage();
}
@Override
public void become(IpSocket socket) {
this.context.become(socket);
}
@Override
public void close() {
this.context.close();
}
void doReadRequestMessage() {
this.context.read(Utf8.decodedParser(Http.standardParser().requestParser()));
}
void doReadRequestEntity(Decoder<HttpRequest<?>> entityDecoder) {
if (entityDecoder.isCont()) {
this.context.read(entityDecoder);
} else {
didRead(entityDecoder.bind());
}
}
@SuppressWarnings("unchecked")
void willRequest(HttpRequest<?> request) {
final HttpResponder<?> responder = this.server.doRequest(request);
final HttpServerResponder<?> responderContext = new HttpServerResponder<Object>(this, (HttpResponder<Object>) responder);
responder.setHttpResponderContext(responderContext);
if (!REQUESTING.compareAndSet(this, null, responderContext)) {
throw new AssertionError();
}
do {
final FingerTrieSeq<HttpServerResponder<?>> oldResponders = RESPONDERS.get(this);
final FingerTrieSeq<HttpServerResponder<?>> newResponders = oldResponders.appended(responderContext);
if (RESPONDERS.compareAndSet(this, oldResponders, newResponders)) {
this.server.willRequest(request);
responderContext.willRequest(request);
if (oldResponders.isEmpty()) {
responderContext.doRespond();
}
break;
}
} while (true);
}
void didRequest(HttpRequest<?> request) {
final HttpServerResponder<?> responderContext = REQUESTING.getAndSet(this, null);
responderContext.didRequest(request);
this.server.didRequest(request);
responderContext.doRespond(request);
}
void doWriteResponse(HttpResponse<?> response) {
willRespond(response);
this.context.write(response.httpEncoder());
}
void willRespond(HttpResponse<?> response) {
this.server.willRespond(response);
RESPONDERS.get(this).head().willRespond(response);
}
void didRespond(HttpResponse<?> response) {
do {
final FingerTrieSeq<HttpServerResponder<?>> oldResponders = RESPONDERS.get(this);
final FingerTrieSeq<HttpServerResponder<?>> newResponders = oldResponders.tail();
if (RESPONDERS.compareAndSet(this, oldResponders, newResponders)) {
final HttpServerResponder<?> responderContext = oldResponders.head();
responderContext.didRespond(response);
this.server.didRespond(response);
if (!newResponders.isEmpty()) {
newResponders.head().doRespond();
}
break;
}
} while (true);
}
@SuppressWarnings("unchecked")
static final AtomicReferenceFieldUpdater<HttpServerModem, HttpServerResponder<?>> REQUESTING =
AtomicReferenceFieldUpdater.newUpdater(HttpServerModem.class, (Class<HttpServerResponder<?>>) (Class<?>) HttpServerResponder.class, "requesting");
@SuppressWarnings("unchecked")
static final AtomicReferenceFieldUpdater<HttpServerModem, FingerTrieSeq<HttpServerResponder<?>>> RESPONDERS =
AtomicReferenceFieldUpdater.newUpdater(HttpServerModem.class, (Class<FingerTrieSeq<HttpServerResponder<?>>>) (Class<?>) FingerTrieSeq.class, "responders");
}
|
0 | java-sources/ai/swim/swim-io-http/3.10.0/swim/io | java-sources/ai/swim/swim-io-http/3.10.0/swim/io/http/HttpServerResponder.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.io.http;
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.codec.Decoder;
import swim.http.HttpException;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
import swim.io.FlowControl;
import swim.io.FlowModifier;
import swim.io.IpSocket;
public class HttpServerResponder<T> implements HttpResponderContext {
protected final HttpServerModem modem;
protected final HttpResponder<T> responder;
volatile HttpResponse<?> response;
volatile int status;
public HttpServerResponder(HttpServerModem modem, HttpResponder<T> responder) {
this.modem = modem;
this.responder = responder;
}
@Override
public boolean isConnected() {
return this.modem.isConnected();
}
@Override
public boolean isClient() {
return this.modem.isClient();
}
@Override
public boolean isServer() {
return this.modem.isServer();
}
@Override
public boolean isSecure() {
return this.modem.isSecure();
}
@Override
public String securityProtocol() {
return this.modem.securityProtocol();
}
@Override
public String cipherSuite() {
return this.modem.cipherSuite();
}
@Override
public InetSocketAddress localAddress() {
return this.modem.localAddress();
}
@Override
public Principal localPrincipal() {
return this.modem.localPrincipal();
}
@Override
public Collection<Certificate> localCertificates() {
return this.modem.localCertificates();
}
@Override
public InetSocketAddress remoteAddress() {
return this.modem.remoteAddress();
}
@Override
public Principal remotePrincipal() {
return this.modem.remotePrincipal();
}
@Override
public Collection<Certificate> remoteCertificates() {
return this.modem.remoteCertificates();
}
@Override
public FlowControl flowControl() {
return this.modem.flowControl();
}
@Override
public void flowControl(FlowControl flowControl) {
this.modem.flowControl(flowControl);
}
@Override
public FlowControl flowControl(FlowModifier flowModifier) {
return this.modem.flowControl(flowModifier);
}
@Override
public HttpSettings httpSettings() {
return this.modem.httpSettings();
}
@Override
public void writeResponse(HttpResponse<?> response) {
this.response = response;
do {
final int oldStatus = STATUS.get(this);
if ((oldStatus & RESPONDED) == 0) {
final int newStatus = oldStatus | RESPONDED;
if (STATUS.compareAndSet(this, oldStatus, newStatus)) {
if ((newStatus & RESPONDING) != 0) {
this.modem.doWriteResponse(response);
}
break;
}
} else {
throw new HttpException("already responded");
}
} while (true);
}
@Override
public void become(IpSocket socket) {
this.modem.become(socket);
}
@Override
public void close() {
this.modem.close();
}
@SuppressWarnings("unchecked")
void willRequest(HttpRequest<?> request) {
this.responder.willRequest(request);
final Decoder<?> contentDecoder = this.responder.contentDecoder(request);
final Decoder<HttpRequest<?>> entityDecoder = (Decoder<HttpRequest<?>>) request.entityDecoder(contentDecoder);
this.modem.doReadRequestEntity(entityDecoder);
}
@SuppressWarnings("unchecked")
void didRequest(HttpRequest<?> request) {
this.responder.didRequest((HttpRequest<T>) request);
}
@SuppressWarnings("unchecked")
void doRespond(HttpRequest<?> request) {
this.responder.doRespond((HttpRequest<T>) request);
}
void doRespond() {
do {
final int oldStatus = STATUS.get(this);
if ((oldStatus & RESPONDING) == 0) {
final int newStatus = oldStatus | RESPONDING;
if (STATUS.compareAndSet(this, oldStatus, newStatus)) {
if ((newStatus & RESPONDED) != 0) {
this.modem.doWriteResponse(this.response);
}
break;
}
} else {
throw new AssertionError();
}
} while (true);
}
void willRespond(HttpResponse<?> response) {
this.responder.willRespond(response);
}
void didRespond(HttpResponse<?> response) {
this.responder.didRespond(response);
}
void willBecome(IpSocket socket) {
this.responder.willBecome(socket);
}
void didBecome(IpSocket socket) {
this.responder.didBecome(socket);
}
void didTimeout() {
this.responder.didTimeout();
}
void didDisconnect() {
this.responder.didDisconnect();
}
void didFail(Throwable error) {
this.responder.didFail(error);
}
static final int RESPONDING = 1 << 0;
static final int RESPONDED = 1 << 1;
@SuppressWarnings("unchecked")
static final AtomicIntegerFieldUpdater<HttpServerResponder<?>> STATUS =
AtomicIntegerFieldUpdater.newUpdater((Class<HttpServerResponder<?>>) (Class<?>) HttpServerResponder.class, "status");
}
|
0 | java-sources/ai/swim/swim-io-http/3.10.0/swim/io | java-sources/ai/swim/swim-io-http/3.10.0/swim/io/http/HttpService.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.io.http;
public interface HttpService {
HttpServiceContext httpServiceContext();
void setHttpServiceContext(HttpServiceContext context);
HttpServer createServer();
void didBind();
void didAccept(HttpServer server);
void didUnbind();
void didFail(Throwable error);
}
|
0 | java-sources/ai/swim/swim-io-http/3.10.0/swim/io | java-sources/ai/swim/swim-io-http/3.10.0/swim/io/http/HttpServiceContext.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.io.http;
import java.net.InetSocketAddress;
import swim.io.FlowContext;
public interface HttpServiceContext extends FlowContext {
HttpSettings httpSettings();
InetSocketAddress localAddress();
void unbind();
}
|
0 | java-sources/ai/swim/swim-io-http/3.10.0/swim/io | java-sources/ai/swim/swim-io-http/3.10.0/swim/io/http/HttpSettings.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.io.http;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.io.IpSettings;
import swim.io.TcpSettings;
import swim.io.TlsSettings;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Record;
import swim.structure.Value;
import swim.util.Murmur3;
/**
* HTTP configuration parameters.
*/
public class HttpSettings implements Debug {
protected final IpSettings ipSettings;
protected final int maxMessageSize;
public HttpSettings(IpSettings ipSettings, int maxMessageSize) {
this.ipSettings = ipSettings;
this.maxMessageSize = maxMessageSize;
}
/**
* Returns the socket configuration.
*/
public final IpSettings ipSettings() {
return this.ipSettings;
}
/**
* Returns a copy of these {@code HttpSettings} configured with the given
* {@code ipSettings}.
*/
public HttpSettings ipSettings(IpSettings ipSettings) {
return copy(ipSettings, this.maxMessageSize);
}
/**
* Returns the TCP socket configuration.
*/
public final TcpSettings tcpSettings() {
return this.ipSettings.tcpSettings();
}
/**
* Returns a copy of these {@code HttpSettings} configured with the given
* {@code tcpSettings}.
*/
public HttpSettings tcpSettings(TcpSettings tcpSettings) {
return ipSettings(this.ipSettings.tcpSettings(tcpSettings));
}
/**
* Returns the TLS socket configuration.
*/
public final TlsSettings tlsSettings() {
return this.ipSettings.tlsSettings();
}
/**
* Returns a copy of these {@code HttpSettings} configured with the given
* {@code tlsSettings}.
*/
public HttpSettings tlsSettings(TlsSettings tlsSettings) {
return ipSettings(this.ipSettings.tlsSettings(tlsSettings));
}
/**
* Returns the maximum size in bytes on the wire of an HTTP request or
* response message + entity.
*/
public int maxMessageSize() {
return this.maxMessageSize;
}
/**
* Returns a copy of these {@code HttpSettings} configured with the given
* {@code maxMessageSize} limit on HTTP message + entity sizes.
*/
public HttpSettings maxMessageSize(int maxMessageSize) {
return copy(this.ipSettings, maxMessageSize);
}
/**
* Returns a new {@code HttpSettings} instance with the given options.
* Subclasses may override this method to ensure the proper class is
* instantiated when updating settings.
*/
protected HttpSettings copy(IpSettings ipSettings, int maxMessageSize) {
return new HttpSettings(ipSettings, maxMessageSize);
}
/**
* Returns a structural {@code Value} representing these {@code HttpSettings}.
*/
public Value toValue() {
return form().mold(this).toValue();
}
/**
* Returns {@code true} if these {@code HttpSettings} can possibly equal some
* {@code other} object.
*/
public boolean canEqual(Object other) {
return other instanceof HttpSettings;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof HttpSettings) {
final HttpSettings that = (HttpSettings) other;
return that.canEqual(this) && this.ipSettings.equals(that.ipSettings)
&& this.maxMessageSize == that.maxMessageSize;
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(HttpSettings.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(hashSeed,
this.ipSettings.hashCode()), this.maxMessageSize));
}
@Override
public void debug(Output<?> output) {
output = output.write("HttpSettings").write('.').write("standard").write('(').write(')')
.write('.').write("ipSettings").write('(').debug(this.ipSettings).write(')')
.write('.').write("maxMessageSize").write('(').debug(this.maxMessageSize).write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static HttpSettings standard;
private static Form<HttpSettings> form;
/**
* Returns the default {@code HttpSettings} instance.
*/
public static HttpSettings standard() {
if (standard == null) {
int maxMessageSize;
try {
maxMessageSize = Integer.parseInt(System.getProperty("swim.http.max.message.size"));
} catch (NumberFormatException error) {
maxMessageSize = 16 * 1024 * 1024;
}
standard = new HttpSettings(IpSettings.standard(), maxMessageSize);
}
return standard;
}
public static HttpSettings from(IpSettings ipSettings) {
return standard().ipSettings(ipSettings);
}
/**
* Returns the structural {@code Form} of {@code HttpSettings}.
*/
@Kind
public static Form<HttpSettings> form() {
if (form == null) {
form = new HttpSettingsForm();
}
return form;
}
}
final class HttpSettingsForm extends Form<HttpSettings> {
@Override
public HttpSettings unit() {
return HttpSettings.standard();
}
@Override
public Class<?> type() {
return HttpSettings.class;
}
@Override
public Item mold(HttpSettings settings) {
if (settings != null) {
final HttpSettings standard = HttpSettings.standard();
final Record http = Record.create(2).attr("http");
if (settings.maxMessageSize != standard.maxMessageSize) {
http.slot("maxMessageSize", settings.maxMessageSize);
}
return Record.of(http).concat(IpSettings.form().mold(settings.ipSettings));
} else {
return Item.extant();
}
}
@Override
public HttpSettings cast(Item item) {
final Value value = item.toValue();
final HttpSettings standard = HttpSettings.standard();
int maxMessageSize = standard.maxMessageSize;
for (Item member : value) {
if (member.getAttr("http").isDefined()) {
maxMessageSize = member.get("maxMessageSize").intValue(maxMessageSize);
}
}
final IpSettings ipSettings = IpSettings.form().cast(item);
return new HttpSettings(ipSettings, maxMessageSize);
}
}
|
0 | java-sources/ai/swim/swim-io-http/3.10.0/swim/io | java-sources/ai/swim/swim-io-http/3.10.0/swim/io/http/HttpSocketService.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.io.http;
import java.net.InetSocketAddress;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
import swim.io.FlowControl;
import swim.io.FlowModifier;
import swim.io.IpService;
import swim.io.IpServiceContext;
import swim.io.IpSocket;
import swim.io.IpSocketModem;
public class HttpSocketService implements IpService, HttpServiceContext {
protected final HttpService service;
protected final HttpSettings httpSettings;
protected IpServiceContext context;
public HttpSocketService(HttpService service, HttpSettings httpSettings) {
this.service = service;
this.httpSettings = httpSettings;
}
@Override
public IpServiceContext ipServiceContext() {
return this.context;
}
@Override
public void setIpServiceContext(IpServiceContext context) {
this.context = context;
this.service.setHttpServiceContext(this);
}
@Override
public IpSocket createSocket() {
final HttpServer server = this.service.createServer();
final HttpServerModem modem = new HttpServerModem(server, this.httpSettings);
return new IpSocketModem<HttpRequest<?>, HttpResponse<?>>(modem);
}
@Override
public void didBind() {
this.service.didBind();
}
@Override
public void didAccept(IpSocket socket) {
if (socket instanceof HttpServerModem) {
this.service.didAccept(((HttpServerModem) socket).server);
}
}
@Override
public void didUnbind() {
this.service.didUnbind();
}
@Override
public void didFail(Throwable error) {
this.service.didFail(error);
}
@Override
public FlowControl flowControl() {
return this.context.flowControl();
}
@Override
public void flowControl(FlowControl flowControl) {
this.context.flowControl(flowControl);
}
@Override
public FlowControl flowControl(FlowModifier flowModifier) {
return this.context.flowControl(flowModifier);
}
@Override
public HttpSettings httpSettings() {
return this.httpSettings;
}
@Override
public InetSocketAddress localAddress() {
return this.context.localAddress();
}
@Override
public void unbind() {
this.context.unbind();
}
}
|
0 | java-sources/ai/swim/swim-io-http/3.10.0/swim/io | java-sources/ai/swim/swim-io-http/3.10.0/swim/io/http/StaticHttpResponder.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.io.http;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
public class StaticHttpResponder<T> extends AbstractHttpResponder<T> {
protected final HttpResponse<T> response;
public StaticHttpResponder(HttpResponse<T> response) {
this.response = response;
}
public final HttpResponse<T> response() {
return this.response;
}
@Override
public void doRespond(HttpRequest<T> request) {
writeResponse(this.response);
}
}
|
0 | java-sources/ai/swim/swim-io-http/3.10.0/swim/io | java-sources/ai/swim/swim-io-http/3.10.0/swim/io/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.
/**
* Flow-controlled HTTP I/O library.
*/
package swim.io.http;
|
0 | java-sources/ai/swim/swim-io-mqtt | java-sources/ai/swim/swim-io-mqtt/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.
/**
* Flow-controlled MQTT I/O library.
*/
module swim.io.mqtt {
requires swim.util;
requires transitive swim.codec;
requires transitive swim.mqtt;
requires transitive swim.io;
exports swim.io.mqtt;
}
|
0 | java-sources/ai/swim/swim-io-mqtt/3.10.0/swim/io | java-sources/ai/swim/swim-io-mqtt/3.10.0/swim/io/mqtt/AbstractMqttService.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.io.mqtt;
import java.net.InetSocketAddress;
import swim.io.FlowContext;
import swim.io.FlowControl;
import swim.io.FlowModifier;
public abstract class AbstractMqttService implements MqttService, FlowContext {
protected MqttServiceContext context;
@Override
public MqttServiceContext mqttServiceContext() {
return this.context;
}
@Override
public void setMqttServiceContext(MqttServiceContext context) {
this.context = context;
}
@Override
public abstract MqttSocket<?, ?> createSocket();
@Override
public void didBind() {
// stub
}
@Override
public void didAccept(MqttSocket<?, ?> socket) {
// stub
}
@Override
public void didUnbind() {
// stub
}
@Override
public void didFail(Throwable error) {
error.printStackTrace();
}
@Override
public FlowControl flowControl() {
return this.context.flowControl();
}
@Override
public void flowControl(FlowControl flowControl) {
this.context.flowControl(flowControl);
}
@Override
public FlowControl flowControl(FlowModifier flowModifier) {
return this.context.flowControl(flowModifier);
}
public MqttSettings mqttSettings() {
return this.context.mqttSettings();
}
public InetSocketAddress localAddress() {
return this.context.localAddress();
}
public void unbind() {
this.context.unbind();
}
}
|
0 | java-sources/ai/swim/swim-io-mqtt/3.10.0/swim/io | java-sources/ai/swim/swim-io-mqtt/3.10.0/swim/io/mqtt/AbstractMqttSocket.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.io.mqtt;
import java.net.InetSocketAddress;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.Collection;
import swim.codec.Decoder;
import swim.io.FlowContext;
import swim.io.FlowControl;
import swim.io.FlowModifier;
import swim.io.IpContext;
import swim.io.IpSocket;
import swim.mqtt.MqttPacket;
public abstract class AbstractMqttSocket<I, O> implements MqttSocket<I, O>, IpContext, FlowContext {
protected MqttSocketContext<I, O> context;
@Override
public MqttSocketContext<I, O> mqttSocketContext() {
return this.context;
}
@Override
public void setMqttSocketContext(MqttSocketContext<I, O> context) {
this.context = context;
}
@Override
public long idleTimeout() {
return -1L; // default timeout
}
@Override
public void doRead() {
// stub
}
@Override
public void didRead(MqttPacket<? extends I> packet) {
// stub
}
@Override
public void doWrite() {
// stub
}
@Override
public void didWrite(MqttPacket<? extends O> packet) {
// stub
}
@Override
public void willConnect() {
// stub
}
@Override
public void didConnect() {
// stub
}
@Override
public void willSecure() {
// stub
}
@Override
public void didSecure() {
// stub
}
@Override
public void willBecome(IpSocket socket) {
// stub
}
@Override
public void didBecome(IpSocket socket) {
// stub
}
@Override
public void didTimeout() {
// stub
}
@Override
public void didDisconnect() {
// stub
}
@Override
public void didFail(Throwable error) {
error.printStackTrace();
}
@Override
public boolean isConnected() {
return this.context.isConnected();
}
@Override
public boolean isClient() {
return this.context.isClient();
}
@Override
public boolean isServer() {
return this.context.isServer();
}
@Override
public boolean isSecure() {
return this.context.isSecure();
}
@Override
public String securityProtocol() {
return this.context.securityProtocol();
}
@Override
public String cipherSuite() {
return this.context.cipherSuite();
}
@Override
public InetSocketAddress localAddress() {
return this.context.localAddress();
}
@Override
public Principal localPrincipal() {
return this.context.localPrincipal();
}
@Override
public Collection<Certificate> localCertificates() {
return this.context.localCertificates();
}
@Override
public InetSocketAddress remoteAddress() {
return this.context.remoteAddress();
}
@Override
public Principal remotePrincipal() {
return this.context.remotePrincipal();
}
@Override
public Collection<Certificate> remoteCertificates() {
return this.context.remoteCertificates();
}
@Override
public FlowControl flowControl() {
return this.context.flowControl();
}
@Override
public void flowControl(FlowControl flowControl) {
this.context.flowControl(flowControl);
}
@Override
public FlowControl flowControl(FlowModifier flowModifier) {
return this.context.flowControl(flowModifier);
}
public MqttSettings mqttSettings() {
return this.context.mqttSettings();
}
public <I2 extends I> void read(Decoder<I2> content) {
this.context.read(content);
}
public <O2 extends O> void write(MqttPacket<O2> packet) {
this.context.write(packet);
}
public void become(IpSocket socket) {
this.context.become(socket);
}
public void close() {
this.context.close();
}
}
|
0 | java-sources/ai/swim/swim-io-mqtt/3.10.0/swim/io | java-sources/ai/swim/swim-io-mqtt/3.10.0/swim/io/mqtt/MqttEndpoint.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.io.mqtt;
import swim.concurrent.Stage;
import swim.io.IpSettings;
import swim.io.IpStation;
import swim.io.Station;
public class MqttEndpoint implements IpStation, MqttInterface {
protected final Station station;
protected MqttSettings mqttSettings;
public MqttEndpoint(Station station, MqttSettings mqttSettings) {
this.station = station;
this.mqttSettings = mqttSettings;
}
public MqttEndpoint(Station station) {
this(station, MqttSettings.standard());
}
public MqttEndpoint(Stage stage, MqttSettings mqttSettings) {
this(new Station(stage), mqttSettings);
}
public MqttEndpoint(Stage stage) {
this(new Station(stage), MqttSettings.standard());
}
public final Stage stage() {
return this.station.stage();
}
@Override
public final Station station() {
return this.station;
}
@Override
public final IpSettings ipSettings() {
return this.mqttSettings.ipSettings();
}
@Override
public final MqttSettings mqttSettings() {
return this.mqttSettings;
}
public void start() {
this.station.start();
}
public void stop() {
this.station.stop();
}
}
|
0 | java-sources/ai/swim/swim-io-mqtt/3.10.0/swim/io | java-sources/ai/swim/swim-io-mqtt/3.10.0/swim/io/mqtt/MqttInterface.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.io.mqtt;
import java.net.InetSocketAddress;
import swim.io.IpInterface;
import swim.io.IpServiceRef;
import swim.io.IpSocketModem;
import swim.io.IpSocketRef;
public interface MqttInterface extends IpInterface {
MqttSettings mqttSettings();
default IpServiceRef bindMqtt(InetSocketAddress localAddress, MqttService service, MqttSettings mqttSettings) {
final MqttSocketService tcpService = new MqttSocketService(service, mqttSettings);
return bindTcp(localAddress, tcpService, mqttSettings.ipSettings());
}
default IpServiceRef bindMqtt(InetSocketAddress localAddress, MqttService service) {
return bindMqtt(localAddress, service, mqttSettings());
}
default IpServiceRef bindMqtt(String address, int port, MqttService service, MqttSettings mqttSettings) {
return bindMqtt(new InetSocketAddress(address, port), service, mqttSettings);
}
default IpServiceRef bindMqtt(String address, int port, MqttService service) {
return bindMqtt(new InetSocketAddress(address, port), service, mqttSettings());
}
default IpServiceRef bindMqtts(InetSocketAddress localAddress, MqttService service, MqttSettings mqttSettings) {
final MqttSocketService tlsService = new MqttSocketService(service, mqttSettings);
return bindTls(localAddress, tlsService, mqttSettings.ipSettings());
}
default IpServiceRef bindMqtts(InetSocketAddress localAddress, MqttService service) {
return bindMqtts(localAddress, service, mqttSettings());
}
default IpServiceRef bindMqtts(String address, int port, MqttService service, MqttSettings mqttSettings) {
return bindMqtts(new InetSocketAddress(address, port), service, mqttSettings);
}
default IpServiceRef bindMqtts(String address, int port, MqttService service) {
return bindMqtts(new InetSocketAddress(address, port), service, mqttSettings());
}
default <I, O> IpSocketRef connectMqtt(InetSocketAddress localAddress, MqttSocket<I, O> socket, MqttSettings mqttSettings) {
final MqttSocketModem<I, O> modem = new MqttSocketModem<I, O>(socket, mqttSettings);
final IpSocketModem<Object, Object> tcpSocket = new IpSocketModem<Object, Object>(modem);
return connectTcp(localAddress, tcpSocket, mqttSettings.ipSettings());
}
default <I, O> IpSocketRef connectMqtt(InetSocketAddress localAddress, MqttSocket<I, O> socket) {
return connectMqtt(localAddress, socket, mqttSettings());
}
default <I, O> IpSocketRef connectMqtt(String address, int port, MqttSocket<I, O> socket, MqttSettings mqttSettings) {
return connectMqtt(new InetSocketAddress(address, port), socket, mqttSettings);
}
default <I, O> IpSocketRef connectMqtt(String address, int port, MqttSocket<I, O> socket) {
return connectMqtt(new InetSocketAddress(address, port), socket, mqttSettings());
}
default <I, O> IpSocketRef connectMqtts(InetSocketAddress localAddress, MqttSocket<I, O> socket, MqttSettings mqttSettings) {
final MqttSocketModem<I, O> modem = new MqttSocketModem<I, O>(socket, mqttSettings);
final IpSocketModem<Object, Object> tlsSocket = new IpSocketModem<Object, Object>(modem);
return connectTls(localAddress, tlsSocket, mqttSettings.ipSettings());
}
default <I, O> IpSocketRef connectMqtts(InetSocketAddress localAddress, MqttSocket<I, O> socket) {
return connectMqtts(localAddress, socket, mqttSettings());
}
default <I, O> IpSocketRef connectMqtts(String address, int port, MqttSocket<I, O> socket, MqttSettings mqttSettings) {
return connectMqtts(new InetSocketAddress(address, port), socket, mqttSettings);
}
default <I, O> IpSocketRef connectMqtts(String address, int port, MqttSocket<I, O> socket) {
return connectMqtts(new InetSocketAddress(address, port), socket, mqttSettings());
}
}
|
0 | java-sources/ai/swim/swim-io-mqtt/3.10.0/swim/io | java-sources/ai/swim/swim-io-mqtt/3.10.0/swim/io/mqtt/MqttService.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.io.mqtt;
public interface MqttService {
MqttServiceContext mqttServiceContext();
void setMqttServiceContext(MqttServiceContext context);
MqttSocket<?, ?> createSocket();
void didBind();
void didAccept(MqttSocket<?, ?> socket);
void didUnbind();
void didFail(Throwable error);
}
|
0 | java-sources/ai/swim/swim-io-mqtt/3.10.0/swim/io | java-sources/ai/swim/swim-io-mqtt/3.10.0/swim/io/mqtt/MqttServiceContext.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.io.mqtt;
import java.net.InetSocketAddress;
import swim.io.FlowContext;
public interface MqttServiceContext extends FlowContext {
MqttSettings mqttSettings();
InetSocketAddress localAddress();
void unbind();
}
|
0 | java-sources/ai/swim/swim-io-mqtt/3.10.0/swim/io | java-sources/ai/swim/swim-io-mqtt/3.10.0/swim/io/mqtt/MqttSettings.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.io.mqtt;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.io.IpSettings;
import swim.io.TcpSettings;
import swim.io.TlsSettings;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Record;
import swim.structure.Value;
import swim.util.Murmur3;
public class MqttSettings implements Debug {
protected final IpSettings ipSettings;
protected final int maxPayloadSize;
public MqttSettings(IpSettings ipSettings, int maxPayloadSize) {
this.ipSettings = ipSettings;
this.maxPayloadSize = maxPayloadSize;
}
public final IpSettings ipSettings() {
return this.ipSettings;
}
public MqttSettings ipSettings(IpSettings ipSettings) {
return copy(ipSettings, this.maxPayloadSize);
}
public final TlsSettings tlsSettings() {
return this.ipSettings.tlsSettings();
}
public MqttSettings tlsSettings(TlsSettings tlsSettings) {
return ipSettings(this.ipSettings.tlsSettings(tlsSettings));
}
public final TcpSettings tcpSettings() {
return this.ipSettings.tcpSettings();
}
public MqttSettings tcpSettings(TcpSettings tcpSettings) {
return ipSettings(this.ipSettings.tcpSettings(tcpSettings));
}
public final int maxPayloadSize() {
return this.maxPayloadSize;
}
public MqttSettings maxPayloadSize(int maxPayloadSize) {
return copy(this.ipSettings, maxPayloadSize);
}
protected MqttSettings copy(IpSettings ipSettings, int maxPayloadSize) {
return new MqttSettings(ipSettings, maxPayloadSize);
}
public Value toValue() {
return form().mold(this).toValue();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof MqttSettings) {
final MqttSettings that = (MqttSettings) other;
return this.ipSettings.equals(that.ipSettings)
&& this.maxPayloadSize == that.maxPayloadSize;
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(MqttSettings.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(hashSeed,
this.ipSettings.hashCode()), this.maxPayloadSize));
}
@Override
public void debug(Output<?> output) {
output = output.write("MqttSettings").write('.').write("standard").write('(').write(')')
.write('.').write("ipSettings").write('(').debug(this.ipSettings).write(')')
.write('.').write("maxPayloadSize").write('(').debug(this.maxPayloadSize).write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static MqttSettings standard;
private static Form<MqttSettings> form;
public static MqttSettings standard() {
if (standard == null) {
int maxPayloadSize;
try {
maxPayloadSize = Integer.parseInt(System.getProperty("swim.mqtt.max.payload.size"));
} catch (NumberFormatException error) {
maxPayloadSize = 16 * 1024 * 1024;
}
standard = new MqttSettings(IpSettings.standard(), maxPayloadSize);
}
return standard;
}
public static MqttSettings from(IpSettings ipSettings) {
return standard().ipSettings(ipSettings);
}
@Kind
public static Form<MqttSettings> form() {
if (form == null) {
form = new MqttSettingsForm();
}
return form;
}
}
final class MqttSettingsForm extends Form<MqttSettings> {
@Override
public MqttSettings unit() {
return MqttSettings.standard();
}
@Override
public Class<?> type() {
return MqttSettings.class;
}
@Override
public Item mold(MqttSettings settings) {
if (settings != null) {
final MqttSettings standard = MqttSettings.standard();
final Record mqtt = Record.create(2).attr("mqtt");
if (settings.maxPayloadSize != standard.maxPayloadSize) {
mqtt.slot("maxPayloadSize", settings.maxPayloadSize);
}
return Record.of(mqtt).concat(IpSettings.form().mold(settings.ipSettings));
} else {
return Item.extant();
}
}
@Override
public MqttSettings cast(Item item) {
final Value value = item.toValue();
final MqttSettings standard = MqttSettings.standard();
int maxPayloadSize = standard.maxPayloadSize;
for (Item member : value) {
if (member.getAttr("mqtt").isDefined()) {
maxPayloadSize = member.get("maxPayloadSize").intValue(maxPayloadSize);
}
}
final IpSettings ipSettings = IpSettings.form().cast(value);
return new MqttSettings(ipSettings, maxPayloadSize);
}
}
|
0 | java-sources/ai/swim/swim-io-mqtt/3.10.0/swim/io | java-sources/ai/swim/swim-io-mqtt/3.10.0/swim/io/mqtt/MqttSocket.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.io.mqtt;
import swim.io.IpSocket;
import swim.mqtt.MqttPacket;
public interface MqttSocket<I, O> {
MqttSocketContext<I, O> mqttSocketContext();
void setMqttSocketContext(MqttSocketContext<I, O> context);
long idleTimeout();
void doRead();
void didRead(MqttPacket<? extends I> packet);
void doWrite();
void didWrite(MqttPacket<? extends O> packet);
void willConnect();
void didConnect();
void willSecure();
void didSecure();
void willBecome(IpSocket socket);
void didBecome(IpSocket socket);
void didTimeout();
void didDisconnect();
void didFail(Throwable error);
}
|
0 | java-sources/ai/swim/swim-io-mqtt/3.10.0/swim/io | java-sources/ai/swim/swim-io-mqtt/3.10.0/swim/io/mqtt/MqttSocketContext.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.io.mqtt;
import swim.codec.Decoder;
import swim.io.FlowContext;
import swim.io.IpContext;
import swim.io.IpSocket;
import swim.mqtt.MqttPacket;
public interface MqttSocketContext<I, O> extends IpContext, FlowContext {
MqttSettings mqttSettings();
<I2 extends I> void read(Decoder<I2> content);
<O2 extends O> void write(MqttPacket<O2> packet);
void become(IpSocket socket);
void close();
}
|
0 | java-sources/ai/swim/swim-io-mqtt/3.10.0/swim/io | java-sources/ai/swim/swim-io-mqtt/3.10.0/swim/io/mqtt/MqttSocketModem.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.io.mqtt;
import java.net.InetSocketAddress;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.Collection;
import swim.codec.Decoder;
import swim.io.FlowControl;
import swim.io.FlowModifier;
import swim.io.IpModem;
import swim.io.IpModemContext;
import swim.io.IpSocket;
import swim.mqtt.Mqtt;
import swim.mqtt.MqttPacket;
public class MqttSocketModem<I, O> implements IpModem<Object, Object>, MqttSocketContext<I, O> {
protected final MqttSocket<I, O> socket;
protected final MqttSettings mqttSettings;
protected IpModemContext<Object, Object> context;
public MqttSocketModem(MqttSocket<I, O> socket, MqttSettings mqttSettings) {
this.socket = socket;
this.mqttSettings = mqttSettings;
}
@Override
public IpModemContext<Object, Object> ipModemContext() {
return this.context;
}
@Override
public void setIpModemContext(IpModemContext<Object, Object> context) {
this.context = context;
this.socket.setMqttSocketContext(this);
}
@Override
public long idleTimeout() {
return this.socket.idleTimeout();
}
@Override
public void doRead() {
this.socket.doRead();
}
@SuppressWarnings("unchecked")
@Override
public void didRead(Object input) {
this.socket.didRead((MqttPacket<I>) input);
}
@Override
public void doWrite() {
this.socket.doWrite();
}
@SuppressWarnings("unchecked")
@Override
public void didWrite(Object output) {
this.socket.didWrite((MqttPacket<O>) output);
}
@Override
public void willConnect() {
this.socket.willConnect();
}
@Override
public void didConnect() {
this.socket.didConnect();
}
@Override
public void willSecure() {
this.socket.willSecure();
}
@Override
public void didSecure() {
this.socket.didSecure();
}
@Override
public void willBecome(IpSocket socket) {
this.socket.willBecome(socket);
}
@Override
public void didBecome(IpSocket socket) {
this.socket.didBecome(socket);
}
@Override
public void didTimeout() {
this.socket.didTimeout();
}
@Override
public void didDisconnect() {
this.socket.didDisconnect();
}
@Override
public void didFail(Throwable error) {
this.socket.didFail(error);
close();
}
@Override
public boolean isConnected() {
final IpModemContext<Object, Object> context = this.context;
return context != null && context.isConnected();
}
@Override
public boolean isClient() {
final IpModemContext<Object, Object> context = this.context;
return context != null && context.isClient();
}
@Override
public boolean isServer() {
final IpModemContext<Object, Object> context = this.context;
return context != null && context.isServer();
}
@Override
public boolean isSecure() {
final IpModemContext<Object, Object> context = this.context;
return context != null && context.isSecure();
}
@Override
public String securityProtocol() {
return this.context.securityProtocol();
}
@Override
public String cipherSuite() {
return this.context.cipherSuite();
}
@Override
public InetSocketAddress localAddress() {
return this.context.localAddress();
}
@Override
public Principal localPrincipal() {
return this.context.localPrincipal();
}
@Override
public Collection<Certificate> localCertificates() {
return this.context.localCertificates();
}
@Override
public InetSocketAddress remoteAddress() {
return this.context.remoteAddress();
}
@Override
public Principal remotePrincipal() {
return this.context.remotePrincipal();
}
@Override
public Collection<Certificate> remoteCertificates() {
return this.context.remoteCertificates();
}
@Override
public FlowControl flowControl() {
return this.context.flowControl();
}
@Override
public void flowControl(FlowControl flowControl) {
this.context.flowControl(flowControl);
}
@Override
public FlowControl flowControl(FlowModifier flowModifier) {
return this.context.flowControl(flowModifier);
}
@Override
public MqttSettings mqttSettings() {
return this.mqttSettings;
}
@Override
public <I2 extends I> void read(Decoder<I2> content) {
this.context.read(Mqtt.standardDecoder().packetDecoder(content));
}
@Override
public <O2 extends O> void write(MqttPacket<O2> packet) {
this.context.write(packet.mqttEncoder(Mqtt.standardEncoder()));
}
@Override
public void become(IpSocket socket) {
this.context.become(socket);
}
@Override
public void close() {
this.context.close();
}
}
|
0 | java-sources/ai/swim/swim-io-mqtt/3.10.0/swim/io | java-sources/ai/swim/swim-io-mqtt/3.10.0/swim/io/mqtt/MqttSocketService.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.io.mqtt;
import java.net.InetSocketAddress;
import swim.io.FlowControl;
import swim.io.FlowModifier;
import swim.io.IpService;
import swim.io.IpServiceContext;
import swim.io.IpSocket;
import swim.io.IpSocketModem;
public class MqttSocketService implements IpService, MqttServiceContext {
protected final MqttService service;
protected final MqttSettings mqttSettings;
protected IpServiceContext context;
public MqttSocketService(MqttService service, MqttSettings mqttSettings) {
this.service = service;
this.mqttSettings = mqttSettings;
}
@Override
public IpServiceContext ipServiceContext() {
return this.context;
}
@Override
public void setIpServiceContext(IpServiceContext context) {
this.context = context;
this.service.setMqttServiceContext(this);
}
@Override
public IpSocket createSocket() {
final MqttSocket<?, ?> socket = this.service.createSocket();
final MqttSocketModem<?, ?> modem = new MqttSocketModem<>(socket, mqttSettings);
return new IpSocketModem<>(modem);
}
@Override
public void didBind() {
this.service.didBind();
}
@Override
public void didAccept(IpSocket socket) {
if (socket instanceof MqttSocketModem) {
this.service.didAccept(((MqttSocketModem) socket).socket);
}
}
@Override
public void didUnbind() {
this.service.didUnbind();
}
@Override
public void didFail(Throwable error) {
this.service.didFail(error);
}
@Override
public FlowControl flowControl() {
return this.context.flowControl();
}
@Override
public void flowControl(FlowControl flowControl) {
this.context.flowControl(flowControl);
}
@Override
public FlowControl flowControl(FlowModifier flowModifier) {
return this.context.flowControl(flowModifier);
}
@Override
public MqttSettings mqttSettings() {
return this.mqttSettings;
}
@Override
public InetSocketAddress localAddress() {
return this.context.localAddress();
}
@Override
public void unbind() {
this.context.unbind();
}
}
|
0 | java-sources/ai/swim/swim-io-mqtt/3.10.0/swim/io | java-sources/ai/swim/swim-io-mqtt/3.10.0/swim/io/mqtt/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.
/**
* Flow-controlled MQTT I/O library.
*/
package swim.io.mqtt;
|
0 | java-sources/ai/swim/swim-io-warp | java-sources/ai/swim/swim-io-warp/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.
/**
* Flow-controlled Web Agent I/O library.
*/
module swim.io.warp {
requires swim.util;
requires transitive swim.codec;
requires transitive swim.uri;
requires transitive swim.http;
requires transitive swim.ws;
requires transitive swim.warp;
requires swim.concurrent;
requires transitive swim.io;
requires transitive swim.io.http;
requires transitive swim.io.ws;
exports swim.io.warp;
}
|
0 | java-sources/ai/swim/swim-io-warp/3.10.0/swim/io | java-sources/ai/swim/swim-io-warp/3.10.0/swim/io/warp/AbstractWarpClient.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.io.warp;
import swim.codec.Decoder;
import swim.io.http.HttpClientContext;
import swim.io.ws.AbstractWsClient;
import swim.io.ws.WebSocketContext;
import swim.io.ws.WsSettings;
import swim.io.ws.WsUpgradeRequester;
import swim.warp.Envelope;
import swim.warp.WarpException;
import swim.ws.WsControl;
import swim.ws.WsData;
import swim.ws.WsRequest;
public abstract class AbstractWarpClient extends AbstractWsClient implements WebSocketContext<Envelope, Envelope> {
protected WarpSettings warpSettings;
public AbstractWarpClient(WarpSettings warpSettings) {
this.wsSettings = warpSettings.wsSettings();
this.warpSettings = warpSettings;
}
public AbstractWarpClient() {
this.wsSettings = null;
this.warpSettings = null;
}
@Override
public void setHttpClientContext(HttpClientContext context) {
this.context = context;
if (this.wsSettings == null) {
this.wsSettings = WsSettings.from(context.httpSettings());
this.warpSettings = WarpSettings.from(this.wsSettings);
}
}
@Override
public <I2 extends Envelope> void read(Decoder<I2> content) {
throw new WarpException("unupgraded websocket");
}
@Override
public <O2 extends Envelope> void write(WsData<O2> frame) {
throw new WarpException("unupgraded websocket");
}
@Override
public <O2 extends Envelope> void write(WsControl<?, O2> frame) {
throw new WarpException("unupgraded websocket");
}
public final WarpSettings warpSettings() {
return this.warpSettings;
}
protected WsUpgradeRequester upgrade(WarpSocket warpSocket, WsRequest wsRequest) {
final WarpWebSocket webSocket = new WarpWebSocket(warpSocket, this.warpSettings);
warpSocket.setWarpSocketContext(webSocket); // eagerly set
return new WsUpgradeRequester(webSocket, wsRequest, this.wsSettings);
}
}
|
0 | java-sources/ai/swim/swim-io-warp/3.10.0/swim/io | java-sources/ai/swim/swim-io-warp/3.10.0/swim/io/warp/AbstractWarpServer.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.io.warp;
import swim.io.http.HttpServerContext;
import swim.io.ws.AbstractWsServer;
import swim.io.ws.WsSettings;
import swim.io.ws.WsUpgradeResponder;
import swim.ws.WsResponse;
public abstract class AbstractWarpServer extends AbstractWsServer {
protected WarpSettings warpSettings;
public AbstractWarpServer(WarpSettings warpSettings) {
this.wsSettings = warpSettings.wsSettings();
this.warpSettings = warpSettings;
}
public AbstractWarpServer() {
this.wsSettings = null;
this.warpSettings = null;
}
@Override
public void setHttpServerContext(HttpServerContext context) {
this.context = context;
if (this.wsSettings == null) {
this.wsSettings = WsSettings.from(context.httpSettings());
this.warpSettings = WarpSettings.from(this.wsSettings);
}
}
public final WarpSettings warpSettings() {
return this.warpSettings;
}
protected WsUpgradeResponder upgrade(WarpSocket warpSocket, WsResponse wsResponse) {
final WarpWebSocket webSocket = new WarpWebSocket(warpSocket, this.warpSettings);
warpSocket.setWarpSocketContext(webSocket); // eagerly set
return new WsUpgradeResponder(webSocket, wsResponse, this.wsSettings);
}
}
|
0 | java-sources/ai/swim/swim-io-warp/3.10.0/swim/io | java-sources/ai/swim/swim-io-warp/3.10.0/swim/io/warp/AbstractWarpSocket.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.io.warp;
import java.net.InetSocketAddress;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.Collection;
import swim.concurrent.PullRequest;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
import swim.io.FlowContext;
import swim.io.FlowControl;
import swim.io.FlowModifier;
import swim.io.IpContext;
import swim.io.IpSocket;
import swim.warp.Envelope;
import swim.ws.WsClose;
import swim.ws.WsControl;
import swim.ws.WsPing;
import swim.ws.WsPong;
public abstract class AbstractWarpSocket implements WarpSocket, IpContext, FlowContext {
protected WarpSocketContext context;
@Override
public WarpSocketContext warpSocketContext() {
return this.context;
}
@Override
public void setWarpSocketContext(WarpSocketContext context) {
this.context = context;
}
@Override
public long idleTimeout() {
return -1L; // default timeout
}
@Override
public void doRead() {
// stub
}
@Override
public void didRead(Envelope envelope) {
// stub
}
@Override
public void didRead(WsControl<?, ?> frame) {
if (frame instanceof WsPing<?, ?>) {
write(WsPong.from(frame.payload()));
} else if (frame instanceof WsClose<?, ?>) {
close();
}
}
@Override
public void doWrite() {
// stub
}
@Override
public void didWrite(Envelope envelope) {
// stub
}
@Override
public void didWrite(WsControl<?, ?> frame) {
if (frame instanceof WsClose<?, ?>) {
close();
}
}
@Override
public void didUpgrade(HttpRequest<?> httpRequest, HttpResponse<?> httpResponse) {
// stub
}
@Override
public void willConnect() {
// stub
}
@Override
public void didConnect() {
// stub
}
@Override
public void willSecure() {
// stub
}
@Override
public void didSecure() {
// stub
}
@Override
public void willBecome(IpSocket socket) {
// stub
}
@Override
public void didBecome(IpSocket socket) {
// stub
}
@Override
public void didTimeout() {
// stub
}
@Override
public void didDisconnect() {
// stub
}
@Override
public void didFail(Throwable error) {
error.printStackTrace();
}
@Override
public boolean isConnected() {
return this.context.isConnected();
}
@Override
public boolean isClient() {
return this.context.isClient();
}
@Override
public boolean isServer() {
return this.context.isServer();
}
@Override
public boolean isSecure() {
return this.context.isSecure();
}
@Override
public String securityProtocol() {
return this.context.securityProtocol();
}
@Override
public String cipherSuite() {
return this.context.cipherSuite();
}
@Override
public InetSocketAddress localAddress() {
return this.context.localAddress();
}
@Override
public Principal localPrincipal() {
return this.context.localPrincipal();
}
@Override
public Collection<Certificate> localCertificates() {
return this.context.localCertificates();
}
@Override
public InetSocketAddress remoteAddress() {
return this.context.remoteAddress();
}
@Override
public Principal remotePrincipal() {
return this.context.remotePrincipal();
}
@Override
public Collection<Certificate> remoteCertificates() {
return this.context.remoteCertificates();
}
@Override
public FlowControl flowControl() {
return this.context.flowControl();
}
@Override
public void flowControl(FlowControl flowControl) {
this.context.flowControl(flowControl);
}
@Override
public FlowControl flowControl(FlowModifier flowModifier) {
return this.context.flowControl(flowModifier);
}
public WarpSettings warpSettings() {
return this.context.warpSettings();
}
public void feed(PullRequest<Envelope> pullRequest) {
this.context.feed(pullRequest);
}
public void feed(Envelope envelope, float prio) {
this.context.feed(envelope, prio);
}
public void feed(Envelope envelope) {
this.context.feed(envelope);
}
public void write(WsControl<?, ? extends Envelope> frame) {
this.context.write(frame);
}
public void become(IpSocket socket) {
this.context.become(socket);
}
public void close() {
this.context.close();
}
}
|
0 | java-sources/ai/swim/swim-io-warp/3.10.0/swim/io | java-sources/ai/swim/swim-io-warp/3.10.0/swim/io/warp/WarpSettings.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.io.warp;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.io.IpSettings;
import swim.io.TcpSettings;
import swim.io.TlsSettings;
import swim.io.http.HttpSettings;
import swim.io.ws.WsSettings;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Value;
import swim.util.Murmur3;
public class WarpSettings implements Debug {
protected final WsSettings wsSettings;
public WarpSettings(WsSettings wsSettings) {
this.wsSettings = wsSettings;
}
public final WsSettings wsSettings() {
return this.wsSettings;
}
public WarpSettings wsSettings(WsSettings wsSettings) {
return new WarpSettings(wsSettings);
}
public final HttpSettings httpSettings() {
return this.wsSettings.httpSettings();
}
public WarpSettings httpSettings(HttpSettings httpSettings) {
return wsSettings(this.wsSettings.httpSettings(httpSettings));
}
public final IpSettings ipSettings() {
return this.wsSettings.ipSettings();
}
public WarpSettings ipSettings(IpSettings ipSettings) {
return wsSettings(this.wsSettings.ipSettings(ipSettings));
}
public final TlsSettings tlsSettings() {
return this.wsSettings.tlsSettings();
}
public WarpSettings tlsSettings(TlsSettings tlsSettings) {
return wsSettings(this.wsSettings.tlsSettings(tlsSettings));
}
public final TcpSettings tcpSettings() {
return this.wsSettings.tcpSettings();
}
public WarpSettings tcpSettings(TcpSettings tcpSettings) {
return wsSettings(this.wsSettings.tcpSettings(tcpSettings));
}
public Value toValue() {
return form().mold(this).toValue();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof WarpSettings) {
final WarpSettings that = (WarpSettings) other;
return this.wsSettings.equals(that.wsSettings);
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(WarpSettings.class);
}
return Murmur3.mash(Murmur3.mix(hashSeed, this.wsSettings.hashCode()));
}
@Override
public void debug(Output<?> output) {
output.write("WarpSettings").write('.').write("standard").write('(').write(')')
.write('.').write("wsSettings").write('(').debug(this.wsSettings).write(')');
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
private static WarpSettings standard;
private static Form<WarpSettings> form;
public static WarpSettings standard() {
if (standard == null) {
standard = new WarpSettings(WsSettings.standard());
}
return standard;
}
public static WarpSettings from(WsSettings wsSettings) {
return new WarpSettings(wsSettings);
}
@Kind
public static Form<WarpSettings> form() {
if (form == null) {
form = new WarpSettingsForm();
}
return form;
}
}
final class WarpSettingsForm extends Form<WarpSettings> {
@Override
public WarpSettings unit() {
return WarpSettings.standard();
}
@Override
public Class<?> type() {
return WarpSettings.class;
}
@Override
public Item mold(WarpSettings settings) {
if (settings != null) {
return WsSettings.form().mold(settings.wsSettings);
} else {
return Item.extant();
}
}
@Override
public WarpSettings cast(Item item) {
final WsSettings wsSettings = WsSettings.form().cast(item);
return new WarpSettings(wsSettings);
}
}
|
0 | java-sources/ai/swim/swim-io-warp/3.10.0/swim/io | java-sources/ai/swim/swim-io-warp/3.10.0/swim/io/warp/WarpSocket.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.io.warp;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
import swim.io.IpSocket;
import swim.warp.Envelope;
import swim.ws.WsControl;
public interface WarpSocket {
WarpSocketContext warpSocketContext();
void setWarpSocketContext(WarpSocketContext context);
long idleTimeout();
void doRead();
void didRead(Envelope envelope);
void didRead(WsControl<?, ?> frame);
void doWrite();
void didWrite(Envelope envelope);
void didWrite(WsControl<?, ?> frame);
void didUpgrade(HttpRequest<?> httpRequest, HttpResponse<?> httpResponse);
void willConnect();
void didConnect();
void willSecure();
void didSecure();
void willBecome(IpSocket socket);
void didBecome(IpSocket socket);
void didTimeout();
void didDisconnect();
void didFail(Throwable error);
}
|
0 | java-sources/ai/swim/swim-io-warp/3.10.0/swim/io | java-sources/ai/swim/swim-io-warp/3.10.0/swim/io/warp/WarpSocketContext.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.io.warp;
import swim.concurrent.PullRequest;
import swim.io.FlowContext;
import swim.io.IpContext;
import swim.io.IpSocket;
import swim.warp.Envelope;
import swim.ws.WsControl;
public interface WarpSocketContext extends IpContext, FlowContext {
WarpSettings warpSettings();
void feed(PullRequest<Envelope> pullRequest);
void feed(Envelope envelope, float prio);
void feed(Envelope envelope);
void write(WsControl<?, ? extends Envelope> frame);
void become(IpSocket socket);
void close();
}
|
0 | java-sources/ai/swim/swim-io-warp/3.10.0/swim/io | java-sources/ai/swim/swim-io-warp/3.10.0/swim/io/warp/WarpWebSocket.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.io.warp;
import java.net.InetSocketAddress;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import swim.concurrent.ConcurrentTrancheQueue;
import swim.concurrent.PullContext;
import swim.concurrent.PullRequest;
import swim.concurrent.PushRequest;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
import swim.io.FlowControl;
import swim.io.FlowModifier;
import swim.io.IpSocket;
import swim.io.ws.WebSocket;
import swim.io.ws.WebSocketContext;
import swim.warp.Envelope;
import swim.warp.WarpException;
import swim.ws.WsClose;
import swim.ws.WsControl;
import swim.ws.WsData;
import swim.ws.WsFragment;
import swim.ws.WsFrame;
import swim.ws.WsText;
public class WarpWebSocket implements WebSocket<Envelope, Envelope>, WarpSocketContext, PullContext<Envelope> {
protected final WarpSocket socket;
protected final WarpSettings warpSettings;
final ConcurrentTrancheQueue<PullRequest<Envelope>> supply;
protected WebSocketContext<Envelope, Envelope> context;
volatile long status;
public WarpWebSocket(WarpSocket socket, WarpSettings warpSettings) {
this.socket = socket;
this.warpSettings = warpSettings;
this.supply = new ConcurrentTrancheQueue<PullRequest<Envelope>>(TRANCHES);
}
@Override
public WebSocketContext<Envelope, Envelope> webSocketContext() {
return this.context;
}
@Override
public void setWebSocketContext(WebSocketContext<Envelope, Envelope> context) {
this.context = context;
this.socket.setWarpSocketContext(this);
}
@Override
public long idleTimeout() {
return this.socket.idleTimeout();
}
@Override
public void doRead() {
this.socket.doRead();
}
@Override
public void didRead(WsFrame<? extends Envelope> frame) {
if (frame instanceof WsFragment<?>) {
final WsFragment<? extends Envelope> fragment = (WsFragment<? extends Envelope>) frame;
this.context.read(fragment.contentDecoder());
} else {
if (frame instanceof WsData<?>) {
this.socket.didRead(frame.get());
} else if (frame instanceof WsControl<?, ?>) {
this.socket.didRead((WsControl<?, ?>) frame);
}
this.context.read(Envelope.decoder());
}
}
@Override
public void doWrite() {
this.socket.doWrite();
generateDemand();
}
@Override
public void didWrite(WsFrame<? extends Envelope> frame) {
if (frame instanceof WsData<?>) {
do {
final long oldStatus = this.status;
final long oldBuffer = (oldStatus & BUFFER_MASK) >>> BUFFER_SHIFT;
final long newBuffer = oldBuffer - 1L;
if (newBuffer >= 0L) {
final long newStatus = oldStatus & ~BUFFER_MASK | newBuffer << BUFFER_SHIFT;
if (STATUS.compareAndSet(this, oldStatus, newStatus)) {
break;
}
} else {
throw new WarpException("overbuffer");
}
} while (true);
this.socket.didWrite(frame.get());
} else if (frame instanceof WsControl<?, ?>) {
this.socket.didWrite((WsControl<?, ?>) frame);
}
generateDemand();
}
@Override
public void didUpgrade(HttpRequest<?> httpRequest, HttpResponse<?> httpResponse) {
do {
final long oldStatus = this.status;
final long newStatus = oldStatus | UPGRADED;
if (oldStatus != newStatus) {
if (STATUS.compareAndSet(this, oldStatus, newStatus)) {
this.socket.didUpgrade(httpRequest, httpResponse);
this.context.read(Envelope.decoder());
generateDemand();
break;
}
} else {
break;
}
} while (true);
}
@Override
public void willConnect() {
this.socket.willConnect();
}
@Override
public void didConnect() {
this.socket.didConnect();
}
@Override
public void willSecure() {
this.socket.willSecure();
}
@Override
public void didSecure() {
this.socket.didSecure();
}
@Override
public void willBecome(IpSocket socket) {
this.socket.willBecome(socket);
}
@Override
public void didBecome(IpSocket socket) {
this.socket.didBecome(socket);
}
@Override
public void didTimeout() {
this.socket.didTimeout();
}
@Override
public void didDisconnect() {
do {
final long oldStatus = this.status;
final long newStatus = oldStatus & ~(UPGRADED | CLOSING);
if (oldStatus != newStatus) {
if (STATUS.compareAndSet(this, oldStatus, newStatus)) {
break;
}
} else {
break;
}
} while (true);
this.socket.didDisconnect();
close();
}
@Override
public void didFail(Throwable error) {
this.socket.didFail(error);
close();
}
@Override
public boolean isConnected() {
final WebSocketContext<Envelope, Envelope> context = this.context;
return context != null && context.isConnected();
}
@Override
public boolean isClient() {
final WebSocketContext<Envelope, Envelope> context = this.context;
return context != null && context.isClient();
}
@Override
public boolean isServer() {
final WebSocketContext<Envelope, Envelope> context = this.context;
return context != null && context.isServer();
}
@Override
public boolean isSecure() {
final WebSocketContext<Envelope, Envelope> context = this.context;
return context != null && context.isSecure();
}
@Override
public String securityProtocol() {
return this.context.securityProtocol();
}
@Override
public String cipherSuite() {
return this.context.cipherSuite();
}
@Override
public InetSocketAddress localAddress() {
return this.context.localAddress();
}
@Override
public Principal localPrincipal() {
return this.context.localPrincipal();
}
@Override
public Collection<Certificate> localCertificates() {
return this.context.localCertificates();
}
@Override
public InetSocketAddress remoteAddress() {
return this.context.remoteAddress();
}
@Override
public Principal remotePrincipal() {
return this.context.remotePrincipal();
}
@Override
public Collection<Certificate> remoteCertificates() {
return this.context.remoteCertificates();
}
@Override
public FlowControl flowControl() {
return this.context.flowControl();
}
@Override
public void flowControl(FlowControl flowControl) {
this.context.flowControl(flowControl);
}
@Override
public FlowControl flowControl(FlowModifier flowModifier) {
return this.context.flowControl(flowModifier);
}
@Override
public WarpSettings warpSettings() {
return this.warpSettings;
}
@Override
public void feed(PullRequest<Envelope> pullRequest) {
do {
final long oldStatus = this.status;
final long oldSupply = oldStatus & SUPPLY_MASK;
final long newSupply = oldSupply + 1L;
if (newSupply <= SUPPLY_MAX) {
final long newStatus = oldStatus & ~SUPPLY_MASK | newSupply;
if (STATUS.compareAndSet(this, oldStatus, newStatus)) {
break;
}
} else {
throw new WarpException("exceeded maximum supply: " + newSupply);
}
} while (true);
this.supply.add(pullRequest, pullRequest.prio());
generateDemand();
}
@Override
public void feed(Envelope envelope, float prio) {
feed(new PushRequest<Envelope>(envelope, prio));
}
@Override
public void feed(Envelope envelope) {
feed(envelope, 0.0f);
}
@Override
public void push(Envelope envelope) {
do {
final long oldStatus = this.status;
final long oldDemand = (oldStatus & DEMAND_MASK) >>> DEMAND_SHIFT;
final long oldBuffer = (oldStatus & BUFFER_MASK) >>> BUFFER_SHIFT;
final long newDemand = oldDemand - 1L;
final long newBuffer = oldBuffer + 1L;
if (newDemand >= 0L) {
if (newBuffer <= BUFFER_MAX) {
final long newStatus = oldStatus & ~(DEMAND_MASK | BUFFER_MASK)
| newDemand << DEMAND_SHIFT
| newBuffer << BUFFER_SHIFT;
if (STATUS.compareAndSet(this, oldStatus, newStatus)) {
break;
}
} else {
throw new WarpException("exceeded maximum buffer: " + newBuffer);
}
} else {
throw new WarpException("overdemand");
}
} while (true);
this.context.write(WsText.from(envelope, envelope.reconEncoder()));
}
@Override
public void skip() {
do {
final long oldStatus = this.status;
final long oldDemand = (oldStatus & DEMAND_MASK) >>> DEMAND_SHIFT;
final long newDemand = oldDemand - 1L;
if (newDemand >= 0L) {
final long newStatus = oldStatus & ~DEMAND_MASK | newDemand << DEMAND_SHIFT;
if (STATUS.compareAndSet(this, oldStatus, newStatus)) {
break;
}
} else {
throw new WarpException("overdemand");
}
} while (true);
}
protected void generateDemand() {
demand: do {
PullRequest<Envelope> pullRequest = null;
do {
final long oldStatus = this.status;
if ((oldStatus & UPGRADED) == 0) {
return;
}
final long oldSupply = oldStatus & SUPPLY_MASK;
final long oldDemand = (oldStatus & DEMAND_MASK) >>> DEMAND_SHIFT;
final long oldBuffer = (oldStatus & BUFFER_MASK) >>> BUFFER_SHIFT;
if (pullRequest == null && oldSupply > 0L && oldDemand + oldBuffer < TARGET_DEMAND) {
pullRequest = supply.poll();
}
if (pullRequest != null) {
final long newDemand = oldDemand + 1L;
final long newSupply = oldSupply - 1L;
if (newSupply >= 0L) {
if (newDemand <= DEMAND_MAX) {
final long newStatus = oldStatus & ~(SUPPLY_MASK | DEMAND_MASK) | newSupply | newDemand << DEMAND_SHIFT;
if (STATUS.compareAndSet(this, oldStatus, newStatus)) {
pullRequest.pull(this);
if (newDemand < TARGET_DEMAND) {
continue demand;
}
break;
}
} else {
throw new WarpException("exceeded maximum demand: " + newDemand);
}
} else {
throw new WarpException("oversupply");
}
} else {
break demand;
}
} while (true);
} while (true);
}
@Override
public void write(WsControl<?, ? extends Envelope> frame) {
if (frame instanceof WsClose<?, ?>) {
do {
final long oldStatus = this.status;
if ((oldStatus & (UPGRADED | CLOSING)) == UPGRADED) {
final long newStatus = oldStatus | CLOSING;
if (STATUS.compareAndSet(this, oldStatus, newStatus)) {
this.context.write(frame);
break;
}
} else {
break;
}
} while (true);
} else {
this.context.write(frame);
}
}
@Override
public void become(IpSocket socket) {
this.context.become(socket);
}
@Override
public void close() {
final WebSocketContext<Envelope, Envelope> context = this.context;
if (context != null) {
context.close();
}
}
static final long SUPPLY_MAX;
static final long DEMAND_MAX;
static final long BUFFER_MAX;
static final int DEMAND_SHIFT;
static final int BUFFER_SHIFT;
static final long SUPPLY_MASK;
static final long DEMAND_MASK;
static final long BUFFER_MASK;
static final long UPGRADED;
static final long CLOSING;
static final long TARGET_DEMAND;
static final int TRANCHES;
static final AtomicLongFieldUpdater<WarpWebSocket> STATUS =
AtomicLongFieldUpdater.newUpdater(WarpWebSocket.class, "status");
static {
int supplyBits;
try {
supplyBits = Integer.parseInt(System.getProperty("swim.warp.supply.bits"));
} catch (NumberFormatException e) {
supplyBits = 24;
}
int demandBits;
try {
demandBits = Integer.parseInt(System.getProperty("swim.warp.demand.bits"));
} catch (NumberFormatException e) {
demandBits = 12;
}
int bufferBits;
try {
bufferBits = Integer.parseInt(System.getProperty("swim.warp.buffer.bits"));
} catch (NumberFormatException e) {
bufferBits = 24;
}
if (supplyBits < 0 || demandBits < 0 || bufferBits < 0 || supplyBits + demandBits + bufferBits > 60) {
throw new ExceptionInInitializerError();
}
SUPPLY_MAX = (1L << supplyBits) - 1L;
DEMAND_MAX = (1L << demandBits) - 1L;
BUFFER_MAX = (1L << bufferBits) - 1L;
DEMAND_SHIFT = supplyBits;
BUFFER_SHIFT = supplyBits + demandBits;
SUPPLY_MASK = SUPPLY_MAX;
DEMAND_MASK = DEMAND_MAX << DEMAND_SHIFT;
BUFFER_MASK = BUFFER_MAX << BUFFER_SHIFT;
UPGRADED = 1L << 60;
CLOSING = 1L << 61;
int targetDemand;
try {
targetDemand = Integer.parseInt(System.getProperty("swim.warp.demand.target"));
} catch (NumberFormatException e) {
targetDemand = 32;
}
TARGET_DEMAND = targetDemand;
int tranches;
try {
tranches = Integer.parseInt(System.getProperty("swim.warp.tranches"));
} catch (NumberFormatException e) {
tranches = 5;
}
TRANCHES = tranches;
}
}
|
0 | java-sources/ai/swim/swim-io-warp/3.10.0/swim/io | java-sources/ai/swim/swim-io-warp/3.10.0/swim/io/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.
/**
* Flow-controlled Web Agent I/O library.
*/
package swim.io.warp;
|
0 | java-sources/ai/swim/swim-io-ws | java-sources/ai/swim/swim-io-ws/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.
/**
* Flow-controlled WebSocket I/O library.
*/
module swim.io.ws {
requires swim.util;
requires transitive swim.codec;
requires transitive swim.structure;
requires transitive swim.http;
requires transitive swim.ws;
requires transitive swim.io;
requires transitive swim.io.http;
exports swim.io.ws;
}
|
0 | java-sources/ai/swim/swim-io-ws/3.10.0/swim/io | java-sources/ai/swim/swim-io-ws/3.10.0/swim/io/ws/AbstractWebSocket.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.io.ws;
import java.net.InetSocketAddress;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.Collection;
import swim.codec.Decoder;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
import swim.io.FlowContext;
import swim.io.FlowControl;
import swim.io.FlowModifier;
import swim.io.IpContext;
import swim.io.IpSocket;
import swim.ws.WsControl;
import swim.ws.WsData;
import swim.ws.WsFrame;
public abstract class AbstractWebSocket<I, O> implements WebSocket<I, O>, IpContext, FlowContext {
protected WebSocketContext<I, O> context;
@Override
public WebSocketContext<I, O> webSocketContext() {
return this.context;
}
@Override
public void setWebSocketContext(WebSocketContext<I, O> context) {
this.context = context;
}
@Override
public long idleTimeout() {
return -1L; // default timeout
}
@Override
public void doRead() {
// stub
}
@Override
public void didRead(WsFrame<? extends I> frame) {
// stub
}
@Override
public void doWrite() {
// stub
}
@Override
public void didWrite(WsFrame<? extends O> frame) {
// stub
}
@Override
public void didUpgrade(HttpRequest<?> httpRequest, HttpResponse<?> httpResponse) {
// stub
}
@Override
public void willConnect() {
// stub
}
@Override
public void didConnect() {
// stub
}
@Override
public void willSecure() {
// stub
}
@Override
public void didSecure() {
// stub
}
@Override
public void willBecome(IpSocket socket) {
// stub
}
@Override
public void didBecome(IpSocket socket) {
// stub
}
@Override
public void didTimeout() {
// stub
}
@Override
public void didDisconnect() {
// stub
}
@Override
public void didFail(Throwable error) {
error.printStackTrace();
}
@Override
public boolean isConnected() {
return this.context.isConnected();
}
@Override
public boolean isClient() {
return this.context.isClient();
}
@Override
public boolean isServer() {
return this.context.isServer();
}
@Override
public boolean isSecure() {
return this.context.isSecure();
}
@Override
public String securityProtocol() {
return this.context.securityProtocol();
}
@Override
public String cipherSuite() {
return this.context.cipherSuite();
}
@Override
public InetSocketAddress localAddress() {
return this.context.localAddress();
}
@Override
public Principal localPrincipal() {
return this.context.localPrincipal();
}
@Override
public Collection<Certificate> localCertificates() {
return this.context.localCertificates();
}
@Override
public InetSocketAddress remoteAddress() {
return this.context.remoteAddress();
}
@Override
public Principal remotePrincipal() {
return this.context.remotePrincipal();
}
@Override
public Collection<Certificate> remoteCertificates() {
return this.context.remoteCertificates();
}
@Override
public FlowControl flowControl() {
return this.context.flowControl();
}
@Override
public void flowControl(FlowControl flowControl) {
this.context.flowControl(flowControl);
}
@Override
public FlowControl flowControl(FlowModifier flowModifier) {
return this.context.flowControl(flowModifier);
}
public WsSettings wsSettings() {
return this.context.wsSettings();
}
public <I2 extends I> void read(Decoder<I2> content) {
this.context.read(content);
}
public <O2 extends O> void write(WsData<O2> frame) {
this.context.write(frame);
}
public <O2 extends O> void write(WsControl<?, O2> frame) {
this.context.write(frame);
}
public void become(IpSocket socket) {
this.context.become(socket);
}
public void close() {
this.context.close();
}
}
|
0 | java-sources/ai/swim/swim-io-ws/3.10.0/swim/io | java-sources/ai/swim/swim-io-ws/3.10.0/swim/io/ws/AbstractWsClient.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.io.ws;
import swim.io.http.AbstractHttpClient;
import swim.io.http.HttpClientContext;
import swim.ws.WsRequest;
public abstract class AbstractWsClient extends AbstractHttpClient {
protected WsSettings wsSettings;
public AbstractWsClient(WsSettings wsSettings) {
this.wsSettings = wsSettings;
}
public AbstractWsClient() {
this(null);
}
@Override
public void setHttpClientContext(HttpClientContext context) {
this.context = context;
if (this.wsSettings == null) {
this.wsSettings = WsSettings.from(context.httpSettings());
}
}
public final WsSettings wsSettings() {
return this.wsSettings;
}
protected WsUpgradeRequester upgrade(WebSocket<?, ?> webSocket, WsRequest wsRequest) {
return new WsUpgradeRequester(webSocket, wsRequest, this.wsSettings);
}
}
|
0 | java-sources/ai/swim/swim-io-ws/3.10.0/swim/io | java-sources/ai/swim/swim-io-ws/3.10.0/swim/io/ws/AbstractWsServer.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.io.ws;
import swim.io.http.AbstractHttpServer;
import swim.io.http.HttpServerContext;
import swim.ws.WsResponse;
public abstract class AbstractWsServer extends AbstractHttpServer {
protected WsSettings wsSettings;
public AbstractWsServer(WsSettings wsSettings) {
this.wsSettings = wsSettings;
}
public AbstractWsServer() {
this(null);
}
@Override
public void setHttpServerContext(HttpServerContext context) {
this.context = context;
if (this.wsSettings == null) {
this.wsSettings = WsSettings.from(context.httpSettings());
}
}
public final WsSettings wsSettings() {
return this.wsSettings;
}
protected WsUpgradeResponder upgrade(WebSocket<?, ?> webSocket, WsResponse wsResponse) {
return new WsUpgradeResponder(webSocket, wsResponse, this.wsSettings);
}
}
|
0 | java-sources/ai/swim/swim-io-ws/3.10.0/swim/io | java-sources/ai/swim/swim-io-ws/3.10.0/swim/io/ws/WebSocket.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.io.ws;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
import swim.io.IpSocket;
import swim.ws.WsFrame;
public interface WebSocket<I, O> {
WebSocketContext<I, O> webSocketContext();
void setWebSocketContext(WebSocketContext<I, O> context);
long idleTimeout();
void doRead();
void didRead(WsFrame<? extends I> frame);
void doWrite();
void didWrite(WsFrame<? extends O> frame);
void didUpgrade(HttpRequest<?> httpRequest, HttpResponse<?> httpResponse);
void willConnect();
void didConnect();
void willSecure();
void didSecure();
void willBecome(IpSocket socket);
void didBecome(IpSocket socket);
void didTimeout();
void didDisconnect();
void didFail(Throwable error);
}
|
0 | java-sources/ai/swim/swim-io-ws/3.10.0/swim/io | java-sources/ai/swim/swim-io-ws/3.10.0/swim/io/ws/WebSocketContext.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.io.ws;
import swim.codec.Decoder;
import swim.io.FlowContext;
import swim.io.IpContext;
import swim.io.IpSocket;
import swim.ws.WsControl;
import swim.ws.WsData;
public interface WebSocketContext<I, O> extends IpContext, FlowContext {
WsSettings wsSettings();
<I2 extends I> void read(Decoder<I2> content);
<O2 extends O> void write(WsData<O2> frame);
<O2 extends O> void write(WsControl<?, O2> frame);
void become(IpSocket socket);
void close();
}
|
0 | java-sources/ai/swim/swim-io-ws/3.10.0/swim/io | java-sources/ai/swim/swim-io-ws/3.10.0/swim/io/ws/WebSocketModem.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.io.ws;
import java.net.InetSocketAddress;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.Collection;
import swim.codec.Decoder;
import swim.io.FlowControl;
import swim.io.FlowModifier;
import swim.io.IpModem;
import swim.io.IpModemContext;
import swim.io.IpSocket;
import swim.ws.WsControl;
import swim.ws.WsData;
import swim.ws.WsDecoder;
import swim.ws.WsEncoder;
import swim.ws.WsFrame;
public class WebSocketModem<I, O> implements IpModem<Object, Object>, WebSocketContext<I, O> {
protected final WebSocket<I, O> socket;
protected final WsSettings wsSettings;
protected final WsDecoder decoder;
protected final WsEncoder encoder;
protected IpModemContext<Object, Object> context;
public WebSocketModem(WebSocket<I, O> socket, WsSettings wsSettings,
WsDecoder decoder, WsEncoder encoder) {
this.socket = socket;
this.wsSettings = wsSettings;
this.decoder = decoder;
this.encoder = encoder;
}
@Override
public IpModemContext<Object, Object> ipModemContext() {
return this.context;
}
@Override
public void setIpModemContext(IpModemContext<Object, Object> context) {
this.context = context;
this.socket.setWebSocketContext(this);
}
@Override
public long idleTimeout() {
return this.socket.idleTimeout();
}
@Override
public void doRead() {
this.socket.doRead();
}
@SuppressWarnings("unchecked")
@Override
public void didRead(Object input) {
this.socket.didRead((WsFrame<I>) input);
}
@Override
public void doWrite() {
this.socket.doWrite();
}
@SuppressWarnings("unchecked")
@Override
public void didWrite(Object output) {
this.socket.didWrite((WsFrame<O>) output);
}
@Override
public void willConnect() {
this.socket.willConnect();
}
@Override
public void didConnect() {
this.socket.didConnect();
}
@Override
public void willSecure() {
this.socket.willSecure();
}
@Override
public void didSecure() {
this.socket.didSecure();
}
@Override
public void willBecome(IpSocket socket) {
this.socket.willBecome(socket);
}
@Override
public void didBecome(IpSocket socket) {
this.socket.didBecome(socket);
}
@Override
public void didTimeout() {
this.socket.didTimeout();
}
@Override
public void didDisconnect() {
this.socket.didDisconnect();
}
@Override
public void didFail(Throwable error) {
this.socket.didFail(error);
close();
}
@Override
public boolean isConnected() {
final IpModemContext<Object, Object> context = this.context;
return context != null && context.isConnected();
}
@Override
public boolean isClient() {
final IpModemContext<Object, Object> context = this.context;
return context != null && context.isClient();
}
@Override
public boolean isServer() {
final IpModemContext<Object, Object> context = this.context;
return context != null && context.isServer();
}
@Override
public boolean isSecure() {
final IpModemContext<Object, Object> context = this.context;
return context != null && context.isSecure();
}
@Override
public String securityProtocol() {
return this.context.securityProtocol();
}
@Override
public String cipherSuite() {
return this.context.cipherSuite();
}
@Override
public InetSocketAddress localAddress() {
return this.context.localAddress();
}
@Override
public Principal localPrincipal() {
return this.context.localPrincipal();
}
@Override
public Collection<Certificate> localCertificates() {
return this.context.localCertificates();
}
@Override
public InetSocketAddress remoteAddress() {
return this.context.remoteAddress();
}
@Override
public Principal remotePrincipal() {
return this.context.remotePrincipal();
}
@Override
public Collection<Certificate> remoteCertificates() {
return this.context.remoteCertificates();
}
@Override
public FlowControl flowControl() {
return this.context.flowControl();
}
@Override
public void flowControl(FlowControl flowControl) {
this.context.flowControl(flowControl);
}
@Override
public FlowControl flowControl(FlowModifier flowModifier) {
return this.context.flowControl(flowModifier);
}
@Override
public WsSettings wsSettings() {
return this.wsSettings;
}
@Override
public <I2 extends I> void read(Decoder<I2> content) {
this.context.read(this.decoder.frameDecoder(content));
}
@Override
public <O2 extends O> void write(WsData<O2> frame) {
this.context.write(this.encoder.frameEncoder(frame));
}
@Override
public <O2 extends O> void write(WsControl<?, O2> frame) {
this.context.write(this.encoder.frameEncoder(frame));
}
@Override
public void become(IpSocket socket) {
this.context.become(socket);
}
@Override
public void close() {
this.context.close();
}
}
|
0 | java-sources/ai/swim/swim-io-ws/3.10.0/swim/io | java-sources/ai/swim/swim-io-ws/3.10.0/swim/io/ws/WsSettings.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.io.ws;
import swim.codec.Output;
import swim.io.IpSettings;
import swim.io.TcpSettings;
import swim.io.TlsSettings;
import swim.io.http.HttpSettings;
import swim.structure.Form;
import swim.structure.Item;
import swim.structure.Kind;
import swim.structure.Record;
import swim.structure.Value;
import swim.util.Murmur3;
import swim.ws.WsEngineSettings;
/**
* WebSocket configuration parameters.
*/
public class WsSettings extends WsEngineSettings {
protected final HttpSettings httpSettings;
public WsSettings(HttpSettings httpSettings, int maxFrameSize, int maxMessageSize,
int serverCompressionLevel, int clientCompressionLevel,
boolean serverNoContextTakeover, boolean clientNoContextTakeover,
int serverMaxWindowBits, int clientMaxWindowBits) {
super(maxFrameSize, maxMessageSize, serverCompressionLevel, clientCompressionLevel,
serverNoContextTakeover, clientNoContextTakeover, serverMaxWindowBits, clientMaxWindowBits);
this.httpSettings = httpSettings;
}
public final HttpSettings httpSettings() {
return this.httpSettings;
}
public WsSettings httpSettings(HttpSettings httpSettings) {
return copy(httpSettings, this.maxFrameSize, this.maxMessageSize,
this.serverCompressionLevel, this.clientCompressionLevel,
this.serverNoContextTakeover, this.clientNoContextTakeover,
this.serverMaxWindowBits, this.clientMaxWindowBits);
}
public final IpSettings ipSettings() {
return this.httpSettings.ipSettings();
}
public WsSettings ipSettings(IpSettings ipSettings) {
return httpSettings(this.httpSettings.ipSettings(ipSettings));
}
public final TlsSettings tlsSettings() {
return this.httpSettings.tlsSettings();
}
public WsSettings tlsSettings(TlsSettings tlsSettings) {
return httpSettings(this.httpSettings.tlsSettings(tlsSettings));
}
public final TcpSettings tcpSettings() {
return this.httpSettings.tcpSettings();
}
public WsSettings tcpSettings(TcpSettings tcpSettings) {
return httpSettings(this.httpSettings.tcpSettings(tcpSettings));
}
public WsSettings engineSettings(WsEngineSettings engineSettings) {
return copy(engineSettings.maxFrameSize(), engineSettings.maxMessageSize(),
engineSettings.serverCompressionLevel(), engineSettings.clientCompressionLevel(),
engineSettings.serverNoContextTakeover(), engineSettings.clientNoContextTakeover(),
engineSettings.serverMaxWindowBits(), engineSettings.clientMaxWindowBits());
}
@Override
public WsSettings maxFrameSize(int maxFrameSize) {
return (WsSettings) super.maxFrameSize(maxFrameSize);
}
@Override
public WsSettings maxMessageSize(int maxMessageSize) {
return (WsSettings) super.maxMessageSize(maxMessageSize);
}
@Override
public WsSettings serverCompressionLevel(int serverCompressionLevel) {
return (WsSettings) super.serverCompressionLevel(serverCompressionLevel);
}
@Override
public WsSettings clientCompressionLevel(int clientCompressionLevel) {
return (WsSettings) super.clientCompressionLevel(clientCompressionLevel);
}
@Override
public WsSettings compressionLevel(int serverCompressionLevel, int clientCompressionLevel) {
return (WsSettings) super.compressionLevel(serverCompressionLevel, clientCompressionLevel);
}
@Override
public WsSettings serverNoContextTakeover(boolean serverNoContextTakeover) {
return (WsSettings) super.serverNoContextTakeover(serverNoContextTakeover);
}
@Override
public WsSettings clientNoContextTakeover(boolean clientNoContextTakeover) {
return (WsSettings) super.clientNoContextTakeover(clientNoContextTakeover);
}
@Override
public WsSettings serverMaxWindowBits(int serverMaxWindowBits) {
return (WsSettings) super.serverMaxWindowBits(serverMaxWindowBits);
}
@Override
public WsSettings clientMaxWindowBits(int clientMaxWindowBits) {
return (WsSettings) super.clientMaxWindowBits(clientMaxWindowBits);
}
@Override
public Value toValue() {
return form().mold(this).toValue();
}
protected WsSettings copy(HttpSettings httpSettings, int maxFrameSize, int maxMessageSize,
int serverCompressionLevel, int clientCompressionLevel,
boolean serverNoContextTakeover, boolean clientNoContextTakeover,
int serverMaxWindowBits, int clientMaxWindowBits) {
return new WsSettings(httpSettings, maxFrameSize, maxMessageSize,
serverCompressionLevel, clientCompressionLevel,
serverNoContextTakeover, clientNoContextTakeover,
serverMaxWindowBits, clientMaxWindowBits);
}
@Override
protected WsSettings copy(int maxFrameSize, int maxMessageSize,
int serverCompressionLevel, int clientCompressionLevel,
boolean serverNoContextTakeover, boolean clientNoContextTakeover,
int serverMaxWindowBits, int clientMaxWindowBits) {
return copy(this.httpSettings, maxFrameSize, maxMessageSize,
serverCompressionLevel, clientCompressionLevel,
serverNoContextTakeover, clientNoContextTakeover,
serverMaxWindowBits, clientMaxWindowBits);
}
public boolean canEqual(Object other) {
return other instanceof WsSettings;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof WsSettings) {
final WsSettings that = (WsSettings) other;
return that.canEqual(this)
&& this.httpSettings.equals(that.httpSettings)
&& this.maxFrameSize == that.maxFrameSize
&& this.maxMessageSize == that.maxMessageSize
&& this.serverCompressionLevel == that.serverCompressionLevel
&& this.clientCompressionLevel == that.clientCompressionLevel
&& this.serverNoContextTakeover == that.serverNoContextTakeover
&& this.clientNoContextTakeover == that.clientNoContextTakeover
&& this.serverMaxWindowBits == that.serverMaxWindowBits
&& this.clientMaxWindowBits == that.clientMaxWindowBits;
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(WsSettings.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(Murmur3.mix(Murmur3.mix(
Murmur3.mix(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed, this.httpSettings.hashCode()),
this.maxFrameSize), this.maxMessageSize), this.serverCompressionLevel), this.clientCompressionLevel),
Murmur3.hash(this.serverNoContextTakeover)), Murmur3.hash(this.clientNoContextTakeover)),
this.serverMaxWindowBits), this.clientMaxWindowBits));
}
@Override
public void debug(Output<?> output) {
output = output.write("WsSettings").write('.').write("standard").write('(').write(')')
.write('.').write("httpSettings").write('(').debug(this.httpSettings).write(')')
.write('.').write("maxFrameSize").write('(').debug(this.maxFrameSize).write(')')
.write('.').write("maxMessageSize").write('(').debug(this.maxMessageSize).write(')')
.write('.').write("serverCompressionLevel").write('(').debug(this.serverCompressionLevel).write(')')
.write('.').write("clientCompressionLevel").write('(').debug(this.clientCompressionLevel).write(')')
.write('.').write("serverNoContextTakeover").write('(').debug(this.serverNoContextTakeover).write(')')
.write('.').write("clientNoContextTakeover").write('(').debug(this.clientNoContextTakeover).write(')')
.write('.').write("serverMaxWindowBits").write('(').debug(this.serverMaxWindowBits).write(')')
.write('.').write("clientMaxWindowBits").write('(').debug(this.clientMaxWindowBits).write(')');
}
private static int hashSeed;
private static WsSettings standard;
private static Form<WsSettings> form;
public static WsSettings standard() {
if (standard == null) {
final WsEngineSettings engineSettings = WsEngineSettings.standard();
standard = new WsSettings(HttpSettings.standard(),
engineSettings.maxFrameSize(), engineSettings.maxMessageSize(),
engineSettings.serverCompressionLevel(), engineSettings.clientCompressionLevel(),
engineSettings.serverNoContextTakeover(), engineSettings.clientNoContextTakeover(),
engineSettings.serverMaxWindowBits(), engineSettings.clientMaxWindowBits());
}
return standard;
}
public static WsSettings noCompression() {
return standard().engineSettings(WsEngineSettings.noCompression());
}
public static WsSettings defaultCompression() {
return standard().engineSettings(WsEngineSettings.defaultCompression());
}
public static WsSettings fastestCompression() {
return standard().engineSettings(WsEngineSettings.fastestCompression());
}
public static WsSettings bestCompression() {
return standard().engineSettings(WsEngineSettings.bestCompression());
}
public static WsSettings from(HttpSettings httpSettings) {
return standard().httpSettings(httpSettings);
}
public static WsSettings from(IpSettings ipSettings) {
return standard().ipSettings(ipSettings);
}
public static WsSettings from(WsEngineSettings engineSettings) {
if (engineSettings instanceof WsSettings) {
return (WsSettings) engineSettings;
} else {
return standard().engineSettings(engineSettings);
}
}
@Kind
public static Form<WsSettings> form() {
if (form == null) {
form = new WsSettingsForm();
}
return form;
}
}
final class WsSettingsForm extends Form<WsSettings> {
@Override
public WsSettings unit() {
return WsSettings.standard();
}
@Override
public Class<?> type() {
return WsSettings.class;
}
@Override
public Item mold(WsSettings settings) {
if (settings != null) {
final WsSettings standard = WsSettings.standard();
final Record ws = Record.create(9).attr("ws");
if (settings.maxFrameSize() != standard.maxFrameSize()) {
ws.slot("maxFrameSize", settings.maxFrameSize());
}
if (settings.maxMessageSize() != standard.maxMessageSize()) {
ws.slot("maxMessageSize", settings.maxMessageSize());
}
if (settings.serverCompressionLevel() != standard.serverCompressionLevel()) {
ws.slot("serverCompressionLevel", settings.serverCompressionLevel());
}
if (settings.clientCompressionLevel() != standard.clientCompressionLevel()) {
ws.slot("clientCompressionLevel", settings.clientCompressionLevel());
}
if (settings.serverNoContextTakeover() != standard.serverNoContextTakeover()) {
ws.slot("serverNoContextTakeover", settings.serverNoContextTakeover());
}
if (settings.clientNoContextTakeover() != standard.clientNoContextTakeover()) {
ws.slot("clientNoContextTakeover", settings.clientNoContextTakeover());
}
if (settings.serverMaxWindowBits() != standard.serverMaxWindowBits()) {
ws.slot("serverMaxWindowBits", settings.serverMaxWindowBits());
}
if (settings.clientMaxWindowBits() != standard.clientMaxWindowBits()) {
ws.slot("clientMaxWindowBits", settings.clientMaxWindowBits());
}
return Record.of(ws).concat(HttpSettings.form().mold(settings.httpSettings));
} else {
return Item.extant();
}
}
@Override
public WsSettings cast(Item item) {
final Value value = item.toValue();
final WsSettings standard = WsSettings.standard();
final HttpSettings httpSettings = HttpSettings.form().cast(item);
int maxFrameSize = standard.maxFrameSize();
int maxMessageSize = standard.maxMessageSize();
int serverCompressionLevel = standard.serverCompressionLevel();
int clientCompressionLevel = standard.clientCompressionLevel();
boolean serverNoContextTakeover = standard.serverNoContextTakeover();
boolean clientNoContextTakeover = standard.clientNoContextTakeover();
int serverMaxWindowBits = standard.serverMaxWindowBits();
int clientMaxWindowBits = standard.clientMaxWindowBits();
for (Item member : value) {
if (member.getAttr("ws").isDefined() || member.getAttr("websocket").isDefined()) {
maxFrameSize = member.get("maxFrameSize").intValue(maxFrameSize);
maxMessageSize = member.get("maxMessageSize").intValue(maxMessageSize);
serverCompressionLevel = member.get("serverCompressionLevel").intValue(serverCompressionLevel);
clientCompressionLevel = member.get("clientCompressionLevel").intValue(clientCompressionLevel);
serverNoContextTakeover = member.get("serverNoContextTakeover").booleanValue(serverNoContextTakeover);
clientNoContextTakeover = member.get("clientNoContextTakeover").booleanValue(clientNoContextTakeover);
serverMaxWindowBits = member.get("serverMaxWindowBits").intValue(serverMaxWindowBits);
clientMaxWindowBits = member.get("clientMaxWindowBits").intValue(clientMaxWindowBits);
}
}
return new WsSettings(httpSettings, maxFrameSize, maxMessageSize,
serverCompressionLevel, clientCompressionLevel,
serverNoContextTakeover, clientNoContextTakeover,
serverMaxWindowBits, clientMaxWindowBits);
}
}
|
0 | java-sources/ai/swim/swim-io-ws/3.10.0/swim/io | java-sources/ai/swim/swim-io-ws/3.10.0/swim/io/ws/WsUpgradeRequester.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.io.ws;
import swim.codec.Decoder;
import swim.http.HttpResponse;
import swim.io.IpSocket;
import swim.io.IpSocketModem;
import swim.io.http.AbstractHttpRequester;
import swim.ws.WsDecoder;
import swim.ws.WsEncoder;
import swim.ws.WsEngine;
import swim.ws.WsRequest;
import swim.ws.WsResponse;
public class WsUpgradeRequester extends AbstractHttpRequester<Object> {
final WebSocket<?, ?> webSocket;
final WsRequest wsRequest;
final WsSettings wsSettings;
public WsUpgradeRequester(WebSocket<?, ?> webSocket, WsRequest wsRequest, WsSettings wsSettings) {
this.webSocket = webSocket;
this.wsRequest = wsRequest;
this.wsSettings = wsSettings;
}
public final WebSocket<?, ?> webSocket() {
return this.webSocket;
}
public final WsRequest wsRequest() {
return this.wsRequest;
}
public final WsSettings wsSettings() {
return this.wsSettings;
}
public WsUpgradeRequester wsSettings(WsSettings wsSettings) {
return new WsUpgradeRequester(this.webSocket, this.wsRequest, wsSettings);
}
@SuppressWarnings("unchecked")
public IpSocket createSocket(WsEngine engine) {
final WebSocket<Object, Object> socket = (WebSocket<Object, Object>) this.webSocket;
final WsDecoder decoder = engine.decoder();
final WsEncoder encoder = engine.encoder();
return new IpSocketModem<Object, Object>(new WebSocketModem<Object, Object>(socket, this.wsSettings,
decoder, encoder));
}
@Override
public Decoder<Object> contentDecoder(HttpResponse<?> httpResponse) {
return Decoder.done();
}
@Override
public void doRequest() {
writeRequest(this.wsRequest.httpRequest());
}
@Override
public void didRespond(HttpResponse<Object> httpResponse) {
final WsResponse wsResponse = this.wsRequest.accept(httpResponse, this.wsSettings);
if (wsResponse != null) {
final WsEngine engine = wsResponse.clientEngine(this.wsSettings);
final IpSocket socket = createSocket(engine);
become(socket);
this.webSocket.didConnect();
this.webSocket.didUpgrade(this.wsRequest.httpRequest(), httpResponse);
} else {
close();
}
}
@Override
public void didDisconnect() {
this.webSocket.didDisconnect();
}
}
|
0 | java-sources/ai/swim/swim-io-ws/3.10.0/swim/io | java-sources/ai/swim/swim-io-ws/3.10.0/swim/io/ws/WsUpgradeResponder.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.io.ws;
import swim.codec.Decoder;
import swim.http.HttpRequest;
import swim.http.HttpResponse;
import swim.io.IpSocket;
import swim.io.IpSocketModem;
import swim.io.http.AbstractHttpResponder;
import swim.ws.WsDecoder;
import swim.ws.WsEncoder;
import swim.ws.WsEngine;
import swim.ws.WsResponse;
public class WsUpgradeResponder extends AbstractHttpResponder<Object> {
final WebSocket<?, ?> webSocket;
final WsResponse wsResponse;
final WsSettings wsSettings;
public WsUpgradeResponder(WebSocket<?, ?> webSocket, WsResponse wsResponse, WsSettings wsSettings) {
this.webSocket = webSocket;
this.wsResponse = wsResponse;
this.wsSettings = wsSettings;
}
public final WebSocket<?, ?> webSocket() {
return this.webSocket;
}
public final WsResponse wsResponse() {
return this.wsResponse;
}
public final WsSettings wsSettings() {
return this.wsSettings;
}
@SuppressWarnings("unchecked")
public IpSocket createSocket(WsEngine engine) {
final WebSocket<Object, Object> socket = (WebSocket<Object, Object>) this.webSocket;
final WsDecoder decoder = engine.decoder();
final WsEncoder encoder = engine.encoder();
return new IpSocketModem<Object, Object>(new WebSocketModem<Object, Object>(socket, this.wsSettings,
decoder, encoder));
}
@Override
public Decoder<Object> contentDecoder(HttpRequest<?> httpRequest) {
return Decoder.done();
}
@Override
public void doRespond(HttpRequest<Object> httpRequest) {
writeResponse(this.wsResponse.httpResponse());
}
@Override
public void didRespond(HttpResponse<?> httpResponse) {
final WsEngine engine = this.wsResponse.serverEngine(this.wsSettings);
final IpSocket socket = createSocket(engine);
become(socket);
this.webSocket.didConnect();
this.webSocket.didUpgrade(this.wsResponse.httpRequest(), httpResponse);
}
@Override
public void didDisconnect() {
this.webSocket.didDisconnect();
}
}
|
0 | java-sources/ai/swim/swim-io-ws/3.10.0/swim/io | java-sources/ai/swim/swim-io-ws/3.10.0/swim/io/ws/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.
/**
* Flow-controlled WebSocket I/O library.
*/
package swim.io.ws;
|
0 | java-sources/ai/swim/swim-java | java-sources/ai/swim/swim-java/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.
/**
* Java kernel runtime.
*/
module swim.java {
requires transitive swim.kernel;
exports swim.java;
provides swim.kernel.Kernel with swim.java.JavaKernel;
}
|
0 | java-sources/ai/swim/swim-java/3.10.0/swim | java-sources/ai/swim/swim-java/3.10.0/swim/java/JavaAgentDef.java | // Copyright 2015-2019 SWIM.AI inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package swim.java;
import swim.api.agent.AgentDef;
import swim.codec.Debug;
import swim.codec.Format;
import swim.codec.Output;
import swim.structure.Value;
import swim.util.Murmur3;
public class JavaAgentDef implements AgentDef, Debug {
final String agentName;
final String className;
final Value props;
public JavaAgentDef(String agentName, String className, Value props) {
this.agentName = agentName;
this.className = className;
this.props = props;
}
@Override
public final String agentName() {
return this.agentName;
}
public JavaAgentDef agentName(String agentName) {
return copy(agentName, this.className, this.props);
}
public final String className() {
return this.className;
}
public JavaAgentDef className(String className) {
return copy(this.agentName, className, this.props);
}
@Override
public final Value props() {
return this.props;
}
public JavaAgentDef props(Value props) {
return copy(this.agentName, this.className, props);
}
protected JavaAgentDef copy(String agentName, String className, Value props) {
return new JavaAgentDef(agentName, className, props);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof JavaAgentDef) {
final JavaAgentDef that = (JavaAgentDef) other;
return (this.agentName == null ? that.agentName == null : this.agentName.equals(that.agentName))
&& (this.className == null ? that.className == null : this.className.equals(that.className))
&& this.props.equals(that.props);
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(JavaAgentDef.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(Murmur3.mix(hashSeed,
Murmur3.hash(this.agentName)), Murmur3.hash(this.className)), this.props.hashCode()));
}
@Override
public void debug(Output<?> output) {
output = output.write("JavaAgentDef").write('.').write("from").write('(')
.debug(this.agentName).write(", ").debug(this.className).write(')');
if (this.props.isDefined()) {
output = output.write('.').write("props").write('(').debug(this.props).write(')');
}
}
@Override
public String toString() {
return Format.debug(this);
}
private static int hashSeed;
public static JavaAgentDef from(String agentName, String className) {
return new JavaAgentDef(agentName, className, Value.absent());
}
public static JavaAgentDef fromClassName(String className) {
return new JavaAgentDef(className, className, Value.absent());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.