repo_name
stringlengths 7
104
| file_path
stringlengths 13
198
| context
stringlengths 67
7.15k
| import_statement
stringlengths 16
4.43k
| code
stringlengths 40
6.98k
| prompt
stringlengths 227
8.27k
| next_line
stringlengths 8
795
|
---|---|---|---|---|---|---|
wepay/kafka-connect-bigquery | kcbq-connector/src/test/java/com/wepay/kafka/connect/bigquery/convert/BigQueryRecordConverterTest.java | // Path: kcbq-api/src/main/java/com/wepay/kafka/connect/bigquery/api/KafkaSchemaRecordType.java
// public enum KafkaSchemaRecordType {
//
// VALUE("value"),
// KEY("key");
//
// private final String str;
//
// KafkaSchemaRecordType(String str) {
// this.str = str;
// }
//
// public String toString() {
// return this.str;
// }
// }
| import org.junit.Test;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import com.wepay.kafka.connect.bigquery.api.KafkaSchemaRecordType;
import com.wepay.kafka.connect.bigquery.exception.ConversionConnectException;
import org.apache.kafka.connect.data.Schema;
import org.apache.kafka.connect.data.SchemaBuilder;
import org.apache.kafka.connect.data.Struct;
import org.apache.kafka.connect.sink.SinkRecord;
import org.junit.Assert; | package com.wepay.kafka.connect.bigquery.convert;
/*
* Copyright 2016 WePay, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
public class BigQueryRecordConverterTest {
private static final Boolean SHOULD_CONVERT_DOUBLE = true;
@Test(expected = ConversionConnectException.class)
public void testTopLevelRecord() {
SinkRecord kafkaConnectRecord = spoofSinkRecord(Schema.BOOLEAN_SCHEMA, false, false); | // Path: kcbq-api/src/main/java/com/wepay/kafka/connect/bigquery/api/KafkaSchemaRecordType.java
// public enum KafkaSchemaRecordType {
//
// VALUE("value"),
// KEY("key");
//
// private final String str;
//
// KafkaSchemaRecordType(String str) {
// this.str = str;
// }
//
// public String toString() {
// return this.str;
// }
// }
// Path: kcbq-connector/src/test/java/com/wepay/kafka/connect/bigquery/convert/BigQueryRecordConverterTest.java
import org.junit.Test;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import com.wepay.kafka.connect.bigquery.api.KafkaSchemaRecordType;
import com.wepay.kafka.connect.bigquery.exception.ConversionConnectException;
import org.apache.kafka.connect.data.Schema;
import org.apache.kafka.connect.data.SchemaBuilder;
import org.apache.kafka.connect.data.Struct;
import org.apache.kafka.connect.sink.SinkRecord;
import org.junit.Assert;
package com.wepay.kafka.connect.bigquery.convert;
/*
* Copyright 2016 WePay, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
public class BigQueryRecordConverterTest {
private static final Boolean SHOULD_CONVERT_DOUBLE = true;
@Test(expected = ConversionConnectException.class)
public void testTopLevelRecord() {
SinkRecord kafkaConnectRecord = spoofSinkRecord(Schema.BOOLEAN_SCHEMA, false, false); | new BigQueryRecordConverter(SHOULD_CONVERT_DOUBLE).convertRecord(kafkaConnectRecord, KafkaSchemaRecordType.VALUE); |
wepay/kafka-connect-bigquery | kcbq-connector/src/main/java/com/wepay/kafka/connect/bigquery/GCSBuilder.java | // Path: kcbq-connector/src/main/java/com/wepay/kafka/connect/bigquery/exception/GCSConnectException.java
// public class GCSConnectException extends ConnectException {
// public GCSConnectException(String msg) {
// super(msg);
// }
//
// public GCSConnectException(String msg, Throwable thr) {
// super(msg, thr);
// }
// }
| import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import com.wepay.kafka.connect.bigquery.exception.GCSConnectException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets; | public Storage build() {
return connect(projectName, key);
}
/**
* Returns a default {@link Storage} instance for the specified project with credentials provided
* in the specified file.
*
* @param projectName The name of the GCS project to work with
* @param key The name of a file containing a JSON key that can be used to provide
* credentials to GCS, or null if no authentication should be performed.
* @return The resulting Storage object.
*/
private Storage connect(String projectName, String key) {
if (key == null) {
return connect(projectName);
}
try {
InputStream credentialsStream;
if (keySource != null && keySource.equals("JSON")) {
credentialsStream = new ByteArrayInputStream(key.getBytes(StandardCharsets.UTF_8));
} else {
credentialsStream = new FileInputStream(key);
}
return StorageOptions.newBuilder()
.setProjectId(projectName)
.setCredentials(GoogleCredentials.fromStream(credentialsStream))
.build()
.getService();
} catch (IOException err) { | // Path: kcbq-connector/src/main/java/com/wepay/kafka/connect/bigquery/exception/GCSConnectException.java
// public class GCSConnectException extends ConnectException {
// public GCSConnectException(String msg) {
// super(msg);
// }
//
// public GCSConnectException(String msg, Throwable thr) {
// super(msg, thr);
// }
// }
// Path: kcbq-connector/src/main/java/com/wepay/kafka/connect/bigquery/GCSBuilder.java
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import com.wepay.kafka.connect.bigquery.exception.GCSConnectException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
public Storage build() {
return connect(projectName, key);
}
/**
* Returns a default {@link Storage} instance for the specified project with credentials provided
* in the specified file.
*
* @param projectName The name of the GCS project to work with
* @param key The name of a file containing a JSON key that can be used to provide
* credentials to GCS, or null if no authentication should be performed.
* @return The resulting Storage object.
*/
private Storage connect(String projectName, String key) {
if (key == null) {
return connect(projectName);
}
try {
InputStream credentialsStream;
if (keySource != null && keySource.equals("JSON")) {
credentialsStream = new ByteArrayInputStream(key.getBytes(StandardCharsets.UTF_8));
} else {
credentialsStream = new FileInputStream(key);
}
return StorageOptions.newBuilder()
.setProjectId(projectName)
.setCredentials(GoogleCredentials.fromStream(credentialsStream))
.build()
.getService();
} catch (IOException err) { | throw new GCSConnectException("Failed to access json key file", err); |
simon-frankau/toy-tcp | test/name/arbitrary/toytcp/ppp/link/UnstufferTest.java | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
| import name.arbitrary.toytcp.Buffer;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.*;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions; | package name.arbitrary.toytcp.ppp.link;
@RunWith(MockitoJUnitRunner.class)
public class UnstufferTest {
@Mock | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
// Path: test/name/arbitrary/toytcp/ppp/link/UnstufferTest.java
import name.arbitrary.toytcp.Buffer;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.*;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
package name.arbitrary.toytcp.ppp.link;
@RunWith(MockitoJUnitRunner.class)
public class UnstufferTest {
@Mock | private Buffer.Listener listener; |
simon-frankau/toy-tcp | test/name/arbitrary/toytcp/ppp/lcp/options/OptionProtocolFieldCompressionTest.java | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
| import name.arbitrary.toytcp.Buffer;
import org.junit.Test;
import static org.junit.Assert.*; | package name.arbitrary.toytcp.ppp.lcp.options;
public class OptionProtocolFieldCompressionTest {
private final Option option = OptionProtocolFieldCompression.INSTANCE;
@Test
public void testCreateSuccess() {
assertEquals(option,
OptionsReader.readOption(OptionsReader.PROTOCOL_FIELD_COMPRESSION, | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
// Path: test/name/arbitrary/toytcp/ppp/lcp/options/OptionProtocolFieldCompressionTest.java
import name.arbitrary.toytcp.Buffer;
import org.junit.Test;
import static org.junit.Assert.*;
package name.arbitrary.toytcp.ppp.lcp.options;
public class OptionProtocolFieldCompressionTest {
private final Option option = OptionProtocolFieldCompression.INSTANCE;
@Test
public void testCreateSuccess() {
assertEquals(option,
OptionsReader.readOption(OptionsReader.PROTOCOL_FIELD_COMPRESSION, | new Buffer())); |
simon-frankau/toy-tcp | test/name/arbitrary/toytcp/ppp/link/MultiplexerTest.java | // Path: src/name/arbitrary/toytcp/WriteBuffer.java
// public class WriteBuffer {
// private final ArrayList<Byte> buffer = new ArrayList<Byte>();
//
// public WriteBuffer() {
// }
//
// public WriteBuffer(int... data) {
// for (int i = 0 ; i < data.length; i++) {
// append((byte)data[i]);
// }
// }
//
// public void append(byte b) {
// buffer.add(b);
// }
//
// public void append(byte... bs) {
// for (byte b : bs) {
// buffer.add(b);
// }
// }
//
// public void append(Buffer data) {
// int n = data.length();
// for (int i = 0; i < n; i++) {
// append(data.get(i));
// }
// }
//
// public void appendU16(int value) {
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public void appendU32(int value) {
// buffer.add((byte)(value >> 24));
// buffer.add((byte)(value >> 16));
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public int getAppendOffset() {
// return buffer.size();
// }
//
// public void put(int i, byte value) {
// buffer.set(i, value);
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value >> 8));
// put(i + 1, (byte)(value & 0xFF));
// }
//
// public byte[] toByteArray() {
// int n = buffer.size();
// byte[] array = new byte[n];
// for (int i = 0; i < n; i++) {
// array[i] = buffer.get(i);
// }
// return array;
// }
//
// @Override
// public String toString() {
// return "WriteBuffer{" +
// "buffer=" + buffer +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// WriteBuffer that = (WriteBuffer) o;
//
// if (!buffer.equals(that.buffer)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return buffer.hashCode();
// }
//
// public interface Listener {
// void send(WriteBuffer buffer);
// }
// }
| import name.arbitrary.toytcp.WriteBuffer;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.*;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions; | package name.arbitrary.toytcp.ppp.link;
@RunWith(MockitoJUnitRunner.class)
public class MultiplexerTest {
private Multiplexer multiplexer;
@Mock | // Path: src/name/arbitrary/toytcp/WriteBuffer.java
// public class WriteBuffer {
// private final ArrayList<Byte> buffer = new ArrayList<Byte>();
//
// public WriteBuffer() {
// }
//
// public WriteBuffer(int... data) {
// for (int i = 0 ; i < data.length; i++) {
// append((byte)data[i]);
// }
// }
//
// public void append(byte b) {
// buffer.add(b);
// }
//
// public void append(byte... bs) {
// for (byte b : bs) {
// buffer.add(b);
// }
// }
//
// public void append(Buffer data) {
// int n = data.length();
// for (int i = 0; i < n; i++) {
// append(data.get(i));
// }
// }
//
// public void appendU16(int value) {
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public void appendU32(int value) {
// buffer.add((byte)(value >> 24));
// buffer.add((byte)(value >> 16));
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public int getAppendOffset() {
// return buffer.size();
// }
//
// public void put(int i, byte value) {
// buffer.set(i, value);
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value >> 8));
// put(i + 1, (byte)(value & 0xFF));
// }
//
// public byte[] toByteArray() {
// int n = buffer.size();
// byte[] array = new byte[n];
// for (int i = 0; i < n; i++) {
// array[i] = buffer.get(i);
// }
// return array;
// }
//
// @Override
// public String toString() {
// return "WriteBuffer{" +
// "buffer=" + buffer +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// WriteBuffer that = (WriteBuffer) o;
//
// if (!buffer.equals(that.buffer)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return buffer.hashCode();
// }
//
// public interface Listener {
// void send(WriteBuffer buffer);
// }
// }
// Path: test/name/arbitrary/toytcp/ppp/link/MultiplexerTest.java
import name.arbitrary.toytcp.WriteBuffer;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.*;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
package name.arbitrary.toytcp.ppp.link;
@RunWith(MockitoJUnitRunner.class)
public class MultiplexerTest {
private Multiplexer multiplexer;
@Mock | private WriteBuffer.Listener listener; |
simon-frankau/toy-tcp | src/name/arbitrary/toytcp/ppp/lcp/options/OptionMagicNumber.java | // Path: src/name/arbitrary/toytcp/WriteBuffer.java
// public class WriteBuffer {
// private final ArrayList<Byte> buffer = new ArrayList<Byte>();
//
// public WriteBuffer() {
// }
//
// public WriteBuffer(int... data) {
// for (int i = 0 ; i < data.length; i++) {
// append((byte)data[i]);
// }
// }
//
// public void append(byte b) {
// buffer.add(b);
// }
//
// public void append(byte... bs) {
// for (byte b : bs) {
// buffer.add(b);
// }
// }
//
// public void append(Buffer data) {
// int n = data.length();
// for (int i = 0; i < n; i++) {
// append(data.get(i));
// }
// }
//
// public void appendU16(int value) {
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public void appendU32(int value) {
// buffer.add((byte)(value >> 24));
// buffer.add((byte)(value >> 16));
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public int getAppendOffset() {
// return buffer.size();
// }
//
// public void put(int i, byte value) {
// buffer.set(i, value);
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value >> 8));
// put(i + 1, (byte)(value & 0xFF));
// }
//
// public byte[] toByteArray() {
// int n = buffer.size();
// byte[] array = new byte[n];
// for (int i = 0; i < n; i++) {
// array[i] = buffer.get(i);
// }
// return array;
// }
//
// @Override
// public String toString() {
// return "WriteBuffer{" +
// "buffer=" + buffer +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// WriteBuffer that = (WriteBuffer) o;
//
// if (!buffer.equals(that.buffer)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return buffer.hashCode();
// }
//
// public interface Listener {
// void send(WriteBuffer buffer);
// }
// }
| import name.arbitrary.toytcp.WriteBuffer; | package name.arbitrary.toytcp.ppp.lcp.options;
/**
* Magic-Number option.
*/
public final class OptionMagicNumber implements Option {
private final int magicNumber;
public OptionMagicNumber(int magicNumber) {
this.magicNumber = magicNumber;
}
@Override
public ResponseType getResponseType() {
// I can't really be bothered with implementing this correctly. So, not at all.
return ResponseType.REJECT;
}
@Override
public Option getAcceptableVersion() {
throw new IllegalStateException("No need for acceptable version - always reject");
}
@Override | // Path: src/name/arbitrary/toytcp/WriteBuffer.java
// public class WriteBuffer {
// private final ArrayList<Byte> buffer = new ArrayList<Byte>();
//
// public WriteBuffer() {
// }
//
// public WriteBuffer(int... data) {
// for (int i = 0 ; i < data.length; i++) {
// append((byte)data[i]);
// }
// }
//
// public void append(byte b) {
// buffer.add(b);
// }
//
// public void append(byte... bs) {
// for (byte b : bs) {
// buffer.add(b);
// }
// }
//
// public void append(Buffer data) {
// int n = data.length();
// for (int i = 0; i < n; i++) {
// append(data.get(i));
// }
// }
//
// public void appendU16(int value) {
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public void appendU32(int value) {
// buffer.add((byte)(value >> 24));
// buffer.add((byte)(value >> 16));
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public int getAppendOffset() {
// return buffer.size();
// }
//
// public void put(int i, byte value) {
// buffer.set(i, value);
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value >> 8));
// put(i + 1, (byte)(value & 0xFF));
// }
//
// public byte[] toByteArray() {
// int n = buffer.size();
// byte[] array = new byte[n];
// for (int i = 0; i < n; i++) {
// array[i] = buffer.get(i);
// }
// return array;
// }
//
// @Override
// public String toString() {
// return "WriteBuffer{" +
// "buffer=" + buffer +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// WriteBuffer that = (WriteBuffer) o;
//
// if (!buffer.equals(that.buffer)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return buffer.hashCode();
// }
//
// public interface Listener {
// void send(WriteBuffer buffer);
// }
// }
// Path: src/name/arbitrary/toytcp/ppp/lcp/options/OptionMagicNumber.java
import name.arbitrary.toytcp.WriteBuffer;
package name.arbitrary.toytcp.ppp.lcp.options;
/**
* Magic-Number option.
*/
public final class OptionMagicNumber implements Option {
private final int magicNumber;
public OptionMagicNumber(int magicNumber) {
this.magicNumber = magicNumber;
}
@Override
public ResponseType getResponseType() {
// I can't really be bothered with implementing this correctly. So, not at all.
return ResponseType.REJECT;
}
@Override
public Option getAcceptableVersion() {
throw new IllegalStateException("No need for acceptable version - always reject");
}
@Override | public void writeTo(WriteBuffer buffer) { |
simon-frankau/toy-tcp | test/name/arbitrary/toytcp/ppp/link/HeaderCompressorTest.java | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
| import name.arbitrary.toytcp.Buffer;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; | package name.arbitrary.toytcp.ppp.link;
@RunWith(MockitoJUnitRunner.class)
public class HeaderCompressorTest {
@Mock | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
// Path: test/name/arbitrary/toytcp/ppp/link/HeaderCompressorTest.java
import name.arbitrary.toytcp.Buffer;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
package name.arbitrary.toytcp.ppp.link;
@RunWith(MockitoJUnitRunner.class)
public class HeaderCompressorTest {
@Mock | private Buffer.Listener listener; |
simon-frankau/toy-tcp | test/name/arbitrary/toytcp/ppp/link/HeaderBuilderTest.java | // Path: src/name/arbitrary/toytcp/WriteBuffer.java
// public class WriteBuffer {
// private final ArrayList<Byte> buffer = new ArrayList<Byte>();
//
// public WriteBuffer() {
// }
//
// public WriteBuffer(int... data) {
// for (int i = 0 ; i < data.length; i++) {
// append((byte)data[i]);
// }
// }
//
// public void append(byte b) {
// buffer.add(b);
// }
//
// public void append(byte... bs) {
// for (byte b : bs) {
// buffer.add(b);
// }
// }
//
// public void append(Buffer data) {
// int n = data.length();
// for (int i = 0; i < n; i++) {
// append(data.get(i));
// }
// }
//
// public void appendU16(int value) {
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public void appendU32(int value) {
// buffer.add((byte)(value >> 24));
// buffer.add((byte)(value >> 16));
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public int getAppendOffset() {
// return buffer.size();
// }
//
// public void put(int i, byte value) {
// buffer.set(i, value);
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value >> 8));
// put(i + 1, (byte)(value & 0xFF));
// }
//
// public byte[] toByteArray() {
// int n = buffer.size();
// byte[] array = new byte[n];
// for (int i = 0; i < n; i++) {
// array[i] = buffer.get(i);
// }
// return array;
// }
//
// @Override
// public String toString() {
// return "WriteBuffer{" +
// "buffer=" + buffer +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// WriteBuffer that = (WriteBuffer) o;
//
// if (!buffer.equals(that.buffer)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return buffer.hashCode();
// }
//
// public interface Listener {
// void send(WriteBuffer buffer);
// }
// }
| import name.arbitrary.toytcp.WriteBuffer;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.*;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions; | package name.arbitrary.toytcp.ppp.link;
@RunWith(MockitoJUnitRunner.class)
public class HeaderBuilderTest {
private HeaderBuilder headerBuilder;
@Mock | // Path: src/name/arbitrary/toytcp/WriteBuffer.java
// public class WriteBuffer {
// private final ArrayList<Byte> buffer = new ArrayList<Byte>();
//
// public WriteBuffer() {
// }
//
// public WriteBuffer(int... data) {
// for (int i = 0 ; i < data.length; i++) {
// append((byte)data[i]);
// }
// }
//
// public void append(byte b) {
// buffer.add(b);
// }
//
// public void append(byte... bs) {
// for (byte b : bs) {
// buffer.add(b);
// }
// }
//
// public void append(Buffer data) {
// int n = data.length();
// for (int i = 0; i < n; i++) {
// append(data.get(i));
// }
// }
//
// public void appendU16(int value) {
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public void appendU32(int value) {
// buffer.add((byte)(value >> 24));
// buffer.add((byte)(value >> 16));
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public int getAppendOffset() {
// return buffer.size();
// }
//
// public void put(int i, byte value) {
// buffer.set(i, value);
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value >> 8));
// put(i + 1, (byte)(value & 0xFF));
// }
//
// public byte[] toByteArray() {
// int n = buffer.size();
// byte[] array = new byte[n];
// for (int i = 0; i < n; i++) {
// array[i] = buffer.get(i);
// }
// return array;
// }
//
// @Override
// public String toString() {
// return "WriteBuffer{" +
// "buffer=" + buffer +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// WriteBuffer that = (WriteBuffer) o;
//
// if (!buffer.equals(that.buffer)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return buffer.hashCode();
// }
//
// public interface Listener {
// void send(WriteBuffer buffer);
// }
// }
// Path: test/name/arbitrary/toytcp/ppp/link/HeaderBuilderTest.java
import name.arbitrary.toytcp.WriteBuffer;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.*;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
package name.arbitrary.toytcp.ppp.link;
@RunWith(MockitoJUnitRunner.class)
public class HeaderBuilderTest {
private HeaderBuilder headerBuilder;
@Mock | private WriteBuffer.Listener listener; |
simon-frankau/toy-tcp | src/name/arbitrary/toytcp/ppp/link/PppLink.java | // Path: src/name/arbitrary/toytcp/WriteBuffer.java
// public class WriteBuffer {
// private final ArrayList<Byte> buffer = new ArrayList<Byte>();
//
// public WriteBuffer() {
// }
//
// public WriteBuffer(int... data) {
// for (int i = 0 ; i < data.length; i++) {
// append((byte)data[i]);
// }
// }
//
// public void append(byte b) {
// buffer.add(b);
// }
//
// public void append(byte... bs) {
// for (byte b : bs) {
// buffer.add(b);
// }
// }
//
// public void append(Buffer data) {
// int n = data.length();
// for (int i = 0; i < n; i++) {
// append(data.get(i));
// }
// }
//
// public void appendU16(int value) {
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public void appendU32(int value) {
// buffer.add((byte)(value >> 24));
// buffer.add((byte)(value >> 16));
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public int getAppendOffset() {
// return buffer.size();
// }
//
// public void put(int i, byte value) {
// buffer.set(i, value);
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value >> 8));
// put(i + 1, (byte)(value & 0xFF));
// }
//
// public byte[] toByteArray() {
// int n = buffer.size();
// byte[] array = new byte[n];
// for (int i = 0; i < n; i++) {
// array[i] = buffer.get(i);
// }
// return array;
// }
//
// @Override
// public String toString() {
// return "WriteBuffer{" +
// "buffer=" + buffer +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// WriteBuffer that = (WriteBuffer) o;
//
// if (!buffer.equals(that.buffer)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return buffer.hashCode();
// }
//
// public interface Listener {
// void send(WriteBuffer buffer);
// }
// }
| import name.arbitrary.toytcp.WriteBuffer;
import java.io.InputStream;
import java.io.OutputStream; | package name.arbitrary.toytcp.ppp.link;
/**
* Represents the PPP link layer. Mostly delegates.
*/
public class PppLink {
private final PppLinkReaderThread readerThread;
private final PppLinkWriterThread writerThread;
private final Demultiplexer demultiplexer;
public PppLink(InputStream inputStream, OutputStream outputStream) {
demultiplexer = new Demultiplexer();
readerThread = new PppLinkReaderThread(inputStream, demultiplexer);
writerThread = new PppLinkWriterThread(outputStream);
}
public void start() {
readerThread.start();
writerThread.start();
}
public void stop() {
readerThread.stop();
writerThread.stop();
}
public void subscribe(int protocol, PppLinkListener listener) {
demultiplexer.subscribe(protocol, listener);
}
public void unsubscribe(int protocol) {
demultiplexer.unsubscribe(protocol);
}
| // Path: src/name/arbitrary/toytcp/WriteBuffer.java
// public class WriteBuffer {
// private final ArrayList<Byte> buffer = new ArrayList<Byte>();
//
// public WriteBuffer() {
// }
//
// public WriteBuffer(int... data) {
// for (int i = 0 ; i < data.length; i++) {
// append((byte)data[i]);
// }
// }
//
// public void append(byte b) {
// buffer.add(b);
// }
//
// public void append(byte... bs) {
// for (byte b : bs) {
// buffer.add(b);
// }
// }
//
// public void append(Buffer data) {
// int n = data.length();
// for (int i = 0; i < n; i++) {
// append(data.get(i));
// }
// }
//
// public void appendU16(int value) {
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public void appendU32(int value) {
// buffer.add((byte)(value >> 24));
// buffer.add((byte)(value >> 16));
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public int getAppendOffset() {
// return buffer.size();
// }
//
// public void put(int i, byte value) {
// buffer.set(i, value);
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value >> 8));
// put(i + 1, (byte)(value & 0xFF));
// }
//
// public byte[] toByteArray() {
// int n = buffer.size();
// byte[] array = new byte[n];
// for (int i = 0; i < n; i++) {
// array[i] = buffer.get(i);
// }
// return array;
// }
//
// @Override
// public String toString() {
// return "WriteBuffer{" +
// "buffer=" + buffer +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// WriteBuffer that = (WriteBuffer) o;
//
// if (!buffer.equals(that.buffer)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return buffer.hashCode();
// }
//
// public interface Listener {
// void send(WriteBuffer buffer);
// }
// }
// Path: src/name/arbitrary/toytcp/ppp/link/PppLink.java
import name.arbitrary.toytcp.WriteBuffer;
import java.io.InputStream;
import java.io.OutputStream;
package name.arbitrary.toytcp.ppp.link;
/**
* Represents the PPP link layer. Mostly delegates.
*/
public class PppLink {
private final PppLinkReaderThread readerThread;
private final PppLinkWriterThread writerThread;
private final Demultiplexer demultiplexer;
public PppLink(InputStream inputStream, OutputStream outputStream) {
demultiplexer = new Demultiplexer();
readerThread = new PppLinkReaderThread(inputStream, demultiplexer);
writerThread = new PppLinkWriterThread(outputStream);
}
public void start() {
readerThread.start();
writerThread.start();
}
public void stop() {
readerThread.stop();
writerThread.stop();
}
public void subscribe(int protocol, PppLinkListener listener) {
demultiplexer.subscribe(protocol, listener);
}
public void unsubscribe(int protocol) {
demultiplexer.unsubscribe(protocol);
}
| public WriteBuffer.Listener getProtocolSender(int protocol) { |
simon-frankau/toy-tcp | src/name/arbitrary/toytcp/ppp/lcp/statemachine/EventProcessor.java | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
//
// Path: src/name/arbitrary/toytcp/ppp/lcp/options/Option.java
// public interface Option {
// enum ResponseType {
// ACCEPT,
// NAK,
// REJECT
// }
//
// ResponseType getResponseType();
//
// Option getAcceptableVersion();
//
// // Write the option into a buffer. Reading equivalent is in OptionsReader.
// void writeTo(WriteBuffer buffer);
// }
| import name.arbitrary.toytcp.Buffer;
import name.arbitrary.toytcp.ppp.lcp.options.Option;
import java.util.List; | package name.arbitrary.toytcp.ppp.lcp.statemachine;
/**
* An interface to represent something that can process LCP frames/events.
*/
public interface EventProcessor {
void onLinkUp();
void onLinkDown();
void onOpen();
void onClose();
| // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
//
// Path: src/name/arbitrary/toytcp/ppp/lcp/options/Option.java
// public interface Option {
// enum ResponseType {
// ACCEPT,
// NAK,
// REJECT
// }
//
// ResponseType getResponseType();
//
// Option getAcceptableVersion();
//
// // Write the option into a buffer. Reading equivalent is in OptionsReader.
// void writeTo(WriteBuffer buffer);
// }
// Path: src/name/arbitrary/toytcp/ppp/lcp/statemachine/EventProcessor.java
import name.arbitrary.toytcp.Buffer;
import name.arbitrary.toytcp.ppp.lcp.options.Option;
import java.util.List;
package name.arbitrary.toytcp.ppp.lcp.statemachine;
/**
* An interface to represent something that can process LCP frames/events.
*/
public interface EventProcessor {
void onLinkUp();
void onLinkDown();
void onOpen();
void onClose();
| void onConfigureRequest(byte identifier, List<Option> options); |
simon-frankau/toy-tcp | src/name/arbitrary/toytcp/ppp/lcp/statemachine/EventProcessor.java | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
//
// Path: src/name/arbitrary/toytcp/ppp/lcp/options/Option.java
// public interface Option {
// enum ResponseType {
// ACCEPT,
// NAK,
// REJECT
// }
//
// ResponseType getResponseType();
//
// Option getAcceptableVersion();
//
// // Write the option into a buffer. Reading equivalent is in OptionsReader.
// void writeTo(WriteBuffer buffer);
// }
| import name.arbitrary.toytcp.Buffer;
import name.arbitrary.toytcp.ppp.lcp.options.Option;
import java.util.List; | package name.arbitrary.toytcp.ppp.lcp.statemachine;
/**
* An interface to represent something that can process LCP frames/events.
*/
public interface EventProcessor {
void onLinkUp();
void onLinkDown();
void onOpen();
void onClose();
void onConfigureRequest(byte identifier, List<Option> options);
void onConfigureAck(byte identifier, List<Option> options);
void onConfigureNak(byte identifier, List<Option> options);
void onConfigureReject(byte identifier, List<Option> options);
| // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
//
// Path: src/name/arbitrary/toytcp/ppp/lcp/options/Option.java
// public interface Option {
// enum ResponseType {
// ACCEPT,
// NAK,
// REJECT
// }
//
// ResponseType getResponseType();
//
// Option getAcceptableVersion();
//
// // Write the option into a buffer. Reading equivalent is in OptionsReader.
// void writeTo(WriteBuffer buffer);
// }
// Path: src/name/arbitrary/toytcp/ppp/lcp/statemachine/EventProcessor.java
import name.arbitrary.toytcp.Buffer;
import name.arbitrary.toytcp.ppp.lcp.options.Option;
import java.util.List;
package name.arbitrary.toytcp.ppp.lcp.statemachine;
/**
* An interface to represent something that can process LCP frames/events.
*/
public interface EventProcessor {
void onLinkUp();
void onLinkDown();
void onOpen();
void onClose();
void onConfigureRequest(byte identifier, List<Option> options);
void onConfigureAck(byte identifier, List<Option> options);
void onConfigureNak(byte identifier, List<Option> options);
void onConfigureReject(byte identifier, List<Option> options);
| void onReceiveTerminateRequest(byte identifier, Buffer buffer); |
simon-frankau/toy-tcp | src/name/arbitrary/toytcp/ppp/lcp/options/OptionMaximumReceiveUnit.java | // Path: src/name/arbitrary/toytcp/WriteBuffer.java
// public class WriteBuffer {
// private final ArrayList<Byte> buffer = new ArrayList<Byte>();
//
// public WriteBuffer() {
// }
//
// public WriteBuffer(int... data) {
// for (int i = 0 ; i < data.length; i++) {
// append((byte)data[i]);
// }
// }
//
// public void append(byte b) {
// buffer.add(b);
// }
//
// public void append(byte... bs) {
// for (byte b : bs) {
// buffer.add(b);
// }
// }
//
// public void append(Buffer data) {
// int n = data.length();
// for (int i = 0; i < n; i++) {
// append(data.get(i));
// }
// }
//
// public void appendU16(int value) {
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public void appendU32(int value) {
// buffer.add((byte)(value >> 24));
// buffer.add((byte)(value >> 16));
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public int getAppendOffset() {
// return buffer.size();
// }
//
// public void put(int i, byte value) {
// buffer.set(i, value);
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value >> 8));
// put(i + 1, (byte)(value & 0xFF));
// }
//
// public byte[] toByteArray() {
// int n = buffer.size();
// byte[] array = new byte[n];
// for (int i = 0; i < n; i++) {
// array[i] = buffer.get(i);
// }
// return array;
// }
//
// @Override
// public String toString() {
// return "WriteBuffer{" +
// "buffer=" + buffer +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// WriteBuffer that = (WriteBuffer) o;
//
// if (!buffer.equals(that.buffer)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return buffer.hashCode();
// }
//
// public interface Listener {
// void send(WriteBuffer buffer);
// }
// }
| import name.arbitrary.toytcp.WriteBuffer; | package name.arbitrary.toytcp.ppp.lcp.options;
/**
* Maximum-Receive-Unit option.
*/
public final class OptionMaximumReceiveUnit implements Option {
private final int maximumReceiveUnit;
public OptionMaximumReceiveUnit(int maximumReceiveUnit) {
this.maximumReceiveUnit = maximumReceiveUnit;
}
@Override
public ResponseType getResponseType() {
// This one's basically advisory (says it can receive larger, or request smaller
// but still must be able to cope with MRU, so we just say "Yeah, whatever".
return ResponseType.ACCEPT;
}
@Override
public Option getAcceptableVersion() {
throw new IllegalStateException("No need for acceptable version - always accept");
}
@Override | // Path: src/name/arbitrary/toytcp/WriteBuffer.java
// public class WriteBuffer {
// private final ArrayList<Byte> buffer = new ArrayList<Byte>();
//
// public WriteBuffer() {
// }
//
// public WriteBuffer(int... data) {
// for (int i = 0 ; i < data.length; i++) {
// append((byte)data[i]);
// }
// }
//
// public void append(byte b) {
// buffer.add(b);
// }
//
// public void append(byte... bs) {
// for (byte b : bs) {
// buffer.add(b);
// }
// }
//
// public void append(Buffer data) {
// int n = data.length();
// for (int i = 0; i < n; i++) {
// append(data.get(i));
// }
// }
//
// public void appendU16(int value) {
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public void appendU32(int value) {
// buffer.add((byte)(value >> 24));
// buffer.add((byte)(value >> 16));
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public int getAppendOffset() {
// return buffer.size();
// }
//
// public void put(int i, byte value) {
// buffer.set(i, value);
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value >> 8));
// put(i + 1, (byte)(value & 0xFF));
// }
//
// public byte[] toByteArray() {
// int n = buffer.size();
// byte[] array = new byte[n];
// for (int i = 0; i < n; i++) {
// array[i] = buffer.get(i);
// }
// return array;
// }
//
// @Override
// public String toString() {
// return "WriteBuffer{" +
// "buffer=" + buffer +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// WriteBuffer that = (WriteBuffer) o;
//
// if (!buffer.equals(that.buffer)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return buffer.hashCode();
// }
//
// public interface Listener {
// void send(WriteBuffer buffer);
// }
// }
// Path: src/name/arbitrary/toytcp/ppp/lcp/options/OptionMaximumReceiveUnit.java
import name.arbitrary.toytcp.WriteBuffer;
package name.arbitrary.toytcp.ppp.lcp.options;
/**
* Maximum-Receive-Unit option.
*/
public final class OptionMaximumReceiveUnit implements Option {
private final int maximumReceiveUnit;
public OptionMaximumReceiveUnit(int maximumReceiveUnit) {
this.maximumReceiveUnit = maximumReceiveUnit;
}
@Override
public ResponseType getResponseType() {
// This one's basically advisory (says it can receive larger, or request smaller
// but still must be able to cope with MRU, so we just say "Yeah, whatever".
return ResponseType.ACCEPT;
}
@Override
public Option getAcceptableVersion() {
throw new IllegalStateException("No need for acceptable version - always accept");
}
@Override | public void writeTo(WriteBuffer buffer) { |
simon-frankau/toy-tcp | src/name/arbitrary/toytcp/ppp/lcp/DefaultConfigChecker.java | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
//
// Path: src/name/arbitrary/toytcp/ppp/lcp/options/Option.java
// public interface Option {
// enum ResponseType {
// ACCEPT,
// NAK,
// REJECT
// }
//
// ResponseType getResponseType();
//
// Option getAcceptableVersion();
//
// // Write the option into a buffer. Reading equivalent is in OptionsReader.
// void writeTo(WriteBuffer buffer);
// }
//
// Path: src/name/arbitrary/toytcp/ppp/lcp/statemachine/LcpConfigChecker.java
// public interface LcpConfigChecker {
// // TODO: Reset the internal state when going via this layer stopped.
//
// // Interface to do with receiving requests and producing responses:
//
// Option.ResponseType processIncomingConfigRequest(List<Option> options);
//
// List<Option> getConfigNakOptions();
// List<Option> getConfigRejectOptions();
//
// // Interface to do with sending requests and handling responses.
//
// List<Option> getRequestedOptions();
//
// // Interface to do with handling rejects.
//
// boolean isRejectAcceptable(Buffer rejected);
// }
| import name.arbitrary.toytcp.Buffer;
import name.arbitrary.toytcp.ppp.lcp.options.Option;
import name.arbitrary.toytcp.ppp.lcp.statemachine.LcpConfigChecker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; | package name.arbitrary.toytcp.ppp.lcp;
/**
* Standard implementation of the config checker.
*/
public class DefaultConfigChecker implements LcpConfigChecker {
private static final Logger logger = LoggerFactory.getLogger(DefaultConfigChecker.class);
| // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
//
// Path: src/name/arbitrary/toytcp/ppp/lcp/options/Option.java
// public interface Option {
// enum ResponseType {
// ACCEPT,
// NAK,
// REJECT
// }
//
// ResponseType getResponseType();
//
// Option getAcceptableVersion();
//
// // Write the option into a buffer. Reading equivalent is in OptionsReader.
// void writeTo(WriteBuffer buffer);
// }
//
// Path: src/name/arbitrary/toytcp/ppp/lcp/statemachine/LcpConfigChecker.java
// public interface LcpConfigChecker {
// // TODO: Reset the internal state when going via this layer stopped.
//
// // Interface to do with receiving requests and producing responses:
//
// Option.ResponseType processIncomingConfigRequest(List<Option> options);
//
// List<Option> getConfigNakOptions();
// List<Option> getConfigRejectOptions();
//
// // Interface to do with sending requests and handling responses.
//
// List<Option> getRequestedOptions();
//
// // Interface to do with handling rejects.
//
// boolean isRejectAcceptable(Buffer rejected);
// }
// Path: src/name/arbitrary/toytcp/ppp/lcp/DefaultConfigChecker.java
import name.arbitrary.toytcp.Buffer;
import name.arbitrary.toytcp.ppp.lcp.options.Option;
import name.arbitrary.toytcp.ppp.lcp.statemachine.LcpConfigChecker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
package name.arbitrary.toytcp.ppp.lcp;
/**
* Standard implementation of the config checker.
*/
public class DefaultConfigChecker implements LcpConfigChecker {
private static final Logger logger = LoggerFactory.getLogger(DefaultConfigChecker.class);
| private List<Option> acceptableReceivedOptions = new ArrayList<Option>(); |
simon-frankau/toy-tcp | src/name/arbitrary/toytcp/ppp/lcp/DefaultConfigChecker.java | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
//
// Path: src/name/arbitrary/toytcp/ppp/lcp/options/Option.java
// public interface Option {
// enum ResponseType {
// ACCEPT,
// NAK,
// REJECT
// }
//
// ResponseType getResponseType();
//
// Option getAcceptableVersion();
//
// // Write the option into a buffer. Reading equivalent is in OptionsReader.
// void writeTo(WriteBuffer buffer);
// }
//
// Path: src/name/arbitrary/toytcp/ppp/lcp/statemachine/LcpConfigChecker.java
// public interface LcpConfigChecker {
// // TODO: Reset the internal state when going via this layer stopped.
//
// // Interface to do with receiving requests and producing responses:
//
// Option.ResponseType processIncomingConfigRequest(List<Option> options);
//
// List<Option> getConfigNakOptions();
// List<Option> getConfigRejectOptions();
//
// // Interface to do with sending requests and handling responses.
//
// List<Option> getRequestedOptions();
//
// // Interface to do with handling rejects.
//
// boolean isRejectAcceptable(Buffer rejected);
// }
| import name.arbitrary.toytcp.Buffer;
import name.arbitrary.toytcp.ppp.lcp.options.Option;
import name.arbitrary.toytcp.ppp.lcp.statemachine.LcpConfigChecker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; |
if (!rejectReceivedOptions.isEmpty()) {
return Option.ResponseType.REJECT;
}
if (!nakReceivedOptions.isEmpty()) {
return Option.ResponseType.NAK;
}
return Option.ResponseType.ACCEPT;
}
@Override
public List<Option> getConfigRejectOptions() {
assert !rejectReceivedOptions.isEmpty();
return rejectReceivedOptions;
}
@Override
public List<Option> getRequestedOptions() {
// We aren't going to request /anything/. Keep it simple!
return Collections.EMPTY_LIST;
}
@Override
public List<Option> getConfigNakOptions() {
assert rejectReceivedOptions.isEmpty();
assert !nakReceivedOptions.isEmpty();
return nakReceivedOptions;
}
@Override | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
//
// Path: src/name/arbitrary/toytcp/ppp/lcp/options/Option.java
// public interface Option {
// enum ResponseType {
// ACCEPT,
// NAK,
// REJECT
// }
//
// ResponseType getResponseType();
//
// Option getAcceptableVersion();
//
// // Write the option into a buffer. Reading equivalent is in OptionsReader.
// void writeTo(WriteBuffer buffer);
// }
//
// Path: src/name/arbitrary/toytcp/ppp/lcp/statemachine/LcpConfigChecker.java
// public interface LcpConfigChecker {
// // TODO: Reset the internal state when going via this layer stopped.
//
// // Interface to do with receiving requests and producing responses:
//
// Option.ResponseType processIncomingConfigRequest(List<Option> options);
//
// List<Option> getConfigNakOptions();
// List<Option> getConfigRejectOptions();
//
// // Interface to do with sending requests and handling responses.
//
// List<Option> getRequestedOptions();
//
// // Interface to do with handling rejects.
//
// boolean isRejectAcceptable(Buffer rejected);
// }
// Path: src/name/arbitrary/toytcp/ppp/lcp/DefaultConfigChecker.java
import name.arbitrary.toytcp.Buffer;
import name.arbitrary.toytcp.ppp.lcp.options.Option;
import name.arbitrary.toytcp.ppp.lcp.statemachine.LcpConfigChecker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
if (!rejectReceivedOptions.isEmpty()) {
return Option.ResponseType.REJECT;
}
if (!nakReceivedOptions.isEmpty()) {
return Option.ResponseType.NAK;
}
return Option.ResponseType.ACCEPT;
}
@Override
public List<Option> getConfigRejectOptions() {
assert !rejectReceivedOptions.isEmpty();
return rejectReceivedOptions;
}
@Override
public List<Option> getRequestedOptions() {
// We aren't going to request /anything/. Keep it simple!
return Collections.EMPTY_LIST;
}
@Override
public List<Option> getConfigNakOptions() {
assert rejectReceivedOptions.isEmpty();
assert !nakReceivedOptions.isEmpty();
return nakReceivedOptions;
}
@Override | public boolean isRejectAcceptable(Buffer rejected) { |
simon-frankau/toy-tcp | test/name/arbitrary/toytcp/ppp/lcp/options/OptionsReaderTest.java | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
| import name.arbitrary.toytcp.Buffer;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*; | package name.arbitrary.toytcp.ppp.lcp.options;
public class OptionsReaderTest {
@Test
public void testSingleOption() {
List<Option> options = new ArrayList<Option>();
options.add(new OptionMagicNumber(0x01020304));
assertEquals(options, | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
// Path: test/name/arbitrary/toytcp/ppp/lcp/options/OptionsReaderTest.java
import name.arbitrary.toytcp.Buffer;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
package name.arbitrary.toytcp.ppp.lcp.options;
public class OptionsReaderTest {
@Test
public void testSingleOption() {
List<Option> options = new ArrayList<Option>();
options.add(new OptionMagicNumber(0x01020304));
assertEquals(options, | OptionsReader.readOptions(new Buffer( |
simon-frankau/toy-tcp | test/name/arbitrary/toytcp/ppp/link/FramerTest.java | // Path: src/name/arbitrary/toytcp/WriteBuffer.java
// public class WriteBuffer {
// private final ArrayList<Byte> buffer = new ArrayList<Byte>();
//
// public WriteBuffer() {
// }
//
// public WriteBuffer(int... data) {
// for (int i = 0 ; i < data.length; i++) {
// append((byte)data[i]);
// }
// }
//
// public void append(byte b) {
// buffer.add(b);
// }
//
// public void append(byte... bs) {
// for (byte b : bs) {
// buffer.add(b);
// }
// }
//
// public void append(Buffer data) {
// int n = data.length();
// for (int i = 0; i < n; i++) {
// append(data.get(i));
// }
// }
//
// public void appendU16(int value) {
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public void appendU32(int value) {
// buffer.add((byte)(value >> 24));
// buffer.add((byte)(value >> 16));
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public int getAppendOffset() {
// return buffer.size();
// }
//
// public void put(int i, byte value) {
// buffer.set(i, value);
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value >> 8));
// put(i + 1, (byte)(value & 0xFF));
// }
//
// public byte[] toByteArray() {
// int n = buffer.size();
// byte[] array = new byte[n];
// for (int i = 0; i < n; i++) {
// array[i] = buffer.get(i);
// }
// return array;
// }
//
// @Override
// public String toString() {
// return "WriteBuffer{" +
// "buffer=" + buffer +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// WriteBuffer that = (WriteBuffer) o;
//
// if (!buffer.equals(that.buffer)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return buffer.hashCode();
// }
//
// public interface Listener {
// void send(WriteBuffer buffer);
// }
// }
| import name.arbitrary.toytcp.WriteBuffer;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.*;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions; | package name.arbitrary.toytcp.ppp.link;
@RunWith(MockitoJUnitRunner.class)
public class FramerTest {
private Framer framer;
@Mock | // Path: src/name/arbitrary/toytcp/WriteBuffer.java
// public class WriteBuffer {
// private final ArrayList<Byte> buffer = new ArrayList<Byte>();
//
// public WriteBuffer() {
// }
//
// public WriteBuffer(int... data) {
// for (int i = 0 ; i < data.length; i++) {
// append((byte)data[i]);
// }
// }
//
// public void append(byte b) {
// buffer.add(b);
// }
//
// public void append(byte... bs) {
// for (byte b : bs) {
// buffer.add(b);
// }
// }
//
// public void append(Buffer data) {
// int n = data.length();
// for (int i = 0; i < n; i++) {
// append(data.get(i));
// }
// }
//
// public void appendU16(int value) {
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public void appendU32(int value) {
// buffer.add((byte)(value >> 24));
// buffer.add((byte)(value >> 16));
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public int getAppendOffset() {
// return buffer.size();
// }
//
// public void put(int i, byte value) {
// buffer.set(i, value);
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value >> 8));
// put(i + 1, (byte)(value & 0xFF));
// }
//
// public byte[] toByteArray() {
// int n = buffer.size();
// byte[] array = new byte[n];
// for (int i = 0; i < n; i++) {
// array[i] = buffer.get(i);
// }
// return array;
// }
//
// @Override
// public String toString() {
// return "WriteBuffer{" +
// "buffer=" + buffer +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// WriteBuffer that = (WriteBuffer) o;
//
// if (!buffer.equals(that.buffer)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return buffer.hashCode();
// }
//
// public interface Listener {
// void send(WriteBuffer buffer);
// }
// }
// Path: test/name/arbitrary/toytcp/ppp/link/FramerTest.java
import name.arbitrary.toytcp.WriteBuffer;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.*;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
package name.arbitrary.toytcp.ppp.link;
@RunWith(MockitoJUnitRunner.class)
public class FramerTest {
private Framer framer;
@Mock | private WriteBuffer.Listener listener; |
simon-frankau/toy-tcp | test/name/arbitrary/toytcp/ppp/lcp/options/OptionAddressAndControlFieldCompressionTest.java | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
| import name.arbitrary.toytcp.Buffer;
import org.junit.Test;
import static org.junit.Assert.*; | package name.arbitrary.toytcp.ppp.lcp.options;
public class OptionAddressAndControlFieldCompressionTest {
private final OptionAddressAndControlFieldCompression option = OptionAddressAndControlFieldCompression.INSTANCE;
@Test
public void testCreateSuccess() {
assertEquals(option,
OptionsReader.readOption(OptionsReader.ADDRESS_AND_CONTROL_COMPRESSION_FIELD, | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
// Path: test/name/arbitrary/toytcp/ppp/lcp/options/OptionAddressAndControlFieldCompressionTest.java
import name.arbitrary.toytcp.Buffer;
import org.junit.Test;
import static org.junit.Assert.*;
package name.arbitrary.toytcp.ppp.lcp.options;
public class OptionAddressAndControlFieldCompressionTest {
private final OptionAddressAndControlFieldCompression option = OptionAddressAndControlFieldCompression.INSTANCE;
@Test
public void testCreateSuccess() {
assertEquals(option,
OptionsReader.readOption(OptionsReader.ADDRESS_AND_CONTROL_COMPRESSION_FIELD, | new Buffer())); |
simon-frankau/toy-tcp | src/name/arbitrary/toytcp/ppp/lcp/FrameWriter.java | // Path: src/name/arbitrary/toytcp/WriteBuffer.java
// public class WriteBuffer {
// private final ArrayList<Byte> buffer = new ArrayList<Byte>();
//
// public WriteBuffer() {
// }
//
// public WriteBuffer(int... data) {
// for (int i = 0 ; i < data.length; i++) {
// append((byte)data[i]);
// }
// }
//
// public void append(byte b) {
// buffer.add(b);
// }
//
// public void append(byte... bs) {
// for (byte b : bs) {
// buffer.add(b);
// }
// }
//
// public void append(Buffer data) {
// int n = data.length();
// for (int i = 0; i < n; i++) {
// append(data.get(i));
// }
// }
//
// public void appendU16(int value) {
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public void appendU32(int value) {
// buffer.add((byte)(value >> 24));
// buffer.add((byte)(value >> 16));
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public int getAppendOffset() {
// return buffer.size();
// }
//
// public void put(int i, byte value) {
// buffer.set(i, value);
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value >> 8));
// put(i + 1, (byte)(value & 0xFF));
// }
//
// public byte[] toByteArray() {
// int n = buffer.size();
// byte[] array = new byte[n];
// for (int i = 0; i < n; i++) {
// array[i] = buffer.get(i);
// }
// return array;
// }
//
// @Override
// public String toString() {
// return "WriteBuffer{" +
// "buffer=" + buffer +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// WriteBuffer that = (WriteBuffer) o;
//
// if (!buffer.equals(that.buffer)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return buffer.hashCode();
// }
//
// public interface Listener {
// void send(WriteBuffer buffer);
// }
// }
//
// Path: src/name/arbitrary/toytcp/ppp/lcp/options/Option.java
// public interface Option {
// enum ResponseType {
// ACCEPT,
// NAK,
// REJECT
// }
//
// ResponseType getResponseType();
//
// Option getAcceptableVersion();
//
// // Write the option into a buffer. Reading equivalent is in OptionsReader.
// void writeTo(WriteBuffer buffer);
// }
//
// Path: src/name/arbitrary/toytcp/ppp/lcp/statemachine/ActionProcessor.java
// public interface ActionProcessor {
// void onThisLayerStarted();
// void onThisLayerFinished();
//
// void sendConfigureRequest(byte identifier, List<Option> options);
// void sendConfigureAcknowledge(byte identifier, List<Option> options);
// void sendConfigureNak(byte identifier, List<Option> options);
// void sendConfigureReject(byte identifier, List<Option> options);
//
// void sendTerminateRequest(byte identifier, WriteBuffer buffer);
// void sendTerminateAcknowledge(byte identifier, WriteBuffer buffer);
//
// void sendCodeReject(byte identifier, WriteBuffer buffer);
//
// void sendEchoReply(byte identifier, WriteBuffer buffer);
// }
| import name.arbitrary.toytcp.WriteBuffer;
import name.arbitrary.toytcp.ppp.lcp.options.Option;
import name.arbitrary.toytcp.ppp.lcp.statemachine.ActionProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List; | package name.arbitrary.toytcp.ppp.lcp;
/**
* Constructs and sends the messages from the state machine.
*/
public class FrameWriter implements ActionProcessor {
private static final Logger logger = LoggerFactory.getLogger(FrameWriter.class);
| // Path: src/name/arbitrary/toytcp/WriteBuffer.java
// public class WriteBuffer {
// private final ArrayList<Byte> buffer = new ArrayList<Byte>();
//
// public WriteBuffer() {
// }
//
// public WriteBuffer(int... data) {
// for (int i = 0 ; i < data.length; i++) {
// append((byte)data[i]);
// }
// }
//
// public void append(byte b) {
// buffer.add(b);
// }
//
// public void append(byte... bs) {
// for (byte b : bs) {
// buffer.add(b);
// }
// }
//
// public void append(Buffer data) {
// int n = data.length();
// for (int i = 0; i < n; i++) {
// append(data.get(i));
// }
// }
//
// public void appendU16(int value) {
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public void appendU32(int value) {
// buffer.add((byte)(value >> 24));
// buffer.add((byte)(value >> 16));
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public int getAppendOffset() {
// return buffer.size();
// }
//
// public void put(int i, byte value) {
// buffer.set(i, value);
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value >> 8));
// put(i + 1, (byte)(value & 0xFF));
// }
//
// public byte[] toByteArray() {
// int n = buffer.size();
// byte[] array = new byte[n];
// for (int i = 0; i < n; i++) {
// array[i] = buffer.get(i);
// }
// return array;
// }
//
// @Override
// public String toString() {
// return "WriteBuffer{" +
// "buffer=" + buffer +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// WriteBuffer that = (WriteBuffer) o;
//
// if (!buffer.equals(that.buffer)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return buffer.hashCode();
// }
//
// public interface Listener {
// void send(WriteBuffer buffer);
// }
// }
//
// Path: src/name/arbitrary/toytcp/ppp/lcp/options/Option.java
// public interface Option {
// enum ResponseType {
// ACCEPT,
// NAK,
// REJECT
// }
//
// ResponseType getResponseType();
//
// Option getAcceptableVersion();
//
// // Write the option into a buffer. Reading equivalent is in OptionsReader.
// void writeTo(WriteBuffer buffer);
// }
//
// Path: src/name/arbitrary/toytcp/ppp/lcp/statemachine/ActionProcessor.java
// public interface ActionProcessor {
// void onThisLayerStarted();
// void onThisLayerFinished();
//
// void sendConfigureRequest(byte identifier, List<Option> options);
// void sendConfigureAcknowledge(byte identifier, List<Option> options);
// void sendConfigureNak(byte identifier, List<Option> options);
// void sendConfigureReject(byte identifier, List<Option> options);
//
// void sendTerminateRequest(byte identifier, WriteBuffer buffer);
// void sendTerminateAcknowledge(byte identifier, WriteBuffer buffer);
//
// void sendCodeReject(byte identifier, WriteBuffer buffer);
//
// void sendEchoReply(byte identifier, WriteBuffer buffer);
// }
// Path: src/name/arbitrary/toytcp/ppp/lcp/FrameWriter.java
import name.arbitrary.toytcp.WriteBuffer;
import name.arbitrary.toytcp.ppp.lcp.options.Option;
import name.arbitrary.toytcp.ppp.lcp.statemachine.ActionProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
package name.arbitrary.toytcp.ppp.lcp;
/**
* Constructs and sends the messages from the state machine.
*/
public class FrameWriter implements ActionProcessor {
private static final Logger logger = LoggerFactory.getLogger(FrameWriter.class);
| private final WriteBuffer.Listener listener; |
simon-frankau/toy-tcp | src/name/arbitrary/toytcp/ppp/lcp/FrameWriter.java | // Path: src/name/arbitrary/toytcp/WriteBuffer.java
// public class WriteBuffer {
// private final ArrayList<Byte> buffer = new ArrayList<Byte>();
//
// public WriteBuffer() {
// }
//
// public WriteBuffer(int... data) {
// for (int i = 0 ; i < data.length; i++) {
// append((byte)data[i]);
// }
// }
//
// public void append(byte b) {
// buffer.add(b);
// }
//
// public void append(byte... bs) {
// for (byte b : bs) {
// buffer.add(b);
// }
// }
//
// public void append(Buffer data) {
// int n = data.length();
// for (int i = 0; i < n; i++) {
// append(data.get(i));
// }
// }
//
// public void appendU16(int value) {
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public void appendU32(int value) {
// buffer.add((byte)(value >> 24));
// buffer.add((byte)(value >> 16));
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public int getAppendOffset() {
// return buffer.size();
// }
//
// public void put(int i, byte value) {
// buffer.set(i, value);
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value >> 8));
// put(i + 1, (byte)(value & 0xFF));
// }
//
// public byte[] toByteArray() {
// int n = buffer.size();
// byte[] array = new byte[n];
// for (int i = 0; i < n; i++) {
// array[i] = buffer.get(i);
// }
// return array;
// }
//
// @Override
// public String toString() {
// return "WriteBuffer{" +
// "buffer=" + buffer +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// WriteBuffer that = (WriteBuffer) o;
//
// if (!buffer.equals(that.buffer)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return buffer.hashCode();
// }
//
// public interface Listener {
// void send(WriteBuffer buffer);
// }
// }
//
// Path: src/name/arbitrary/toytcp/ppp/lcp/options/Option.java
// public interface Option {
// enum ResponseType {
// ACCEPT,
// NAK,
// REJECT
// }
//
// ResponseType getResponseType();
//
// Option getAcceptableVersion();
//
// // Write the option into a buffer. Reading equivalent is in OptionsReader.
// void writeTo(WriteBuffer buffer);
// }
//
// Path: src/name/arbitrary/toytcp/ppp/lcp/statemachine/ActionProcessor.java
// public interface ActionProcessor {
// void onThisLayerStarted();
// void onThisLayerFinished();
//
// void sendConfigureRequest(byte identifier, List<Option> options);
// void sendConfigureAcknowledge(byte identifier, List<Option> options);
// void sendConfigureNak(byte identifier, List<Option> options);
// void sendConfigureReject(byte identifier, List<Option> options);
//
// void sendTerminateRequest(byte identifier, WriteBuffer buffer);
// void sendTerminateAcknowledge(byte identifier, WriteBuffer buffer);
//
// void sendCodeReject(byte identifier, WriteBuffer buffer);
//
// void sendEchoReply(byte identifier, WriteBuffer buffer);
// }
| import name.arbitrary.toytcp.WriteBuffer;
import name.arbitrary.toytcp.ppp.lcp.options.Option;
import name.arbitrary.toytcp.ppp.lcp.statemachine.ActionProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List; | package name.arbitrary.toytcp.ppp.lcp;
/**
* Constructs and sends the messages from the state machine.
*/
public class FrameWriter implements ActionProcessor {
private static final Logger logger = LoggerFactory.getLogger(FrameWriter.class);
private final WriteBuffer.Listener listener;
public FrameWriter(WriteBuffer.Listener listener) {
this.listener = listener;
}
@Override
public void onThisLayerStarted() {
logger.info("TLS");
}
@Override
public void onThisLayerFinished() {
logger.info("TLF");
}
@Override | // Path: src/name/arbitrary/toytcp/WriteBuffer.java
// public class WriteBuffer {
// private final ArrayList<Byte> buffer = new ArrayList<Byte>();
//
// public WriteBuffer() {
// }
//
// public WriteBuffer(int... data) {
// for (int i = 0 ; i < data.length; i++) {
// append((byte)data[i]);
// }
// }
//
// public void append(byte b) {
// buffer.add(b);
// }
//
// public void append(byte... bs) {
// for (byte b : bs) {
// buffer.add(b);
// }
// }
//
// public void append(Buffer data) {
// int n = data.length();
// for (int i = 0; i < n; i++) {
// append(data.get(i));
// }
// }
//
// public void appendU16(int value) {
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public void appendU32(int value) {
// buffer.add((byte)(value >> 24));
// buffer.add((byte)(value >> 16));
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public int getAppendOffset() {
// return buffer.size();
// }
//
// public void put(int i, byte value) {
// buffer.set(i, value);
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value >> 8));
// put(i + 1, (byte)(value & 0xFF));
// }
//
// public byte[] toByteArray() {
// int n = buffer.size();
// byte[] array = new byte[n];
// for (int i = 0; i < n; i++) {
// array[i] = buffer.get(i);
// }
// return array;
// }
//
// @Override
// public String toString() {
// return "WriteBuffer{" +
// "buffer=" + buffer +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// WriteBuffer that = (WriteBuffer) o;
//
// if (!buffer.equals(that.buffer)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return buffer.hashCode();
// }
//
// public interface Listener {
// void send(WriteBuffer buffer);
// }
// }
//
// Path: src/name/arbitrary/toytcp/ppp/lcp/options/Option.java
// public interface Option {
// enum ResponseType {
// ACCEPT,
// NAK,
// REJECT
// }
//
// ResponseType getResponseType();
//
// Option getAcceptableVersion();
//
// // Write the option into a buffer. Reading equivalent is in OptionsReader.
// void writeTo(WriteBuffer buffer);
// }
//
// Path: src/name/arbitrary/toytcp/ppp/lcp/statemachine/ActionProcessor.java
// public interface ActionProcessor {
// void onThisLayerStarted();
// void onThisLayerFinished();
//
// void sendConfigureRequest(byte identifier, List<Option> options);
// void sendConfigureAcknowledge(byte identifier, List<Option> options);
// void sendConfigureNak(byte identifier, List<Option> options);
// void sendConfigureReject(byte identifier, List<Option> options);
//
// void sendTerminateRequest(byte identifier, WriteBuffer buffer);
// void sendTerminateAcknowledge(byte identifier, WriteBuffer buffer);
//
// void sendCodeReject(byte identifier, WriteBuffer buffer);
//
// void sendEchoReply(byte identifier, WriteBuffer buffer);
// }
// Path: src/name/arbitrary/toytcp/ppp/lcp/FrameWriter.java
import name.arbitrary.toytcp.WriteBuffer;
import name.arbitrary.toytcp.ppp.lcp.options.Option;
import name.arbitrary.toytcp.ppp.lcp.statemachine.ActionProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
package name.arbitrary.toytcp.ppp.lcp;
/**
* Constructs and sends the messages from the state machine.
*/
public class FrameWriter implements ActionProcessor {
private static final Logger logger = LoggerFactory.getLogger(FrameWriter.class);
private final WriteBuffer.Listener listener;
public FrameWriter(WriteBuffer.Listener listener) {
this.listener = listener;
}
@Override
public void onThisLayerStarted() {
logger.info("TLS");
}
@Override
public void onThisLayerFinished() {
logger.info("TLF");
}
@Override | public void sendConfigureRequest(byte identifier, List<Option> options) { |
simon-frankau/toy-tcp | test/name/arbitrary/toytcp/ppp/link/FcsCheckerTest.java | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
| import name.arbitrary.toytcp.Buffer;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; | package name.arbitrary.toytcp.ppp.link;
@RunWith(MockitoJUnitRunner.class)
public class FcsCheckerTest {
@Mock | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
// Path: test/name/arbitrary/toytcp/ppp/link/FcsCheckerTest.java
import name.arbitrary.toytcp.Buffer;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
package name.arbitrary.toytcp.ppp.link;
@RunWith(MockitoJUnitRunner.class)
public class FcsCheckerTest {
@Mock | private Buffer.Listener listener; |
simon-frankau/toy-tcp | src/name/arbitrary/toytcp/ppp/lcp/options/OptionAsyncControlCharacterMap.java | // Path: src/name/arbitrary/toytcp/WriteBuffer.java
// public class WriteBuffer {
// private final ArrayList<Byte> buffer = new ArrayList<Byte>();
//
// public WriteBuffer() {
// }
//
// public WriteBuffer(int... data) {
// for (int i = 0 ; i < data.length; i++) {
// append((byte)data[i]);
// }
// }
//
// public void append(byte b) {
// buffer.add(b);
// }
//
// public void append(byte... bs) {
// for (byte b : bs) {
// buffer.add(b);
// }
// }
//
// public void append(Buffer data) {
// int n = data.length();
// for (int i = 0; i < n; i++) {
// append(data.get(i));
// }
// }
//
// public void appendU16(int value) {
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public void appendU32(int value) {
// buffer.add((byte)(value >> 24));
// buffer.add((byte)(value >> 16));
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public int getAppendOffset() {
// return buffer.size();
// }
//
// public void put(int i, byte value) {
// buffer.set(i, value);
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value >> 8));
// put(i + 1, (byte)(value & 0xFF));
// }
//
// public byte[] toByteArray() {
// int n = buffer.size();
// byte[] array = new byte[n];
// for (int i = 0; i < n; i++) {
// array[i] = buffer.get(i);
// }
// return array;
// }
//
// @Override
// public String toString() {
// return "WriteBuffer{" +
// "buffer=" + buffer +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// WriteBuffer that = (WriteBuffer) o;
//
// if (!buffer.equals(that.buffer)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return buffer.hashCode();
// }
//
// public interface Listener {
// void send(WriteBuffer buffer);
// }
// }
| import name.arbitrary.toytcp.WriteBuffer; | package name.arbitrary.toytcp.ppp.lcp.options;
/**
* Async-Control-Character-Map option.
*/
public final class OptionAsyncControlCharacterMap implements Option {
private final int asyncMap;
public OptionAsyncControlCharacterMap(int asyncMap) {
this.asyncMap = asyncMap;
}
@Override
public ResponseType getResponseType() {
// We're happy to escape whatever they ask for.
return ResponseType.ACCEPT;
}
@Override
public Option getAcceptableVersion() {
throw new IllegalStateException("No need for acceptable version - always accept");
}
@Override | // Path: src/name/arbitrary/toytcp/WriteBuffer.java
// public class WriteBuffer {
// private final ArrayList<Byte> buffer = new ArrayList<Byte>();
//
// public WriteBuffer() {
// }
//
// public WriteBuffer(int... data) {
// for (int i = 0 ; i < data.length; i++) {
// append((byte)data[i]);
// }
// }
//
// public void append(byte b) {
// buffer.add(b);
// }
//
// public void append(byte... bs) {
// for (byte b : bs) {
// buffer.add(b);
// }
// }
//
// public void append(Buffer data) {
// int n = data.length();
// for (int i = 0; i < n; i++) {
// append(data.get(i));
// }
// }
//
// public void appendU16(int value) {
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public void appendU32(int value) {
// buffer.add((byte)(value >> 24));
// buffer.add((byte)(value >> 16));
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public int getAppendOffset() {
// return buffer.size();
// }
//
// public void put(int i, byte value) {
// buffer.set(i, value);
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value >> 8));
// put(i + 1, (byte)(value & 0xFF));
// }
//
// public byte[] toByteArray() {
// int n = buffer.size();
// byte[] array = new byte[n];
// for (int i = 0; i < n; i++) {
// array[i] = buffer.get(i);
// }
// return array;
// }
//
// @Override
// public String toString() {
// return "WriteBuffer{" +
// "buffer=" + buffer +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// WriteBuffer that = (WriteBuffer) o;
//
// if (!buffer.equals(that.buffer)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return buffer.hashCode();
// }
//
// public interface Listener {
// void send(WriteBuffer buffer);
// }
// }
// Path: src/name/arbitrary/toytcp/ppp/lcp/options/OptionAsyncControlCharacterMap.java
import name.arbitrary.toytcp.WriteBuffer;
package name.arbitrary.toytcp.ppp.lcp.options;
/**
* Async-Control-Character-Map option.
*/
public final class OptionAsyncControlCharacterMap implements Option {
private final int asyncMap;
public OptionAsyncControlCharacterMap(int asyncMap) {
this.asyncMap = asyncMap;
}
@Override
public ResponseType getResponseType() {
// We're happy to escape whatever they ask for.
return ResponseType.ACCEPT;
}
@Override
public Option getAcceptableVersion() {
throw new IllegalStateException("No need for acceptable version - always accept");
}
@Override | public void writeTo(WriteBuffer buffer) { |
simon-frankau/toy-tcp | src/name/arbitrary/toytcp/ppp/lcp/options/OptionAddressAndControlFieldCompression.java | // Path: src/name/arbitrary/toytcp/WriteBuffer.java
// public class WriteBuffer {
// private final ArrayList<Byte> buffer = new ArrayList<Byte>();
//
// public WriteBuffer() {
// }
//
// public WriteBuffer(int... data) {
// for (int i = 0 ; i < data.length; i++) {
// append((byte)data[i]);
// }
// }
//
// public void append(byte b) {
// buffer.add(b);
// }
//
// public void append(byte... bs) {
// for (byte b : bs) {
// buffer.add(b);
// }
// }
//
// public void append(Buffer data) {
// int n = data.length();
// for (int i = 0; i < n; i++) {
// append(data.get(i));
// }
// }
//
// public void appendU16(int value) {
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public void appendU32(int value) {
// buffer.add((byte)(value >> 24));
// buffer.add((byte)(value >> 16));
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public int getAppendOffset() {
// return buffer.size();
// }
//
// public void put(int i, byte value) {
// buffer.set(i, value);
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value >> 8));
// put(i + 1, (byte)(value & 0xFF));
// }
//
// public byte[] toByteArray() {
// int n = buffer.size();
// byte[] array = new byte[n];
// for (int i = 0; i < n; i++) {
// array[i] = buffer.get(i);
// }
// return array;
// }
//
// @Override
// public String toString() {
// return "WriteBuffer{" +
// "buffer=" + buffer +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// WriteBuffer that = (WriteBuffer) o;
//
// if (!buffer.equals(that.buffer)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return buffer.hashCode();
// }
//
// public interface Listener {
// void send(WriteBuffer buffer);
// }
// }
| import name.arbitrary.toytcp.WriteBuffer; | package name.arbitrary.toytcp.ppp.lcp.options;
/**
* Address-And-Control-Field-Compression option.
*/
public enum OptionAddressAndControlFieldCompression implements Option {
INSTANCE;
@Override
public ResponseType getResponseType() {
return ResponseType.ACCEPT;
}
@Override
public Option getAcceptableVersion() {
throw new IllegalStateException("No need for acceptable version - always accept");
}
@Override | // Path: src/name/arbitrary/toytcp/WriteBuffer.java
// public class WriteBuffer {
// private final ArrayList<Byte> buffer = new ArrayList<Byte>();
//
// public WriteBuffer() {
// }
//
// public WriteBuffer(int... data) {
// for (int i = 0 ; i < data.length; i++) {
// append((byte)data[i]);
// }
// }
//
// public void append(byte b) {
// buffer.add(b);
// }
//
// public void append(byte... bs) {
// for (byte b : bs) {
// buffer.add(b);
// }
// }
//
// public void append(Buffer data) {
// int n = data.length();
// for (int i = 0; i < n; i++) {
// append(data.get(i));
// }
// }
//
// public void appendU16(int value) {
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public void appendU32(int value) {
// buffer.add((byte)(value >> 24));
// buffer.add((byte)(value >> 16));
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public int getAppendOffset() {
// return buffer.size();
// }
//
// public void put(int i, byte value) {
// buffer.set(i, value);
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value >> 8));
// put(i + 1, (byte)(value & 0xFF));
// }
//
// public byte[] toByteArray() {
// int n = buffer.size();
// byte[] array = new byte[n];
// for (int i = 0; i < n; i++) {
// array[i] = buffer.get(i);
// }
// return array;
// }
//
// @Override
// public String toString() {
// return "WriteBuffer{" +
// "buffer=" + buffer +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// WriteBuffer that = (WriteBuffer) o;
//
// if (!buffer.equals(that.buffer)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return buffer.hashCode();
// }
//
// public interface Listener {
// void send(WriteBuffer buffer);
// }
// }
// Path: src/name/arbitrary/toytcp/ppp/lcp/options/OptionAddressAndControlFieldCompression.java
import name.arbitrary.toytcp.WriteBuffer;
package name.arbitrary.toytcp.ppp.lcp.options;
/**
* Address-And-Control-Field-Compression option.
*/
public enum OptionAddressAndControlFieldCompression implements Option {
INSTANCE;
@Override
public ResponseType getResponseType() {
return ResponseType.ACCEPT;
}
@Override
public Option getAcceptableVersion() {
throw new IllegalStateException("No need for acceptable version - always accept");
}
@Override | public void writeTo(WriteBuffer buffer) { |
simon-frankau/toy-tcp | test/name/arbitrary/toytcp/ppp/lcp/options/OptionMaximumReceiveUnitTest.java | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
| import name.arbitrary.toytcp.Buffer;
import org.junit.Test;
import static org.junit.Assert.*; | package name.arbitrary.toytcp.ppp.lcp.options;
public class OptionMaximumReceiveUnitTest {
private final Option option = new OptionMaximumReceiveUnit(0x0102);
@Test
public void testCreateSuccess() {
assertEquals(option,
OptionsReader.readOption(OptionsReader.MAXIMUM_RECEIVE_UNIT, | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
// Path: test/name/arbitrary/toytcp/ppp/lcp/options/OptionMaximumReceiveUnitTest.java
import name.arbitrary.toytcp.Buffer;
import org.junit.Test;
import static org.junit.Assert.*;
package name.arbitrary.toytcp.ppp.lcp.options;
public class OptionMaximumReceiveUnitTest {
private final Option option = new OptionMaximumReceiveUnit(0x0102);
@Test
public void testCreateSuccess() {
assertEquals(option,
OptionsReader.readOption(OptionsReader.MAXIMUM_RECEIVE_UNIT, | new Buffer(0x01, 0x02))); |
simon-frankau/toy-tcp | src/name/arbitrary/toytcp/ppp/lcp/options/Option.java | // Path: src/name/arbitrary/toytcp/WriteBuffer.java
// public class WriteBuffer {
// private final ArrayList<Byte> buffer = new ArrayList<Byte>();
//
// public WriteBuffer() {
// }
//
// public WriteBuffer(int... data) {
// for (int i = 0 ; i < data.length; i++) {
// append((byte)data[i]);
// }
// }
//
// public void append(byte b) {
// buffer.add(b);
// }
//
// public void append(byte... bs) {
// for (byte b : bs) {
// buffer.add(b);
// }
// }
//
// public void append(Buffer data) {
// int n = data.length();
// for (int i = 0; i < n; i++) {
// append(data.get(i));
// }
// }
//
// public void appendU16(int value) {
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public void appendU32(int value) {
// buffer.add((byte)(value >> 24));
// buffer.add((byte)(value >> 16));
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public int getAppendOffset() {
// return buffer.size();
// }
//
// public void put(int i, byte value) {
// buffer.set(i, value);
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value >> 8));
// put(i + 1, (byte)(value & 0xFF));
// }
//
// public byte[] toByteArray() {
// int n = buffer.size();
// byte[] array = new byte[n];
// for (int i = 0; i < n; i++) {
// array[i] = buffer.get(i);
// }
// return array;
// }
//
// @Override
// public String toString() {
// return "WriteBuffer{" +
// "buffer=" + buffer +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// WriteBuffer that = (WriteBuffer) o;
//
// if (!buffer.equals(that.buffer)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return buffer.hashCode();
// }
//
// public interface Listener {
// void send(WriteBuffer buffer);
// }
// }
| import name.arbitrary.toytcp.WriteBuffer; | package name.arbitrary.toytcp.ppp.lcp.options;
/**
* Interface to represent an LCP option.
*/
public interface Option {
enum ResponseType {
ACCEPT,
NAK,
REJECT
}
ResponseType getResponseType();
Option getAcceptableVersion();
// Write the option into a buffer. Reading equivalent is in OptionsReader. | // Path: src/name/arbitrary/toytcp/WriteBuffer.java
// public class WriteBuffer {
// private final ArrayList<Byte> buffer = new ArrayList<Byte>();
//
// public WriteBuffer() {
// }
//
// public WriteBuffer(int... data) {
// for (int i = 0 ; i < data.length; i++) {
// append((byte)data[i]);
// }
// }
//
// public void append(byte b) {
// buffer.add(b);
// }
//
// public void append(byte... bs) {
// for (byte b : bs) {
// buffer.add(b);
// }
// }
//
// public void append(Buffer data) {
// int n = data.length();
// for (int i = 0; i < n; i++) {
// append(data.get(i));
// }
// }
//
// public void appendU16(int value) {
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public void appendU32(int value) {
// buffer.add((byte)(value >> 24));
// buffer.add((byte)(value >> 16));
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public int getAppendOffset() {
// return buffer.size();
// }
//
// public void put(int i, byte value) {
// buffer.set(i, value);
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value >> 8));
// put(i + 1, (byte)(value & 0xFF));
// }
//
// public byte[] toByteArray() {
// int n = buffer.size();
// byte[] array = new byte[n];
// for (int i = 0; i < n; i++) {
// array[i] = buffer.get(i);
// }
// return array;
// }
//
// @Override
// public String toString() {
// return "WriteBuffer{" +
// "buffer=" + buffer +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// WriteBuffer that = (WriteBuffer) o;
//
// if (!buffer.equals(that.buffer)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return buffer.hashCode();
// }
//
// public interface Listener {
// void send(WriteBuffer buffer);
// }
// }
// Path: src/name/arbitrary/toytcp/ppp/lcp/options/Option.java
import name.arbitrary.toytcp.WriteBuffer;
package name.arbitrary.toytcp.ppp.lcp.options;
/**
* Interface to represent an LCP option.
*/
public interface Option {
enum ResponseType {
ACCEPT,
NAK,
REJECT
}
ResponseType getResponseType();
Option getAcceptableVersion();
// Write the option into a buffer. Reading equivalent is in OptionsReader. | void writeTo(WriteBuffer buffer); |
simon-frankau/toy-tcp | test/name/arbitrary/toytcp/ppp/lcp/DefaultConfigCheckerTest.java | // Path: src/name/arbitrary/toytcp/ppp/lcp/options/Option.java
// public interface Option {
// enum ResponseType {
// ACCEPT,
// NAK,
// REJECT
// }
//
// ResponseType getResponseType();
//
// Option getAcceptableVersion();
//
// // Write the option into a buffer. Reading equivalent is in OptionsReader.
// void writeTo(WriteBuffer buffer);
// }
| import name.arbitrary.toytcp.ppp.lcp.options.Option;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.junit.Assert.*;
import static org.mockito.Mockito.when; | package name.arbitrary.toytcp.ppp.lcp;
@RunWith(MockitoJUnitRunner.class)
public class DefaultConfigCheckerTest {
private DefaultConfigChecker checker;
@Mock | // Path: src/name/arbitrary/toytcp/ppp/lcp/options/Option.java
// public interface Option {
// enum ResponseType {
// ACCEPT,
// NAK,
// REJECT
// }
//
// ResponseType getResponseType();
//
// Option getAcceptableVersion();
//
// // Write the option into a buffer. Reading equivalent is in OptionsReader.
// void writeTo(WriteBuffer buffer);
// }
// Path: test/name/arbitrary/toytcp/ppp/lcp/DefaultConfigCheckerTest.java
import name.arbitrary.toytcp.ppp.lcp.options.Option;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.junit.Assert.*;
import static org.mockito.Mockito.when;
package name.arbitrary.toytcp.ppp.lcp;
@RunWith(MockitoJUnitRunner.class)
public class DefaultConfigCheckerTest {
private DefaultConfigChecker checker;
@Mock | private Option ackOption; |
simon-frankau/toy-tcp | src/name/arbitrary/toytcp/ppp/link/Unframer.java | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
| import name.arbitrary.toytcp.Buffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream; | package name.arbitrary.toytcp.ppp.link;
/**
* Unframer reads from an InputStream, and breaks the input into PPP frames.
*/
class Unframer {
private static final Logger logger = LoggerFactory.getLogger(Unframer.class);
// Maximum Receive Unit informs the receive buffer size we set up
public static final int MRU = 1500;
// Allow some buffer overhead for flags, escaping, extra fields etc.
private static final int BUFFER_SLACK = 32;
// The character representing the start/end of frames.
public static final byte FLAG_CHAR = (byte)0x7E;
// Allow worst-case space for all characters being escaped!
private final byte[] buffer = new byte[2 * MRU + BUFFER_SLACK];
private final InputStream inputStream; | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
// Path: src/name/arbitrary/toytcp/ppp/link/Unframer.java
import name.arbitrary.toytcp.Buffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
package name.arbitrary.toytcp.ppp.link;
/**
* Unframer reads from an InputStream, and breaks the input into PPP frames.
*/
class Unframer {
private static final Logger logger = LoggerFactory.getLogger(Unframer.class);
// Maximum Receive Unit informs the receive buffer size we set up
public static final int MRU = 1500;
// Allow some buffer overhead for flags, escaping, extra fields etc.
private static final int BUFFER_SLACK = 32;
// The character representing the start/end of frames.
public static final byte FLAG_CHAR = (byte)0x7E;
// Allow worst-case space for all characters being escaped!
private final byte[] buffer = new byte[2 * MRU + BUFFER_SLACK];
private final InputStream inputStream; | private final Buffer.Listener listener; |
simon-frankau/toy-tcp | src/name/arbitrary/toytcp/ppp/lcp/statemachine/ActionProcessor.java | // Path: src/name/arbitrary/toytcp/WriteBuffer.java
// public class WriteBuffer {
// private final ArrayList<Byte> buffer = new ArrayList<Byte>();
//
// public WriteBuffer() {
// }
//
// public WriteBuffer(int... data) {
// for (int i = 0 ; i < data.length; i++) {
// append((byte)data[i]);
// }
// }
//
// public void append(byte b) {
// buffer.add(b);
// }
//
// public void append(byte... bs) {
// for (byte b : bs) {
// buffer.add(b);
// }
// }
//
// public void append(Buffer data) {
// int n = data.length();
// for (int i = 0; i < n; i++) {
// append(data.get(i));
// }
// }
//
// public void appendU16(int value) {
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public void appendU32(int value) {
// buffer.add((byte)(value >> 24));
// buffer.add((byte)(value >> 16));
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public int getAppendOffset() {
// return buffer.size();
// }
//
// public void put(int i, byte value) {
// buffer.set(i, value);
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value >> 8));
// put(i + 1, (byte)(value & 0xFF));
// }
//
// public byte[] toByteArray() {
// int n = buffer.size();
// byte[] array = new byte[n];
// for (int i = 0; i < n; i++) {
// array[i] = buffer.get(i);
// }
// return array;
// }
//
// @Override
// public String toString() {
// return "WriteBuffer{" +
// "buffer=" + buffer +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// WriteBuffer that = (WriteBuffer) o;
//
// if (!buffer.equals(that.buffer)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return buffer.hashCode();
// }
//
// public interface Listener {
// void send(WriteBuffer buffer);
// }
// }
//
// Path: src/name/arbitrary/toytcp/ppp/lcp/options/Option.java
// public interface Option {
// enum ResponseType {
// ACCEPT,
// NAK,
// REJECT
// }
//
// ResponseType getResponseType();
//
// Option getAcceptableVersion();
//
// // Write the option into a buffer. Reading equivalent is in OptionsReader.
// void writeTo(WriteBuffer buffer);
// }
| import name.arbitrary.toytcp.WriteBuffer;
import name.arbitrary.toytcp.ppp.lcp.options.Option;
import java.util.List; | package name.arbitrary.toytcp.ppp.lcp.statemachine;
/**
* Interface for the messages to send out and link layer actions associated with state machine actions.
*/
public interface ActionProcessor {
void onThisLayerStarted();
void onThisLayerFinished();
| // Path: src/name/arbitrary/toytcp/WriteBuffer.java
// public class WriteBuffer {
// private final ArrayList<Byte> buffer = new ArrayList<Byte>();
//
// public WriteBuffer() {
// }
//
// public WriteBuffer(int... data) {
// for (int i = 0 ; i < data.length; i++) {
// append((byte)data[i]);
// }
// }
//
// public void append(byte b) {
// buffer.add(b);
// }
//
// public void append(byte... bs) {
// for (byte b : bs) {
// buffer.add(b);
// }
// }
//
// public void append(Buffer data) {
// int n = data.length();
// for (int i = 0; i < n; i++) {
// append(data.get(i));
// }
// }
//
// public void appendU16(int value) {
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public void appendU32(int value) {
// buffer.add((byte)(value >> 24));
// buffer.add((byte)(value >> 16));
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public int getAppendOffset() {
// return buffer.size();
// }
//
// public void put(int i, byte value) {
// buffer.set(i, value);
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value >> 8));
// put(i + 1, (byte)(value & 0xFF));
// }
//
// public byte[] toByteArray() {
// int n = buffer.size();
// byte[] array = new byte[n];
// for (int i = 0; i < n; i++) {
// array[i] = buffer.get(i);
// }
// return array;
// }
//
// @Override
// public String toString() {
// return "WriteBuffer{" +
// "buffer=" + buffer +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// WriteBuffer that = (WriteBuffer) o;
//
// if (!buffer.equals(that.buffer)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return buffer.hashCode();
// }
//
// public interface Listener {
// void send(WriteBuffer buffer);
// }
// }
//
// Path: src/name/arbitrary/toytcp/ppp/lcp/options/Option.java
// public interface Option {
// enum ResponseType {
// ACCEPT,
// NAK,
// REJECT
// }
//
// ResponseType getResponseType();
//
// Option getAcceptableVersion();
//
// // Write the option into a buffer. Reading equivalent is in OptionsReader.
// void writeTo(WriteBuffer buffer);
// }
// Path: src/name/arbitrary/toytcp/ppp/lcp/statemachine/ActionProcessor.java
import name.arbitrary.toytcp.WriteBuffer;
import name.arbitrary.toytcp.ppp.lcp.options.Option;
import java.util.List;
package name.arbitrary.toytcp.ppp.lcp.statemachine;
/**
* Interface for the messages to send out and link layer actions associated with state machine actions.
*/
public interface ActionProcessor {
void onThisLayerStarted();
void onThisLayerFinished();
| void sendConfigureRequest(byte identifier, List<Option> options); |
simon-frankau/toy-tcp | src/name/arbitrary/toytcp/ppp/lcp/statemachine/ActionProcessor.java | // Path: src/name/arbitrary/toytcp/WriteBuffer.java
// public class WriteBuffer {
// private final ArrayList<Byte> buffer = new ArrayList<Byte>();
//
// public WriteBuffer() {
// }
//
// public WriteBuffer(int... data) {
// for (int i = 0 ; i < data.length; i++) {
// append((byte)data[i]);
// }
// }
//
// public void append(byte b) {
// buffer.add(b);
// }
//
// public void append(byte... bs) {
// for (byte b : bs) {
// buffer.add(b);
// }
// }
//
// public void append(Buffer data) {
// int n = data.length();
// for (int i = 0; i < n; i++) {
// append(data.get(i));
// }
// }
//
// public void appendU16(int value) {
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public void appendU32(int value) {
// buffer.add((byte)(value >> 24));
// buffer.add((byte)(value >> 16));
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public int getAppendOffset() {
// return buffer.size();
// }
//
// public void put(int i, byte value) {
// buffer.set(i, value);
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value >> 8));
// put(i + 1, (byte)(value & 0xFF));
// }
//
// public byte[] toByteArray() {
// int n = buffer.size();
// byte[] array = new byte[n];
// for (int i = 0; i < n; i++) {
// array[i] = buffer.get(i);
// }
// return array;
// }
//
// @Override
// public String toString() {
// return "WriteBuffer{" +
// "buffer=" + buffer +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// WriteBuffer that = (WriteBuffer) o;
//
// if (!buffer.equals(that.buffer)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return buffer.hashCode();
// }
//
// public interface Listener {
// void send(WriteBuffer buffer);
// }
// }
//
// Path: src/name/arbitrary/toytcp/ppp/lcp/options/Option.java
// public interface Option {
// enum ResponseType {
// ACCEPT,
// NAK,
// REJECT
// }
//
// ResponseType getResponseType();
//
// Option getAcceptableVersion();
//
// // Write the option into a buffer. Reading equivalent is in OptionsReader.
// void writeTo(WriteBuffer buffer);
// }
| import name.arbitrary.toytcp.WriteBuffer;
import name.arbitrary.toytcp.ppp.lcp.options.Option;
import java.util.List; | package name.arbitrary.toytcp.ppp.lcp.statemachine;
/**
* Interface for the messages to send out and link layer actions associated with state machine actions.
*/
public interface ActionProcessor {
void onThisLayerStarted();
void onThisLayerFinished();
void sendConfigureRequest(byte identifier, List<Option> options);
void sendConfigureAcknowledge(byte identifier, List<Option> options);
void sendConfigureNak(byte identifier, List<Option> options);
void sendConfigureReject(byte identifier, List<Option> options);
| // Path: src/name/arbitrary/toytcp/WriteBuffer.java
// public class WriteBuffer {
// private final ArrayList<Byte> buffer = new ArrayList<Byte>();
//
// public WriteBuffer() {
// }
//
// public WriteBuffer(int... data) {
// for (int i = 0 ; i < data.length; i++) {
// append((byte)data[i]);
// }
// }
//
// public void append(byte b) {
// buffer.add(b);
// }
//
// public void append(byte... bs) {
// for (byte b : bs) {
// buffer.add(b);
// }
// }
//
// public void append(Buffer data) {
// int n = data.length();
// for (int i = 0; i < n; i++) {
// append(data.get(i));
// }
// }
//
// public void appendU16(int value) {
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public void appendU32(int value) {
// buffer.add((byte)(value >> 24));
// buffer.add((byte)(value >> 16));
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public int getAppendOffset() {
// return buffer.size();
// }
//
// public void put(int i, byte value) {
// buffer.set(i, value);
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value >> 8));
// put(i + 1, (byte)(value & 0xFF));
// }
//
// public byte[] toByteArray() {
// int n = buffer.size();
// byte[] array = new byte[n];
// for (int i = 0; i < n; i++) {
// array[i] = buffer.get(i);
// }
// return array;
// }
//
// @Override
// public String toString() {
// return "WriteBuffer{" +
// "buffer=" + buffer +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// WriteBuffer that = (WriteBuffer) o;
//
// if (!buffer.equals(that.buffer)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return buffer.hashCode();
// }
//
// public interface Listener {
// void send(WriteBuffer buffer);
// }
// }
//
// Path: src/name/arbitrary/toytcp/ppp/lcp/options/Option.java
// public interface Option {
// enum ResponseType {
// ACCEPT,
// NAK,
// REJECT
// }
//
// ResponseType getResponseType();
//
// Option getAcceptableVersion();
//
// // Write the option into a buffer. Reading equivalent is in OptionsReader.
// void writeTo(WriteBuffer buffer);
// }
// Path: src/name/arbitrary/toytcp/ppp/lcp/statemachine/ActionProcessor.java
import name.arbitrary.toytcp.WriteBuffer;
import name.arbitrary.toytcp.ppp.lcp.options.Option;
import java.util.List;
package name.arbitrary.toytcp.ppp.lcp.statemachine;
/**
* Interface for the messages to send out and link layer actions associated with state machine actions.
*/
public interface ActionProcessor {
void onThisLayerStarted();
void onThisLayerFinished();
void sendConfigureRequest(byte identifier, List<Option> options);
void sendConfigureAcknowledge(byte identifier, List<Option> options);
void sendConfigureNak(byte identifier, List<Option> options);
void sendConfigureReject(byte identifier, List<Option> options);
| void sendTerminateRequest(byte identifier, WriteBuffer buffer); |
simon-frankau/toy-tcp | src/name/arbitrary/toytcp/ppp/link/PppLinkReaderThread.java | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
| import name.arbitrary.toytcp.Buffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream; | package name.arbitrary.toytcp.ppp.link;
/**
* PPP link layer reader thread
*/
class PppLinkReaderThread {
private static final Logger logger = LoggerFactory.getLogger(PppLinkReaderThread.class);
private final InputStream inputStream;
private final PppLinkListener listener;
private Thread readerThread;
public PppLinkReaderThread(InputStream inputStream, PppLinkListener listener) {
this.inputStream = inputStream;
this.listener = listener;
}
public void start() {
readerThread = new Thread(new PppBufferProcessor());
readerThread.start();
}
public void stop() {
// TODO: Support interrupt-based shut down.
throw new UnsupportedOperationException();
}
class PppBufferProcessor implements Runnable {
@Override
public void run() {
listener.onLinkUp();
try {
Unframer unframer =
new Unframer(inputStream,
new Unstuffer(
new FcsChecker(
new HeaderCompressor( | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
// Path: src/name/arbitrary/toytcp/ppp/link/PppLinkReaderThread.java
import name.arbitrary.toytcp.Buffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
package name.arbitrary.toytcp.ppp.link;
/**
* PPP link layer reader thread
*/
class PppLinkReaderThread {
private static final Logger logger = LoggerFactory.getLogger(PppLinkReaderThread.class);
private final InputStream inputStream;
private final PppLinkListener listener;
private Thread readerThread;
public PppLinkReaderThread(InputStream inputStream, PppLinkListener listener) {
this.inputStream = inputStream;
this.listener = listener;
}
public void start() {
readerThread = new Thread(new PppBufferProcessor());
readerThread.start();
}
public void stop() {
// TODO: Support interrupt-based shut down.
throw new UnsupportedOperationException();
}
class PppBufferProcessor implements Runnable {
@Override
public void run() {
listener.onLinkUp();
try {
Unframer unframer =
new Unframer(inputStream,
new Unstuffer(
new FcsChecker(
new HeaderCompressor( | new Buffer.Listener() { |
simon-frankau/toy-tcp | src/name/arbitrary/toytcp/ppp/lcp/statemachine/LcpConfigChecker.java | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
//
// Path: src/name/arbitrary/toytcp/ppp/lcp/options/Option.java
// public interface Option {
// enum ResponseType {
// ACCEPT,
// NAK,
// REJECT
// }
//
// ResponseType getResponseType();
//
// Option getAcceptableVersion();
//
// // Write the option into a buffer. Reading equivalent is in OptionsReader.
// void writeTo(WriteBuffer buffer);
// }
| import name.arbitrary.toytcp.Buffer;
import name.arbitrary.toytcp.ppp.lcp.options.Option;
import java.util.List; | package name.arbitrary.toytcp.ppp.lcp.statemachine;
/**
* Interface for something that actually handles the details of configuration.
*
* It has sub-interfaces to handle receiving requests, sending requests, and code/protocol rejects.
*/
public interface LcpConfigChecker {
// TODO: Reset the internal state when going via this layer stopped.
// Interface to do with receiving requests and producing responses:
Option.ResponseType processIncomingConfigRequest(List<Option> options);
List<Option> getConfigNakOptions();
List<Option> getConfigRejectOptions();
// Interface to do with sending requests and handling responses.
List<Option> getRequestedOptions();
// Interface to do with handling rejects.
| // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
//
// Path: src/name/arbitrary/toytcp/ppp/lcp/options/Option.java
// public interface Option {
// enum ResponseType {
// ACCEPT,
// NAK,
// REJECT
// }
//
// ResponseType getResponseType();
//
// Option getAcceptableVersion();
//
// // Write the option into a buffer. Reading equivalent is in OptionsReader.
// void writeTo(WriteBuffer buffer);
// }
// Path: src/name/arbitrary/toytcp/ppp/lcp/statemachine/LcpConfigChecker.java
import name.arbitrary.toytcp.Buffer;
import name.arbitrary.toytcp.ppp.lcp.options.Option;
import java.util.List;
package name.arbitrary.toytcp.ppp.lcp.statemachine;
/**
* Interface for something that actually handles the details of configuration.
*
* It has sub-interfaces to handle receiving requests, sending requests, and code/protocol rejects.
*/
public interface LcpConfigChecker {
// TODO: Reset the internal state when going via this layer stopped.
// Interface to do with receiving requests and producing responses:
Option.ResponseType processIncomingConfigRequest(List<Option> options);
List<Option> getConfigNakOptions();
List<Option> getConfigRejectOptions();
// Interface to do with sending requests and handling responses.
List<Option> getRequestedOptions();
// Interface to do with handling rejects.
| boolean isRejectAcceptable(Buffer rejected); |
simon-frankau/toy-tcp | test/name/arbitrary/toytcp/ppp/lcp/options/OptionMagicNumberTest.java | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
| import name.arbitrary.toytcp.Buffer;
import org.junit.Test;
import static org.junit.Assert.*; | package name.arbitrary.toytcp.ppp.lcp.options;
public class OptionMagicNumberTest {
private final Option option = new OptionMagicNumber(0x01020304);
@Test
public void testCreateSuccess() {
assertEquals(option,
OptionsReader.readOption(OptionsReader.MAGIC_NUMBER, | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
// Path: test/name/arbitrary/toytcp/ppp/lcp/options/OptionMagicNumberTest.java
import name.arbitrary.toytcp.Buffer;
import org.junit.Test;
import static org.junit.Assert.*;
package name.arbitrary.toytcp.ppp.lcp.options;
public class OptionMagicNumberTest {
private final Option option = new OptionMagicNumber(0x01020304);
@Test
public void testCreateSuccess() {
assertEquals(option,
OptionsReader.readOption(OptionsReader.MAGIC_NUMBER, | new Buffer(0x01, 0x02, 0x03, 0x04))); |
simon-frankau/toy-tcp | src/name/arbitrary/toytcp/ppp/lcp/options/OptionsReader.java | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
| import name.arbitrary.toytcp.Buffer;
import java.util.LinkedList;
import java.util.List; | package name.arbitrary.toytcp.ppp.lcp.options;
/**
* Reads an option or set of options. Helper class for FrameReader.
*/
public class OptionsReader {
public static final byte MAXIMUM_RECEIVE_UNIT = 1;
public static final byte ASYNC_CONTROL_CHARACTER_MAP = 2;
public static final byte AUTHENTICATION_PROTOCOL = 3;
public static final byte QUALITY_PROTOCOL = 4;
public static final byte MAGIC_NUMBER = 5;
public static final byte PROTOCOL_FIELD_COMPRESSION = 7;
public static final byte ADDRESS_AND_CONTROL_COMPRESSION_FIELD= 8;
private OptionsReader() {
// Static method holder class.
}
| // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
// Path: src/name/arbitrary/toytcp/ppp/lcp/options/OptionsReader.java
import name.arbitrary.toytcp.Buffer;
import java.util.LinkedList;
import java.util.List;
package name.arbitrary.toytcp.ppp.lcp.options;
/**
* Reads an option or set of options. Helper class for FrameReader.
*/
public class OptionsReader {
public static final byte MAXIMUM_RECEIVE_UNIT = 1;
public static final byte ASYNC_CONTROL_CHARACTER_MAP = 2;
public static final byte AUTHENTICATION_PROTOCOL = 3;
public static final byte QUALITY_PROTOCOL = 4;
public static final byte MAGIC_NUMBER = 5;
public static final byte PROTOCOL_FIELD_COMPRESSION = 7;
public static final byte ADDRESS_AND_CONTROL_COMPRESSION_FIELD= 8;
private OptionsReader() {
// Static method holder class.
}
| public static List<Option> readOptions(Buffer buffer) { |
simon-frankau/toy-tcp | test/name/arbitrary/toytcp/ppp/link/UnframerTest.java | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
//
// Path: test/name/arbitrary/toytcp/DeepCopyingBufferListener.java
// public class DeepCopyingBufferListener implements Buffer.Listener {
// private final Buffer.Listener listener;
//
// public DeepCopyingBufferListener(Buffer.Listener listener) {
// this.listener = listener;
// }
//
// @Override
// public void receive(Buffer buffer) {
// listener.receive(buffer.deepCopy());
// }
// }
| import name.arbitrary.toytcp.Buffer;
import name.arbitrary.toytcp.DeepCopyingBufferListener;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Arrays;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*; | package name.arbitrary.toytcp.ppp.link;
@RunWith(MockitoJUnitRunner.class)
public class UnframerTest {
@Mock | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
//
// Path: test/name/arbitrary/toytcp/DeepCopyingBufferListener.java
// public class DeepCopyingBufferListener implements Buffer.Listener {
// private final Buffer.Listener listener;
//
// public DeepCopyingBufferListener(Buffer.Listener listener) {
// this.listener = listener;
// }
//
// @Override
// public void receive(Buffer buffer) {
// listener.receive(buffer.deepCopy());
// }
// }
// Path: test/name/arbitrary/toytcp/ppp/link/UnframerTest.java
import name.arbitrary.toytcp.Buffer;
import name.arbitrary.toytcp.DeepCopyingBufferListener;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Arrays;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
package name.arbitrary.toytcp.ppp.link;
@RunWith(MockitoJUnitRunner.class)
public class UnframerTest {
@Mock | private Buffer.Listener listener; |
simon-frankau/toy-tcp | test/name/arbitrary/toytcp/ppp/link/UnframerTest.java | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
//
// Path: test/name/arbitrary/toytcp/DeepCopyingBufferListener.java
// public class DeepCopyingBufferListener implements Buffer.Listener {
// private final Buffer.Listener listener;
//
// public DeepCopyingBufferListener(Buffer.Listener listener) {
// this.listener = listener;
// }
//
// @Override
// public void receive(Buffer buffer) {
// listener.receive(buffer.deepCopy());
// }
// }
| import name.arbitrary.toytcp.Buffer;
import name.arbitrary.toytcp.DeepCopyingBufferListener;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Arrays;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*; | package name.arbitrary.toytcp.ppp.link;
@RunWith(MockitoJUnitRunner.class)
public class UnframerTest {
@Mock
private Buffer.Listener listener;
@Test
public void testInitialDataIsSkipped() throws Exception {
byte[] data = new byte[Unframer.MRU * 10];
Arrays.fill(data, (byte)0x42);
InputStream inputStream = new ByteArrayInputStream(data);
Unframer unframer = new Unframer(inputStream, listener);
while (unframer.process()) {
}
verify(listener, never()).receive(any(Buffer.class));
}
@Test
public void testFrameIsReceived() throws Exception{
byte[] data = new byte[] { 0x01, Unframer.FLAG_CHAR, 0x02, Unframer.FLAG_CHAR, 0x03 };
InputStream inputStream = new ByteArrayInputStream(data); | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
//
// Path: test/name/arbitrary/toytcp/DeepCopyingBufferListener.java
// public class DeepCopyingBufferListener implements Buffer.Listener {
// private final Buffer.Listener listener;
//
// public DeepCopyingBufferListener(Buffer.Listener listener) {
// this.listener = listener;
// }
//
// @Override
// public void receive(Buffer buffer) {
// listener.receive(buffer.deepCopy());
// }
// }
// Path: test/name/arbitrary/toytcp/ppp/link/UnframerTest.java
import name.arbitrary.toytcp.Buffer;
import name.arbitrary.toytcp.DeepCopyingBufferListener;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Arrays;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
package name.arbitrary.toytcp.ppp.link;
@RunWith(MockitoJUnitRunner.class)
public class UnframerTest {
@Mock
private Buffer.Listener listener;
@Test
public void testInitialDataIsSkipped() throws Exception {
byte[] data = new byte[Unframer.MRU * 10];
Arrays.fill(data, (byte)0x42);
InputStream inputStream = new ByteArrayInputStream(data);
Unframer unframer = new Unframer(inputStream, listener);
while (unframer.process()) {
}
verify(listener, never()).receive(any(Buffer.class));
}
@Test
public void testFrameIsReceived() throws Exception{
byte[] data = new byte[] { 0x01, Unframer.FLAG_CHAR, 0x02, Unframer.FLAG_CHAR, 0x03 };
InputStream inputStream = new ByteArrayInputStream(data); | Unframer unframer = new Unframer(inputStream, new DeepCopyingBufferListener(listener)); |
simon-frankau/toy-tcp | test/name/arbitrary/toytcp/ppp/link/PppLinkReaderThreadTest.java | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
| import name.arbitrary.toytcp.Buffer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import java.io.ByteArrayInputStream;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*; | final Semaphore semaphore = new Semaphore(0);
PppLinkListener listener = new PppLinkAdapter() {
@Override
public void onLinkDown() {
semaphore.release();
}
};
PppLinkReaderThread link = new PppLinkReaderThread(new ByteArrayInputStream(new byte[0]), listener);
assertEquals(0, semaphore.availablePermits());
link.start();
// Should automatically shut down if no data's available.
assertTrue(semaphore.tryAcquire(3, TimeUnit.SECONDS));
}
@Test
public void testProcessesPackets() throws Exception {
byte[] inputData = new byte[] {
Unframer.FLAG_CHAR,
(byte)0xff, 0x03, (byte)0xc0, 0x21, 0x01, 0x01, 0x00, 0x14,
0x02, 0x06, 0x00, 0x00, 0x00, 0x00, 0x05, 0x06,
0x4e, 0x28, 0x19, (byte)0xbd, 0x07, 0x02, 0x08, 0x02,
(byte)0x8f, (byte)0xbc,
Unframer.FLAG_CHAR,
(byte)0xff, 0x03, (byte)0xc0, 0x21, 0x01, 0x01, 0x00, 0x14,
0x02, 0x06, 0x00, 0x00, 0x00, 0x00, 0x05, 0x06,
0x4e, 0x28, 0x19, (byte)0xbd, 0x07, 0x02, 0x08, 0x02,
(byte)0x8f, (byte)0xbc,
Unframer.FLAG_CHAR
};
| // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
// Path: test/name/arbitrary/toytcp/ppp/link/PppLinkReaderThreadTest.java
import name.arbitrary.toytcp.Buffer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import java.io.ByteArrayInputStream;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*;
final Semaphore semaphore = new Semaphore(0);
PppLinkListener listener = new PppLinkAdapter() {
@Override
public void onLinkDown() {
semaphore.release();
}
};
PppLinkReaderThread link = new PppLinkReaderThread(new ByteArrayInputStream(new byte[0]), listener);
assertEquals(0, semaphore.availablePermits());
link.start();
// Should automatically shut down if no data's available.
assertTrue(semaphore.tryAcquire(3, TimeUnit.SECONDS));
}
@Test
public void testProcessesPackets() throws Exception {
byte[] inputData = new byte[] {
Unframer.FLAG_CHAR,
(byte)0xff, 0x03, (byte)0xc0, 0x21, 0x01, 0x01, 0x00, 0x14,
0x02, 0x06, 0x00, 0x00, 0x00, 0x00, 0x05, 0x06,
0x4e, 0x28, 0x19, (byte)0xbd, 0x07, 0x02, 0x08, 0x02,
(byte)0x8f, (byte)0xbc,
Unframer.FLAG_CHAR,
(byte)0xff, 0x03, (byte)0xc0, 0x21, 0x01, 0x01, 0x00, 0x14,
0x02, 0x06, 0x00, 0x00, 0x00, 0x00, 0x05, 0x06,
0x4e, 0x28, 0x19, (byte)0xbd, 0x07, 0x02, 0x08, 0x02,
(byte)0x8f, (byte)0xbc,
Unframer.FLAG_CHAR
};
| final Buffer expectedResult = new Buffer( |
simon-frankau/toy-tcp | test/name/arbitrary/toytcp/ppp/lcp/options/OptionAsyncControlCharacterMapTest.java | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
| import name.arbitrary.toytcp.Buffer;
import org.junit.Test;
import static org.junit.Assert.*; | package name.arbitrary.toytcp.ppp.lcp.options;
public class OptionAsyncControlCharacterMapTest {
private final OptionAsyncControlCharacterMap option = new OptionAsyncControlCharacterMap(0x01020304);
@Test
public void testCreateSuccess() {
assertEquals(option,
OptionsReader.readOption(OptionsReader.ASYNC_CONTROL_CHARACTER_MAP, | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
// Path: test/name/arbitrary/toytcp/ppp/lcp/options/OptionAsyncControlCharacterMapTest.java
import name.arbitrary.toytcp.Buffer;
import org.junit.Test;
import static org.junit.Assert.*;
package name.arbitrary.toytcp.ppp.lcp.options;
public class OptionAsyncControlCharacterMapTest {
private final OptionAsyncControlCharacterMap option = new OptionAsyncControlCharacterMap(0x01020304);
@Test
public void testCreateSuccess() {
assertEquals(option,
OptionsReader.readOption(OptionsReader.ASYNC_CONTROL_CHARACTER_MAP, | new Buffer(0x01, 0x02, 0x03, 0x04))); |
simon-frankau/toy-tcp | test/name/arbitrary/toytcp/ppp/link/DemultiplexerTest.java | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
| import name.arbitrary.toytcp.Buffer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions; | verifyNoMoreInteractions(listener);
demultiplexer.onLinkUp();
verify(listener).onLinkUp();
verifyNoMoreInteractions(listener);
}
@Test
public void testDownPassesThrough() {
Demultiplexer demultiplexer = new Demultiplexer();
demultiplexer.subscribe(41, listener);
demultiplexer.onLinkUp();
verify(listener).onLinkUp();
verifyNoMoreInteractions(listener);
demultiplexer.onLinkDown();
verify(listener).onLinkDown();
verifyNoMoreInteractions(listener);
}
@Test
public void testEightBitProtocol() {
Demultiplexer demultiplexer = new Demultiplexer();
demultiplexer.subscribe(0x41, listener);
demultiplexer.onLinkUp();
verify(listener).onLinkUp();
verifyNoMoreInteractions(listener);
| // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
// Path: test/name/arbitrary/toytcp/ppp/link/DemultiplexerTest.java
import name.arbitrary.toytcp.Buffer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
verifyNoMoreInteractions(listener);
demultiplexer.onLinkUp();
verify(listener).onLinkUp();
verifyNoMoreInteractions(listener);
}
@Test
public void testDownPassesThrough() {
Demultiplexer demultiplexer = new Demultiplexer();
demultiplexer.subscribe(41, listener);
demultiplexer.onLinkUp();
verify(listener).onLinkUp();
verifyNoMoreInteractions(listener);
demultiplexer.onLinkDown();
verify(listener).onLinkDown();
verifyNoMoreInteractions(listener);
}
@Test
public void testEightBitProtocol() {
Demultiplexer demultiplexer = new Demultiplexer();
demultiplexer.subscribe(0x41, listener);
demultiplexer.onLinkUp();
verify(listener).onLinkUp();
verifyNoMoreInteractions(listener);
| demultiplexer.onFrame(new Buffer(0x41)); |
simon-frankau/toy-tcp | src/name/arbitrary/toytcp/ppp/link/Demultiplexer.java | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
| import name.arbitrary.toytcp.Buffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; | package name.arbitrary.toytcp.ppp.link;
/**
* Handles subscriptions (one per protocol) and demultiplexes frames based on protocol.
*
* Subscriptions must not be changed once the link is up, to keep thing simple.
*/
class Demultiplexer implements PppLinkListener {
private static final Logger logger = LoggerFactory.getLogger(Demultiplexer.class);
private final Map<Integer, PppLinkListener> listeners = new ConcurrentHashMap<Integer, PppLinkListener>();
private boolean isLinkUp;
public void subscribe(int protocol, PppLinkListener listener) {
assert !isLinkUp;
assert !listeners.containsKey(protocol);
listeners.put(protocol, listener);
}
public void unsubscribe(int protocol) {
assert !isLinkUp;
assert listeners.containsKey(protocol);
listeners.remove(protocol);
}
@Override | // Path: src/name/arbitrary/toytcp/Buffer.java
// public final class Buffer {
// private final byte[] data;
// private final int start;
// private final int length;
//
// public Buffer(byte[] data, int start, int length) {
// this.data = data;
// this.start = start;
// this.length = length;
// }
//
// public Buffer(int... data) {
// this.data = new byte[data.length];
// for (int i = 0 ; i < data.length; i++) {
// this.data[i] = (byte)data[i];
// }
// this.start = 0;
// this.length = data.length;
// }
//
// public byte get(int i) {
// return data[start + i];
// }
//
// public int getU8(int i) {
// return 0xFF & (int)data[start + i];
// }
//
// public int getU16(int i) {
// return getU8(i) << 8 | getU8(i+1);
// }
//
// public int getS32(int i) {
// return getU8(i) << 24 | getU8(i + 1) << 16 | getU8(i + 2) << 8 | getU8(i + 3);
// }
//
// // TODO: Should 'put' be on a standard buffer?
//
// public void put(int i, byte value) {
// data[start + i] = value;
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value & 0xFF));
// put(i, (byte)(value >> 8));
// }
//
// public int length() {
// return length;
// }
//
// public Buffer getSubBuffer(int offset) {
// return new Buffer(data, start + offset, length - offset);
// }
//
// public Buffer getSubBuffer(int offset, int length) {
// return new Buffer(data, start + offset, length);
// }
//
// // Sub-buffer construction shares the underlying data. deepCopy removes the sharing.
// public Buffer deepCopy() {
// return new Buffer(Arrays.copyOfRange(data, start, start + length), 0, length);
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// String format = "%02x";
// int end = start + length;
// for (int i = start; i != end; i++) {
// sb.append(String.format(format, data[i]));
// format = " %02x";
// }
// return sb.toString();
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Buffer buffer = (Buffer) o;
//
// if (length != buffer.length) return false;
//
// // Equality only covers the part of the buffer we're interested in,
// // not how it's encapsulated.
// for (int i = 0; i < length; i++) {
// if (buffer.get(i) != get(i)) {
// return false;
// }
// }
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = 0;
// for (int i = 0; i < length; i++) {
// result = 31 * get(i) + result;
// }
// result = 31 * result + length;
// return result;
// }
//
// public interface Listener {
// void receive(Buffer buffer);
// }
// }
// Path: src/name/arbitrary/toytcp/ppp/link/Demultiplexer.java
import name.arbitrary.toytcp.Buffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
package name.arbitrary.toytcp.ppp.link;
/**
* Handles subscriptions (one per protocol) and demultiplexes frames based on protocol.
*
* Subscriptions must not be changed once the link is up, to keep thing simple.
*/
class Demultiplexer implements PppLinkListener {
private static final Logger logger = LoggerFactory.getLogger(Demultiplexer.class);
private final Map<Integer, PppLinkListener> listeners = new ConcurrentHashMap<Integer, PppLinkListener>();
private boolean isLinkUp;
public void subscribe(int protocol, PppLinkListener listener) {
assert !isLinkUp;
assert !listeners.containsKey(protocol);
listeners.put(protocol, listener);
}
public void unsubscribe(int protocol) {
assert !isLinkUp;
assert listeners.containsKey(protocol);
listeners.remove(protocol);
}
@Override | public void onFrame(Buffer buffer) { |
simon-frankau/toy-tcp | src/name/arbitrary/toytcp/ppp/lcp/options/OptionProtocolFieldCompression.java | // Path: src/name/arbitrary/toytcp/WriteBuffer.java
// public class WriteBuffer {
// private final ArrayList<Byte> buffer = new ArrayList<Byte>();
//
// public WriteBuffer() {
// }
//
// public WriteBuffer(int... data) {
// for (int i = 0 ; i < data.length; i++) {
// append((byte)data[i]);
// }
// }
//
// public void append(byte b) {
// buffer.add(b);
// }
//
// public void append(byte... bs) {
// for (byte b : bs) {
// buffer.add(b);
// }
// }
//
// public void append(Buffer data) {
// int n = data.length();
// for (int i = 0; i < n; i++) {
// append(data.get(i));
// }
// }
//
// public void appendU16(int value) {
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public void appendU32(int value) {
// buffer.add((byte)(value >> 24));
// buffer.add((byte)(value >> 16));
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public int getAppendOffset() {
// return buffer.size();
// }
//
// public void put(int i, byte value) {
// buffer.set(i, value);
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value >> 8));
// put(i + 1, (byte)(value & 0xFF));
// }
//
// public byte[] toByteArray() {
// int n = buffer.size();
// byte[] array = new byte[n];
// for (int i = 0; i < n; i++) {
// array[i] = buffer.get(i);
// }
// return array;
// }
//
// @Override
// public String toString() {
// return "WriteBuffer{" +
// "buffer=" + buffer +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// WriteBuffer that = (WriteBuffer) o;
//
// if (!buffer.equals(that.buffer)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return buffer.hashCode();
// }
//
// public interface Listener {
// void send(WriteBuffer buffer);
// }
// }
| import name.arbitrary.toytcp.WriteBuffer; | package name.arbitrary.toytcp.ppp.lcp.options;
/**
* Protocol-Field-Compression option.
*/
public enum OptionProtocolFieldCompression implements Option {
INSTANCE;
@Override
public ResponseType getResponseType() {
return ResponseType.ACCEPT;
}
@Override
public Option getAcceptableVersion() {
throw new IllegalStateException("No need for acceptable version - always accept");
}
@Override | // Path: src/name/arbitrary/toytcp/WriteBuffer.java
// public class WriteBuffer {
// private final ArrayList<Byte> buffer = new ArrayList<Byte>();
//
// public WriteBuffer() {
// }
//
// public WriteBuffer(int... data) {
// for (int i = 0 ; i < data.length; i++) {
// append((byte)data[i]);
// }
// }
//
// public void append(byte b) {
// buffer.add(b);
// }
//
// public void append(byte... bs) {
// for (byte b : bs) {
// buffer.add(b);
// }
// }
//
// public void append(Buffer data) {
// int n = data.length();
// for (int i = 0; i < n; i++) {
// append(data.get(i));
// }
// }
//
// public void appendU16(int value) {
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public void appendU32(int value) {
// buffer.add((byte)(value >> 24));
// buffer.add((byte)(value >> 16));
// buffer.add((byte)(value >> 8));
// buffer.add((byte)(value & 0xFF));
// }
//
// public int getAppendOffset() {
// return buffer.size();
// }
//
// public void put(int i, byte value) {
// buffer.set(i, value);
// }
//
// public void putU8(int i, int value) {
// put(i, (byte)value);
// }
//
// public void putU16(int i, int value) {
// put(i, (byte)(value >> 8));
// put(i + 1, (byte)(value & 0xFF));
// }
//
// public byte[] toByteArray() {
// int n = buffer.size();
// byte[] array = new byte[n];
// for (int i = 0; i < n; i++) {
// array[i] = buffer.get(i);
// }
// return array;
// }
//
// @Override
// public String toString() {
// return "WriteBuffer{" +
// "buffer=" + buffer +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// WriteBuffer that = (WriteBuffer) o;
//
// if (!buffer.equals(that.buffer)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// return buffer.hashCode();
// }
//
// public interface Listener {
// void send(WriteBuffer buffer);
// }
// }
// Path: src/name/arbitrary/toytcp/ppp/lcp/options/OptionProtocolFieldCompression.java
import name.arbitrary.toytcp.WriteBuffer;
package name.arbitrary.toytcp.ppp.lcp.options;
/**
* Protocol-Field-Compression option.
*/
public enum OptionProtocolFieldCompression implements Option {
INSTANCE;
@Override
public ResponseType getResponseType() {
return ResponseType.ACCEPT;
}
@Override
public Option getAcceptableVersion() {
throw new IllegalStateException("No need for acceptable version - always accept");
}
@Override | public void writeTo(WriteBuffer buffer) { |
jpush/jmessage-android-uikit | MultiSelectPhotos/src/main/java/cn/jmessage/android/uikit/multiselectphotos/photoview/PhotoView.java | // Path: MultiSelectPhotos/src/main/java/cn/jmessage/android/uikit/multiselectphotos/photoview/PhotoViewAttacher.java
// public static interface OnMatrixChangedListener {
// /**
// * Callback for when the Matrix displaying the Drawable has changed.
// * This could be because the View's bounds have changed, or the user has
// * zoomed.
// *
// * @param rect - Rectangle displaying the Drawable's new bounds.
// */
// void onMatrixChanged(RectF rect);
// }
//
// Path: MultiSelectPhotos/src/main/java/cn/jmessage/android/uikit/multiselectphotos/photoview/PhotoViewAttacher.java
// public static interface OnPhotoTapListener {
//
// /**
// * A callback to receive where the user taps on a photo. You will only
// * receive a callback if the user taps on the actual photo, tapping on
// * 'whitespace' will be ignored.
// *
// * @param view - View the user tapped.
// * @param x - where the user tapped from the of the Drawable, as
// * percentage of the Drawable width.
// * @param y - where the user tapped from the top of the Drawable, as
// * percentage of the Drawable height.
// */
// void onPhotoTap(View view, float x, float y);
// }
//
// Path: MultiSelectPhotos/src/main/java/cn/jmessage/android/uikit/multiselectphotos/photoview/PhotoViewAttacher.java
// public static interface OnViewTapListener {
//
// /**
// * A callback to receive where the user taps on a ImageView. You will
// * receive a callback if the user taps anywhere on the view, tapping on
// * 'whitespace' will not be ignored.
// *
// * @param view - View the user tapped.
// * @param x - where the user tapped from the left of the View.
// * @param y - where the user tapped from the top of the View.
// */
// void onViewTap(View view, float x, float y);
// }
| import cn.jmessage.android.uikit.multiselectphotos.photoview.PhotoViewAttacher.OnMatrixChangedListener;
import cn.jmessage.android.uikit.multiselectphotos.photoview.PhotoViewAttacher.OnPhotoTapListener;
import cn.jmessage.android.uikit.multiselectphotos.photoview.PhotoViewAttacher.OnViewTapListener;
import android.content.Context;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.widget.ImageView; | public void setMaxScale(float maxScale) {
mAttacher.setMaxScale(maxScale);
}
@Override
// setImageBitmap calls through to this method
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setImageResource(int resId) {
super.setImageResource(resId);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override | // Path: MultiSelectPhotos/src/main/java/cn/jmessage/android/uikit/multiselectphotos/photoview/PhotoViewAttacher.java
// public static interface OnMatrixChangedListener {
// /**
// * Callback for when the Matrix displaying the Drawable has changed.
// * This could be because the View's bounds have changed, or the user has
// * zoomed.
// *
// * @param rect - Rectangle displaying the Drawable's new bounds.
// */
// void onMatrixChanged(RectF rect);
// }
//
// Path: MultiSelectPhotos/src/main/java/cn/jmessage/android/uikit/multiselectphotos/photoview/PhotoViewAttacher.java
// public static interface OnPhotoTapListener {
//
// /**
// * A callback to receive where the user taps on a photo. You will only
// * receive a callback if the user taps on the actual photo, tapping on
// * 'whitespace' will be ignored.
// *
// * @param view - View the user tapped.
// * @param x - where the user tapped from the of the Drawable, as
// * percentage of the Drawable width.
// * @param y - where the user tapped from the top of the Drawable, as
// * percentage of the Drawable height.
// */
// void onPhotoTap(View view, float x, float y);
// }
//
// Path: MultiSelectPhotos/src/main/java/cn/jmessage/android/uikit/multiselectphotos/photoview/PhotoViewAttacher.java
// public static interface OnViewTapListener {
//
// /**
// * A callback to receive where the user taps on a ImageView. You will
// * receive a callback if the user taps anywhere on the view, tapping on
// * 'whitespace' will not be ignored.
// *
// * @param view - View the user tapped.
// * @param x - where the user tapped from the left of the View.
// * @param y - where the user tapped from the top of the View.
// */
// void onViewTap(View view, float x, float y);
// }
// Path: MultiSelectPhotos/src/main/java/cn/jmessage/android/uikit/multiselectphotos/photoview/PhotoView.java
import cn.jmessage.android.uikit.multiselectphotos.photoview.PhotoViewAttacher.OnMatrixChangedListener;
import cn.jmessage.android.uikit.multiselectphotos.photoview.PhotoViewAttacher.OnPhotoTapListener;
import cn.jmessage.android.uikit.multiselectphotos.photoview.PhotoViewAttacher.OnViewTapListener;
import android.content.Context;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.widget.ImageView;
public void setMaxScale(float maxScale) {
mAttacher.setMaxScale(maxScale);
}
@Override
// setImageBitmap calls through to this method
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setImageResource(int resId) {
super.setImageResource(resId);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override | public void setOnMatrixChangeListener(OnMatrixChangedListener listener) { |
jpush/jmessage-android-uikit | MultiSelectPhotos/src/main/java/cn/jmessage/android/uikit/multiselectphotos/photoview/PhotoView.java | // Path: MultiSelectPhotos/src/main/java/cn/jmessage/android/uikit/multiselectphotos/photoview/PhotoViewAttacher.java
// public static interface OnMatrixChangedListener {
// /**
// * Callback for when the Matrix displaying the Drawable has changed.
// * This could be because the View's bounds have changed, or the user has
// * zoomed.
// *
// * @param rect - Rectangle displaying the Drawable's new bounds.
// */
// void onMatrixChanged(RectF rect);
// }
//
// Path: MultiSelectPhotos/src/main/java/cn/jmessage/android/uikit/multiselectphotos/photoview/PhotoViewAttacher.java
// public static interface OnPhotoTapListener {
//
// /**
// * A callback to receive where the user taps on a photo. You will only
// * receive a callback if the user taps on the actual photo, tapping on
// * 'whitespace' will be ignored.
// *
// * @param view - View the user tapped.
// * @param x - where the user tapped from the of the Drawable, as
// * percentage of the Drawable width.
// * @param y - where the user tapped from the top of the Drawable, as
// * percentage of the Drawable height.
// */
// void onPhotoTap(View view, float x, float y);
// }
//
// Path: MultiSelectPhotos/src/main/java/cn/jmessage/android/uikit/multiselectphotos/photoview/PhotoViewAttacher.java
// public static interface OnViewTapListener {
//
// /**
// * A callback to receive where the user taps on a ImageView. You will
// * receive a callback if the user taps anywhere on the view, tapping on
// * 'whitespace' will not be ignored.
// *
// * @param view - View the user tapped.
// * @param x - where the user tapped from the left of the View.
// * @param y - where the user tapped from the top of the View.
// */
// void onViewTap(View view, float x, float y);
// }
| import cn.jmessage.android.uikit.multiselectphotos.photoview.PhotoViewAttacher.OnMatrixChangedListener;
import cn.jmessage.android.uikit.multiselectphotos.photoview.PhotoViewAttacher.OnPhotoTapListener;
import cn.jmessage.android.uikit.multiselectphotos.photoview.PhotoViewAttacher.OnViewTapListener;
import android.content.Context;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.widget.ImageView; | }
}
@Override
public void setImageResource(int resId) {
super.setImageResource(resId);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setOnMatrixChangeListener(OnMatrixChangedListener listener) {
mAttacher.setOnMatrixChangeListener(listener);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mAttacher.setOnLongClickListener(l);
}
@Override | // Path: MultiSelectPhotos/src/main/java/cn/jmessage/android/uikit/multiselectphotos/photoview/PhotoViewAttacher.java
// public static interface OnMatrixChangedListener {
// /**
// * Callback for when the Matrix displaying the Drawable has changed.
// * This could be because the View's bounds have changed, or the user has
// * zoomed.
// *
// * @param rect - Rectangle displaying the Drawable's new bounds.
// */
// void onMatrixChanged(RectF rect);
// }
//
// Path: MultiSelectPhotos/src/main/java/cn/jmessage/android/uikit/multiselectphotos/photoview/PhotoViewAttacher.java
// public static interface OnPhotoTapListener {
//
// /**
// * A callback to receive where the user taps on a photo. You will only
// * receive a callback if the user taps on the actual photo, tapping on
// * 'whitespace' will be ignored.
// *
// * @param view - View the user tapped.
// * @param x - where the user tapped from the of the Drawable, as
// * percentage of the Drawable width.
// * @param y - where the user tapped from the top of the Drawable, as
// * percentage of the Drawable height.
// */
// void onPhotoTap(View view, float x, float y);
// }
//
// Path: MultiSelectPhotos/src/main/java/cn/jmessage/android/uikit/multiselectphotos/photoview/PhotoViewAttacher.java
// public static interface OnViewTapListener {
//
// /**
// * A callback to receive where the user taps on a ImageView. You will
// * receive a callback if the user taps anywhere on the view, tapping on
// * 'whitespace' will not be ignored.
// *
// * @param view - View the user tapped.
// * @param x - where the user tapped from the left of the View.
// * @param y - where the user tapped from the top of the View.
// */
// void onViewTap(View view, float x, float y);
// }
// Path: MultiSelectPhotos/src/main/java/cn/jmessage/android/uikit/multiselectphotos/photoview/PhotoView.java
import cn.jmessage.android.uikit.multiselectphotos.photoview.PhotoViewAttacher.OnMatrixChangedListener;
import cn.jmessage.android.uikit.multiselectphotos.photoview.PhotoViewAttacher.OnPhotoTapListener;
import cn.jmessage.android.uikit.multiselectphotos.photoview.PhotoViewAttacher.OnViewTapListener;
import android.content.Context;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.widget.ImageView;
}
}
@Override
public void setImageResource(int resId) {
super.setImageResource(resId);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setOnMatrixChangeListener(OnMatrixChangedListener listener) {
mAttacher.setOnMatrixChangeListener(listener);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mAttacher.setOnLongClickListener(l);
}
@Override | public void setOnPhotoTapListener(OnPhotoTapListener listener) { |
jpush/jmessage-android-uikit | MultiSelectPhotos/src/main/java/cn/jmessage/android/uikit/multiselectphotos/photoview/PhotoView.java | // Path: MultiSelectPhotos/src/main/java/cn/jmessage/android/uikit/multiselectphotos/photoview/PhotoViewAttacher.java
// public static interface OnMatrixChangedListener {
// /**
// * Callback for when the Matrix displaying the Drawable has changed.
// * This could be because the View's bounds have changed, or the user has
// * zoomed.
// *
// * @param rect - Rectangle displaying the Drawable's new bounds.
// */
// void onMatrixChanged(RectF rect);
// }
//
// Path: MultiSelectPhotos/src/main/java/cn/jmessage/android/uikit/multiselectphotos/photoview/PhotoViewAttacher.java
// public static interface OnPhotoTapListener {
//
// /**
// * A callback to receive where the user taps on a photo. You will only
// * receive a callback if the user taps on the actual photo, tapping on
// * 'whitespace' will be ignored.
// *
// * @param view - View the user tapped.
// * @param x - where the user tapped from the of the Drawable, as
// * percentage of the Drawable width.
// * @param y - where the user tapped from the top of the Drawable, as
// * percentage of the Drawable height.
// */
// void onPhotoTap(View view, float x, float y);
// }
//
// Path: MultiSelectPhotos/src/main/java/cn/jmessage/android/uikit/multiselectphotos/photoview/PhotoViewAttacher.java
// public static interface OnViewTapListener {
//
// /**
// * A callback to receive where the user taps on a ImageView. You will
// * receive a callback if the user taps anywhere on the view, tapping on
// * 'whitespace' will not be ignored.
// *
// * @param view - View the user tapped.
// * @param x - where the user tapped from the left of the View.
// * @param y - where the user tapped from the top of the View.
// */
// void onViewTap(View view, float x, float y);
// }
| import cn.jmessage.android.uikit.multiselectphotos.photoview.PhotoViewAttacher.OnMatrixChangedListener;
import cn.jmessage.android.uikit.multiselectphotos.photoview.PhotoViewAttacher.OnPhotoTapListener;
import cn.jmessage.android.uikit.multiselectphotos.photoview.PhotoViewAttacher.OnViewTapListener;
import android.content.Context;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.widget.ImageView; | super.setImageResource(resId);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setOnMatrixChangeListener(OnMatrixChangedListener listener) {
mAttacher.setOnMatrixChangeListener(listener);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mAttacher.setOnLongClickListener(l);
}
@Override
public void setOnPhotoTapListener(OnPhotoTapListener listener) {
mAttacher.setOnPhotoTapListener(listener);
}
@Override | // Path: MultiSelectPhotos/src/main/java/cn/jmessage/android/uikit/multiselectphotos/photoview/PhotoViewAttacher.java
// public static interface OnMatrixChangedListener {
// /**
// * Callback for when the Matrix displaying the Drawable has changed.
// * This could be because the View's bounds have changed, or the user has
// * zoomed.
// *
// * @param rect - Rectangle displaying the Drawable's new bounds.
// */
// void onMatrixChanged(RectF rect);
// }
//
// Path: MultiSelectPhotos/src/main/java/cn/jmessage/android/uikit/multiselectphotos/photoview/PhotoViewAttacher.java
// public static interface OnPhotoTapListener {
//
// /**
// * A callback to receive where the user taps on a photo. You will only
// * receive a callback if the user taps on the actual photo, tapping on
// * 'whitespace' will be ignored.
// *
// * @param view - View the user tapped.
// * @param x - where the user tapped from the of the Drawable, as
// * percentage of the Drawable width.
// * @param y - where the user tapped from the top of the Drawable, as
// * percentage of the Drawable height.
// */
// void onPhotoTap(View view, float x, float y);
// }
//
// Path: MultiSelectPhotos/src/main/java/cn/jmessage/android/uikit/multiselectphotos/photoview/PhotoViewAttacher.java
// public static interface OnViewTapListener {
//
// /**
// * A callback to receive where the user taps on a ImageView. You will
// * receive a callback if the user taps anywhere on the view, tapping on
// * 'whitespace' will not be ignored.
// *
// * @param view - View the user tapped.
// * @param x - where the user tapped from the left of the View.
// * @param y - where the user tapped from the top of the View.
// */
// void onViewTap(View view, float x, float y);
// }
// Path: MultiSelectPhotos/src/main/java/cn/jmessage/android/uikit/multiselectphotos/photoview/PhotoView.java
import cn.jmessage.android.uikit.multiselectphotos.photoview.PhotoViewAttacher.OnMatrixChangedListener;
import cn.jmessage.android.uikit.multiselectphotos.photoview.PhotoViewAttacher.OnPhotoTapListener;
import cn.jmessage.android.uikit.multiselectphotos.photoview.PhotoViewAttacher.OnViewTapListener;
import android.content.Context;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.widget.ImageView;
super.setImageResource(resId);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setOnMatrixChangeListener(OnMatrixChangedListener listener) {
mAttacher.setOnMatrixChangeListener(listener);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mAttacher.setOnLongClickListener(l);
}
@Override
public void setOnPhotoTapListener(OnPhotoTapListener listener) {
mAttacher.setOnPhotoTapListener(listener);
}
@Override | public void setOnViewTapListener(OnViewTapListener listener) { |
jpush/jmessage-android-uikit | Chatting/src/cn/jmessage/android/uikit/chatting/photoview/PhotoView.java | // Path: Chatting/src/cn/jmessage/android/uikit/chatting/photoview/PhotoViewAttacher.java
// public static interface OnMatrixChangedListener {
// /**
// * Callback for when the Matrix displaying the Drawable has changed.
// * This could be because the View's bounds have changed, or the user has
// * zoomed.
// *
// * @param rect - Rectangle displaying the Drawable's new bounds.
// */
// void onMatrixChanged(RectF rect);
// }
//
// Path: Chatting/src/cn/jmessage/android/uikit/chatting/photoview/PhotoViewAttacher.java
// public static interface OnPhotoTapListener {
//
// /**
// * A callback to receive where the user taps on a photo. You will only
// * receive a callback if the user taps on the actual photo, tapping on
// * 'whitespace' will be ignored.
// *
// * @param view - View the user tapped.
// * @param x - where the user tapped from the of the Drawable, as
// * percentage of the Drawable width.
// * @param y - where the user tapped from the top of the Drawable, as
// * percentage of the Drawable height.
// */
// void onPhotoTap(View view, float x, float y);
// }
//
// Path: Chatting/src/cn/jmessage/android/uikit/chatting/photoview/PhotoViewAttacher.java
// public static interface OnViewTapListener {
//
// /**
// * A callback to receive where the user taps on a ImageView. You will
// * receive a callback if the user taps anywhere on the view, tapping on
// * 'whitespace' will not be ignored.
// *
// * @param view - View the user tapped.
// * @param x - where the user tapped from the left of the View.
// * @param y - where the user tapped from the top of the View.
// */
// void onViewTap(View view, float x, float y);
// }
| import cn.jmessage.android.uikit.chatting.photoview.PhotoViewAttacher.OnMatrixChangedListener;
import cn.jmessage.android.uikit.chatting.photoview.PhotoViewAttacher.OnPhotoTapListener;
import cn.jmessage.android.uikit.chatting.photoview.PhotoViewAttacher.OnViewTapListener;
import android.content.Context;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.widget.ImageView; | public void setMaxScale(float maxScale) {
mAttacher.setMaxScale(maxScale);
}
@Override
// setImageBitmap calls through to this method
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setImageResource(int resId) {
super.setImageResource(resId);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override | // Path: Chatting/src/cn/jmessage/android/uikit/chatting/photoview/PhotoViewAttacher.java
// public static interface OnMatrixChangedListener {
// /**
// * Callback for when the Matrix displaying the Drawable has changed.
// * This could be because the View's bounds have changed, or the user has
// * zoomed.
// *
// * @param rect - Rectangle displaying the Drawable's new bounds.
// */
// void onMatrixChanged(RectF rect);
// }
//
// Path: Chatting/src/cn/jmessage/android/uikit/chatting/photoview/PhotoViewAttacher.java
// public static interface OnPhotoTapListener {
//
// /**
// * A callback to receive where the user taps on a photo. You will only
// * receive a callback if the user taps on the actual photo, tapping on
// * 'whitespace' will be ignored.
// *
// * @param view - View the user tapped.
// * @param x - where the user tapped from the of the Drawable, as
// * percentage of the Drawable width.
// * @param y - where the user tapped from the top of the Drawable, as
// * percentage of the Drawable height.
// */
// void onPhotoTap(View view, float x, float y);
// }
//
// Path: Chatting/src/cn/jmessage/android/uikit/chatting/photoview/PhotoViewAttacher.java
// public static interface OnViewTapListener {
//
// /**
// * A callback to receive where the user taps on a ImageView. You will
// * receive a callback if the user taps anywhere on the view, tapping on
// * 'whitespace' will not be ignored.
// *
// * @param view - View the user tapped.
// * @param x - where the user tapped from the left of the View.
// * @param y - where the user tapped from the top of the View.
// */
// void onViewTap(View view, float x, float y);
// }
// Path: Chatting/src/cn/jmessage/android/uikit/chatting/photoview/PhotoView.java
import cn.jmessage.android.uikit.chatting.photoview.PhotoViewAttacher.OnMatrixChangedListener;
import cn.jmessage.android.uikit.chatting.photoview.PhotoViewAttacher.OnPhotoTapListener;
import cn.jmessage.android.uikit.chatting.photoview.PhotoViewAttacher.OnViewTapListener;
import android.content.Context;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.widget.ImageView;
public void setMaxScale(float maxScale) {
mAttacher.setMaxScale(maxScale);
}
@Override
// setImageBitmap calls through to this method
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setImageResource(int resId) {
super.setImageResource(resId);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override | public void setOnMatrixChangeListener(OnMatrixChangedListener listener) { |
jpush/jmessage-android-uikit | Chatting/src/cn/jmessage/android/uikit/chatting/photoview/PhotoView.java | // Path: Chatting/src/cn/jmessage/android/uikit/chatting/photoview/PhotoViewAttacher.java
// public static interface OnMatrixChangedListener {
// /**
// * Callback for when the Matrix displaying the Drawable has changed.
// * This could be because the View's bounds have changed, or the user has
// * zoomed.
// *
// * @param rect - Rectangle displaying the Drawable's new bounds.
// */
// void onMatrixChanged(RectF rect);
// }
//
// Path: Chatting/src/cn/jmessage/android/uikit/chatting/photoview/PhotoViewAttacher.java
// public static interface OnPhotoTapListener {
//
// /**
// * A callback to receive where the user taps on a photo. You will only
// * receive a callback if the user taps on the actual photo, tapping on
// * 'whitespace' will be ignored.
// *
// * @param view - View the user tapped.
// * @param x - where the user tapped from the of the Drawable, as
// * percentage of the Drawable width.
// * @param y - where the user tapped from the top of the Drawable, as
// * percentage of the Drawable height.
// */
// void onPhotoTap(View view, float x, float y);
// }
//
// Path: Chatting/src/cn/jmessage/android/uikit/chatting/photoview/PhotoViewAttacher.java
// public static interface OnViewTapListener {
//
// /**
// * A callback to receive where the user taps on a ImageView. You will
// * receive a callback if the user taps anywhere on the view, tapping on
// * 'whitespace' will not be ignored.
// *
// * @param view - View the user tapped.
// * @param x - where the user tapped from the left of the View.
// * @param y - where the user tapped from the top of the View.
// */
// void onViewTap(View view, float x, float y);
// }
| import cn.jmessage.android.uikit.chatting.photoview.PhotoViewAttacher.OnMatrixChangedListener;
import cn.jmessage.android.uikit.chatting.photoview.PhotoViewAttacher.OnPhotoTapListener;
import cn.jmessage.android.uikit.chatting.photoview.PhotoViewAttacher.OnViewTapListener;
import android.content.Context;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.widget.ImageView; | }
}
@Override
public void setImageResource(int resId) {
super.setImageResource(resId);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setOnMatrixChangeListener(OnMatrixChangedListener listener) {
mAttacher.setOnMatrixChangeListener(listener);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mAttacher.setOnLongClickListener(l);
}
@Override | // Path: Chatting/src/cn/jmessage/android/uikit/chatting/photoview/PhotoViewAttacher.java
// public static interface OnMatrixChangedListener {
// /**
// * Callback for when the Matrix displaying the Drawable has changed.
// * This could be because the View's bounds have changed, or the user has
// * zoomed.
// *
// * @param rect - Rectangle displaying the Drawable's new bounds.
// */
// void onMatrixChanged(RectF rect);
// }
//
// Path: Chatting/src/cn/jmessage/android/uikit/chatting/photoview/PhotoViewAttacher.java
// public static interface OnPhotoTapListener {
//
// /**
// * A callback to receive where the user taps on a photo. You will only
// * receive a callback if the user taps on the actual photo, tapping on
// * 'whitespace' will be ignored.
// *
// * @param view - View the user tapped.
// * @param x - where the user tapped from the of the Drawable, as
// * percentage of the Drawable width.
// * @param y - where the user tapped from the top of the Drawable, as
// * percentage of the Drawable height.
// */
// void onPhotoTap(View view, float x, float y);
// }
//
// Path: Chatting/src/cn/jmessage/android/uikit/chatting/photoview/PhotoViewAttacher.java
// public static interface OnViewTapListener {
//
// /**
// * A callback to receive where the user taps on a ImageView. You will
// * receive a callback if the user taps anywhere on the view, tapping on
// * 'whitespace' will not be ignored.
// *
// * @param view - View the user tapped.
// * @param x - where the user tapped from the left of the View.
// * @param y - where the user tapped from the top of the View.
// */
// void onViewTap(View view, float x, float y);
// }
// Path: Chatting/src/cn/jmessage/android/uikit/chatting/photoview/PhotoView.java
import cn.jmessage.android.uikit.chatting.photoview.PhotoViewAttacher.OnMatrixChangedListener;
import cn.jmessage.android.uikit.chatting.photoview.PhotoViewAttacher.OnPhotoTapListener;
import cn.jmessage.android.uikit.chatting.photoview.PhotoViewAttacher.OnViewTapListener;
import android.content.Context;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.widget.ImageView;
}
}
@Override
public void setImageResource(int resId) {
super.setImageResource(resId);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setOnMatrixChangeListener(OnMatrixChangedListener listener) {
mAttacher.setOnMatrixChangeListener(listener);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mAttacher.setOnLongClickListener(l);
}
@Override | public void setOnPhotoTapListener(OnPhotoTapListener listener) { |
jpush/jmessage-android-uikit | Chatting/src/cn/jmessage/android/uikit/chatting/photoview/PhotoView.java | // Path: Chatting/src/cn/jmessage/android/uikit/chatting/photoview/PhotoViewAttacher.java
// public static interface OnMatrixChangedListener {
// /**
// * Callback for when the Matrix displaying the Drawable has changed.
// * This could be because the View's bounds have changed, or the user has
// * zoomed.
// *
// * @param rect - Rectangle displaying the Drawable's new bounds.
// */
// void onMatrixChanged(RectF rect);
// }
//
// Path: Chatting/src/cn/jmessage/android/uikit/chatting/photoview/PhotoViewAttacher.java
// public static interface OnPhotoTapListener {
//
// /**
// * A callback to receive where the user taps on a photo. You will only
// * receive a callback if the user taps on the actual photo, tapping on
// * 'whitespace' will be ignored.
// *
// * @param view - View the user tapped.
// * @param x - where the user tapped from the of the Drawable, as
// * percentage of the Drawable width.
// * @param y - where the user tapped from the top of the Drawable, as
// * percentage of the Drawable height.
// */
// void onPhotoTap(View view, float x, float y);
// }
//
// Path: Chatting/src/cn/jmessage/android/uikit/chatting/photoview/PhotoViewAttacher.java
// public static interface OnViewTapListener {
//
// /**
// * A callback to receive where the user taps on a ImageView. You will
// * receive a callback if the user taps anywhere on the view, tapping on
// * 'whitespace' will not be ignored.
// *
// * @param view - View the user tapped.
// * @param x - where the user tapped from the left of the View.
// * @param y - where the user tapped from the top of the View.
// */
// void onViewTap(View view, float x, float y);
// }
| import cn.jmessage.android.uikit.chatting.photoview.PhotoViewAttacher.OnMatrixChangedListener;
import cn.jmessage.android.uikit.chatting.photoview.PhotoViewAttacher.OnPhotoTapListener;
import cn.jmessage.android.uikit.chatting.photoview.PhotoViewAttacher.OnViewTapListener;
import android.content.Context;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.widget.ImageView; | super.setImageResource(resId);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setOnMatrixChangeListener(OnMatrixChangedListener listener) {
mAttacher.setOnMatrixChangeListener(listener);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mAttacher.setOnLongClickListener(l);
}
@Override
public void setOnPhotoTapListener(OnPhotoTapListener listener) {
mAttacher.setOnPhotoTapListener(listener);
}
@Override | // Path: Chatting/src/cn/jmessage/android/uikit/chatting/photoview/PhotoViewAttacher.java
// public static interface OnMatrixChangedListener {
// /**
// * Callback for when the Matrix displaying the Drawable has changed.
// * This could be because the View's bounds have changed, or the user has
// * zoomed.
// *
// * @param rect - Rectangle displaying the Drawable's new bounds.
// */
// void onMatrixChanged(RectF rect);
// }
//
// Path: Chatting/src/cn/jmessage/android/uikit/chatting/photoview/PhotoViewAttacher.java
// public static interface OnPhotoTapListener {
//
// /**
// * A callback to receive where the user taps on a photo. You will only
// * receive a callback if the user taps on the actual photo, tapping on
// * 'whitespace' will be ignored.
// *
// * @param view - View the user tapped.
// * @param x - where the user tapped from the of the Drawable, as
// * percentage of the Drawable width.
// * @param y - where the user tapped from the top of the Drawable, as
// * percentage of the Drawable height.
// */
// void onPhotoTap(View view, float x, float y);
// }
//
// Path: Chatting/src/cn/jmessage/android/uikit/chatting/photoview/PhotoViewAttacher.java
// public static interface OnViewTapListener {
//
// /**
// * A callback to receive where the user taps on a ImageView. You will
// * receive a callback if the user taps anywhere on the view, tapping on
// * 'whitespace' will not be ignored.
// *
// * @param view - View the user tapped.
// * @param x - where the user tapped from the left of the View.
// * @param y - where the user tapped from the top of the View.
// */
// void onViewTap(View view, float x, float y);
// }
// Path: Chatting/src/cn/jmessage/android/uikit/chatting/photoview/PhotoView.java
import cn.jmessage.android.uikit.chatting.photoview.PhotoViewAttacher.OnMatrixChangedListener;
import cn.jmessage.android.uikit.chatting.photoview.PhotoViewAttacher.OnPhotoTapListener;
import cn.jmessage.android.uikit.chatting.photoview.PhotoViewAttacher.OnViewTapListener;
import android.content.Context;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.widget.ImageView;
super.setImageResource(resId);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setOnMatrixChangeListener(OnMatrixChangedListener listener) {
mAttacher.setOnMatrixChangeListener(listener);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mAttacher.setOnLongClickListener(l);
}
@Override
public void setOnPhotoTapListener(OnPhotoTapListener listener) {
mAttacher.setOnPhotoTapListener(listener);
}
@Override | public void setOnViewTapListener(OnViewTapListener listener) { |
jpush/jmessage-android-uikit | Chatting/src/cn/jmessage/android/uikit/chatting/shader/BubbleShader.java | // Path: Chatting/src/cn/jmessage/android/uikit/chatting/utils/IdHelper.java
// public class IdHelper {
//
// public static int getLayout(Context context, String layoutName) {
// return context.getResources().getIdentifier(layoutName, "layout",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getViewID(Context context, String IDName) {
// return context.getResources().getIdentifier(IDName, "id",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getDrawable(Context context, String drawableName) {
// return context.getResources().getIdentifier(drawableName, "drawable",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getAttr(Context context, String attrName) {
// return context.getResources().getIdentifier(attrName, "attr",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getString(Context context, String stringName) {
// return context.getResources().getIdentifier(stringName, "string",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getStyle(Context context, String styleName) {
// return context.getResources().getIdentifier(styleName, "style",
// context.getApplicationContext().getPackageName());
// }
//
// public static int[] getResourceDeclareStyleableIntArray(Context context, String name) {
// try {
// Field[] fields2 = Class.forName(context.getPackageName() + ".R$styleable").getFields();
//
// //browse all fields
// for (Field f : fields2) {
// //pick matching field
// if (f.getName().equals(name)) {
// //return as int array
// return (int[]) f.get(null);
// }
// }
// } catch (Throwable t) {
// t.printStackTrace();
// }
//
// return null;
// }
//
// public static int getAnim(Context context, String animName) {
// return context.getResources().getIdentifier(animName, "anim",
// context.getApplicationContext().getPackageName());
// }
// }
| import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import cn.jmessage.android.uikit.chatting.utils.IdHelper; | package cn.jmessage.android.uikit.chatting.shader;
/**
*The MIT License (MIT)
Copyright (c) 2015 Siyamed Sinir
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
public class BubbleShader extends ShaderHelper {
private static final int DEFAULT_HEIGHT_DP = 10;
private enum ArrowPosition {
@SuppressLint("RtlHardcoded")
LEFT,
RIGHT
}
private final Path path = new Path();
private int radius = 0;
private int triangleHeightPx;
private ArrowPosition arrowPosition = ArrowPosition.LEFT;
public BubbleShader() {
}
@Override
public void init(Context context, AttributeSet attrs, int defStyle) {
super.init(context, attrs, defStyle);
borderWidth = 0;
if (attrs != null) { | // Path: Chatting/src/cn/jmessage/android/uikit/chatting/utils/IdHelper.java
// public class IdHelper {
//
// public static int getLayout(Context context, String layoutName) {
// return context.getResources().getIdentifier(layoutName, "layout",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getViewID(Context context, String IDName) {
// return context.getResources().getIdentifier(IDName, "id",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getDrawable(Context context, String drawableName) {
// return context.getResources().getIdentifier(drawableName, "drawable",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getAttr(Context context, String attrName) {
// return context.getResources().getIdentifier(attrName, "attr",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getString(Context context, String stringName) {
// return context.getResources().getIdentifier(stringName, "string",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getStyle(Context context, String styleName) {
// return context.getResources().getIdentifier(styleName, "style",
// context.getApplicationContext().getPackageName());
// }
//
// public static int[] getResourceDeclareStyleableIntArray(Context context, String name) {
// try {
// Field[] fields2 = Class.forName(context.getPackageName() + ".R$styleable").getFields();
//
// //browse all fields
// for (Field f : fields2) {
// //pick matching field
// if (f.getName().equals(name)) {
// //return as int array
// return (int[]) f.get(null);
// }
// }
// } catch (Throwable t) {
// t.printStackTrace();
// }
//
// return null;
// }
//
// public static int getAnim(Context context, String animName) {
// return context.getResources().getIdentifier(animName, "anim",
// context.getApplicationContext().getPackageName());
// }
// }
// Path: Chatting/src/cn/jmessage/android/uikit/chatting/shader/BubbleShader.java
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import cn.jmessage.android.uikit.chatting.utils.IdHelper;
package cn.jmessage.android.uikit.chatting.shader;
/**
*The MIT License (MIT)
Copyright (c) 2015 Siyamed Sinir
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
public class BubbleShader extends ShaderHelper {
private static final int DEFAULT_HEIGHT_DP = 10;
private enum ArrowPosition {
@SuppressLint("RtlHardcoded")
LEFT,
RIGHT
}
private final Path path = new Path();
private int radius = 0;
private int triangleHeightPx;
private ArrowPosition arrowPosition = ArrowPosition.LEFT;
public BubbleShader() {
}
@Override
public void init(Context context, AttributeSet attrs, int defStyle) {
super.init(context, attrs, defStyle);
borderWidth = 0;
if (attrs != null) { | int[] declareStyleableArray = IdHelper.getResourceDeclareStyleableIntArray(context, "ShaderImageView"); |
jpush/jmessage-android-uikit | Chatting/src/cn/jmessage/android/uikit/chatting/shader/ShaderHelper.java | // Path: Chatting/src/cn/jmessage/android/uikit/chatting/utils/IdHelper.java
// public class IdHelper {
//
// public static int getLayout(Context context, String layoutName) {
// return context.getResources().getIdentifier(layoutName, "layout",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getViewID(Context context, String IDName) {
// return context.getResources().getIdentifier(IDName, "id",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getDrawable(Context context, String drawableName) {
// return context.getResources().getIdentifier(drawableName, "drawable",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getAttr(Context context, String attrName) {
// return context.getResources().getIdentifier(attrName, "attr",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getString(Context context, String stringName) {
// return context.getResources().getIdentifier(stringName, "string",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getStyle(Context context, String styleName) {
// return context.getResources().getIdentifier(styleName, "style",
// context.getApplicationContext().getPackageName());
// }
//
// public static int[] getResourceDeclareStyleableIntArray(Context context, String name) {
// try {
// Field[] fields2 = Class.forName(context.getPackageName() + ".R$styleable").getFields();
//
// //browse all fields
// for (Field f : fields2) {
// //pick matching field
// if (f.getName().equals(name)) {
// //return as int array
// return (int[]) f.get(null);
// }
// }
// } catch (Throwable t) {
// t.printStackTrace();
// }
//
// return null;
// }
//
// public static int getAnim(Context context, String animName) {
// return context.getResources().getIdentifier(animName, "anim",
// context.getApplicationContext().getPackageName());
// }
// }
| import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import cn.jmessage.android.uikit.R;
import cn.jmessage.android.uikit.chatting.utils.IdHelper; | protected BitmapShader shader;
protected Drawable drawable;
protected final Matrix matrix = new Matrix();
public ShaderHelper() {
borderPaint = new Paint();
borderPaint.setStyle(Paint.Style.STROKE);
borderPaint.setAntiAlias(true);
imagePaint = new Paint();
imagePaint.setAntiAlias(true);
}
public abstract void draw(Canvas canvas, Paint imagePaint, Paint borderPaint);
public abstract void reset();
@SuppressWarnings("UnusedParameters")
public abstract void calculate(int bitmapWidth, int bitmapHeight, float width, float height, float scale, float translateX, float translateY);
@SuppressWarnings("SameParameterValue")
protected final int dpToPx(DisplayMetrics displayMetrics, int dp) {
return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
}
public boolean isSquare() {
return square;
}
public void init(Context context, AttributeSet attrs, int defStyle) {
if(attrs != null){ | // Path: Chatting/src/cn/jmessage/android/uikit/chatting/utils/IdHelper.java
// public class IdHelper {
//
// public static int getLayout(Context context, String layoutName) {
// return context.getResources().getIdentifier(layoutName, "layout",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getViewID(Context context, String IDName) {
// return context.getResources().getIdentifier(IDName, "id",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getDrawable(Context context, String drawableName) {
// return context.getResources().getIdentifier(drawableName, "drawable",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getAttr(Context context, String attrName) {
// return context.getResources().getIdentifier(attrName, "attr",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getString(Context context, String stringName) {
// return context.getResources().getIdentifier(stringName, "string",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getStyle(Context context, String styleName) {
// return context.getResources().getIdentifier(styleName, "style",
// context.getApplicationContext().getPackageName());
// }
//
// public static int[] getResourceDeclareStyleableIntArray(Context context, String name) {
// try {
// Field[] fields2 = Class.forName(context.getPackageName() + ".R$styleable").getFields();
//
// //browse all fields
// for (Field f : fields2) {
// //pick matching field
// if (f.getName().equals(name)) {
// //return as int array
// return (int[]) f.get(null);
// }
// }
// } catch (Throwable t) {
// t.printStackTrace();
// }
//
// return null;
// }
//
// public static int getAnim(Context context, String animName) {
// return context.getResources().getIdentifier(animName, "anim",
// context.getApplicationContext().getPackageName());
// }
// }
// Path: Chatting/src/cn/jmessage/android/uikit/chatting/shader/ShaderHelper.java
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import cn.jmessage.android.uikit.R;
import cn.jmessage.android.uikit.chatting.utils.IdHelper;
protected BitmapShader shader;
protected Drawable drawable;
protected final Matrix matrix = new Matrix();
public ShaderHelper() {
borderPaint = new Paint();
borderPaint.setStyle(Paint.Style.STROKE);
borderPaint.setAntiAlias(true);
imagePaint = new Paint();
imagePaint.setAntiAlias(true);
}
public abstract void draw(Canvas canvas, Paint imagePaint, Paint borderPaint);
public abstract void reset();
@SuppressWarnings("UnusedParameters")
public abstract void calculate(int bitmapWidth, int bitmapHeight, float width, float height, float scale, float translateX, float translateY);
@SuppressWarnings("SameParameterValue")
protected final int dpToPx(DisplayMetrics displayMetrics, int dp) {
return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
}
public boolean isSquare() {
return square;
}
public void init(Context context, AttributeSet attrs, int defStyle) {
if(attrs != null){ | int[] declareStyleableArray = IdHelper.getResourceDeclareStyleableIntArray(context, "ShaderImageView"); |
jpush/jmessage-android-uikit | Chatting/src/cn/jmessage/android/uikit/chatting/DropDownListView.java | // Path: Chatting/src/cn/jmessage/android/uikit/chatting/utils/IdHelper.java
// public class IdHelper {
//
// public static int getLayout(Context context, String layoutName) {
// return context.getResources().getIdentifier(layoutName, "layout",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getViewID(Context context, String IDName) {
// return context.getResources().getIdentifier(IDName, "id",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getDrawable(Context context, String drawableName) {
// return context.getResources().getIdentifier(drawableName, "drawable",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getAttr(Context context, String attrName) {
// return context.getResources().getIdentifier(attrName, "attr",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getString(Context context, String stringName) {
// return context.getResources().getIdentifier(stringName, "string",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getStyle(Context context, String styleName) {
// return context.getResources().getIdentifier(styleName, "style",
// context.getApplicationContext().getPackageName());
// }
//
// public static int[] getResourceDeclareStyleableIntArray(Context context, String name) {
// try {
// Field[] fields2 = Class.forName(context.getPackageName() + ".R$styleable").getFields();
//
// //browse all fields
// for (Field f : fields2) {
// //pick matching field
// if (f.getName().equals(name)) {
// //return as int array
// return (int[]) f.get(null);
// }
// }
// } catch (Throwable t) {
// t.printStackTrace();
// }
//
// return null;
// }
//
// public static int getAnim(Context context, String animName) {
// return context.getResources().getIdentifier(animName, "anim",
// context.getApplicationContext().getPackageName());
// }
// }
| import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import cn.jmessage.android.uikit.chatting.utils.IdHelper; | super(context, attrs, defStyle);
getAttrs(context, attrs);
init(context);
}
private void init(Context context) {
this.context = context;
initDropDownStyle();
// should set, to run onScroll method and so on
super.setOnScrollListener(this);
}
/**
* init drop down style, only init once
*/
private void initDropDownStyle() {
if (headerLayout != null) {
if (isDropDownStyle) {
addHeaderView(headerLayout);
} else {
removeHeaderView(headerLayout);
}
return;
}
if (!isDropDownStyle) {
return;
}
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); | // Path: Chatting/src/cn/jmessage/android/uikit/chatting/utils/IdHelper.java
// public class IdHelper {
//
// public static int getLayout(Context context, String layoutName) {
// return context.getResources().getIdentifier(layoutName, "layout",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getViewID(Context context, String IDName) {
// return context.getResources().getIdentifier(IDName, "id",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getDrawable(Context context, String drawableName) {
// return context.getResources().getIdentifier(drawableName, "drawable",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getAttr(Context context, String attrName) {
// return context.getResources().getIdentifier(attrName, "attr",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getString(Context context, String stringName) {
// return context.getResources().getIdentifier(stringName, "string",
// context.getApplicationContext().getPackageName());
// }
//
// public static int getStyle(Context context, String styleName) {
// return context.getResources().getIdentifier(styleName, "style",
// context.getApplicationContext().getPackageName());
// }
//
// public static int[] getResourceDeclareStyleableIntArray(Context context, String name) {
// try {
// Field[] fields2 = Class.forName(context.getPackageName() + ".R$styleable").getFields();
//
// //browse all fields
// for (Field f : fields2) {
// //pick matching field
// if (f.getName().equals(name)) {
// //return as int array
// return (int[]) f.get(null);
// }
// }
// } catch (Throwable t) {
// t.printStackTrace();
// }
//
// return null;
// }
//
// public static int getAnim(Context context, String animName) {
// return context.getResources().getIdentifier(animName, "anim",
// context.getApplicationContext().getPackageName());
// }
// }
// Path: Chatting/src/cn/jmessage/android/uikit/chatting/DropDownListView.java
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import cn.jmessage.android.uikit.chatting.utils.IdHelper;
super(context, attrs, defStyle);
getAttrs(context, attrs);
init(context);
}
private void init(Context context) {
this.context = context;
initDropDownStyle();
// should set, to run onScroll method and so on
super.setOnScrollListener(this);
}
/**
* init drop down style, only init once
*/
private void initDropDownStyle() {
if (headerLayout != null) {
if (isDropDownStyle) {
addHeaderView(headerLayout);
} else {
removeHeaderView(headerLayout);
}
return;
}
if (!isDropDownStyle) {
return;
}
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); | headerLayout = (RelativeLayout) inflater.inflate(IdHelper.getLayout(context, "jmui_drop_down_list_header"), |
jpush/jmessage-android-uikit | MultiSelectPhotos/src/main/java/cn/jmessage/android/uikit/multiselectphotos/BrowserViewPagerActivity.java | // Path: MultiSelectPhotos/src/main/java/cn/jmessage/android/uikit/multiselectphotos/photoview/PhotoView.java
// public class PhotoView extends ImageView implements IPhotoView {
//
// private final PhotoViewAttacher mAttacher;
//
// private ScaleType mPendingScaleType;
//
// public PhotoView(Context context) {
// this(context, null);
// }
//
// public PhotoView(Context context, AttributeSet attr) {
// this(context, attr, 0);
// }
//
// public PhotoView(Context context, AttributeSet attr, int defStyle) {
// super(context, attr, defStyle);
// super.setScaleType(ScaleType.MATRIX);
// mAttacher = new PhotoViewAttacher(this, context);
//
// if (null != mPendingScaleType) {
// setScaleType(mPendingScaleType);
// mPendingScaleType = null;
// }
// }
//
// @Override
// public boolean canZoom() {
// return mAttacher.canZoom();
// }
//
// @Override
// public RectF getDisplayRect() {
// return mAttacher.getDisplayRect();
// }
//
// @Override
// public float getMinScale() {
// return mAttacher.getMinScale();
// }
//
// @Override
// public float getMidScale() {
// return mAttacher.getMidScale();
// }
//
// @Override
// public float getMaxScale() {
// return mAttacher.getMaxScale();
// }
//
// @Override
// public float getScale() {
// return mAttacher.getScale();
// }
//
// @Override
// public ScaleType getScaleType() {
// return mAttacher.getScaleType();
// }
//
// @Override
// public void setAllowParentInterceptOnEdge(boolean allow) {
// mAttacher.setAllowParentInterceptOnEdge(allow);
// }
//
// @Override
// public void setMinScale(float minScale) {
// mAttacher.setMinScale(minScale);
// }
//
// @Override
// public void setMidScale(float midScale) {
// mAttacher.setMidScale(midScale);
// }
//
// @Override
// public void setMaxScale(float maxScale) {
// mAttacher.setMaxScale(maxScale);
// }
//
// @Override
// // setImageBitmap calls through to this method
// public void setImageDrawable(Drawable drawable) {
// super.setImageDrawable(drawable);
// if (null != mAttacher) {
// mAttacher.update();
// }
// }
//
// @Override
// public void setImageResource(int resId) {
// super.setImageResource(resId);
// if (null != mAttacher) {
// mAttacher.update();
// }
// }
//
// @Override
// public void setImageURI(Uri uri) {
// super.setImageURI(uri);
// if (null != mAttacher) {
// mAttacher.update();
// }
// }
//
// @Override
// public void setOnMatrixChangeListener(OnMatrixChangedListener listener) {
// mAttacher.setOnMatrixChangeListener(listener);
// }
//
// @Override
// public void setOnLongClickListener(OnLongClickListener l) {
// mAttacher.setOnLongClickListener(l);
// }
//
// @Override
// public void setOnPhotoTapListener(OnPhotoTapListener listener) {
// mAttacher.setOnPhotoTapListener(listener);
// }
//
// @Override
// public void setOnViewTapListener(OnViewTapListener listener) {
// mAttacher.setOnViewTapListener(listener);
// }
//
// @Override
// public void setScaleType(ScaleType scaleType) {
// if (null != mAttacher) {
// mAttacher.setScaleType(scaleType);
// } else {
// mPendingScaleType = scaleType;
// }
// }
//
// @Override
// public void setZoomable(boolean zoomable) {
// mAttacher.setZoomable(zoomable);
// }
//
// @Override
// public void zoomTo(float scale, float focalX, float focalY) {
// mAttacher.zoomTo(scale, focalX, focalY);
// }
//
// @Override
// protected void onDetachedFromWindow() {
// mAttacher.cleanup();
// super.onDetachedFromWindow();
// }
//
// }
| import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.CompoundButton;
import android.widget.Toast;
import cn.jmessage.android.uikit.R;
import cn.jmessage.android.uikit.multiselectphotos.photoview.PhotoView;
import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List; | package cn.jmessage.android.uikit.multiselectphotos;
//用于浏览图片
public class BrowserViewPagerActivity extends BaseActivity implements OnClickListener, CompoundButton.OnCheckedChangeListener {
private static String TAG = BrowserViewPagerActivity.class.getSimpleName();
private BrowserView mBrowserView; | // Path: MultiSelectPhotos/src/main/java/cn/jmessage/android/uikit/multiselectphotos/photoview/PhotoView.java
// public class PhotoView extends ImageView implements IPhotoView {
//
// private final PhotoViewAttacher mAttacher;
//
// private ScaleType mPendingScaleType;
//
// public PhotoView(Context context) {
// this(context, null);
// }
//
// public PhotoView(Context context, AttributeSet attr) {
// this(context, attr, 0);
// }
//
// public PhotoView(Context context, AttributeSet attr, int defStyle) {
// super(context, attr, defStyle);
// super.setScaleType(ScaleType.MATRIX);
// mAttacher = new PhotoViewAttacher(this, context);
//
// if (null != mPendingScaleType) {
// setScaleType(mPendingScaleType);
// mPendingScaleType = null;
// }
// }
//
// @Override
// public boolean canZoom() {
// return mAttacher.canZoom();
// }
//
// @Override
// public RectF getDisplayRect() {
// return mAttacher.getDisplayRect();
// }
//
// @Override
// public float getMinScale() {
// return mAttacher.getMinScale();
// }
//
// @Override
// public float getMidScale() {
// return mAttacher.getMidScale();
// }
//
// @Override
// public float getMaxScale() {
// return mAttacher.getMaxScale();
// }
//
// @Override
// public float getScale() {
// return mAttacher.getScale();
// }
//
// @Override
// public ScaleType getScaleType() {
// return mAttacher.getScaleType();
// }
//
// @Override
// public void setAllowParentInterceptOnEdge(boolean allow) {
// mAttacher.setAllowParentInterceptOnEdge(allow);
// }
//
// @Override
// public void setMinScale(float minScale) {
// mAttacher.setMinScale(minScale);
// }
//
// @Override
// public void setMidScale(float midScale) {
// mAttacher.setMidScale(midScale);
// }
//
// @Override
// public void setMaxScale(float maxScale) {
// mAttacher.setMaxScale(maxScale);
// }
//
// @Override
// // setImageBitmap calls through to this method
// public void setImageDrawable(Drawable drawable) {
// super.setImageDrawable(drawable);
// if (null != mAttacher) {
// mAttacher.update();
// }
// }
//
// @Override
// public void setImageResource(int resId) {
// super.setImageResource(resId);
// if (null != mAttacher) {
// mAttacher.update();
// }
// }
//
// @Override
// public void setImageURI(Uri uri) {
// super.setImageURI(uri);
// if (null != mAttacher) {
// mAttacher.update();
// }
// }
//
// @Override
// public void setOnMatrixChangeListener(OnMatrixChangedListener listener) {
// mAttacher.setOnMatrixChangeListener(listener);
// }
//
// @Override
// public void setOnLongClickListener(OnLongClickListener l) {
// mAttacher.setOnLongClickListener(l);
// }
//
// @Override
// public void setOnPhotoTapListener(OnPhotoTapListener listener) {
// mAttacher.setOnPhotoTapListener(listener);
// }
//
// @Override
// public void setOnViewTapListener(OnViewTapListener listener) {
// mAttacher.setOnViewTapListener(listener);
// }
//
// @Override
// public void setScaleType(ScaleType scaleType) {
// if (null != mAttacher) {
// mAttacher.setScaleType(scaleType);
// } else {
// mPendingScaleType = scaleType;
// }
// }
//
// @Override
// public void setZoomable(boolean zoomable) {
// mAttacher.setZoomable(zoomable);
// }
//
// @Override
// public void zoomTo(float scale, float focalX, float focalY) {
// mAttacher.zoomTo(scale, focalX, focalY);
// }
//
// @Override
// protected void onDetachedFromWindow() {
// mAttacher.cleanup();
// super.onDetachedFromWindow();
// }
//
// }
// Path: MultiSelectPhotos/src/main/java/cn/jmessage/android/uikit/multiselectphotos/BrowserViewPagerActivity.java
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.CompoundButton;
import android.widget.Toast;
import cn.jmessage.android.uikit.R;
import cn.jmessage.android.uikit.multiselectphotos.photoview.PhotoView;
import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
package cn.jmessage.android.uikit.multiselectphotos;
//用于浏览图片
public class BrowserViewPagerActivity extends BaseActivity implements OnClickListener, CompoundButton.OnCheckedChangeListener {
private static String TAG = BrowserViewPagerActivity.class.getSimpleName();
private BrowserView mBrowserView; | private PhotoView photoView; |
jchambers/jvptree | src/benchmark/java/com/eatthepath/jvptree/VPTreeQueryBenchmark.java | // Path: src/main/java/com/eatthepath/jvptree/util/SamplingMedianDistanceThresholdSelectionStrategy.java
// public class SamplingMedianDistanceThresholdSelectionStrategy<P, E extends P> extends MedianDistanceThresholdSelectionStrategy<P, E> implements ThresholdSelectionStrategy<P, E> {
//
// private final int numberOfSamples;
//
// public static final int DEFAULT_NUMBER_OF_SAMPLES = 32;
//
// /**
// * Constructs a threshold selector that uses up to a default ({@value DEFAULT_NUMBER_OF_SAMPLES}) number of samples
// * from a list of points to choose a median distance.
// */
// public SamplingMedianDistanceThresholdSelectionStrategy() {
// this(DEFAULT_NUMBER_OF_SAMPLES);
// }
//
// /**
// * Constructs a threshold selector that uses up to the given number of samples from a list of points to choose a
// * median distance.
// *
// * @param numberOfSamples the maximum number of samples to use when choosing a median distance
// */
// public SamplingMedianDistanceThresholdSelectionStrategy(final int numberOfSamples) {
// this.numberOfSamples = numberOfSamples;
// }
//
// /**
// * Returns the median distance of a subset of the given points from the given origin. The given list of points may
// * be partially sorted in the process.
// *
// * @param points the list of points from which a median distance will be chosen
// * @param origin the point from which distances to other points will be calculated
// * @param distanceFunction the function to be used to calculate the distance between the origin and other points
// *
// * @return the median distance from the origin to the given list of points
// */
// @Override
// public double selectThreshold(final List<E> points, final P origin, final DistanceFunction<P> distanceFunction) {
// return super.selectThreshold(this.getSampledPoints(points), origin, distanceFunction);
// }
//
// /**
// * Chooses a subset of points from which to calculate a median by sampling the given list.
// *
// * @param points the points from which to choose a subset of points
// *
// * @return a list containing at most the number of points chosen at construction time
// */
// List<E> getSampledPoints(final List<E> points) {
// final List<E> sampledPoints;
//
// if (points.size() > this.numberOfSamples) {
// sampledPoints = new ArrayList<>(this.numberOfSamples);
// final int step = points.size() / this.numberOfSamples;
//
// for (int i = 0; i < this.numberOfSamples; i++) {
// sampledPoints.add(points.get(i * step));
// }
// } else {
// sampledPoints = points;
// }
//
// return sampledPoints;
// }
// }
| import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import com.eatthepath.jvptree.util.SamplingMedianDistanceThresholdSelectionStrategy; | package com.eatthepath.jvptree;
@State(Scope.Thread)
public class VPTreeQueryBenchmark {
@Param({"100000"})
public int pointCount;
@Param({"2", "16", "128"})
public int nodeSize;
@Param({"2", "16", "128"})
public int resultSetSize;
private List<CartesianPoint> points;
private VPTree<CartesianPoint, CartesianPoint> vptree;
private final Random random = new Random();
private final CartesianDistanceFunction distanceFunction = new CartesianDistanceFunction();
@Setup
public void setUp() {
this.points = new ArrayList<>(this.pointCount);
for (int i = 0; i < this.pointCount; i++) {
this.points.add(this.createRandomPoint());
}
this.vptree = new VPTree<>(this.distanceFunction, | // Path: src/main/java/com/eatthepath/jvptree/util/SamplingMedianDistanceThresholdSelectionStrategy.java
// public class SamplingMedianDistanceThresholdSelectionStrategy<P, E extends P> extends MedianDistanceThresholdSelectionStrategy<P, E> implements ThresholdSelectionStrategy<P, E> {
//
// private final int numberOfSamples;
//
// public static final int DEFAULT_NUMBER_OF_SAMPLES = 32;
//
// /**
// * Constructs a threshold selector that uses up to a default ({@value DEFAULT_NUMBER_OF_SAMPLES}) number of samples
// * from a list of points to choose a median distance.
// */
// public SamplingMedianDistanceThresholdSelectionStrategy() {
// this(DEFAULT_NUMBER_OF_SAMPLES);
// }
//
// /**
// * Constructs a threshold selector that uses up to the given number of samples from a list of points to choose a
// * median distance.
// *
// * @param numberOfSamples the maximum number of samples to use when choosing a median distance
// */
// public SamplingMedianDistanceThresholdSelectionStrategy(final int numberOfSamples) {
// this.numberOfSamples = numberOfSamples;
// }
//
// /**
// * Returns the median distance of a subset of the given points from the given origin. The given list of points may
// * be partially sorted in the process.
// *
// * @param points the list of points from which a median distance will be chosen
// * @param origin the point from which distances to other points will be calculated
// * @param distanceFunction the function to be used to calculate the distance between the origin and other points
// *
// * @return the median distance from the origin to the given list of points
// */
// @Override
// public double selectThreshold(final List<E> points, final P origin, final DistanceFunction<P> distanceFunction) {
// return super.selectThreshold(this.getSampledPoints(points), origin, distanceFunction);
// }
//
// /**
// * Chooses a subset of points from which to calculate a median by sampling the given list.
// *
// * @param points the points from which to choose a subset of points
// *
// * @return a list containing at most the number of points chosen at construction time
// */
// List<E> getSampledPoints(final List<E> points) {
// final List<E> sampledPoints;
//
// if (points.size() > this.numberOfSamples) {
// sampledPoints = new ArrayList<>(this.numberOfSamples);
// final int step = points.size() / this.numberOfSamples;
//
// for (int i = 0; i < this.numberOfSamples; i++) {
// sampledPoints.add(points.get(i * step));
// }
// } else {
// sampledPoints = points;
// }
//
// return sampledPoints;
// }
// }
// Path: src/benchmark/java/com/eatthepath/jvptree/VPTreeQueryBenchmark.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import com.eatthepath.jvptree.util.SamplingMedianDistanceThresholdSelectionStrategy;
package com.eatthepath.jvptree;
@State(Scope.Thread)
public class VPTreeQueryBenchmark {
@Param({"100000"})
public int pointCount;
@Param({"2", "16", "128"})
public int nodeSize;
@Param({"2", "16", "128"})
public int resultSetSize;
private List<CartesianPoint> points;
private VPTree<CartesianPoint, CartesianPoint> vptree;
private final Random random = new Random();
private final CartesianDistanceFunction distanceFunction = new CartesianDistanceFunction();
@Setup
public void setUp() {
this.points = new ArrayList<>(this.pointCount);
for (int i = 0; i < this.pointCount; i++) {
this.points.add(this.createRandomPoint());
}
this.vptree = new VPTree<>(this.distanceFunction, | new SamplingMedianDistanceThresholdSelectionStrategy<CartesianPoint, CartesianPoint>(32), |
jchambers/jvptree | src/main/java/com/eatthepath/jvptree/util/SamplingMedianDistanceThresholdSelectionStrategy.java | // Path: src/main/java/com/eatthepath/jvptree/DistanceFunction.java
// public interface DistanceFunction<T> {
//
// /**
// * Returns the distance between two points.
// *
// * @param firstPoint the first point
// * @param secondPoint the second point
// *
// * @return the distance between the two points
// */
// double getDistance(T firstPoint, T secondPoint);
// }
//
// Path: src/main/java/com/eatthepath/jvptree/ThresholdSelectionStrategy.java
// public interface ThresholdSelectionStrategy<P, E extends P> {
//
// /**
// * Chooses a partitioning distance threshold appropriate for the given list of points. Implementations are allowed to
// * reorder the list of points, but must not add or remove points from the list.
// *
// * @param points the points for which to choose a partitioning distance threshold
// * @param origin the point from which the threshold distances should be calculated
// * @param distanceFunction the function to be used to calculate distances between points
// *
// * @return a partitioning threshold distance appropriate for the given list of points; ideally, some points should
// * be closer to the origin than the returned threshold, and some should be farther
// */
// double selectThreshold(List<E> points, P origin, DistanceFunction<P> distanceFunction);
// }
| import java.util.ArrayList;
import java.util.List;
import com.eatthepath.jvptree.DistanceFunction;
import com.eatthepath.jvptree.ThresholdSelectionStrategy; | package com.eatthepath.jvptree.util;
/**
* A threshold distance selection strategy that uses the median distance from the origin to a subset of the given list
* of points as the threshold.
*
* @author <a href="https://github.com/jchambers">Jon Chambers</a>
*/
public class SamplingMedianDistanceThresholdSelectionStrategy<P, E extends P> extends MedianDistanceThresholdSelectionStrategy<P, E> implements ThresholdSelectionStrategy<P, E> {
private final int numberOfSamples;
public static final int DEFAULT_NUMBER_OF_SAMPLES = 32;
/**
* Constructs a threshold selector that uses up to a default ({@value DEFAULT_NUMBER_OF_SAMPLES}) number of samples
* from a list of points to choose a median distance.
*/
public SamplingMedianDistanceThresholdSelectionStrategy() {
this(DEFAULT_NUMBER_OF_SAMPLES);
}
/**
* Constructs a threshold selector that uses up to the given number of samples from a list of points to choose a
* median distance.
*
* @param numberOfSamples the maximum number of samples to use when choosing a median distance
*/
public SamplingMedianDistanceThresholdSelectionStrategy(final int numberOfSamples) {
this.numberOfSamples = numberOfSamples;
}
/**
* Returns the median distance of a subset of the given points from the given origin. The given list of points may
* be partially sorted in the process.
*
* @param points the list of points from which a median distance will be chosen
* @param origin the point from which distances to other points will be calculated
* @param distanceFunction the function to be used to calculate the distance between the origin and other points
*
* @return the median distance from the origin to the given list of points
*/
@Override | // Path: src/main/java/com/eatthepath/jvptree/DistanceFunction.java
// public interface DistanceFunction<T> {
//
// /**
// * Returns the distance between two points.
// *
// * @param firstPoint the first point
// * @param secondPoint the second point
// *
// * @return the distance between the two points
// */
// double getDistance(T firstPoint, T secondPoint);
// }
//
// Path: src/main/java/com/eatthepath/jvptree/ThresholdSelectionStrategy.java
// public interface ThresholdSelectionStrategy<P, E extends P> {
//
// /**
// * Chooses a partitioning distance threshold appropriate for the given list of points. Implementations are allowed to
// * reorder the list of points, but must not add or remove points from the list.
// *
// * @param points the points for which to choose a partitioning distance threshold
// * @param origin the point from which the threshold distances should be calculated
// * @param distanceFunction the function to be used to calculate distances between points
// *
// * @return a partitioning threshold distance appropriate for the given list of points; ideally, some points should
// * be closer to the origin than the returned threshold, and some should be farther
// */
// double selectThreshold(List<E> points, P origin, DistanceFunction<P> distanceFunction);
// }
// Path: src/main/java/com/eatthepath/jvptree/util/SamplingMedianDistanceThresholdSelectionStrategy.java
import java.util.ArrayList;
import java.util.List;
import com.eatthepath.jvptree.DistanceFunction;
import com.eatthepath.jvptree.ThresholdSelectionStrategy;
package com.eatthepath.jvptree.util;
/**
* A threshold distance selection strategy that uses the median distance from the origin to a subset of the given list
* of points as the threshold.
*
* @author <a href="https://github.com/jchambers">Jon Chambers</a>
*/
public class SamplingMedianDistanceThresholdSelectionStrategy<P, E extends P> extends MedianDistanceThresholdSelectionStrategy<P, E> implements ThresholdSelectionStrategy<P, E> {
private final int numberOfSamples;
public static final int DEFAULT_NUMBER_OF_SAMPLES = 32;
/**
* Constructs a threshold selector that uses up to a default ({@value DEFAULT_NUMBER_OF_SAMPLES}) number of samples
* from a list of points to choose a median distance.
*/
public SamplingMedianDistanceThresholdSelectionStrategy() {
this(DEFAULT_NUMBER_OF_SAMPLES);
}
/**
* Constructs a threshold selector that uses up to the given number of samples from a list of points to choose a
* median distance.
*
* @param numberOfSamples the maximum number of samples to use when choosing a median distance
*/
public SamplingMedianDistanceThresholdSelectionStrategy(final int numberOfSamples) {
this.numberOfSamples = numberOfSamples;
}
/**
* Returns the median distance of a subset of the given points from the given origin. The given list of points may
* be partially sorted in the process.
*
* @param points the list of points from which a median distance will be chosen
* @param origin the point from which distances to other points will be calculated
* @param distanceFunction the function to be used to calculate the distance between the origin and other points
*
* @return the median distance from the origin to the given list of points
*/
@Override | public double selectThreshold(final List<E> points, final P origin, final DistanceFunction<P> distanceFunction) { |
jchambers/jvptree | src/test/java/com/eatthepath/jvptree/VPTreeNodeTest.java | // Path: src/main/java/com/eatthepath/jvptree/util/MedianDistanceThresholdSelectionStrategy.java
// public class MedianDistanceThresholdSelectionStrategy<P, E extends P> implements ThresholdSelectionStrategy<P, E> {
//
// /**
// * Returns the median distance of the given points from the given origin. This method will partially sort the list
// * of points in the process.
// *
// * @param points the list of points from which a median distance will be chosen
// * @param origin the point from which distances to other points will be calculated
// * @param distanceFunction the function to be used to calculate the distance between the origin and other points
// *
// * @return the median distance from the origin to the given list of points
// *
// * @throws IllegalArgumentException if the given list of points is empty
// */
// public double selectThreshold(final List<E> points, final P origin, final DistanceFunction<P> distanceFunction) {
// if (points.isEmpty()) {
// throw new IllegalArgumentException("Point list must not be empty.");
// }
//
// int left = 0;
// int right = points.size() - 1;
//
// final int medianIndex = points.size() / 2;
// final Random random = new Random();
//
// // The strategy here is to use quickselect (https://en.wikipedia.org/wiki/Quickselect) to recursively partition
// // the parts of a list on one side of a pivot, working our way toward the center of the list.
// while (left != right) {
// final int pivotIndex = left + (right - left == 0 ? 0 : random.nextInt(right - left));
// final double pivotDistance = distanceFunction.getDistance(origin, points.get(pivotIndex));
//
// // Temporarily move the pivot point all the way out to the end of this section of the list
// java.util.Collections.swap(points, pivotIndex, right);
//
// int storeIndex = left;
//
// for (int i = left; i < right; i++) {
// if (distanceFunction.getDistance(origin, points.get(i)) < pivotDistance) {
// java.util.Collections.swap(points, storeIndex++, i);
// }
// }
//
// // ...and now bring that original pivot point back to its rightful place.
// java.util.Collections.swap(points, right, storeIndex);
//
// if (storeIndex == medianIndex) {
// // Mission accomplished; we've placed the point that should rightfully be at the median index
// break;
// } else if (storeIndex < medianIndex) {
// // We need to work on the section of the list to the right of the pivot
// left = storeIndex + 1;
// } else {
// // We need to work on the section of the list to the left of the pivot
// right = storeIndex - 1;
// }
// }
//
// return distanceFunction.getDistance(origin, points.get(medianIndex));
// }
// }
| import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import com.eatthepath.jvptree.util.MedianDistanceThresholdSelectionStrategy;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*; | package com.eatthepath.jvptree;
public class VPTreeNodeTest {
private static final int TEST_NODE_SIZE = 32;
private static final PointFilter<Object> NO_OP_POINT_FILTER = point -> true;
@Test
void testVPNodeNoPoints() {
assertThrows(IllegalArgumentException.class,
() -> new VPTreeNode<>(new ArrayList<Integer>(), new IntegerDistanceFunction(), | // Path: src/main/java/com/eatthepath/jvptree/util/MedianDistanceThresholdSelectionStrategy.java
// public class MedianDistanceThresholdSelectionStrategy<P, E extends P> implements ThresholdSelectionStrategy<P, E> {
//
// /**
// * Returns the median distance of the given points from the given origin. This method will partially sort the list
// * of points in the process.
// *
// * @param points the list of points from which a median distance will be chosen
// * @param origin the point from which distances to other points will be calculated
// * @param distanceFunction the function to be used to calculate the distance between the origin and other points
// *
// * @return the median distance from the origin to the given list of points
// *
// * @throws IllegalArgumentException if the given list of points is empty
// */
// public double selectThreshold(final List<E> points, final P origin, final DistanceFunction<P> distanceFunction) {
// if (points.isEmpty()) {
// throw new IllegalArgumentException("Point list must not be empty.");
// }
//
// int left = 0;
// int right = points.size() - 1;
//
// final int medianIndex = points.size() / 2;
// final Random random = new Random();
//
// // The strategy here is to use quickselect (https://en.wikipedia.org/wiki/Quickselect) to recursively partition
// // the parts of a list on one side of a pivot, working our way toward the center of the list.
// while (left != right) {
// final int pivotIndex = left + (right - left == 0 ? 0 : random.nextInt(right - left));
// final double pivotDistance = distanceFunction.getDistance(origin, points.get(pivotIndex));
//
// // Temporarily move the pivot point all the way out to the end of this section of the list
// java.util.Collections.swap(points, pivotIndex, right);
//
// int storeIndex = left;
//
// for (int i = left; i < right; i++) {
// if (distanceFunction.getDistance(origin, points.get(i)) < pivotDistance) {
// java.util.Collections.swap(points, storeIndex++, i);
// }
// }
//
// // ...and now bring that original pivot point back to its rightful place.
// java.util.Collections.swap(points, right, storeIndex);
//
// if (storeIndex == medianIndex) {
// // Mission accomplished; we've placed the point that should rightfully be at the median index
// break;
// } else if (storeIndex < medianIndex) {
// // We need to work on the section of the list to the right of the pivot
// left = storeIndex + 1;
// } else {
// // We need to work on the section of the list to the left of the pivot
// right = storeIndex - 1;
// }
// }
//
// return distanceFunction.getDistance(origin, points.get(medianIndex));
// }
// }
// Path: src/test/java/com/eatthepath/jvptree/VPTreeNodeTest.java
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import com.eatthepath.jvptree.util.MedianDistanceThresholdSelectionStrategy;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
package com.eatthepath.jvptree;
public class VPTreeNodeTest {
private static final int TEST_NODE_SIZE = 32;
private static final PointFilter<Object> NO_OP_POINT_FILTER = point -> true;
@Test
void testVPNodeNoPoints() {
assertThrows(IllegalArgumentException.class,
() -> new VPTreeNode<>(new ArrayList<Integer>(), new IntegerDistanceFunction(), | new MedianDistanceThresholdSelectionStrategy<>(), VPTree.DEFAULT_NODE_CAPACITY)); |
jchambers/jvptree | src/test/java/com/eatthepath/jvptree/util/MedianDistanceThresholdSelectionStrategyTest.java | // Path: src/test/java/com/eatthepath/jvptree/IntegerDistanceFunction.java
// public class IntegerDistanceFunction implements DistanceFunction<Number> {
//
// public double getDistance(final Number firstPoint, final Number secondPoint) {
// return Math.abs(firstPoint.intValue() - secondPoint.intValue());
// }
// }
| import java.util.ArrayList;
import java.util.List;
import com.eatthepath.jvptree.IntegerDistanceFunction;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows; | package com.eatthepath.jvptree.util;
public class MedianDistanceThresholdSelectionStrategyTest {
@Test
void testSelectThreshold() {
final MedianDistanceThresholdSelectionStrategy<Number, Integer> strategy =
new MedianDistanceThresholdSelectionStrategy<>();
{
final List<Integer> singleIntegerList = new ArrayList<>();
singleIntegerList.add(7);
| // Path: src/test/java/com/eatthepath/jvptree/IntegerDistanceFunction.java
// public class IntegerDistanceFunction implements DistanceFunction<Number> {
//
// public double getDistance(final Number firstPoint, final Number secondPoint) {
// return Math.abs(firstPoint.intValue() - secondPoint.intValue());
// }
// }
// Path: src/test/java/com/eatthepath/jvptree/util/MedianDistanceThresholdSelectionStrategyTest.java
import java.util.ArrayList;
import java.util.List;
import com.eatthepath.jvptree.IntegerDistanceFunction;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
package com.eatthepath.jvptree.util;
public class MedianDistanceThresholdSelectionStrategyTest {
@Test
void testSelectThreshold() {
final MedianDistanceThresholdSelectionStrategy<Number, Integer> strategy =
new MedianDistanceThresholdSelectionStrategy<>();
{
final List<Integer> singleIntegerList = new ArrayList<>();
singleIntegerList.add(7);
| assertEquals(7, (int)strategy.selectThreshold(singleIntegerList, 0, new IntegerDistanceFunction())); |
jchambers/jvptree | src/main/java/com/eatthepath/jvptree/VPTree.java | // Path: src/main/java/com/eatthepath/jvptree/util/SamplingMedianDistanceThresholdSelectionStrategy.java
// public class SamplingMedianDistanceThresholdSelectionStrategy<P, E extends P> extends MedianDistanceThresholdSelectionStrategy<P, E> implements ThresholdSelectionStrategy<P, E> {
//
// private final int numberOfSamples;
//
// public static final int DEFAULT_NUMBER_OF_SAMPLES = 32;
//
// /**
// * Constructs a threshold selector that uses up to a default ({@value DEFAULT_NUMBER_OF_SAMPLES}) number of samples
// * from a list of points to choose a median distance.
// */
// public SamplingMedianDistanceThresholdSelectionStrategy() {
// this(DEFAULT_NUMBER_OF_SAMPLES);
// }
//
// /**
// * Constructs a threshold selector that uses up to the given number of samples from a list of points to choose a
// * median distance.
// *
// * @param numberOfSamples the maximum number of samples to use when choosing a median distance
// */
// public SamplingMedianDistanceThresholdSelectionStrategy(final int numberOfSamples) {
// this.numberOfSamples = numberOfSamples;
// }
//
// /**
// * Returns the median distance of a subset of the given points from the given origin. The given list of points may
// * be partially sorted in the process.
// *
// * @param points the list of points from which a median distance will be chosen
// * @param origin the point from which distances to other points will be calculated
// * @param distanceFunction the function to be used to calculate the distance between the origin and other points
// *
// * @return the median distance from the origin to the given list of points
// */
// @Override
// public double selectThreshold(final List<E> points, final P origin, final DistanceFunction<P> distanceFunction) {
// return super.selectThreshold(this.getSampledPoints(points), origin, distanceFunction);
// }
//
// /**
// * Chooses a subset of points from which to calculate a median by sampling the given list.
// *
// * @param points the points from which to choose a subset of points
// *
// * @return a list containing at most the number of points chosen at construction time
// */
// List<E> getSampledPoints(final List<E> points) {
// final List<E> sampledPoints;
//
// if (points.size() > this.numberOfSamples) {
// sampledPoints = new ArrayList<>(this.numberOfSamples);
// final int step = points.size() / this.numberOfSamples;
//
// for (int i = 0; i < this.numberOfSamples; i++) {
// sampledPoints.add(points.get(i * step));
// }
// } else {
// sampledPoints = points;
// }
//
// return sampledPoints;
// }
// }
| import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import com.eatthepath.jvptree.util.SamplingMedianDistanceThresholdSelectionStrategy; | package com.eatthepath.jvptree;
/**
* <p>A vantage-point tree (or vp-tree) is a binary space partitioning collection of points in a metric space. The main
* feature of vantage point trees is that they allow for k-nearest-neighbor searches in any metric space in
* <em>O(log(n))</em> time.</p>
*
* <p>Vantage point trees recursively partition points by choosing a "vantage point" and a distance threshold;
* points are then partitioned into one collection that contains all of the points closer to the vantage point than the
* chosen threshold and one collection that contains all of the points farther away than the chosen threshold.</p>
*
* <p>A {@linkplain DistanceFunction distance function} that satisfies the properties of a metric space must be provided
* when constructing a vantage point tree. Callers may also specify a threshold selection strategy (a sampling median
* strategy is used by default) and a node size to tune the ratio of nodes searched to points inspected per node.
* Vantage point trees may be constructed with or without an initial collection of points, though specifying a
* collection of points at construction time is the most efficient approach.</p>
*
* @author <a href="https://github.com/jchambers">Jon Chambers</a>
*
* @param <P> the base type of points between which distances can be measured
* @param <E> the specific type of point contained in this vantage point tree
*/
public class VPTree<P, E extends P> implements SpatialIndex<P, E> {
private final DistanceFunction<P> distanceFunction;
private final ThresholdSelectionStrategy<P, E> thresholdSelectionStrategy;
private final int nodeCapacity;
private VPTreeNode<P, E> rootNode;
public static final int DEFAULT_NODE_CAPACITY = 32;
private static final PointFilter<Object> NO_OP_POINT_FILTER = new PointFilter<Object>() {
@Override
public boolean allowPoint(final Object point) {
return true;
}
};
/**
* Constructs a new vp-tree that uses the given distance function and is initially empty. The constructed tree will
* use a default {@link SamplingMedianDistanceThresholdSelectionStrategy} and node capacity
* ({@value VPTree#DEFAULT_NODE_CAPACITY} points).
*
* @param distanceFunction the distance function to use to calculate the distance between points
*/
public VPTree(final DistanceFunction<P> distanceFunction) {
this(distanceFunction, (Collection<E>) null);
}
/**
* Constructs a new vp-tree that uses the given distance function and is initially populated with the given
* collection of points. The constructed tree will use a default
* {@link SamplingMedianDistanceThresholdSelectionStrategy} and node capacity
* ({@value VPTree#DEFAULT_NODE_CAPACITY} points).
*
* @param distanceFunction the distance function to use to calculate the distance between points
* @param points the points with which this tree should be initially populated; may be {@code null}
*/
public VPTree(final DistanceFunction<P> distanceFunction, final Collection<E> points) { | // Path: src/main/java/com/eatthepath/jvptree/util/SamplingMedianDistanceThresholdSelectionStrategy.java
// public class SamplingMedianDistanceThresholdSelectionStrategy<P, E extends P> extends MedianDistanceThresholdSelectionStrategy<P, E> implements ThresholdSelectionStrategy<P, E> {
//
// private final int numberOfSamples;
//
// public static final int DEFAULT_NUMBER_OF_SAMPLES = 32;
//
// /**
// * Constructs a threshold selector that uses up to a default ({@value DEFAULT_NUMBER_OF_SAMPLES}) number of samples
// * from a list of points to choose a median distance.
// */
// public SamplingMedianDistanceThresholdSelectionStrategy() {
// this(DEFAULT_NUMBER_OF_SAMPLES);
// }
//
// /**
// * Constructs a threshold selector that uses up to the given number of samples from a list of points to choose a
// * median distance.
// *
// * @param numberOfSamples the maximum number of samples to use when choosing a median distance
// */
// public SamplingMedianDistanceThresholdSelectionStrategy(final int numberOfSamples) {
// this.numberOfSamples = numberOfSamples;
// }
//
// /**
// * Returns the median distance of a subset of the given points from the given origin. The given list of points may
// * be partially sorted in the process.
// *
// * @param points the list of points from which a median distance will be chosen
// * @param origin the point from which distances to other points will be calculated
// * @param distanceFunction the function to be used to calculate the distance between the origin and other points
// *
// * @return the median distance from the origin to the given list of points
// */
// @Override
// public double selectThreshold(final List<E> points, final P origin, final DistanceFunction<P> distanceFunction) {
// return super.selectThreshold(this.getSampledPoints(points), origin, distanceFunction);
// }
//
// /**
// * Chooses a subset of points from which to calculate a median by sampling the given list.
// *
// * @param points the points from which to choose a subset of points
// *
// * @return a list containing at most the number of points chosen at construction time
// */
// List<E> getSampledPoints(final List<E> points) {
// final List<E> sampledPoints;
//
// if (points.size() > this.numberOfSamples) {
// sampledPoints = new ArrayList<>(this.numberOfSamples);
// final int step = points.size() / this.numberOfSamples;
//
// for (int i = 0; i < this.numberOfSamples; i++) {
// sampledPoints.add(points.get(i * step));
// }
// } else {
// sampledPoints = points;
// }
//
// return sampledPoints;
// }
// }
// Path: src/main/java/com/eatthepath/jvptree/VPTree.java
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import com.eatthepath.jvptree.util.SamplingMedianDistanceThresholdSelectionStrategy;
package com.eatthepath.jvptree;
/**
* <p>A vantage-point tree (or vp-tree) is a binary space partitioning collection of points in a metric space. The main
* feature of vantage point trees is that they allow for k-nearest-neighbor searches in any metric space in
* <em>O(log(n))</em> time.</p>
*
* <p>Vantage point trees recursively partition points by choosing a "vantage point" and a distance threshold;
* points are then partitioned into one collection that contains all of the points closer to the vantage point than the
* chosen threshold and one collection that contains all of the points farther away than the chosen threshold.</p>
*
* <p>A {@linkplain DistanceFunction distance function} that satisfies the properties of a metric space must be provided
* when constructing a vantage point tree. Callers may also specify a threshold selection strategy (a sampling median
* strategy is used by default) and a node size to tune the ratio of nodes searched to points inspected per node.
* Vantage point trees may be constructed with or without an initial collection of points, though specifying a
* collection of points at construction time is the most efficient approach.</p>
*
* @author <a href="https://github.com/jchambers">Jon Chambers</a>
*
* @param <P> the base type of points between which distances can be measured
* @param <E> the specific type of point contained in this vantage point tree
*/
public class VPTree<P, E extends P> implements SpatialIndex<P, E> {
private final DistanceFunction<P> distanceFunction;
private final ThresholdSelectionStrategy<P, E> thresholdSelectionStrategy;
private final int nodeCapacity;
private VPTreeNode<P, E> rootNode;
public static final int DEFAULT_NODE_CAPACITY = 32;
private static final PointFilter<Object> NO_OP_POINT_FILTER = new PointFilter<Object>() {
@Override
public boolean allowPoint(final Object point) {
return true;
}
};
/**
* Constructs a new vp-tree that uses the given distance function and is initially empty. The constructed tree will
* use a default {@link SamplingMedianDistanceThresholdSelectionStrategy} and node capacity
* ({@value VPTree#DEFAULT_NODE_CAPACITY} points).
*
* @param distanceFunction the distance function to use to calculate the distance between points
*/
public VPTree(final DistanceFunction<P> distanceFunction) {
this(distanceFunction, (Collection<E>) null);
}
/**
* Constructs a new vp-tree that uses the given distance function and is initially populated with the given
* collection of points. The constructed tree will use a default
* {@link SamplingMedianDistanceThresholdSelectionStrategy} and node capacity
* ({@value VPTree#DEFAULT_NODE_CAPACITY} points).
*
* @param distanceFunction the distance function to use to calculate the distance between points
* @param points the points with which this tree should be initially populated; may be {@code null}
*/
public VPTree(final DistanceFunction<P> distanceFunction, final Collection<E> points) { | this(distanceFunction, new SamplingMedianDistanceThresholdSelectionStrategy<P, E>( |
NickAcPT/Lithium-Forge | src/main/java/net/nickac/lithium/frontend/mod/network/packethandler/in/ControlChanged.java | // Path: src/main/java/net/nickac/lithium/frontend/mod/LithiumMod.java
// @SuppressWarnings("WeakerAccess")
// @Mod(modid = LithiumMod.MODID, version = LithiumMod.VERSION, clientSideOnly = true, canBeDeactivated = true)
// public class LithiumMod {
// public static final String MODID = "lithium";
// public static final String CHANNELNAME = "Lithium";
// public static final String VERSION = "1.2-BETA";
//
// private static LithiumWindowManager windowManager = new LithiumWindowManager();
// private static NewLithiumGUI currentLithium;
// private static LOverlay currentLithiumOverlay;
// private static SimpleNetworkWrapper network;
// private static LithiumOverlay overlayRenderer;
// private static ResourceLocation mainResourceLocation;
//
// public static LOverlay getCurrentLithiumOverlay() {
// return currentLithiumOverlay;
// }
//
// public static void setCurrentLithiumOverlay(LOverlay currentLithiumOverlay) {
// LithiumMod.currentLithiumOverlay = currentLithiumOverlay;
// }
//
// public static void log(String s) {
// System.out.println(s);
// }
//
// public static NewLithiumGUI getCurrentLithium() {
// return currentLithium;
// }
//
// public static void setCurrentLithium(NewLithiumGUI currentLithium) {
// LithiumMod.currentLithium = currentLithium;
// }
//
// public static LithiumWindowManager getWindowManager() {
// return windowManager;
// }
//
// public static void setWindowManager(LithiumWindowManager windowManager) {
// LithiumMod.windowManager = windowManager;
// }
//
// @SideOnly(Side.CLIENT)
// public static void replaceControl(LContainer cc, UUID u, LControl c) {
// for (LControl control : cc.getControls()) {
// if (control instanceof LContainer) {
// replaceControl(((LContainer) control), u, c);
// } else if (control.getUUID().equals(u)) {
// if (currentLithium != null) {
// //Try to check if it is a window
// currentLithium.removeControl(control);
// currentLithium.addControlToGUI(c);
// } else if (currentLithiumOverlay != null) {
// //It might be the overlay
// currentLithiumOverlay.addControl(c);
// }
// }
// }
// }
//
// public static SimpleNetworkWrapper getSimpleNetworkWrapper() {
// return network;
// }
//
// public static ResourceLocation getMainResourceLocation() {
// return mainResourceLocation;
// }
//
// @EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// mainResourceLocation = new ResourceLocation(event.getModConfigurationDirectory() + "/lithium/images/");
//
// }
//
// @SideOnly(Side.CLIENT)
// @EventHandler
// public void init(FMLInitializationEvent event) {
// overlayRenderer = new LithiumOverlay();
// MinecraftForge.EVENT_BUS.register(NetworkEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(overlayRenderer);
// network = NetworkRegistry.INSTANCE.newSimpleChannel(LithiumMod.CHANNELNAME);
// Handle.setPacketHandler(new PacketHandlerImpl());
// getSimpleNetworkWrapper().registerMessage(Handle.class, LithiumMessage.class, 0, Side.CLIENT);
//
// }
// }
//
// Path: src/main/java/net/nickac/lithium/frontend/mod/network/packethandler/abstracts/PacketIn.java
// public interface PacketIn {
//
// void execute(List<String> data);
//
// String key();
// }
| import net.minecraft.client.Minecraft;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.nickac.lithium.backend.controls.LControl;
import net.nickac.lithium.backend.other.LithiumConstants;
import net.nickac.lithium.backend.serializer.SerializationUtils;
import net.nickac.lithium.frontend.mod.LithiumMod;
import net.nickac.lithium.frontend.mod.network.packethandler.abstracts.PacketIn;
import java.util.List; | package net.nickac.lithium.frontend.mod.network.packethandler.in;
public class ControlChanged implements PacketIn {
@SideOnly(Side.CLIENT)
@Override
public void execute(List<String> data) {
String c = data.get(0);
LControl newC = SerializationUtils.stringToObject(c, LControl.class);
if (newC.getParent() != null) { | // Path: src/main/java/net/nickac/lithium/frontend/mod/LithiumMod.java
// @SuppressWarnings("WeakerAccess")
// @Mod(modid = LithiumMod.MODID, version = LithiumMod.VERSION, clientSideOnly = true, canBeDeactivated = true)
// public class LithiumMod {
// public static final String MODID = "lithium";
// public static final String CHANNELNAME = "Lithium";
// public static final String VERSION = "1.2-BETA";
//
// private static LithiumWindowManager windowManager = new LithiumWindowManager();
// private static NewLithiumGUI currentLithium;
// private static LOverlay currentLithiumOverlay;
// private static SimpleNetworkWrapper network;
// private static LithiumOverlay overlayRenderer;
// private static ResourceLocation mainResourceLocation;
//
// public static LOverlay getCurrentLithiumOverlay() {
// return currentLithiumOverlay;
// }
//
// public static void setCurrentLithiumOverlay(LOverlay currentLithiumOverlay) {
// LithiumMod.currentLithiumOverlay = currentLithiumOverlay;
// }
//
// public static void log(String s) {
// System.out.println(s);
// }
//
// public static NewLithiumGUI getCurrentLithium() {
// return currentLithium;
// }
//
// public static void setCurrentLithium(NewLithiumGUI currentLithium) {
// LithiumMod.currentLithium = currentLithium;
// }
//
// public static LithiumWindowManager getWindowManager() {
// return windowManager;
// }
//
// public static void setWindowManager(LithiumWindowManager windowManager) {
// LithiumMod.windowManager = windowManager;
// }
//
// @SideOnly(Side.CLIENT)
// public static void replaceControl(LContainer cc, UUID u, LControl c) {
// for (LControl control : cc.getControls()) {
// if (control instanceof LContainer) {
// replaceControl(((LContainer) control), u, c);
// } else if (control.getUUID().equals(u)) {
// if (currentLithium != null) {
// //Try to check if it is a window
// currentLithium.removeControl(control);
// currentLithium.addControlToGUI(c);
// } else if (currentLithiumOverlay != null) {
// //It might be the overlay
// currentLithiumOverlay.addControl(c);
// }
// }
// }
// }
//
// public static SimpleNetworkWrapper getSimpleNetworkWrapper() {
// return network;
// }
//
// public static ResourceLocation getMainResourceLocation() {
// return mainResourceLocation;
// }
//
// @EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// mainResourceLocation = new ResourceLocation(event.getModConfigurationDirectory() + "/lithium/images/");
//
// }
//
// @SideOnly(Side.CLIENT)
// @EventHandler
// public void init(FMLInitializationEvent event) {
// overlayRenderer = new LithiumOverlay();
// MinecraftForge.EVENT_BUS.register(NetworkEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(overlayRenderer);
// network = NetworkRegistry.INSTANCE.newSimpleChannel(LithiumMod.CHANNELNAME);
// Handle.setPacketHandler(new PacketHandlerImpl());
// getSimpleNetworkWrapper().registerMessage(Handle.class, LithiumMessage.class, 0, Side.CLIENT);
//
// }
// }
//
// Path: src/main/java/net/nickac/lithium/frontend/mod/network/packethandler/abstracts/PacketIn.java
// public interface PacketIn {
//
// void execute(List<String> data);
//
// String key();
// }
// Path: src/main/java/net/nickac/lithium/frontend/mod/network/packethandler/in/ControlChanged.java
import net.minecraft.client.Minecraft;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.nickac.lithium.backend.controls.LControl;
import net.nickac.lithium.backend.other.LithiumConstants;
import net.nickac.lithium.backend.serializer.SerializationUtils;
import net.nickac.lithium.frontend.mod.LithiumMod;
import net.nickac.lithium.frontend.mod.network.packethandler.abstracts.PacketIn;
import java.util.List;
package net.nickac.lithium.frontend.mod.network.packethandler.in;
public class ControlChanged implements PacketIn {
@SideOnly(Side.CLIENT)
@Override
public void execute(List<String> data) {
String c = data.get(0);
LControl newC = SerializationUtils.stringToObject(c, LControl.class);
if (newC.getParent() != null) { | Minecraft.getMinecraft().addScheduledTask(() -> LithiumMod.replaceControl(newC.getParent(), newC.getUUID(), newC)); |
NickAcPT/Lithium-Forge | src/main/java/net/nickac/lithium/frontend/mod/network/packethandler/in/ShowOverlay.java | // Path: src/main/java/net/nickac/lithium/frontend/mod/LithiumMod.java
// @SuppressWarnings("WeakerAccess")
// @Mod(modid = LithiumMod.MODID, version = LithiumMod.VERSION, clientSideOnly = true, canBeDeactivated = true)
// public class LithiumMod {
// public static final String MODID = "lithium";
// public static final String CHANNELNAME = "Lithium";
// public static final String VERSION = "1.2-BETA";
//
// private static LithiumWindowManager windowManager = new LithiumWindowManager();
// private static NewLithiumGUI currentLithium;
// private static LOverlay currentLithiumOverlay;
// private static SimpleNetworkWrapper network;
// private static LithiumOverlay overlayRenderer;
// private static ResourceLocation mainResourceLocation;
//
// public static LOverlay getCurrentLithiumOverlay() {
// return currentLithiumOverlay;
// }
//
// public static void setCurrentLithiumOverlay(LOverlay currentLithiumOverlay) {
// LithiumMod.currentLithiumOverlay = currentLithiumOverlay;
// }
//
// public static void log(String s) {
// System.out.println(s);
// }
//
// public static NewLithiumGUI getCurrentLithium() {
// return currentLithium;
// }
//
// public static void setCurrentLithium(NewLithiumGUI currentLithium) {
// LithiumMod.currentLithium = currentLithium;
// }
//
// public static LithiumWindowManager getWindowManager() {
// return windowManager;
// }
//
// public static void setWindowManager(LithiumWindowManager windowManager) {
// LithiumMod.windowManager = windowManager;
// }
//
// @SideOnly(Side.CLIENT)
// public static void replaceControl(LContainer cc, UUID u, LControl c) {
// for (LControl control : cc.getControls()) {
// if (control instanceof LContainer) {
// replaceControl(((LContainer) control), u, c);
// } else if (control.getUUID().equals(u)) {
// if (currentLithium != null) {
// //Try to check if it is a window
// currentLithium.removeControl(control);
// currentLithium.addControlToGUI(c);
// } else if (currentLithiumOverlay != null) {
// //It might be the overlay
// currentLithiumOverlay.addControl(c);
// }
// }
// }
// }
//
// public static SimpleNetworkWrapper getSimpleNetworkWrapper() {
// return network;
// }
//
// public static ResourceLocation getMainResourceLocation() {
// return mainResourceLocation;
// }
//
// @EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// mainResourceLocation = new ResourceLocation(event.getModConfigurationDirectory() + "/lithium/images/");
//
// }
//
// @SideOnly(Side.CLIENT)
// @EventHandler
// public void init(FMLInitializationEvent event) {
// overlayRenderer = new LithiumOverlay();
// MinecraftForge.EVENT_BUS.register(NetworkEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(overlayRenderer);
// network = NetworkRegistry.INSTANCE.newSimpleChannel(LithiumMod.CHANNELNAME);
// Handle.setPacketHandler(new PacketHandlerImpl());
// getSimpleNetworkWrapper().registerMessage(Handle.class, LithiumMessage.class, 0, Side.CLIENT);
//
// }
// }
//
// Path: src/main/java/net/nickac/lithium/frontend/mod/network/packethandler/abstracts/PacketIn.java
// public interface PacketIn {
//
// void execute(List<String> data);
//
// String key();
// }
| import net.nickac.lithium.backend.controls.impl.LOverlay;
import net.nickac.lithium.backend.other.LithiumConstants;
import net.nickac.lithium.backend.serializer.SerializationUtils;
import net.nickac.lithium.frontend.mod.LithiumMod;
import net.nickac.lithium.frontend.mod.network.packethandler.abstracts.PacketIn;
import java.util.List; | package net.nickac.lithium.frontend.mod.network.packethandler.in;
public class ShowOverlay implements PacketIn {
@Override
public void execute(List<String> data) {
try {
LOverlay overlay = SerializationUtils.stringToObject(data.get(0), LOverlay.class); | // Path: src/main/java/net/nickac/lithium/frontend/mod/LithiumMod.java
// @SuppressWarnings("WeakerAccess")
// @Mod(modid = LithiumMod.MODID, version = LithiumMod.VERSION, clientSideOnly = true, canBeDeactivated = true)
// public class LithiumMod {
// public static final String MODID = "lithium";
// public static final String CHANNELNAME = "Lithium";
// public static final String VERSION = "1.2-BETA";
//
// private static LithiumWindowManager windowManager = new LithiumWindowManager();
// private static NewLithiumGUI currentLithium;
// private static LOverlay currentLithiumOverlay;
// private static SimpleNetworkWrapper network;
// private static LithiumOverlay overlayRenderer;
// private static ResourceLocation mainResourceLocation;
//
// public static LOverlay getCurrentLithiumOverlay() {
// return currentLithiumOverlay;
// }
//
// public static void setCurrentLithiumOverlay(LOverlay currentLithiumOverlay) {
// LithiumMod.currentLithiumOverlay = currentLithiumOverlay;
// }
//
// public static void log(String s) {
// System.out.println(s);
// }
//
// public static NewLithiumGUI getCurrentLithium() {
// return currentLithium;
// }
//
// public static void setCurrentLithium(NewLithiumGUI currentLithium) {
// LithiumMod.currentLithium = currentLithium;
// }
//
// public static LithiumWindowManager getWindowManager() {
// return windowManager;
// }
//
// public static void setWindowManager(LithiumWindowManager windowManager) {
// LithiumMod.windowManager = windowManager;
// }
//
// @SideOnly(Side.CLIENT)
// public static void replaceControl(LContainer cc, UUID u, LControl c) {
// for (LControl control : cc.getControls()) {
// if (control instanceof LContainer) {
// replaceControl(((LContainer) control), u, c);
// } else if (control.getUUID().equals(u)) {
// if (currentLithium != null) {
// //Try to check if it is a window
// currentLithium.removeControl(control);
// currentLithium.addControlToGUI(c);
// } else if (currentLithiumOverlay != null) {
// //It might be the overlay
// currentLithiumOverlay.addControl(c);
// }
// }
// }
// }
//
// public static SimpleNetworkWrapper getSimpleNetworkWrapper() {
// return network;
// }
//
// public static ResourceLocation getMainResourceLocation() {
// return mainResourceLocation;
// }
//
// @EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// mainResourceLocation = new ResourceLocation(event.getModConfigurationDirectory() + "/lithium/images/");
//
// }
//
// @SideOnly(Side.CLIENT)
// @EventHandler
// public void init(FMLInitializationEvent event) {
// overlayRenderer = new LithiumOverlay();
// MinecraftForge.EVENT_BUS.register(NetworkEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(overlayRenderer);
// network = NetworkRegistry.INSTANCE.newSimpleChannel(LithiumMod.CHANNELNAME);
// Handle.setPacketHandler(new PacketHandlerImpl());
// getSimpleNetworkWrapper().registerMessage(Handle.class, LithiumMessage.class, 0, Side.CLIENT);
//
// }
// }
//
// Path: src/main/java/net/nickac/lithium/frontend/mod/network/packethandler/abstracts/PacketIn.java
// public interface PacketIn {
//
// void execute(List<String> data);
//
// String key();
// }
// Path: src/main/java/net/nickac/lithium/frontend/mod/network/packethandler/in/ShowOverlay.java
import net.nickac.lithium.backend.controls.impl.LOverlay;
import net.nickac.lithium.backend.other.LithiumConstants;
import net.nickac.lithium.backend.serializer.SerializationUtils;
import net.nickac.lithium.frontend.mod.LithiumMod;
import net.nickac.lithium.frontend.mod.network.packethandler.abstracts.PacketIn;
import java.util.List;
package net.nickac.lithium.frontend.mod.network.packethandler.in;
public class ShowOverlay implements PacketIn {
@Override
public void execute(List<String> data) {
try {
LOverlay overlay = SerializationUtils.stringToObject(data.get(0), LOverlay.class); | LithiumMod.setCurrentLithiumOverlay(overlay); |
NickAcPT/Lithium-Forge | src/main/java/net/nickac/lithium/frontend/mod/network/packethandler/PacketMap.java | // Path: src/main/java/net/nickac/lithium/frontend/mod/network/packethandler/abstracts/PacketIn.java
// public interface PacketIn {
//
// void execute(List<String> data);
//
// String key();
// }
| import net.nickac.lithium.frontend.mod.network.packethandler.abstracts.PacketIn;
import java.util.HashMap;
import java.util.Map; | package net.nickac.lithium.frontend.mod.network.packethandler;
public class PacketMap {
public final static PacketMap instance = new PacketMap();
private PacketMap() {
}
| // Path: src/main/java/net/nickac/lithium/frontend/mod/network/packethandler/abstracts/PacketIn.java
// public interface PacketIn {
//
// void execute(List<String> data);
//
// String key();
// }
// Path: src/main/java/net/nickac/lithium/frontend/mod/network/packethandler/PacketMap.java
import net.nickac.lithium.frontend.mod.network.packethandler.abstracts.PacketIn;
import java.util.HashMap;
import java.util.Map;
package net.nickac.lithium.frontend.mod.network.packethandler;
public class PacketMap {
public final static PacketMap instance = new PacketMap();
private PacketMap() {
}
| private final Map<String, PacketIn> classStringMap = new HashMap<>(); |
NickAcPT/Lithium-Forge | src/main/java/net/nickac/lithium/frontend/mod/ui/NickGuiTextField.java | // Path: src/main/java/net/nickac/lithium/frontend/mod/utils/MiscUtils.java
// public class MiscUtils {
// public static String stringToStars(String input) {
// char[] ca = new char[input.length()];
// Arrays.fill(ca, '*');
// return new String(ca);
// }
//
// public static boolean isCenteredX(LControl c) {
// return c.getCentered() != LControl.CenterOptions.NONE && c.getCentered() != LControl.CenterOptions.VERTICAL;
// }
//
// public static boolean isCenteredY(LControl c) {
// return c.getCentered() != LControl.CenterOptions.NONE && c.getCentered() != LControl.CenterOptions.HORIZONTAL;
// }
//
// public static int ConvertRange(int originalStart, int originalEnd, int newStart, int newEnd, int value) {
// double scale = (double) (newEnd - newStart) / (originalEnd - originalStart);
// return (int) (newStart + ((value - originalStart) * scale));
// }
//
// public static String getURLFileExt(String url) {
// if (url.contains(".")) {
// return url.substring(url.lastIndexOf("."));
// }
// return "";
//
// }
// }
| import net.minecraft.client.gui.GuiPageButtonList;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.ChatAllowedCharacters;
import net.minecraft.util.math.MathHelper;
import net.nickac.lithium.frontend.mod.utils.MiscUtils;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui; | boolean flag2 = this.cursorPosition < this.text.length() || this.text.length() >= this.getMaxStringLength();
int k1 = j1;
if (!flag) {
k1 = j > 0 ? l + this.width : l;
} else if (flag2) {
k1 = j1 - 1;
--j1;
}
if (!s.isEmpty() && flag && j < s.length()) {
j1 = drawExtendedStringWithShadow(i, j1, i1, s.substring(j));
}
if (flag1) {
if (flag2) {
Gui.drawRect(k1, i1 - 1, k1 + 1, i1 + 1 + this.fontRenderer.FONT_HEIGHT, -3092272);
} else {
this.fontRenderer.drawStringWithShadow("_", (float) k1, (float) i1, i);
}
}
if (k != j) {
int l1 = l + this.fontRenderer.getStringWidth(s.substring(0, k));
this.drawSelectionBox(k1, i1 - 1, l1 - 1, i1 + 1 + this.fontRenderer.FONT_HEIGHT);
}
}
}
private int drawExtendedStringWithShadow(int i, float l, float i1, String s1) { | // Path: src/main/java/net/nickac/lithium/frontend/mod/utils/MiscUtils.java
// public class MiscUtils {
// public static String stringToStars(String input) {
// char[] ca = new char[input.length()];
// Arrays.fill(ca, '*');
// return new String(ca);
// }
//
// public static boolean isCenteredX(LControl c) {
// return c.getCentered() != LControl.CenterOptions.NONE && c.getCentered() != LControl.CenterOptions.VERTICAL;
// }
//
// public static boolean isCenteredY(LControl c) {
// return c.getCentered() != LControl.CenterOptions.NONE && c.getCentered() != LControl.CenterOptions.HORIZONTAL;
// }
//
// public static int ConvertRange(int originalStart, int originalEnd, int newStart, int newEnd, int value) {
// double scale = (double) (newEnd - newStart) / (originalEnd - originalStart);
// return (int) (newStart + ((value - originalStart) * scale));
// }
//
// public static String getURLFileExt(String url) {
// if (url.contains(".")) {
// return url.substring(url.lastIndexOf("."));
// }
// return "";
//
// }
// }
// Path: src/main/java/net/nickac/lithium/frontend/mod/ui/NickGuiTextField.java
import net.minecraft.client.gui.GuiPageButtonList;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.ChatAllowedCharacters;
import net.minecraft.util.math.MathHelper;
import net.nickac.lithium.frontend.mod.utils.MiscUtils;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
boolean flag2 = this.cursorPosition < this.text.length() || this.text.length() >= this.getMaxStringLength();
int k1 = j1;
if (!flag) {
k1 = j > 0 ? l + this.width : l;
} else if (flag2) {
k1 = j1 - 1;
--j1;
}
if (!s.isEmpty() && flag && j < s.length()) {
j1 = drawExtendedStringWithShadow(i, j1, i1, s.substring(j));
}
if (flag1) {
if (flag2) {
Gui.drawRect(k1, i1 - 1, k1 + 1, i1 + 1 + this.fontRenderer.FONT_HEIGHT, -3092272);
} else {
this.fontRenderer.drawStringWithShadow("_", (float) k1, (float) i1, i);
}
}
if (k != j) {
int l1 = l + this.fontRenderer.getStringWidth(s.substring(0, k));
this.drawSelectionBox(k1, i1 - 1, l1 - 1, i1 + 1 + this.fontRenderer.FONT_HEIGHT);
}
}
}
private int drawExtendedStringWithShadow(int i, float l, float i1, String s1) { | return this.fontRenderer.drawStringWithShadow(password ? MiscUtils.stringToStars(s1) : s1, l, i1, i); |
NickAcPT/Lithium-Forge | src/main/java/net/nickac/lithium/frontend/mod/network/packethandler/in/RemoveFromContainer.java | // Path: src/main/java/net/nickac/lithium/frontend/mod/LithiumMod.java
// @SuppressWarnings("WeakerAccess")
// @Mod(modid = LithiumMod.MODID, version = LithiumMod.VERSION, clientSideOnly = true, canBeDeactivated = true)
// public class LithiumMod {
// public static final String MODID = "lithium";
// public static final String CHANNELNAME = "Lithium";
// public static final String VERSION = "1.2-BETA";
//
// private static LithiumWindowManager windowManager = new LithiumWindowManager();
// private static NewLithiumGUI currentLithium;
// private static LOverlay currentLithiumOverlay;
// private static SimpleNetworkWrapper network;
// private static LithiumOverlay overlayRenderer;
// private static ResourceLocation mainResourceLocation;
//
// public static LOverlay getCurrentLithiumOverlay() {
// return currentLithiumOverlay;
// }
//
// public static void setCurrentLithiumOverlay(LOverlay currentLithiumOverlay) {
// LithiumMod.currentLithiumOverlay = currentLithiumOverlay;
// }
//
// public static void log(String s) {
// System.out.println(s);
// }
//
// public static NewLithiumGUI getCurrentLithium() {
// return currentLithium;
// }
//
// public static void setCurrentLithium(NewLithiumGUI currentLithium) {
// LithiumMod.currentLithium = currentLithium;
// }
//
// public static LithiumWindowManager getWindowManager() {
// return windowManager;
// }
//
// public static void setWindowManager(LithiumWindowManager windowManager) {
// LithiumMod.windowManager = windowManager;
// }
//
// @SideOnly(Side.CLIENT)
// public static void replaceControl(LContainer cc, UUID u, LControl c) {
// for (LControl control : cc.getControls()) {
// if (control instanceof LContainer) {
// replaceControl(((LContainer) control), u, c);
// } else if (control.getUUID().equals(u)) {
// if (currentLithium != null) {
// //Try to check if it is a window
// currentLithium.removeControl(control);
// currentLithium.addControlToGUI(c);
// } else if (currentLithiumOverlay != null) {
// //It might be the overlay
// currentLithiumOverlay.addControl(c);
// }
// }
// }
// }
//
// public static SimpleNetworkWrapper getSimpleNetworkWrapper() {
// return network;
// }
//
// public static ResourceLocation getMainResourceLocation() {
// return mainResourceLocation;
// }
//
// @EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// mainResourceLocation = new ResourceLocation(event.getModConfigurationDirectory() + "/lithium/images/");
//
// }
//
// @SideOnly(Side.CLIENT)
// @EventHandler
// public void init(FMLInitializationEvent event) {
// overlayRenderer = new LithiumOverlay();
// MinecraftForge.EVENT_BUS.register(NetworkEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(overlayRenderer);
// network = NetworkRegistry.INSTANCE.newSimpleChannel(LithiumMod.CHANNELNAME);
// Handle.setPacketHandler(new PacketHandlerImpl());
// getSimpleNetworkWrapper().registerMessage(Handle.class, LithiumMessage.class, 0, Side.CLIENT);
//
// }
// }
//
// Path: src/main/java/net/nickac/lithium/frontend/mod/network/packethandler/abstracts/PacketIn.java
// public interface PacketIn {
//
// void execute(List<String> data);
//
// String key();
// }
| import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.nickac.lithium.backend.controls.LContainer;
import net.nickac.lithium.backend.controls.LControl;
import net.nickac.lithium.backend.other.LithiumConstants;
import net.nickac.lithium.frontend.mod.LithiumMod;
import net.nickac.lithium.frontend.mod.network.packethandler.abstracts.PacketIn;
import java.util.List;
import java.util.UUID; | package net.nickac.lithium.frontend.mod.network.packethandler.in;
public class RemoveFromContainer implements PacketIn {
@SideOnly(Side.CLIENT)
@Override
public void execute(List<String> data) {
UUID containerUUID = UUID.fromString(data.get(0));
UUID controlUUID = UUID.fromString(data.get(1));
| // Path: src/main/java/net/nickac/lithium/frontend/mod/LithiumMod.java
// @SuppressWarnings("WeakerAccess")
// @Mod(modid = LithiumMod.MODID, version = LithiumMod.VERSION, clientSideOnly = true, canBeDeactivated = true)
// public class LithiumMod {
// public static final String MODID = "lithium";
// public static final String CHANNELNAME = "Lithium";
// public static final String VERSION = "1.2-BETA";
//
// private static LithiumWindowManager windowManager = new LithiumWindowManager();
// private static NewLithiumGUI currentLithium;
// private static LOverlay currentLithiumOverlay;
// private static SimpleNetworkWrapper network;
// private static LithiumOverlay overlayRenderer;
// private static ResourceLocation mainResourceLocation;
//
// public static LOverlay getCurrentLithiumOverlay() {
// return currentLithiumOverlay;
// }
//
// public static void setCurrentLithiumOverlay(LOverlay currentLithiumOverlay) {
// LithiumMod.currentLithiumOverlay = currentLithiumOverlay;
// }
//
// public static void log(String s) {
// System.out.println(s);
// }
//
// public static NewLithiumGUI getCurrentLithium() {
// return currentLithium;
// }
//
// public static void setCurrentLithium(NewLithiumGUI currentLithium) {
// LithiumMod.currentLithium = currentLithium;
// }
//
// public static LithiumWindowManager getWindowManager() {
// return windowManager;
// }
//
// public static void setWindowManager(LithiumWindowManager windowManager) {
// LithiumMod.windowManager = windowManager;
// }
//
// @SideOnly(Side.CLIENT)
// public static void replaceControl(LContainer cc, UUID u, LControl c) {
// for (LControl control : cc.getControls()) {
// if (control instanceof LContainer) {
// replaceControl(((LContainer) control), u, c);
// } else if (control.getUUID().equals(u)) {
// if (currentLithium != null) {
// //Try to check if it is a window
// currentLithium.removeControl(control);
// currentLithium.addControlToGUI(c);
// } else if (currentLithiumOverlay != null) {
// //It might be the overlay
// currentLithiumOverlay.addControl(c);
// }
// }
// }
// }
//
// public static SimpleNetworkWrapper getSimpleNetworkWrapper() {
// return network;
// }
//
// public static ResourceLocation getMainResourceLocation() {
// return mainResourceLocation;
// }
//
// @EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// mainResourceLocation = new ResourceLocation(event.getModConfigurationDirectory() + "/lithium/images/");
//
// }
//
// @SideOnly(Side.CLIENT)
// @EventHandler
// public void init(FMLInitializationEvent event) {
// overlayRenderer = new LithiumOverlay();
// MinecraftForge.EVENT_BUS.register(NetworkEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(overlayRenderer);
// network = NetworkRegistry.INSTANCE.newSimpleChannel(LithiumMod.CHANNELNAME);
// Handle.setPacketHandler(new PacketHandlerImpl());
// getSimpleNetworkWrapper().registerMessage(Handle.class, LithiumMessage.class, 0, Side.CLIENT);
//
// }
// }
//
// Path: src/main/java/net/nickac/lithium/frontend/mod/network/packethandler/abstracts/PacketIn.java
// public interface PacketIn {
//
// void execute(List<String> data);
//
// String key();
// }
// Path: src/main/java/net/nickac/lithium/frontend/mod/network/packethandler/in/RemoveFromContainer.java
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.nickac.lithium.backend.controls.LContainer;
import net.nickac.lithium.backend.controls.LControl;
import net.nickac.lithium.backend.other.LithiumConstants;
import net.nickac.lithium.frontend.mod.LithiumMod;
import net.nickac.lithium.frontend.mod.network.packethandler.abstracts.PacketIn;
import java.util.List;
import java.util.UUID;
package net.nickac.lithium.frontend.mod.network.packethandler.in;
public class RemoveFromContainer implements PacketIn {
@SideOnly(Side.CLIENT)
@Override
public void execute(List<String> data) {
UUID containerUUID = UUID.fromString(data.get(0));
UUID controlUUID = UUID.fromString(data.get(1));
| LControl container = LithiumMod.getWindowManager().getControlById(containerUUID); |
NickAcPT/Lithium-Forge | src/main/java/net/nickac/lithium/frontend/mod/network/Handle.java | // Path: src/main/java/net/nickac/lithium/frontend/mod/network/packethandler/abstracts/MessageImpl.java
// public class MessageImpl implements Message {
//
// private String key;
// private List<String> data;
//
// public MessageImpl(String key, List<String> data) {
// this.key = key;
// this.data = data;
// }
//
// @Override
// public String getKey() {
// return key;
// }
//
// @Override
// public List<String> getData() {
// return data;
// }
// }
//
// Path: src/main/java/net/nickac/lithium/frontend/mod/network/packethandler/abstracts/PacketHandler.java
// public interface PacketHandler {
// @SideOnly(Side.CLIENT)
// void handlePacket(Message message);
// }
| import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.nickac.lithium.frontend.mod.network.packethandler.abstracts.MessageImpl;
import net.nickac.lithium.frontend.mod.network.packethandler.abstracts.PacketHandler;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; | package net.nickac.lithium.frontend.mod.network;
public class Handle implements IMessageHandler<LithiumMessage, IMessage> {
private static PacketHandler packetHandler;
public static void setPacketHandler(PacketHandler packetHandler) {
Handle.packetHandler = packetHandler;
}
@SideOnly(Side.CLIENT)
@Override
public IMessage onMessage(LithiumMessage message, MessageContext ctx) {
String receivedMessage = message.getText().trim();
String[] msgArray = receivedMessage.split("\\|");
String key = msgArray[0];
List<String> data = new ArrayList<>();
if(msgArray.length>1){
List<String> par = Arrays.asList(msgArray).subList(1, msgArray.length);
System.out.println(par);
data.addAll(par);
} | // Path: src/main/java/net/nickac/lithium/frontend/mod/network/packethandler/abstracts/MessageImpl.java
// public class MessageImpl implements Message {
//
// private String key;
// private List<String> data;
//
// public MessageImpl(String key, List<String> data) {
// this.key = key;
// this.data = data;
// }
//
// @Override
// public String getKey() {
// return key;
// }
//
// @Override
// public List<String> getData() {
// return data;
// }
// }
//
// Path: src/main/java/net/nickac/lithium/frontend/mod/network/packethandler/abstracts/PacketHandler.java
// public interface PacketHandler {
// @SideOnly(Side.CLIENT)
// void handlePacket(Message message);
// }
// Path: src/main/java/net/nickac/lithium/frontend/mod/network/Handle.java
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.nickac.lithium.frontend.mod.network.packethandler.abstracts.MessageImpl;
import net.nickac.lithium.frontend.mod.network.packethandler.abstracts.PacketHandler;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
package net.nickac.lithium.frontend.mod.network;
public class Handle implements IMessageHandler<LithiumMessage, IMessage> {
private static PacketHandler packetHandler;
public static void setPacketHandler(PacketHandler packetHandler) {
Handle.packetHandler = packetHandler;
}
@SideOnly(Side.CLIENT)
@Override
public IMessage onMessage(LithiumMessage message, MessageContext ctx) {
String receivedMessage = message.getText().trim();
String[] msgArray = receivedMessage.split("\\|");
String key = msgArray[0];
List<String> data = new ArrayList<>();
if(msgArray.length>1){
List<String> par = Arrays.asList(msgArray).subList(1, msgArray.length);
System.out.println(par);
data.addAll(par);
} | packetHandler.handlePacket(new MessageImpl(key, data)); |
NickAcPT/Lithium-Forge | src/main/java/net/nickac/lithium/frontend/mod/network/packethandler/abstracts/PacketHandlerImpl.java | // Path: src/main/java/net/nickac/lithium/frontend/mod/network/packethandler/PacketMap.java
// public class PacketMap {
//
// public final static PacketMap instance = new PacketMap();
//
// private PacketMap() {
// }
//
// private final Map<String, PacketIn> classStringMap = new HashMap<>();
//
// public void registerPacketIn(String key, PacketIn packet) {
// classStringMap.put(key, packet);
// }
//
// public PacketIn getByString(String keyString) {
// return classStringMap.get(keyString);
// }
//
//
// }
| import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.nickac.lithium.frontend.mod.network.packethandler.PacketMap;
import net.nickac.lithium.frontend.mod.network.packethandler.in.*;
import java.util.Arrays;
import java.util.List; | package net.nickac.lithium.frontend.mod.network.packethandler.abstracts;
public class PacketHandlerImpl implements PacketHandler {
static {
List<PacketIn> packetIns = Arrays.asList(
new AddToContainer(),
new CloseWindow(),
new ControlChanged(),
new ReceiveWindow(),
new RemoveFromContainer(),
new ShowOverlay()); | // Path: src/main/java/net/nickac/lithium/frontend/mod/network/packethandler/PacketMap.java
// public class PacketMap {
//
// public final static PacketMap instance = new PacketMap();
//
// private PacketMap() {
// }
//
// private final Map<String, PacketIn> classStringMap = new HashMap<>();
//
// public void registerPacketIn(String key, PacketIn packet) {
// classStringMap.put(key, packet);
// }
//
// public PacketIn getByString(String keyString) {
// return classStringMap.get(keyString);
// }
//
//
// }
// Path: src/main/java/net/nickac/lithium/frontend/mod/network/packethandler/abstracts/PacketHandlerImpl.java
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.nickac.lithium.frontend.mod.network.packethandler.PacketMap;
import net.nickac.lithium.frontend.mod.network.packethandler.in.*;
import java.util.Arrays;
import java.util.List;
package net.nickac.lithium.frontend.mod.network.packethandler.abstracts;
public class PacketHandlerImpl implements PacketHandler {
static {
List<PacketIn> packetIns = Arrays.asList(
new AddToContainer(),
new CloseWindow(),
new ControlChanged(),
new ReceiveWindow(),
new RemoveFromContainer(),
new ShowOverlay()); | packetIns.forEach((p) -> PacketMap.instance.registerPacketIn(p.key(), p)); |
NickAcPT/Lithium-Forge | src/main/java/net/nickac/lithium/frontend/mod/network/packethandler/in/AddToContainer.java | // Path: src/main/java/net/nickac/lithium/frontend/mod/LithiumMod.java
// @SuppressWarnings("WeakerAccess")
// @Mod(modid = LithiumMod.MODID, version = LithiumMod.VERSION, clientSideOnly = true, canBeDeactivated = true)
// public class LithiumMod {
// public static final String MODID = "lithium";
// public static final String CHANNELNAME = "Lithium";
// public static final String VERSION = "1.2-BETA";
//
// private static LithiumWindowManager windowManager = new LithiumWindowManager();
// private static NewLithiumGUI currentLithium;
// private static LOverlay currentLithiumOverlay;
// private static SimpleNetworkWrapper network;
// private static LithiumOverlay overlayRenderer;
// private static ResourceLocation mainResourceLocation;
//
// public static LOverlay getCurrentLithiumOverlay() {
// return currentLithiumOverlay;
// }
//
// public static void setCurrentLithiumOverlay(LOverlay currentLithiumOverlay) {
// LithiumMod.currentLithiumOverlay = currentLithiumOverlay;
// }
//
// public static void log(String s) {
// System.out.println(s);
// }
//
// public static NewLithiumGUI getCurrentLithium() {
// return currentLithium;
// }
//
// public static void setCurrentLithium(NewLithiumGUI currentLithium) {
// LithiumMod.currentLithium = currentLithium;
// }
//
// public static LithiumWindowManager getWindowManager() {
// return windowManager;
// }
//
// public static void setWindowManager(LithiumWindowManager windowManager) {
// LithiumMod.windowManager = windowManager;
// }
//
// @SideOnly(Side.CLIENT)
// public static void replaceControl(LContainer cc, UUID u, LControl c) {
// for (LControl control : cc.getControls()) {
// if (control instanceof LContainer) {
// replaceControl(((LContainer) control), u, c);
// } else if (control.getUUID().equals(u)) {
// if (currentLithium != null) {
// //Try to check if it is a window
// currentLithium.removeControl(control);
// currentLithium.addControlToGUI(c);
// } else if (currentLithiumOverlay != null) {
// //It might be the overlay
// currentLithiumOverlay.addControl(c);
// }
// }
// }
// }
//
// public static SimpleNetworkWrapper getSimpleNetworkWrapper() {
// return network;
// }
//
// public static ResourceLocation getMainResourceLocation() {
// return mainResourceLocation;
// }
//
// @EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// mainResourceLocation = new ResourceLocation(event.getModConfigurationDirectory() + "/lithium/images/");
//
// }
//
// @SideOnly(Side.CLIENT)
// @EventHandler
// public void init(FMLInitializationEvent event) {
// overlayRenderer = new LithiumOverlay();
// MinecraftForge.EVENT_BUS.register(NetworkEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(overlayRenderer);
// network = NetworkRegistry.INSTANCE.newSimpleChannel(LithiumMod.CHANNELNAME);
// Handle.setPacketHandler(new PacketHandlerImpl());
// getSimpleNetworkWrapper().registerMessage(Handle.class, LithiumMessage.class, 0, Side.CLIENT);
//
// }
// }
//
// Path: src/main/java/net/nickac/lithium/frontend/mod/network/packethandler/abstracts/PacketIn.java
// public interface PacketIn {
//
// void execute(List<String> data);
//
// String key();
// }
| import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.nickac.lithium.backend.controls.LContainer;
import net.nickac.lithium.backend.controls.LControl;
import net.nickac.lithium.backend.controls.impl.LWindow;
import net.nickac.lithium.backend.other.LithiumConstants;
import net.nickac.lithium.backend.serializer.SerializationUtils;
import net.nickac.lithium.frontend.mod.LithiumMod;
import net.nickac.lithium.frontend.mod.network.packethandler.abstracts.PacketIn;
import java.util.List;
import java.util.UUID; | package net.nickac.lithium.frontend.mod.network.packethandler.in;
public class AddToContainer implements PacketIn {
@SideOnly(Side.CLIENT)
@Override
public void execute(List<String> data) {
try {
//Deserialize the control
LControl newC = SerializationUtils.stringToObject(data.get(1), LControl.class);
UUID uuid = UUID.fromString(data.get(0)); | // Path: src/main/java/net/nickac/lithium/frontend/mod/LithiumMod.java
// @SuppressWarnings("WeakerAccess")
// @Mod(modid = LithiumMod.MODID, version = LithiumMod.VERSION, clientSideOnly = true, canBeDeactivated = true)
// public class LithiumMod {
// public static final String MODID = "lithium";
// public static final String CHANNELNAME = "Lithium";
// public static final String VERSION = "1.2-BETA";
//
// private static LithiumWindowManager windowManager = new LithiumWindowManager();
// private static NewLithiumGUI currentLithium;
// private static LOverlay currentLithiumOverlay;
// private static SimpleNetworkWrapper network;
// private static LithiumOverlay overlayRenderer;
// private static ResourceLocation mainResourceLocation;
//
// public static LOverlay getCurrentLithiumOverlay() {
// return currentLithiumOverlay;
// }
//
// public static void setCurrentLithiumOverlay(LOverlay currentLithiumOverlay) {
// LithiumMod.currentLithiumOverlay = currentLithiumOverlay;
// }
//
// public static void log(String s) {
// System.out.println(s);
// }
//
// public static NewLithiumGUI getCurrentLithium() {
// return currentLithium;
// }
//
// public static void setCurrentLithium(NewLithiumGUI currentLithium) {
// LithiumMod.currentLithium = currentLithium;
// }
//
// public static LithiumWindowManager getWindowManager() {
// return windowManager;
// }
//
// public static void setWindowManager(LithiumWindowManager windowManager) {
// LithiumMod.windowManager = windowManager;
// }
//
// @SideOnly(Side.CLIENT)
// public static void replaceControl(LContainer cc, UUID u, LControl c) {
// for (LControl control : cc.getControls()) {
// if (control instanceof LContainer) {
// replaceControl(((LContainer) control), u, c);
// } else if (control.getUUID().equals(u)) {
// if (currentLithium != null) {
// //Try to check if it is a window
// currentLithium.removeControl(control);
// currentLithium.addControlToGUI(c);
// } else if (currentLithiumOverlay != null) {
// //It might be the overlay
// currentLithiumOverlay.addControl(c);
// }
// }
// }
// }
//
// public static SimpleNetworkWrapper getSimpleNetworkWrapper() {
// return network;
// }
//
// public static ResourceLocation getMainResourceLocation() {
// return mainResourceLocation;
// }
//
// @EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// mainResourceLocation = new ResourceLocation(event.getModConfigurationDirectory() + "/lithium/images/");
//
// }
//
// @SideOnly(Side.CLIENT)
// @EventHandler
// public void init(FMLInitializationEvent event) {
// overlayRenderer = new LithiumOverlay();
// MinecraftForge.EVENT_BUS.register(NetworkEventHandler.INSTANCE);
// MinecraftForge.EVENT_BUS.register(overlayRenderer);
// network = NetworkRegistry.INSTANCE.newSimpleChannel(LithiumMod.CHANNELNAME);
// Handle.setPacketHandler(new PacketHandlerImpl());
// getSimpleNetworkWrapper().registerMessage(Handle.class, LithiumMessage.class, 0, Side.CLIENT);
//
// }
// }
//
// Path: src/main/java/net/nickac/lithium/frontend/mod/network/packethandler/abstracts/PacketIn.java
// public interface PacketIn {
//
// void execute(List<String> data);
//
// String key();
// }
// Path: src/main/java/net/nickac/lithium/frontend/mod/network/packethandler/in/AddToContainer.java
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.nickac.lithium.backend.controls.LContainer;
import net.nickac.lithium.backend.controls.LControl;
import net.nickac.lithium.backend.controls.impl.LWindow;
import net.nickac.lithium.backend.other.LithiumConstants;
import net.nickac.lithium.backend.serializer.SerializationUtils;
import net.nickac.lithium.frontend.mod.LithiumMod;
import net.nickac.lithium.frontend.mod.network.packethandler.abstracts.PacketIn;
import java.util.List;
import java.util.UUID;
package net.nickac.lithium.frontend.mod.network.packethandler.in;
public class AddToContainer implements PacketIn {
@SideOnly(Side.CLIENT)
@Override
public void execute(List<String> data) {
try {
//Deserialize the control
LControl newC = SerializationUtils.stringToObject(data.get(1), LControl.class);
UUID uuid = UUID.fromString(data.get(0)); | LControl l = LithiumMod.getWindowManager().getControlById(uuid); |
deephacks/westty | westty-core/src/main/java/org/deephacks/westty/internal/core/executor/ThreadPoolExecutor.java | // Path: westty-api/src/main/java/org/deephacks/westty/config/ExecutorConfig.java
// @ConfigScope
// @Config(name = "executor",
// desc = "Thread pool executor. Changes requires server restart.")
// public class ExecutorConfig {
//
// @Config(desc = "The maximum number of active threads.")
// @NotNull
// @Size(min = 1, max = 65535)
// private Integer corePoolSize = 20;
//
// @Config(desc = "The maximum total size of the queued events in bytes. 0 to disable.")
// @NotNull
// private Long maxChannelMemorySize = 1048560L;
//
// @Config(desc = "The maximum total size of the queued events. 0 to disable.")
// @NotNull
// private Long maxTotalMemorySize = 16776960L;
//
// @Config(desc = "The amount of time for an inactive thread to shut itself down in seconds.")
// @NotNull
// private Integer keepAliveTime = 60;
//
// public Integer getCorePoolSize() {
// return corePoolSize;
// }
//
// public Long getMaxChannelMemorySize() {
// return maxChannelMemorySize;
// }
//
// public Long getMaxTotalMemorySize() {
// return maxTotalMemorySize;
// }
//
// public Integer getKeepAliveTime() {
// return keepAliveTime;
// }
//
// }
| import org.deephacks.westty.config.ExecutorConfig;
import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger; | package org.deephacks.westty.internal.core.executor;
@Singleton
public class ThreadPoolExecutor extends OrderedMemoryAwareThreadPoolExecutor {
@Inject | // Path: westty-api/src/main/java/org/deephacks/westty/config/ExecutorConfig.java
// @ConfigScope
// @Config(name = "executor",
// desc = "Thread pool executor. Changes requires server restart.")
// public class ExecutorConfig {
//
// @Config(desc = "The maximum number of active threads.")
// @NotNull
// @Size(min = 1, max = 65535)
// private Integer corePoolSize = 20;
//
// @Config(desc = "The maximum total size of the queued events in bytes. 0 to disable.")
// @NotNull
// private Long maxChannelMemorySize = 1048560L;
//
// @Config(desc = "The maximum total size of the queued events. 0 to disable.")
// @NotNull
// private Long maxTotalMemorySize = 16776960L;
//
// @Config(desc = "The amount of time for an inactive thread to shut itself down in seconds.")
// @NotNull
// private Integer keepAliveTime = 60;
//
// public Integer getCorePoolSize() {
// return corePoolSize;
// }
//
// public Long getMaxChannelMemorySize() {
// return maxChannelMemorySize;
// }
//
// public Long getMaxTotalMemorySize() {
// return maxTotalMemorySize;
// }
//
// public Integer getKeepAliveTime() {
// return keepAliveTime;
// }
//
// }
// Path: westty-core/src/main/java/org/deephacks/westty/internal/core/executor/ThreadPoolExecutor.java
import org.deephacks.westty.config.ExecutorConfig;
import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
package org.deephacks.westty.internal.core.executor;
@Singleton
public class ThreadPoolExecutor extends OrderedMemoryAwareThreadPoolExecutor {
@Inject | public ThreadPoolExecutor(ExecutorConfig config) { |
deephacks/westty | westty-protobuf/src/main/java/org/deephacks/westty/internal/protobuf/ProtobufProducer.java | // Path: westty-protobuf/src/main/java/org/deephacks/westty/protobuf/ProtobufSerializer.java
// @Alternative
// public class ProtobufSerializer {
// private static final Logger log = LoggerFactory.getLogger(ProtobufSerializer.class);
// private HashMap<Integer, Method> numToMethod = new HashMap<>();
// private HashMap<String, Integer> protoToNum = new HashMap<>();
// private static final String UNRECOGNIZED_PROTOCOL_MSG = "Unrecognized protocol.";
//
// public ProtobufSerializer() {
// registerResource("META-INF/failure.desc");
// registerResource("META-INF/void.desc");
// }
//
// public void register(URL protodesc) {
// try {
// registerDesc(protodesc.getFile(), protodesc.openStream());
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public void register(File protodesc) {
// try {
// registerDesc(protodesc.getName(), new FileInputStream(protodesc));
// } catch (FileNotFoundException e) {
// throw new RuntimeException(e);
// }
// }
//
// public void registerResource(String protodesc) {
// URL url = Thread.currentThread().getContextClassLoader().getResource(protodesc);
// register(url);
// }
//
// private void registerDesc(String name, InputStream in) {
// try {
// FileDescriptorSet descriptorSet = FileDescriptorSet.parseFrom(in);
// for (FileDescriptorProto fdp : descriptorSet.getFileList()) {
// FileDescriptor fd = FileDescriptor.buildFrom(fdp, new FileDescriptor[] {});
//
// for (Descriptor desc : fd.getMessageTypes()) {
// FieldDescriptor fdesc = desc.findFieldByName("protoType");
// if (fdesc == null) {
// throw new IllegalArgumentException(name
// + ".proto file must define protoType field "
// + "with unqiue number that identify proto type");
// }
// String packageName = fdp.getOptions().getJavaPackage();
//
// if (Strings.isNullOrEmpty(packageName)) {
// throw new IllegalArgumentException(name
// + ".proto file must define java_package");
// }
// String simpleClassName = fdp.getOptions().getJavaOuterClassname();
// if (Strings.isNullOrEmpty(simpleClassName)) {
// throw new IllegalArgumentException(name
// + " .proto file must define java_outer_classname");
// }
//
// String className = packageName + "." + simpleClassName + "$" + desc.getName();
// Class<?> cls = Thread.currentThread().getContextClassLoader()
// .loadClass(className);
// protoToNum.put(desc.getFullName(), fdesc.getNumber());
// numToMethod.put(fdesc.getNumber(), cls.getMethod("parseFrom", byte[].class));
// log.debug("Registered protobuf resource {}.", name);
// }
// }
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public Object read(byte[] bytes) throws Exception {
// try {
// ByteBuffer buf = ByteBuffer.wrap(bytes);
// Varint32 vint = new Varint32(buf);
// int protoTypeNum = vint.read();
// buf = vint.getByteBuffer();
// byte[] message = new byte[buf.remaining()];
// buf.get(message);
// Method m = numToMethod.get(protoTypeNum);
// if (m == null) {
// return Failure.newBuilder().setCode(BAD_REQUEST.getCode())
// .setMsg("proto_type=" + protoTypeNum).build();
// }
// return m.invoke(null, message);
// } catch (Exception e) {
// return Failure.newBuilder().setCode(BAD_REQUEST.getCode())
// .setMsg(UNRECOGNIZED_PROTOCOL_MSG).build();
// }
// }
//
// public byte[] write(Object proto) throws IOException {
// Message msg = (Message) proto;
// String protoName = msg.getDescriptorForType().getFullName();
// Integer num = protoToNum.get(protoName);
// if(num == null){
// throw new IllegalArgumentException("Could not find protoType mapping for " + protoName);
// }
// byte[] msgBytes = msg.toByteArray();
// Varint32 vint = new Varint32(num);
// int vsize = vint.getSize();
// byte[] bytes = new byte[vsize + msgBytes.length];
// System.arraycopy(vint.write(), 0, bytes, 0, vsize);
// System.arraycopy(msgBytes, 0, bytes, vsize, msgBytes.length);
// return bytes;
// }
// }
| import org.deephacks.westty.protobuf.ProtobufSerializer;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import javax.inject.Singleton; | package org.deephacks.westty.internal.protobuf;
@Singleton
class ProtobufProducer {
@Inject
private ProtobufExtension extension;
@Produces
@Singleton | // Path: westty-protobuf/src/main/java/org/deephacks/westty/protobuf/ProtobufSerializer.java
// @Alternative
// public class ProtobufSerializer {
// private static final Logger log = LoggerFactory.getLogger(ProtobufSerializer.class);
// private HashMap<Integer, Method> numToMethod = new HashMap<>();
// private HashMap<String, Integer> protoToNum = new HashMap<>();
// private static final String UNRECOGNIZED_PROTOCOL_MSG = "Unrecognized protocol.";
//
// public ProtobufSerializer() {
// registerResource("META-INF/failure.desc");
// registerResource("META-INF/void.desc");
// }
//
// public void register(URL protodesc) {
// try {
// registerDesc(protodesc.getFile(), protodesc.openStream());
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public void register(File protodesc) {
// try {
// registerDesc(protodesc.getName(), new FileInputStream(protodesc));
// } catch (FileNotFoundException e) {
// throw new RuntimeException(e);
// }
// }
//
// public void registerResource(String protodesc) {
// URL url = Thread.currentThread().getContextClassLoader().getResource(protodesc);
// register(url);
// }
//
// private void registerDesc(String name, InputStream in) {
// try {
// FileDescriptorSet descriptorSet = FileDescriptorSet.parseFrom(in);
// for (FileDescriptorProto fdp : descriptorSet.getFileList()) {
// FileDescriptor fd = FileDescriptor.buildFrom(fdp, new FileDescriptor[] {});
//
// for (Descriptor desc : fd.getMessageTypes()) {
// FieldDescriptor fdesc = desc.findFieldByName("protoType");
// if (fdesc == null) {
// throw new IllegalArgumentException(name
// + ".proto file must define protoType field "
// + "with unqiue number that identify proto type");
// }
// String packageName = fdp.getOptions().getJavaPackage();
//
// if (Strings.isNullOrEmpty(packageName)) {
// throw new IllegalArgumentException(name
// + ".proto file must define java_package");
// }
// String simpleClassName = fdp.getOptions().getJavaOuterClassname();
// if (Strings.isNullOrEmpty(simpleClassName)) {
// throw new IllegalArgumentException(name
// + " .proto file must define java_outer_classname");
// }
//
// String className = packageName + "." + simpleClassName + "$" + desc.getName();
// Class<?> cls = Thread.currentThread().getContextClassLoader()
// .loadClass(className);
// protoToNum.put(desc.getFullName(), fdesc.getNumber());
// numToMethod.put(fdesc.getNumber(), cls.getMethod("parseFrom", byte[].class));
// log.debug("Registered protobuf resource {}.", name);
// }
// }
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public Object read(byte[] bytes) throws Exception {
// try {
// ByteBuffer buf = ByteBuffer.wrap(bytes);
// Varint32 vint = new Varint32(buf);
// int protoTypeNum = vint.read();
// buf = vint.getByteBuffer();
// byte[] message = new byte[buf.remaining()];
// buf.get(message);
// Method m = numToMethod.get(protoTypeNum);
// if (m == null) {
// return Failure.newBuilder().setCode(BAD_REQUEST.getCode())
// .setMsg("proto_type=" + protoTypeNum).build();
// }
// return m.invoke(null, message);
// } catch (Exception e) {
// return Failure.newBuilder().setCode(BAD_REQUEST.getCode())
// .setMsg(UNRECOGNIZED_PROTOCOL_MSG).build();
// }
// }
//
// public byte[] write(Object proto) throws IOException {
// Message msg = (Message) proto;
// String protoName = msg.getDescriptorForType().getFullName();
// Integer num = protoToNum.get(protoName);
// if(num == null){
// throw new IllegalArgumentException("Could not find protoType mapping for " + protoName);
// }
// byte[] msgBytes = msg.toByteArray();
// Varint32 vint = new Varint32(num);
// int vsize = vint.getSize();
// byte[] bytes = new byte[vsize + msgBytes.length];
// System.arraycopy(vint.write(), 0, bytes, 0, vsize);
// System.arraycopy(msgBytes, 0, bytes, vsize, msgBytes.length);
// return bytes;
// }
// }
// Path: westty-protobuf/src/main/java/org/deephacks/westty/internal/protobuf/ProtobufProducer.java
import org.deephacks.westty.protobuf.ProtobufSerializer;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import javax.inject.Singleton;
package org.deephacks.westty.internal.protobuf;
@Singleton
class ProtobufProducer {
@Inject
private ProtobufExtension extension;
@Produces
@Singleton | public ProtobufSerializer produceSerializer(){ |
deephacks/westty | westty-datasource/src/main/java/org/deephacks/westty/internal/datasource/DataSourceProducer.java | // Path: westty-api/src/main/java/org/deephacks/westty/config/DataSourceConfig.java
// @Config(name="datasource")
// @ConfigScope
// public class DataSourceConfig {
//
// private String password = "westty";
// private String user = "westty";
// private String driver = "org.apache.derby.jdbc.EmbeddedDriver";
// private String url ="jdbc:derby:memory:westty;create=true";
//
// public DataSourceConfig() {
// }
//
// public String getPassword() {
// return password;
// }
//
// public String getUser() {
// return user;
// }
//
// public String getDriver() {
// return driver;
// }
//
// public String getUrl() {
// return url;
// }
// }
| import com.jolbox.bonecp.BoneCPDataSource;
import org.deephacks.westty.config.DataSourceConfig;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import javax.inject.Singleton; | package org.deephacks.westty.internal.datasource;
class DataSourceProducer {
@Inject | // Path: westty-api/src/main/java/org/deephacks/westty/config/DataSourceConfig.java
// @Config(name="datasource")
// @ConfigScope
// public class DataSourceConfig {
//
// private String password = "westty";
// private String user = "westty";
// private String driver = "org.apache.derby.jdbc.EmbeddedDriver";
// private String url ="jdbc:derby:memory:westty;create=true";
//
// public DataSourceConfig() {
// }
//
// public String getPassword() {
// return password;
// }
//
// public String getUser() {
// return user;
// }
//
// public String getDriver() {
// return driver;
// }
//
// public String getUrl() {
// return url;
// }
// }
// Path: westty-datasource/src/main/java/org/deephacks/westty/internal/datasource/DataSourceProducer.java
import com.jolbox.bonecp.BoneCPDataSource;
import org.deephacks.westty.config.DataSourceConfig;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import javax.inject.Singleton;
package org.deephacks.westty.internal.datasource;
class DataSourceProducer {
@Inject | private DataSourceConfig config; |
deephacks/westty | westty-sockjs/src/test/java/org/deephacks/westty/sockjs/SockJsTestEndpoint.java | // Path: westty-api/src/main/java/org/deephacks/westty/cluster/Cluster.java
// public interface Cluster {
//
// public Set<Server> getMembers();
//
// public <K, V> DistributedMultiMap<K, V> getMultiMap(String name);
//
// }
//
// Path: westty-api/src/main/java/org/deephacks/westty/config/ServerConfig.java
// @ConfigScope
// @Config(name = "servers",
// desc = "Server engine configuration. Changes requires server restart.")
// public class ServerConfig {
//
// public static final String DEFAULT_SERVER_NAME = "server";
// public static final String DEFAULT_CONF_DIR = "conf";
// public static final String DEFAULT_LIB_DIR = "lib";
// public static final String DEFAULT_BIN_DIR = "bin";
// public static final String DEFAULT_HTML_DIR = "html";
// public static final String DEFAULT_IP_ADDRESS = "127.0.0.1";
// public static final int DEFAULT_HTTP_PORT = 8080;
// public static final int DEFAULT_CLUSTER_PORT = 5701;
//
// @Id(desc="Name of this server")
// private String name = DEFAULT_SERVER_NAME;
//
// @Config(desc = "Public Ip Address.")
// private String publicIp = DEFAULT_IP_ADDRESS;
//
// @Config(desc = "Private Ip Address.")
// private String privateIp = DEFAULT_IP_ADDRESS;
//
// @Config(desc="Port that this server uses for the cluster.")
// private Integer clusterPort = DEFAULT_CLUSTER_PORT;
//
// @Config(desc="Ip address that this server uses for the cluster.")
// private String clusterIp = DEFAULT_IP_ADDRESS;
//
// @Config(desc = "Root directory.")
// private String rootDir = System.getProperty("root.dir");
//
// @Config(desc = "Location of the conf directory relative to the root directory.")
// private String confDir = DEFAULT_CONF_DIR;
//
// @Config(desc = "Location of the lib directory relative to the root directory.")
// private String libDir = DEFAULT_LIB_DIR;
//
// @Config(desc = "Location of the bin directory relative to the root directory.")
// private String binDir = DEFAULT_BIN_DIR;
//
// @Config(desc = "Location of the html directory relative to the root directory.")
// private String htmlDir = DEFAULT_HTML_DIR;
//
//
// @Config(desc = "Http listening port.")
// @NotNull
// @Min(0)
// @Max(65535)
// private Integer httpPort = DEFAULT_HTTP_PORT;
//
// @Config(desc = "Specify the worker count to use. "
// + "See netty javadoc NioServerSocketChannelFactory.")
// @Min(1)
// @NotNull
// private Integer ioWorkerCount = Runtime.getRuntime().availableProcessors() * 2;
//
// @Config(desc = "Set the max request size in bytes. If this size exceeded "
// + "\"413 Request Entity Too Large\" willl be sent to the client.")
// @NotNull
// @Min(4096)
// private Integer maxRequestSize = 1024 * 1024 * 10;
//
// @Config(desc = "Maximum byte length of aggregated http content. "
// + "TooLongFrameException raised if length exceeded.")
// @NotNull
// @Min(16384)
// private Integer maxHttpContentChunkLength = 65536;
//
// public ServerConfig() {
//
// }
//
// public ServerConfig(String serverName) {
// this.name = serverName;
// }
//
// public Integer getIoWorkerCount() {
// return ioWorkerCount;
// }
//
// public Integer getMaxRequestSize() {
// return maxRequestSize;
// }
//
// public Integer getHttpPort() {
// return httpPort;
// }
//
// public Integer getMaxHttpContentChunkLength() {
// return maxHttpContentChunkLength;
// }
//
// public String getPublicIp() {
// return publicIp;
// }
//
// public String getPrivateIp() {
// return privateIp;
// }
//
// public int getClusterPort() {
// return clusterPort;
// }
//
// public File getLibDir() {
// return new File(rootDir, libDir);
// }
//
// public File getConfDir() {
// return new File(rootDir, confDir);
// }
//
// public File getBinDir() {
// return new File(rootDir, binDir);
// }
//
// public File getHtmlDir() {
// return new File(rootDir, htmlDir);
// }
//
// public void setHttpPort(Integer httpPort) {
// this.httpPort = httpPort;
// }
//
// public void setServerName(String serverName) {
// this.name = serverName;
// }
//
// public void setPublicIp(String publicIp) {
// this.publicIp = publicIp;
// }
//
// public void setPrivateIp(String privateIp) {
// this.privateIp = privateIp;
// }
//
// public void setClusterPort(Integer clusterPort) {
// this.clusterPort = clusterPort;
// }
//
// public void setClusterIpAddress(String clusterIpAddress) {
// this.clusterIp = clusterIpAddress;
// }
//
// }
| import org.deephacks.westty.cluster.Cluster;
import org.deephacks.westty.config.ServerConfig;
import org.vertx.java.core.eventbus.EventBus;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.json.JsonObject;
import javax.inject.Inject;
import java.util.LinkedList; | package org.deephacks.westty.sockjs;
@SockJsEndpoint
public class SockJsTestEndpoint {
public static final String SERVER_ADDRESS = "server";
public static final String REPLY_ADDRESS = "reply";
public static final String CLIENT_ADDRESS = "client";
public static final LinkedList<JsonObject> messages = new LinkedList<>();
@Inject | // Path: westty-api/src/main/java/org/deephacks/westty/cluster/Cluster.java
// public interface Cluster {
//
// public Set<Server> getMembers();
//
// public <K, V> DistributedMultiMap<K, V> getMultiMap(String name);
//
// }
//
// Path: westty-api/src/main/java/org/deephacks/westty/config/ServerConfig.java
// @ConfigScope
// @Config(name = "servers",
// desc = "Server engine configuration. Changes requires server restart.")
// public class ServerConfig {
//
// public static final String DEFAULT_SERVER_NAME = "server";
// public static final String DEFAULT_CONF_DIR = "conf";
// public static final String DEFAULT_LIB_DIR = "lib";
// public static final String DEFAULT_BIN_DIR = "bin";
// public static final String DEFAULT_HTML_DIR = "html";
// public static final String DEFAULT_IP_ADDRESS = "127.0.0.1";
// public static final int DEFAULT_HTTP_PORT = 8080;
// public static final int DEFAULT_CLUSTER_PORT = 5701;
//
// @Id(desc="Name of this server")
// private String name = DEFAULT_SERVER_NAME;
//
// @Config(desc = "Public Ip Address.")
// private String publicIp = DEFAULT_IP_ADDRESS;
//
// @Config(desc = "Private Ip Address.")
// private String privateIp = DEFAULT_IP_ADDRESS;
//
// @Config(desc="Port that this server uses for the cluster.")
// private Integer clusterPort = DEFAULT_CLUSTER_PORT;
//
// @Config(desc="Ip address that this server uses for the cluster.")
// private String clusterIp = DEFAULT_IP_ADDRESS;
//
// @Config(desc = "Root directory.")
// private String rootDir = System.getProperty("root.dir");
//
// @Config(desc = "Location of the conf directory relative to the root directory.")
// private String confDir = DEFAULT_CONF_DIR;
//
// @Config(desc = "Location of the lib directory relative to the root directory.")
// private String libDir = DEFAULT_LIB_DIR;
//
// @Config(desc = "Location of the bin directory relative to the root directory.")
// private String binDir = DEFAULT_BIN_DIR;
//
// @Config(desc = "Location of the html directory relative to the root directory.")
// private String htmlDir = DEFAULT_HTML_DIR;
//
//
// @Config(desc = "Http listening port.")
// @NotNull
// @Min(0)
// @Max(65535)
// private Integer httpPort = DEFAULT_HTTP_PORT;
//
// @Config(desc = "Specify the worker count to use. "
// + "See netty javadoc NioServerSocketChannelFactory.")
// @Min(1)
// @NotNull
// private Integer ioWorkerCount = Runtime.getRuntime().availableProcessors() * 2;
//
// @Config(desc = "Set the max request size in bytes. If this size exceeded "
// + "\"413 Request Entity Too Large\" willl be sent to the client.")
// @NotNull
// @Min(4096)
// private Integer maxRequestSize = 1024 * 1024 * 10;
//
// @Config(desc = "Maximum byte length of aggregated http content. "
// + "TooLongFrameException raised if length exceeded.")
// @NotNull
// @Min(16384)
// private Integer maxHttpContentChunkLength = 65536;
//
// public ServerConfig() {
//
// }
//
// public ServerConfig(String serverName) {
// this.name = serverName;
// }
//
// public Integer getIoWorkerCount() {
// return ioWorkerCount;
// }
//
// public Integer getMaxRequestSize() {
// return maxRequestSize;
// }
//
// public Integer getHttpPort() {
// return httpPort;
// }
//
// public Integer getMaxHttpContentChunkLength() {
// return maxHttpContentChunkLength;
// }
//
// public String getPublicIp() {
// return publicIp;
// }
//
// public String getPrivateIp() {
// return privateIp;
// }
//
// public int getClusterPort() {
// return clusterPort;
// }
//
// public File getLibDir() {
// return new File(rootDir, libDir);
// }
//
// public File getConfDir() {
// return new File(rootDir, confDir);
// }
//
// public File getBinDir() {
// return new File(rootDir, binDir);
// }
//
// public File getHtmlDir() {
// return new File(rootDir, htmlDir);
// }
//
// public void setHttpPort(Integer httpPort) {
// this.httpPort = httpPort;
// }
//
// public void setServerName(String serverName) {
// this.name = serverName;
// }
//
// public void setPublicIp(String publicIp) {
// this.publicIp = publicIp;
// }
//
// public void setPrivateIp(String privateIp) {
// this.privateIp = privateIp;
// }
//
// public void setClusterPort(Integer clusterPort) {
// this.clusterPort = clusterPort;
// }
//
// public void setClusterIpAddress(String clusterIpAddress) {
// this.clusterIp = clusterIpAddress;
// }
//
// }
// Path: westty-sockjs/src/test/java/org/deephacks/westty/sockjs/SockJsTestEndpoint.java
import org.deephacks.westty.cluster.Cluster;
import org.deephacks.westty.config.ServerConfig;
import org.vertx.java.core.eventbus.EventBus;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.json.JsonObject;
import javax.inject.Inject;
import java.util.LinkedList;
package org.deephacks.westty.sockjs;
@SockJsEndpoint
public class SockJsTestEndpoint {
public static final String SERVER_ADDRESS = "server";
public static final String REPLY_ADDRESS = "reply";
public static final String CLIENT_ADDRESS = "client";
public static final LinkedList<JsonObject> messages = new LinkedList<>();
@Inject | private ServerConfig config; |
deephacks/westty | westty-sockjs/src/test/java/org/deephacks/westty/sockjs/SockJsTestEndpoint.java | // Path: westty-api/src/main/java/org/deephacks/westty/cluster/Cluster.java
// public interface Cluster {
//
// public Set<Server> getMembers();
//
// public <K, V> DistributedMultiMap<K, V> getMultiMap(String name);
//
// }
//
// Path: westty-api/src/main/java/org/deephacks/westty/config/ServerConfig.java
// @ConfigScope
// @Config(name = "servers",
// desc = "Server engine configuration. Changes requires server restart.")
// public class ServerConfig {
//
// public static final String DEFAULT_SERVER_NAME = "server";
// public static final String DEFAULT_CONF_DIR = "conf";
// public static final String DEFAULT_LIB_DIR = "lib";
// public static final String DEFAULT_BIN_DIR = "bin";
// public static final String DEFAULT_HTML_DIR = "html";
// public static final String DEFAULT_IP_ADDRESS = "127.0.0.1";
// public static final int DEFAULT_HTTP_PORT = 8080;
// public static final int DEFAULT_CLUSTER_PORT = 5701;
//
// @Id(desc="Name of this server")
// private String name = DEFAULT_SERVER_NAME;
//
// @Config(desc = "Public Ip Address.")
// private String publicIp = DEFAULT_IP_ADDRESS;
//
// @Config(desc = "Private Ip Address.")
// private String privateIp = DEFAULT_IP_ADDRESS;
//
// @Config(desc="Port that this server uses for the cluster.")
// private Integer clusterPort = DEFAULT_CLUSTER_PORT;
//
// @Config(desc="Ip address that this server uses for the cluster.")
// private String clusterIp = DEFAULT_IP_ADDRESS;
//
// @Config(desc = "Root directory.")
// private String rootDir = System.getProperty("root.dir");
//
// @Config(desc = "Location of the conf directory relative to the root directory.")
// private String confDir = DEFAULT_CONF_DIR;
//
// @Config(desc = "Location of the lib directory relative to the root directory.")
// private String libDir = DEFAULT_LIB_DIR;
//
// @Config(desc = "Location of the bin directory relative to the root directory.")
// private String binDir = DEFAULT_BIN_DIR;
//
// @Config(desc = "Location of the html directory relative to the root directory.")
// private String htmlDir = DEFAULT_HTML_DIR;
//
//
// @Config(desc = "Http listening port.")
// @NotNull
// @Min(0)
// @Max(65535)
// private Integer httpPort = DEFAULT_HTTP_PORT;
//
// @Config(desc = "Specify the worker count to use. "
// + "See netty javadoc NioServerSocketChannelFactory.")
// @Min(1)
// @NotNull
// private Integer ioWorkerCount = Runtime.getRuntime().availableProcessors() * 2;
//
// @Config(desc = "Set the max request size in bytes. If this size exceeded "
// + "\"413 Request Entity Too Large\" willl be sent to the client.")
// @NotNull
// @Min(4096)
// private Integer maxRequestSize = 1024 * 1024 * 10;
//
// @Config(desc = "Maximum byte length of aggregated http content. "
// + "TooLongFrameException raised if length exceeded.")
// @NotNull
// @Min(16384)
// private Integer maxHttpContentChunkLength = 65536;
//
// public ServerConfig() {
//
// }
//
// public ServerConfig(String serverName) {
// this.name = serverName;
// }
//
// public Integer getIoWorkerCount() {
// return ioWorkerCount;
// }
//
// public Integer getMaxRequestSize() {
// return maxRequestSize;
// }
//
// public Integer getHttpPort() {
// return httpPort;
// }
//
// public Integer getMaxHttpContentChunkLength() {
// return maxHttpContentChunkLength;
// }
//
// public String getPublicIp() {
// return publicIp;
// }
//
// public String getPrivateIp() {
// return privateIp;
// }
//
// public int getClusterPort() {
// return clusterPort;
// }
//
// public File getLibDir() {
// return new File(rootDir, libDir);
// }
//
// public File getConfDir() {
// return new File(rootDir, confDir);
// }
//
// public File getBinDir() {
// return new File(rootDir, binDir);
// }
//
// public File getHtmlDir() {
// return new File(rootDir, htmlDir);
// }
//
// public void setHttpPort(Integer httpPort) {
// this.httpPort = httpPort;
// }
//
// public void setServerName(String serverName) {
// this.name = serverName;
// }
//
// public void setPublicIp(String publicIp) {
// this.publicIp = publicIp;
// }
//
// public void setPrivateIp(String privateIp) {
// this.privateIp = privateIp;
// }
//
// public void setClusterPort(Integer clusterPort) {
// this.clusterPort = clusterPort;
// }
//
// public void setClusterIpAddress(String clusterIpAddress) {
// this.clusterIp = clusterIpAddress;
// }
//
// }
| import org.deephacks.westty.cluster.Cluster;
import org.deephacks.westty.config.ServerConfig;
import org.vertx.java.core.eventbus.EventBus;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.json.JsonObject;
import javax.inject.Inject;
import java.util.LinkedList; | package org.deephacks.westty.sockjs;
@SockJsEndpoint
public class SockJsTestEndpoint {
public static final String SERVER_ADDRESS = "server";
public static final String REPLY_ADDRESS = "reply";
public static final String CLIENT_ADDRESS = "client";
public static final LinkedList<JsonObject> messages = new LinkedList<>();
@Inject
private ServerConfig config;
@Inject | // Path: westty-api/src/main/java/org/deephacks/westty/cluster/Cluster.java
// public interface Cluster {
//
// public Set<Server> getMembers();
//
// public <K, V> DistributedMultiMap<K, V> getMultiMap(String name);
//
// }
//
// Path: westty-api/src/main/java/org/deephacks/westty/config/ServerConfig.java
// @ConfigScope
// @Config(name = "servers",
// desc = "Server engine configuration. Changes requires server restart.")
// public class ServerConfig {
//
// public static final String DEFAULT_SERVER_NAME = "server";
// public static final String DEFAULT_CONF_DIR = "conf";
// public static final String DEFAULT_LIB_DIR = "lib";
// public static final String DEFAULT_BIN_DIR = "bin";
// public static final String DEFAULT_HTML_DIR = "html";
// public static final String DEFAULT_IP_ADDRESS = "127.0.0.1";
// public static final int DEFAULT_HTTP_PORT = 8080;
// public static final int DEFAULT_CLUSTER_PORT = 5701;
//
// @Id(desc="Name of this server")
// private String name = DEFAULT_SERVER_NAME;
//
// @Config(desc = "Public Ip Address.")
// private String publicIp = DEFAULT_IP_ADDRESS;
//
// @Config(desc = "Private Ip Address.")
// private String privateIp = DEFAULT_IP_ADDRESS;
//
// @Config(desc="Port that this server uses for the cluster.")
// private Integer clusterPort = DEFAULT_CLUSTER_PORT;
//
// @Config(desc="Ip address that this server uses for the cluster.")
// private String clusterIp = DEFAULT_IP_ADDRESS;
//
// @Config(desc = "Root directory.")
// private String rootDir = System.getProperty("root.dir");
//
// @Config(desc = "Location of the conf directory relative to the root directory.")
// private String confDir = DEFAULT_CONF_DIR;
//
// @Config(desc = "Location of the lib directory relative to the root directory.")
// private String libDir = DEFAULT_LIB_DIR;
//
// @Config(desc = "Location of the bin directory relative to the root directory.")
// private String binDir = DEFAULT_BIN_DIR;
//
// @Config(desc = "Location of the html directory relative to the root directory.")
// private String htmlDir = DEFAULT_HTML_DIR;
//
//
// @Config(desc = "Http listening port.")
// @NotNull
// @Min(0)
// @Max(65535)
// private Integer httpPort = DEFAULT_HTTP_PORT;
//
// @Config(desc = "Specify the worker count to use. "
// + "See netty javadoc NioServerSocketChannelFactory.")
// @Min(1)
// @NotNull
// private Integer ioWorkerCount = Runtime.getRuntime().availableProcessors() * 2;
//
// @Config(desc = "Set the max request size in bytes. If this size exceeded "
// + "\"413 Request Entity Too Large\" willl be sent to the client.")
// @NotNull
// @Min(4096)
// private Integer maxRequestSize = 1024 * 1024 * 10;
//
// @Config(desc = "Maximum byte length of aggregated http content. "
// + "TooLongFrameException raised if length exceeded.")
// @NotNull
// @Min(16384)
// private Integer maxHttpContentChunkLength = 65536;
//
// public ServerConfig() {
//
// }
//
// public ServerConfig(String serverName) {
// this.name = serverName;
// }
//
// public Integer getIoWorkerCount() {
// return ioWorkerCount;
// }
//
// public Integer getMaxRequestSize() {
// return maxRequestSize;
// }
//
// public Integer getHttpPort() {
// return httpPort;
// }
//
// public Integer getMaxHttpContentChunkLength() {
// return maxHttpContentChunkLength;
// }
//
// public String getPublicIp() {
// return publicIp;
// }
//
// public String getPrivateIp() {
// return privateIp;
// }
//
// public int getClusterPort() {
// return clusterPort;
// }
//
// public File getLibDir() {
// return new File(rootDir, libDir);
// }
//
// public File getConfDir() {
// return new File(rootDir, confDir);
// }
//
// public File getBinDir() {
// return new File(rootDir, binDir);
// }
//
// public File getHtmlDir() {
// return new File(rootDir, htmlDir);
// }
//
// public void setHttpPort(Integer httpPort) {
// this.httpPort = httpPort;
// }
//
// public void setServerName(String serverName) {
// this.name = serverName;
// }
//
// public void setPublicIp(String publicIp) {
// this.publicIp = publicIp;
// }
//
// public void setPrivateIp(String privateIp) {
// this.privateIp = privateIp;
// }
//
// public void setClusterPort(Integer clusterPort) {
// this.clusterPort = clusterPort;
// }
//
// public void setClusterIpAddress(String clusterIpAddress) {
// this.clusterIp = clusterIpAddress;
// }
//
// }
// Path: westty-sockjs/src/test/java/org/deephacks/westty/sockjs/SockJsTestEndpoint.java
import org.deephacks.westty.cluster.Cluster;
import org.deephacks.westty.config.ServerConfig;
import org.vertx.java.core.eventbus.EventBus;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.json.JsonObject;
import javax.inject.Inject;
import java.util.LinkedList;
package org.deephacks.westty.sockjs;
@SockJsEndpoint
public class SockJsTestEndpoint {
public static final String SERVER_ADDRESS = "server";
public static final String REPLY_ADDRESS = "reply";
public static final String CLIENT_ADDRESS = "client";
public static final LinkedList<JsonObject> messages = new LinkedList<>();
@Inject
private ServerConfig config;
@Inject | private Cluster cluster; |
deephacks/westty | westty-tests/src/main/java/org/deephacks/westty/tests/ExceptionHandler.java | // Path: westty-protobuf/src/main/java/org/deephacks/westty/protobuf/ProtobufException.java
// public class ProtobufException extends RuntimeException {
//
// private static final long serialVersionUID = -7994691832123397253L;
// private Integer code;
// private String message;
//
// public ProtobufException(String message, Integer code) {
// this.code = Preconditions.checkNotNull(code);
// this.message = Preconditions.checkNotNull(message);
// }
//
// public ProtobufException(String message, Integer code, Exception e) {
// super(e);
// this.code = Preconditions.checkNotNull(code);
// }
//
// public static void throwBadRequest(String message) {
// throw new ProtobufException(message, FailureCode.BAD_REQUEST.code);
// }
//
// public static void throwUnauthorized(String message) {
// throw new ProtobufException(message, FailureCode.UNAUTHORIZED.code);
// }
//
// public static void throwForbidden(String message) {
// throw new ProtobufException(message, FailureCode.FORBIDDEN.code);
// }
//
// public static void throwNotFound(String message) {
// throw new ProtobufException(message, FailureCode.NOT_FOUND.code);
// }
//
// public static void throwTimeout(String message) {
// throw new ProtobufException(message, FailureCode.TIMEOUT.code);
// }
//
// public static void throwConflic(String message) {
// throw new ProtobufException(message, FailureCode.CONFLICT.code);
// }
//
// public static void throwGone(String message) {
// throw new ProtobufException(message, FailureCode.GONE.code);
// }
//
// public static void throwTooLarge(String message) {
// throw new ProtobufException(message, FailureCode.TOO_LARGE.code);
// }
//
// public static void throwInternalError(String message) {
// throw new ProtobufException(message, FailureCode.INTERNAL_ERROR.code);
// }
//
// public static void throwNotImplemented(String message) {
// throw new ProtobufException(message, FailureCode.NOT_IMPLEMENTED.code);
// }
//
// public static void throwServiceUnavailable(String message) {
// throw new ProtobufException(message, FailureCode.BAD_REQUEST.code);
// }
//
// public Integer getCode() {
// return code;
// }
//
// public String getProtobufMessage() {
// return message;
// }
//
// @Override
// public String getMessage() {
// return codeToString(code) + ": " + message;
// }
//
// static String codeToString(Integer code) {
// if (code == FailureCode.BAD_REQUEST.code) {
// return FailureCode.BAD_REQUEST.toString();
// } else if (code == FailureCode.UNAUTHORIZED.code) {
// return FailureCode.UNAUTHORIZED.toString();
// } else if (code == FailureCode.FORBIDDEN.code) {
// return FailureCode.FORBIDDEN.toString();
// } else if (code == FailureCode.NOT_FOUND.code) {
// return FailureCode.NOT_FOUND.toString();
// } else if (code == FailureCode.TIMEOUT.code) {
// return FailureCode.TIMEOUT.toString();
// } else if (code == FailureCode.CONFLICT.code) {
// return FailureCode.CONFLICT.toString();
// } else if (code == FailureCode.GONE.code) {
// return FailureCode.GONE.toString();
// } else if (code == FailureCode.TOO_LARGE.code) {
// return FailureCode.TOO_LARGE.toString();
// } else if (code == FailureCode.INTERNAL_ERROR.code) {
// return FailureCode.INTERNAL_ERROR.toString();
// } else if (code == FailureCode.NOT_IMPLEMENTED.code) {
// return FailureCode.NOT_IMPLEMENTED.toString();
// } else if (code == FailureCode.SERVICE_UNAVAILABLE.code) {
// return FailureCode.SERVICE_UNAVAILABLE.toString();
// } else {
// return Integer.toString(code);
// }
// }
//
// public static enum FailureCode {
// BAD_REQUEST(1), UNAUTHORIZED(2), FORBIDDEN(3), NOT_FOUND(4), TIMEOUT(5), CONFLICT(6), GONE(
// 6), TOO_LARGE(7), INTERNAL_ERROR(8), NOT_IMPLEMENTED(9), SERVICE_UNAVAILABLE(10);
// private final Integer code;
//
// private FailureCode(Integer code) {
// this.code = code;
// }
//
// public Integer getCode() {
// return code;
// }
// }
//
// }
| import org.deephacks.westty.protobuf.ProtobufException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper; | package org.deephacks.westty.tests;
public class ExceptionHandler implements ExceptionMapper<Exception> {
private static final Logger log = LoggerFactory.getLogger(ExceptionHandler.class);
public Response toResponse(Exception ex) {
log.warn("{}", ex.getMessage());
log.debug("Exception occured", ex);
Status status = null;
String message = "";
if (ex instanceof HttpException) {
HttpException e = ((HttpException) ex);
status = e.getCode();
message = e.getMessage(); | // Path: westty-protobuf/src/main/java/org/deephacks/westty/protobuf/ProtobufException.java
// public class ProtobufException extends RuntimeException {
//
// private static final long serialVersionUID = -7994691832123397253L;
// private Integer code;
// private String message;
//
// public ProtobufException(String message, Integer code) {
// this.code = Preconditions.checkNotNull(code);
// this.message = Preconditions.checkNotNull(message);
// }
//
// public ProtobufException(String message, Integer code, Exception e) {
// super(e);
// this.code = Preconditions.checkNotNull(code);
// }
//
// public static void throwBadRequest(String message) {
// throw new ProtobufException(message, FailureCode.BAD_REQUEST.code);
// }
//
// public static void throwUnauthorized(String message) {
// throw new ProtobufException(message, FailureCode.UNAUTHORIZED.code);
// }
//
// public static void throwForbidden(String message) {
// throw new ProtobufException(message, FailureCode.FORBIDDEN.code);
// }
//
// public static void throwNotFound(String message) {
// throw new ProtobufException(message, FailureCode.NOT_FOUND.code);
// }
//
// public static void throwTimeout(String message) {
// throw new ProtobufException(message, FailureCode.TIMEOUT.code);
// }
//
// public static void throwConflic(String message) {
// throw new ProtobufException(message, FailureCode.CONFLICT.code);
// }
//
// public static void throwGone(String message) {
// throw new ProtobufException(message, FailureCode.GONE.code);
// }
//
// public static void throwTooLarge(String message) {
// throw new ProtobufException(message, FailureCode.TOO_LARGE.code);
// }
//
// public static void throwInternalError(String message) {
// throw new ProtobufException(message, FailureCode.INTERNAL_ERROR.code);
// }
//
// public static void throwNotImplemented(String message) {
// throw new ProtobufException(message, FailureCode.NOT_IMPLEMENTED.code);
// }
//
// public static void throwServiceUnavailable(String message) {
// throw new ProtobufException(message, FailureCode.BAD_REQUEST.code);
// }
//
// public Integer getCode() {
// return code;
// }
//
// public String getProtobufMessage() {
// return message;
// }
//
// @Override
// public String getMessage() {
// return codeToString(code) + ": " + message;
// }
//
// static String codeToString(Integer code) {
// if (code == FailureCode.BAD_REQUEST.code) {
// return FailureCode.BAD_REQUEST.toString();
// } else if (code == FailureCode.UNAUTHORIZED.code) {
// return FailureCode.UNAUTHORIZED.toString();
// } else if (code == FailureCode.FORBIDDEN.code) {
// return FailureCode.FORBIDDEN.toString();
// } else if (code == FailureCode.NOT_FOUND.code) {
// return FailureCode.NOT_FOUND.toString();
// } else if (code == FailureCode.TIMEOUT.code) {
// return FailureCode.TIMEOUT.toString();
// } else if (code == FailureCode.CONFLICT.code) {
// return FailureCode.CONFLICT.toString();
// } else if (code == FailureCode.GONE.code) {
// return FailureCode.GONE.toString();
// } else if (code == FailureCode.TOO_LARGE.code) {
// return FailureCode.TOO_LARGE.toString();
// } else if (code == FailureCode.INTERNAL_ERROR.code) {
// return FailureCode.INTERNAL_ERROR.toString();
// } else if (code == FailureCode.NOT_IMPLEMENTED.code) {
// return FailureCode.NOT_IMPLEMENTED.toString();
// } else if (code == FailureCode.SERVICE_UNAVAILABLE.code) {
// return FailureCode.SERVICE_UNAVAILABLE.toString();
// } else {
// return Integer.toString(code);
// }
// }
//
// public static enum FailureCode {
// BAD_REQUEST(1), UNAUTHORIZED(2), FORBIDDEN(3), NOT_FOUND(4), TIMEOUT(5), CONFLICT(6), GONE(
// 6), TOO_LARGE(7), INTERNAL_ERROR(8), NOT_IMPLEMENTED(9), SERVICE_UNAVAILABLE(10);
// private final Integer code;
//
// private FailureCode(Integer code) {
// this.code = code;
// }
//
// public Integer getCode() {
// return code;
// }
// }
//
// }
// Path: westty-tests/src/main/java/org/deephacks/westty/tests/ExceptionHandler.java
import org.deephacks.westty.protobuf.ProtobufException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
package org.deephacks.westty.tests;
public class ExceptionHandler implements ExceptionMapper<Exception> {
private static final Logger log = LoggerFactory.getLogger(ExceptionHandler.class);
public Response toResponse(Exception ex) {
log.warn("{}", ex.getMessage());
log.debug("Exception occured", ex);
Status status = null;
String message = "";
if (ex instanceof HttpException) {
HttpException e = ((HttpException) ex);
status = e.getCode();
message = e.getMessage(); | } else if (ex instanceof ProtobufException) { |
deephacks/westty | westty-cluster/src/main/java/org/deephacks/westty/internal/cluster/WesttyEntryEvent.java | // Path: westty-api/src/main/java/org/deephacks/westty/cluster/EntryEvent.java
// public interface EntryEvent<K, V> {
// /**
// * Returns the key of the entry event
// *
// * @return the key
// */
// public K getKey();
//
// /**
// * Returns the old value of the entry event
// *
// * @return
// */
// public V getOldValue();
//
// /**
// * Returns the value of the entry event
// *
// * @return
// */
// public V getValue();
//
// /**
// * Returns the member fired this event.
// *
// * @return the member fired this event.
// */
// public Server getMember();
//
// /**
// * Return the event type
// *
// * @return event type
// */
// public EntryEventType getEventType();
//
// /**
// * Returns the name of the map for this event.
// *
// * @return name of the map.
// */
// public String getName();
//
// public static enum EntryEventType {
// ADDED(1), REMOVED(2), UPDATED(3), EVICTED(4);
//
// private int type;
//
// private EntryEventType(final int type) {
// this.type = type;
// }
//
// public int getType() {
// return type;
// }
//
// public static EntryEventType getByType(final int eventType) {
// for (EntryEventType entryEventType : values()) {
// if (entryEventType.type == eventType) {
// return entryEventType;
// }
// }
// return null;
// }
// }
//
// }
//
// Path: westty-api/src/main/java/org/deephacks/westty/server/Server.java
// public class Server implements Serializable {
//
// private int port;
// private String host;
//
// public Server(String host, int port) {
// this.port = port;
// this.host = host;
// }
//
// public Server() {
// }
//
// public int getPort(){
// return port;
// }
//
// public String getHost(){
// return host;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o)
// return true;
// if (o == null || getClass() != o.getClass())
// return false;
//
// Server server = (Server) o;
//
// if (port != server.port)
// return false;
// if (!host.equals(server.host))
// return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = port;
// result = 31 * result + host.hashCode();
// return result;
// }
//
// public String toString() {
// return host + ":" + port;
// }
//
// }
| import com.hazelcast.core.Member;
import org.deephacks.westty.cluster.EntryEvent;
import org.deephacks.westty.server.Server;
import java.net.InetSocketAddress; | package org.deephacks.westty.internal.cluster;
public class WesttyEntryEvent<K, V> implements EntryEvent<K, V> {
private com.hazelcast.core.EntryEvent<K, V> event;
public WesttyEntryEvent(com.hazelcast.core.EntryEvent<K, V> event) {
this.event = event;
}
@Override
public K getKey() {
return event.getKey();
}
@Override
public V getOldValue() {
return event.getOldValue();
}
@Override
public V getValue() {
return event.getValue();
}
@Override | // Path: westty-api/src/main/java/org/deephacks/westty/cluster/EntryEvent.java
// public interface EntryEvent<K, V> {
// /**
// * Returns the key of the entry event
// *
// * @return the key
// */
// public K getKey();
//
// /**
// * Returns the old value of the entry event
// *
// * @return
// */
// public V getOldValue();
//
// /**
// * Returns the value of the entry event
// *
// * @return
// */
// public V getValue();
//
// /**
// * Returns the member fired this event.
// *
// * @return the member fired this event.
// */
// public Server getMember();
//
// /**
// * Return the event type
// *
// * @return event type
// */
// public EntryEventType getEventType();
//
// /**
// * Returns the name of the map for this event.
// *
// * @return name of the map.
// */
// public String getName();
//
// public static enum EntryEventType {
// ADDED(1), REMOVED(2), UPDATED(3), EVICTED(4);
//
// private int type;
//
// private EntryEventType(final int type) {
// this.type = type;
// }
//
// public int getType() {
// return type;
// }
//
// public static EntryEventType getByType(final int eventType) {
// for (EntryEventType entryEventType : values()) {
// if (entryEventType.type == eventType) {
// return entryEventType;
// }
// }
// return null;
// }
// }
//
// }
//
// Path: westty-api/src/main/java/org/deephacks/westty/server/Server.java
// public class Server implements Serializable {
//
// private int port;
// private String host;
//
// public Server(String host, int port) {
// this.port = port;
// this.host = host;
// }
//
// public Server() {
// }
//
// public int getPort(){
// return port;
// }
//
// public String getHost(){
// return host;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o)
// return true;
// if (o == null || getClass() != o.getClass())
// return false;
//
// Server server = (Server) o;
//
// if (port != server.port)
// return false;
// if (!host.equals(server.host))
// return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = port;
// result = 31 * result + host.hashCode();
// return result;
// }
//
// public String toString() {
// return host + ":" + port;
// }
//
// }
// Path: westty-cluster/src/main/java/org/deephacks/westty/internal/cluster/WesttyEntryEvent.java
import com.hazelcast.core.Member;
import org.deephacks.westty.cluster.EntryEvent;
import org.deephacks.westty.server.Server;
import java.net.InetSocketAddress;
package org.deephacks.westty.internal.cluster;
public class WesttyEntryEvent<K, V> implements EntryEvent<K, V> {
private com.hazelcast.core.EntryEvent<K, V> event;
public WesttyEntryEvent(com.hazelcast.core.EntryEvent<K, V> event) {
this.event = event;
}
@Override
public K getKey() {
return event.getKey();
}
@Override
public V getOldValue() {
return event.getOldValue();
}
@Override
public V getValue() {
return event.getValue();
}
@Override | public Server getMember() { |
deephacks/westty | westty-cluster/src/main/java/org/deephacks/westty/internal/cluster/WesttyDistributedMultiMap.java | // Path: westty-api/src/main/java/org/deephacks/westty/cluster/ClusterListener.java
// public interface ClusterListener<K, V> {
// /**
// * Invoked when an entry is added.
// *
// * @param event entry event
// */
// void entryAdded(EntryEvent<K, V> event);
//
// /**
// * Invoked when an entry is removed.
// *
// * @param event entry event
// */
// void entryRemoved(EntryEvent<K, V> event);
//
// /**
// * Invoked when an entry is updated.
// *
// * @param event entry event
// */
// void entryUpdated(EntryEvent<K, V> event);
//
// /**
// * Invoked when an entry is evicted.
// *
// * @param event entry event
// */
// void entryEvicted(EntryEvent<K, V> event);
//
// }
//
// Path: westty-api/src/main/java/org/deephacks/westty/cluster/DistributedMultiMap.java
// public interface DistributedMultiMap<K, V> {
//
// boolean remove(Object key, Object value);
//
// boolean put(K key, V value);
//
// void addEntryListener(ClusterListener<K, V> listener, boolean includeValue);
//
// Set<Map.Entry<K, V>> entrySet();
//
// Collection<V> get(K key);
// }
| import com.hazelcast.core.EntryEvent;
import com.hazelcast.core.EntryListener;
import com.hazelcast.core.MultiMap;
import org.deephacks.westty.cluster.ClusterListener;
import org.deephacks.westty.cluster.DistributedMultiMap;
import java.util.Collection;
import java.util.Map.Entry;
import java.util.Set; | package org.deephacks.westty.internal.cluster;
class WesttyDistributedMultiMap<K, V> implements DistributedMultiMap<K, V> {
private MultiMap<K, V> map;
public WesttyDistributedMultiMap(MultiMap<K, V> map) {
this.map = map;
}
@Override
public boolean remove(Object key, Object value) {
return map.remove(key, value);
}
@Override
public boolean put(K key, V value) {
return map.put(key, value);
}
@Override | // Path: westty-api/src/main/java/org/deephacks/westty/cluster/ClusterListener.java
// public interface ClusterListener<K, V> {
// /**
// * Invoked when an entry is added.
// *
// * @param event entry event
// */
// void entryAdded(EntryEvent<K, V> event);
//
// /**
// * Invoked when an entry is removed.
// *
// * @param event entry event
// */
// void entryRemoved(EntryEvent<K, V> event);
//
// /**
// * Invoked when an entry is updated.
// *
// * @param event entry event
// */
// void entryUpdated(EntryEvent<K, V> event);
//
// /**
// * Invoked when an entry is evicted.
// *
// * @param event entry event
// */
// void entryEvicted(EntryEvent<K, V> event);
//
// }
//
// Path: westty-api/src/main/java/org/deephacks/westty/cluster/DistributedMultiMap.java
// public interface DistributedMultiMap<K, V> {
//
// boolean remove(Object key, Object value);
//
// boolean put(K key, V value);
//
// void addEntryListener(ClusterListener<K, V> listener, boolean includeValue);
//
// Set<Map.Entry<K, V>> entrySet();
//
// Collection<V> get(K key);
// }
// Path: westty-cluster/src/main/java/org/deephacks/westty/internal/cluster/WesttyDistributedMultiMap.java
import com.hazelcast.core.EntryEvent;
import com.hazelcast.core.EntryListener;
import com.hazelcast.core.MultiMap;
import org.deephacks.westty.cluster.ClusterListener;
import org.deephacks.westty.cluster.DistributedMultiMap;
import java.util.Collection;
import java.util.Map.Entry;
import java.util.Set;
package org.deephacks.westty.internal.cluster;
class WesttyDistributedMultiMap<K, V> implements DistributedMultiMap<K, V> {
private MultiMap<K, V> map;
public WesttyDistributedMultiMap(MultiMap<K, V> map) {
this.map = map;
}
@Override
public boolean remove(Object key, Object value) {
return map.remove(key, value);
}
@Override
public boolean put(K key, V value) {
return map.put(key, value);
}
@Override | public void addEntryListener(final ClusterListener<K, V> listener, boolean includeValue) { |
deephacks/westty | westty-tests/src/test/java/org/deephacks/westty/tests/JaxrsClient.java | // Path: westty-api/src/main/java/org/deephacks/westty/config/ServerConfig.java
// @ConfigScope
// @Config(name = "servers",
// desc = "Server engine configuration. Changes requires server restart.")
// public class ServerConfig {
//
// public static final String DEFAULT_SERVER_NAME = "server";
// public static final String DEFAULT_CONF_DIR = "conf";
// public static final String DEFAULT_LIB_DIR = "lib";
// public static final String DEFAULT_BIN_DIR = "bin";
// public static final String DEFAULT_HTML_DIR = "html";
// public static final String DEFAULT_IP_ADDRESS = "127.0.0.1";
// public static final int DEFAULT_HTTP_PORT = 8080;
// public static final int DEFAULT_CLUSTER_PORT = 5701;
//
// @Id(desc="Name of this server")
// private String name = DEFAULT_SERVER_NAME;
//
// @Config(desc = "Public Ip Address.")
// private String publicIp = DEFAULT_IP_ADDRESS;
//
// @Config(desc = "Private Ip Address.")
// private String privateIp = DEFAULT_IP_ADDRESS;
//
// @Config(desc="Port that this server uses for the cluster.")
// private Integer clusterPort = DEFAULT_CLUSTER_PORT;
//
// @Config(desc="Ip address that this server uses for the cluster.")
// private String clusterIp = DEFAULT_IP_ADDRESS;
//
// @Config(desc = "Root directory.")
// private String rootDir = System.getProperty("root.dir");
//
// @Config(desc = "Location of the conf directory relative to the root directory.")
// private String confDir = DEFAULT_CONF_DIR;
//
// @Config(desc = "Location of the lib directory relative to the root directory.")
// private String libDir = DEFAULT_LIB_DIR;
//
// @Config(desc = "Location of the bin directory relative to the root directory.")
// private String binDir = DEFAULT_BIN_DIR;
//
// @Config(desc = "Location of the html directory relative to the root directory.")
// private String htmlDir = DEFAULT_HTML_DIR;
//
//
// @Config(desc = "Http listening port.")
// @NotNull
// @Min(0)
// @Max(65535)
// private Integer httpPort = DEFAULT_HTTP_PORT;
//
// @Config(desc = "Specify the worker count to use. "
// + "See netty javadoc NioServerSocketChannelFactory.")
// @Min(1)
// @NotNull
// private Integer ioWorkerCount = Runtime.getRuntime().availableProcessors() * 2;
//
// @Config(desc = "Set the max request size in bytes. If this size exceeded "
// + "\"413 Request Entity Too Large\" willl be sent to the client.")
// @NotNull
// @Min(4096)
// private Integer maxRequestSize = 1024 * 1024 * 10;
//
// @Config(desc = "Maximum byte length of aggregated http content. "
// + "TooLongFrameException raised if length exceeded.")
// @NotNull
// @Min(16384)
// private Integer maxHttpContentChunkLength = 65536;
//
// public ServerConfig() {
//
// }
//
// public ServerConfig(String serverName) {
// this.name = serverName;
// }
//
// public Integer getIoWorkerCount() {
// return ioWorkerCount;
// }
//
// public Integer getMaxRequestSize() {
// return maxRequestSize;
// }
//
// public Integer getHttpPort() {
// return httpPort;
// }
//
// public Integer getMaxHttpContentChunkLength() {
// return maxHttpContentChunkLength;
// }
//
// public String getPublicIp() {
// return publicIp;
// }
//
// public String getPrivateIp() {
// return privateIp;
// }
//
// public int getClusterPort() {
// return clusterPort;
// }
//
// public File getLibDir() {
// return new File(rootDir, libDir);
// }
//
// public File getConfDir() {
// return new File(rootDir, confDir);
// }
//
// public File getBinDir() {
// return new File(rootDir, binDir);
// }
//
// public File getHtmlDir() {
// return new File(rootDir, htmlDir);
// }
//
// public void setHttpPort(Integer httpPort) {
// this.httpPort = httpPort;
// }
//
// public void setServerName(String serverName) {
// this.name = serverName;
// }
//
// public void setPublicIp(String publicIp) {
// this.publicIp = publicIp;
// }
//
// public void setPrivateIp(String privateIp) {
// this.privateIp = privateIp;
// }
//
// public void setClusterPort(Integer clusterPort) {
// this.clusterPort = clusterPort;
// }
//
// public void setClusterIpAddress(String clusterIpAddress) {
// this.clusterIp = clusterIpAddress;
// }
//
// }
| import com.google.common.base.Charsets;
import com.google.common.io.CharStreams;
import com.google.common.io.Closeables;
import org.deephacks.westty.config.ServerConfig;
import javax.ws.rs.core.Response.Status;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import static javax.ws.rs.core.HttpHeaders.CONTENT_TYPE;
import static javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON; | package org.deephacks.westty.tests;
public class JaxrsClient {
private final String address;
public JaxrsClient() { | // Path: westty-api/src/main/java/org/deephacks/westty/config/ServerConfig.java
// @ConfigScope
// @Config(name = "servers",
// desc = "Server engine configuration. Changes requires server restart.")
// public class ServerConfig {
//
// public static final String DEFAULT_SERVER_NAME = "server";
// public static final String DEFAULT_CONF_DIR = "conf";
// public static final String DEFAULT_LIB_DIR = "lib";
// public static final String DEFAULT_BIN_DIR = "bin";
// public static final String DEFAULT_HTML_DIR = "html";
// public static final String DEFAULT_IP_ADDRESS = "127.0.0.1";
// public static final int DEFAULT_HTTP_PORT = 8080;
// public static final int DEFAULT_CLUSTER_PORT = 5701;
//
// @Id(desc="Name of this server")
// private String name = DEFAULT_SERVER_NAME;
//
// @Config(desc = "Public Ip Address.")
// private String publicIp = DEFAULT_IP_ADDRESS;
//
// @Config(desc = "Private Ip Address.")
// private String privateIp = DEFAULT_IP_ADDRESS;
//
// @Config(desc="Port that this server uses for the cluster.")
// private Integer clusterPort = DEFAULT_CLUSTER_PORT;
//
// @Config(desc="Ip address that this server uses for the cluster.")
// private String clusterIp = DEFAULT_IP_ADDRESS;
//
// @Config(desc = "Root directory.")
// private String rootDir = System.getProperty("root.dir");
//
// @Config(desc = "Location of the conf directory relative to the root directory.")
// private String confDir = DEFAULT_CONF_DIR;
//
// @Config(desc = "Location of the lib directory relative to the root directory.")
// private String libDir = DEFAULT_LIB_DIR;
//
// @Config(desc = "Location of the bin directory relative to the root directory.")
// private String binDir = DEFAULT_BIN_DIR;
//
// @Config(desc = "Location of the html directory relative to the root directory.")
// private String htmlDir = DEFAULT_HTML_DIR;
//
//
// @Config(desc = "Http listening port.")
// @NotNull
// @Min(0)
// @Max(65535)
// private Integer httpPort = DEFAULT_HTTP_PORT;
//
// @Config(desc = "Specify the worker count to use. "
// + "See netty javadoc NioServerSocketChannelFactory.")
// @Min(1)
// @NotNull
// private Integer ioWorkerCount = Runtime.getRuntime().availableProcessors() * 2;
//
// @Config(desc = "Set the max request size in bytes. If this size exceeded "
// + "\"413 Request Entity Too Large\" willl be sent to the client.")
// @NotNull
// @Min(4096)
// private Integer maxRequestSize = 1024 * 1024 * 10;
//
// @Config(desc = "Maximum byte length of aggregated http content. "
// + "TooLongFrameException raised if length exceeded.")
// @NotNull
// @Min(16384)
// private Integer maxHttpContentChunkLength = 65536;
//
// public ServerConfig() {
//
// }
//
// public ServerConfig(String serverName) {
// this.name = serverName;
// }
//
// public Integer getIoWorkerCount() {
// return ioWorkerCount;
// }
//
// public Integer getMaxRequestSize() {
// return maxRequestSize;
// }
//
// public Integer getHttpPort() {
// return httpPort;
// }
//
// public Integer getMaxHttpContentChunkLength() {
// return maxHttpContentChunkLength;
// }
//
// public String getPublicIp() {
// return publicIp;
// }
//
// public String getPrivateIp() {
// return privateIp;
// }
//
// public int getClusterPort() {
// return clusterPort;
// }
//
// public File getLibDir() {
// return new File(rootDir, libDir);
// }
//
// public File getConfDir() {
// return new File(rootDir, confDir);
// }
//
// public File getBinDir() {
// return new File(rootDir, binDir);
// }
//
// public File getHtmlDir() {
// return new File(rootDir, htmlDir);
// }
//
// public void setHttpPort(Integer httpPort) {
// this.httpPort = httpPort;
// }
//
// public void setServerName(String serverName) {
// this.name = serverName;
// }
//
// public void setPublicIp(String publicIp) {
// this.publicIp = publicIp;
// }
//
// public void setPrivateIp(String privateIp) {
// this.privateIp = privateIp;
// }
//
// public void setClusterPort(Integer clusterPort) {
// this.clusterPort = clusterPort;
// }
//
// public void setClusterIpAddress(String clusterIpAddress) {
// this.clusterIp = clusterIpAddress;
// }
//
// }
// Path: westty-tests/src/test/java/org/deephacks/westty/tests/JaxrsClient.java
import com.google.common.base.Charsets;
import com.google.common.io.CharStreams;
import com.google.common.io.Closeables;
import org.deephacks.westty.config.ServerConfig;
import javax.ws.rs.core.Response.Status;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import static javax.ws.rs.core.HttpHeaders.CONTENT_TYPE;
import static javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
package org.deephacks.westty.tests;
public class JaxrsClient {
private final String address;
public JaxrsClient() { | this(ServerConfig.DEFAULT_IP_ADDRESS, ServerConfig.DEFAULT_HTTP_PORT); |
deephacks/westty | westty-sockjs/src/main/java/org/deephacks/westty/internal/sockjs/WesttySubsMap.java | // Path: westty-api/src/main/java/org/deephacks/westty/cluster/ClusterListener.java
// public interface ClusterListener<K, V> {
// /**
// * Invoked when an entry is added.
// *
// * @param event entry event
// */
// void entryAdded(EntryEvent<K, V> event);
//
// /**
// * Invoked when an entry is removed.
// *
// * @param event entry event
// */
// void entryRemoved(EntryEvent<K, V> event);
//
// /**
// * Invoked when an entry is updated.
// *
// * @param event entry event
// */
// void entryUpdated(EntryEvent<K, V> event);
//
// /**
// * Invoked when an entry is evicted.
// *
// * @param event entry event
// */
// void entryEvicted(EntryEvent<K, V> event);
//
// }
//
// Path: westty-api/src/main/java/org/deephacks/westty/cluster/DistributedMultiMap.java
// public interface DistributedMultiMap<K, V> {
//
// boolean remove(Object key, Object value);
//
// boolean put(K key, V value);
//
// void addEntryListener(ClusterListener<K, V> listener, boolean includeValue);
//
// Set<Map.Entry<K, V>> entrySet();
//
// Collection<V> get(K key);
// }
//
// Path: westty-api/src/main/java/org/deephacks/westty/cluster/EntryEvent.java
// public interface EntryEvent<K, V> {
// /**
// * Returns the key of the entry event
// *
// * @return the key
// */
// public K getKey();
//
// /**
// * Returns the old value of the entry event
// *
// * @return
// */
// public V getOldValue();
//
// /**
// * Returns the value of the entry event
// *
// * @return
// */
// public V getValue();
//
// /**
// * Returns the member fired this event.
// *
// * @return the member fired this event.
// */
// public Server getMember();
//
// /**
// * Return the event type
// *
// * @return event type
// */
// public EntryEventType getEventType();
//
// /**
// * Returns the name of the map for this event.
// *
// * @return name of the map.
// */
// public String getName();
//
// public static enum EntryEventType {
// ADDED(1), REMOVED(2), UPDATED(3), EVICTED(4);
//
// private int type;
//
// private EntryEventType(final int type) {
// this.type = type;
// }
//
// public int getType() {
// return type;
// }
//
// public static EntryEventType getByType(final int eventType) {
// for (EntryEventType entryEventType : values()) {
// if (entryEventType.type == eventType) {
// return entryEventType;
// }
// }
// return null;
// }
// }
//
// }
| import org.deephacks.westty.cluster.ClusterListener;
import org.deephacks.westty.cluster.DistributedMultiMap;
import org.deephacks.westty.cluster.EntryEvent;
import org.vertx.java.core.AsyncResult;
import org.vertx.java.core.AsyncResultHandler;
import org.vertx.java.core.eventbus.impl.ServerIDs;
import org.vertx.java.core.eventbus.impl.SubsMap;
import org.vertx.java.core.eventbus.impl.hazelcast.HazelcastServerID;
import org.vertx.java.core.impl.BlockingAction;
import org.vertx.java.core.impl.VertxInternal;
import org.vertx.java.core.net.impl.ServerID;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap; | package org.deephacks.westty.internal.sockjs;
/**
* Modified version of HazelcastSubsMap by <a href="http://tfox.org">Tim Fox</a>.
*
* Purpose is to decouple hazelcast implementation from Vertx.
*/
public class WesttySubsMap implements SubsMap, ClusterListener<String, HazelcastServerID> {
private final VertxInternal vertx; | // Path: westty-api/src/main/java/org/deephacks/westty/cluster/ClusterListener.java
// public interface ClusterListener<K, V> {
// /**
// * Invoked when an entry is added.
// *
// * @param event entry event
// */
// void entryAdded(EntryEvent<K, V> event);
//
// /**
// * Invoked when an entry is removed.
// *
// * @param event entry event
// */
// void entryRemoved(EntryEvent<K, V> event);
//
// /**
// * Invoked when an entry is updated.
// *
// * @param event entry event
// */
// void entryUpdated(EntryEvent<K, V> event);
//
// /**
// * Invoked when an entry is evicted.
// *
// * @param event entry event
// */
// void entryEvicted(EntryEvent<K, V> event);
//
// }
//
// Path: westty-api/src/main/java/org/deephacks/westty/cluster/DistributedMultiMap.java
// public interface DistributedMultiMap<K, V> {
//
// boolean remove(Object key, Object value);
//
// boolean put(K key, V value);
//
// void addEntryListener(ClusterListener<K, V> listener, boolean includeValue);
//
// Set<Map.Entry<K, V>> entrySet();
//
// Collection<V> get(K key);
// }
//
// Path: westty-api/src/main/java/org/deephacks/westty/cluster/EntryEvent.java
// public interface EntryEvent<K, V> {
// /**
// * Returns the key of the entry event
// *
// * @return the key
// */
// public K getKey();
//
// /**
// * Returns the old value of the entry event
// *
// * @return
// */
// public V getOldValue();
//
// /**
// * Returns the value of the entry event
// *
// * @return
// */
// public V getValue();
//
// /**
// * Returns the member fired this event.
// *
// * @return the member fired this event.
// */
// public Server getMember();
//
// /**
// * Return the event type
// *
// * @return event type
// */
// public EntryEventType getEventType();
//
// /**
// * Returns the name of the map for this event.
// *
// * @return name of the map.
// */
// public String getName();
//
// public static enum EntryEventType {
// ADDED(1), REMOVED(2), UPDATED(3), EVICTED(4);
//
// private int type;
//
// private EntryEventType(final int type) {
// this.type = type;
// }
//
// public int getType() {
// return type;
// }
//
// public static EntryEventType getByType(final int eventType) {
// for (EntryEventType entryEventType : values()) {
// if (entryEventType.type == eventType) {
// return entryEventType;
// }
// }
// return null;
// }
// }
//
// }
// Path: westty-sockjs/src/main/java/org/deephacks/westty/internal/sockjs/WesttySubsMap.java
import org.deephacks.westty.cluster.ClusterListener;
import org.deephacks.westty.cluster.DistributedMultiMap;
import org.deephacks.westty.cluster.EntryEvent;
import org.vertx.java.core.AsyncResult;
import org.vertx.java.core.AsyncResultHandler;
import org.vertx.java.core.eventbus.impl.ServerIDs;
import org.vertx.java.core.eventbus.impl.SubsMap;
import org.vertx.java.core.eventbus.impl.hazelcast.HazelcastServerID;
import org.vertx.java.core.impl.BlockingAction;
import org.vertx.java.core.impl.VertxInternal;
import org.vertx.java.core.net.impl.ServerID;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
package org.deephacks.westty.internal.sockjs;
/**
* Modified version of HazelcastSubsMap by <a href="http://tfox.org">Tim Fox</a>.
*
* Purpose is to decouple hazelcast implementation from Vertx.
*/
public class WesttySubsMap implements SubsMap, ClusterListener<String, HazelcastServerID> {
private final VertxInternal vertx; | private final DistributedMultiMap<String, HazelcastServerID> map; |
deephacks/westty | westty-sockjs/src/main/java/org/deephacks/westty/internal/sockjs/WesttySubsMap.java | // Path: westty-api/src/main/java/org/deephacks/westty/cluster/ClusterListener.java
// public interface ClusterListener<K, V> {
// /**
// * Invoked when an entry is added.
// *
// * @param event entry event
// */
// void entryAdded(EntryEvent<K, V> event);
//
// /**
// * Invoked when an entry is removed.
// *
// * @param event entry event
// */
// void entryRemoved(EntryEvent<K, V> event);
//
// /**
// * Invoked when an entry is updated.
// *
// * @param event entry event
// */
// void entryUpdated(EntryEvent<K, V> event);
//
// /**
// * Invoked when an entry is evicted.
// *
// * @param event entry event
// */
// void entryEvicted(EntryEvent<K, V> event);
//
// }
//
// Path: westty-api/src/main/java/org/deephacks/westty/cluster/DistributedMultiMap.java
// public interface DistributedMultiMap<K, V> {
//
// boolean remove(Object key, Object value);
//
// boolean put(K key, V value);
//
// void addEntryListener(ClusterListener<K, V> listener, boolean includeValue);
//
// Set<Map.Entry<K, V>> entrySet();
//
// Collection<V> get(K key);
// }
//
// Path: westty-api/src/main/java/org/deephacks/westty/cluster/EntryEvent.java
// public interface EntryEvent<K, V> {
// /**
// * Returns the key of the entry event
// *
// * @return the key
// */
// public K getKey();
//
// /**
// * Returns the old value of the entry event
// *
// * @return
// */
// public V getOldValue();
//
// /**
// * Returns the value of the entry event
// *
// * @return
// */
// public V getValue();
//
// /**
// * Returns the member fired this event.
// *
// * @return the member fired this event.
// */
// public Server getMember();
//
// /**
// * Return the event type
// *
// * @return event type
// */
// public EntryEventType getEventType();
//
// /**
// * Returns the name of the map for this event.
// *
// * @return name of the map.
// */
// public String getName();
//
// public static enum EntryEventType {
// ADDED(1), REMOVED(2), UPDATED(3), EVICTED(4);
//
// private int type;
//
// private EntryEventType(final int type) {
// this.type = type;
// }
//
// public int getType() {
// return type;
// }
//
// public static EntryEventType getByType(final int eventType) {
// for (EntryEventType entryEventType : values()) {
// if (entryEventType.type == eventType) {
// return entryEventType;
// }
// }
// return null;
// }
// }
//
// }
| import org.deephacks.westty.cluster.ClusterListener;
import org.deephacks.westty.cluster.DistributedMultiMap;
import org.deephacks.westty.cluster.EntryEvent;
import org.vertx.java.core.AsyncResult;
import org.vertx.java.core.AsyncResultHandler;
import org.vertx.java.core.eventbus.impl.ServerIDs;
import org.vertx.java.core.eventbus.impl.SubsMap;
import org.vertx.java.core.eventbus.impl.hazelcast.HazelcastServerID;
import org.vertx.java.core.impl.BlockingAction;
import org.vertx.java.core.impl.VertxInternal;
import org.vertx.java.core.net.impl.ServerID;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap; | // Merge them
prev.merge(sids);
sids = prev;
}
sids.setInitialised();
sresult = new AsyncResult<>(sids);
} else {
sresult = new AsyncResult<>(result.exception);
}
completionHandler.handle(sresult);
}
}) {
public Collection<HazelcastServerID> action() throws Exception {
return map.get(subName);
}
}.run();
}
}
@Override
public void remove(final String subName, final ServerID serverID,
final AsyncResultHandler<Boolean> completionHandler) {
new BlockingAction<Boolean>(vertx, completionHandler) {
public Boolean action() throws Exception {
return map.remove(subName, new HazelcastServerID(serverID));
}
}.run();
}
@Override | // Path: westty-api/src/main/java/org/deephacks/westty/cluster/ClusterListener.java
// public interface ClusterListener<K, V> {
// /**
// * Invoked when an entry is added.
// *
// * @param event entry event
// */
// void entryAdded(EntryEvent<K, V> event);
//
// /**
// * Invoked when an entry is removed.
// *
// * @param event entry event
// */
// void entryRemoved(EntryEvent<K, V> event);
//
// /**
// * Invoked when an entry is updated.
// *
// * @param event entry event
// */
// void entryUpdated(EntryEvent<K, V> event);
//
// /**
// * Invoked when an entry is evicted.
// *
// * @param event entry event
// */
// void entryEvicted(EntryEvent<K, V> event);
//
// }
//
// Path: westty-api/src/main/java/org/deephacks/westty/cluster/DistributedMultiMap.java
// public interface DistributedMultiMap<K, V> {
//
// boolean remove(Object key, Object value);
//
// boolean put(K key, V value);
//
// void addEntryListener(ClusterListener<K, V> listener, boolean includeValue);
//
// Set<Map.Entry<K, V>> entrySet();
//
// Collection<V> get(K key);
// }
//
// Path: westty-api/src/main/java/org/deephacks/westty/cluster/EntryEvent.java
// public interface EntryEvent<K, V> {
// /**
// * Returns the key of the entry event
// *
// * @return the key
// */
// public K getKey();
//
// /**
// * Returns the old value of the entry event
// *
// * @return
// */
// public V getOldValue();
//
// /**
// * Returns the value of the entry event
// *
// * @return
// */
// public V getValue();
//
// /**
// * Returns the member fired this event.
// *
// * @return the member fired this event.
// */
// public Server getMember();
//
// /**
// * Return the event type
// *
// * @return event type
// */
// public EntryEventType getEventType();
//
// /**
// * Returns the name of the map for this event.
// *
// * @return name of the map.
// */
// public String getName();
//
// public static enum EntryEventType {
// ADDED(1), REMOVED(2), UPDATED(3), EVICTED(4);
//
// private int type;
//
// private EntryEventType(final int type) {
// this.type = type;
// }
//
// public int getType() {
// return type;
// }
//
// public static EntryEventType getByType(final int eventType) {
// for (EntryEventType entryEventType : values()) {
// if (entryEventType.type == eventType) {
// return entryEventType;
// }
// }
// return null;
// }
// }
//
// }
// Path: westty-sockjs/src/main/java/org/deephacks/westty/internal/sockjs/WesttySubsMap.java
import org.deephacks.westty.cluster.ClusterListener;
import org.deephacks.westty.cluster.DistributedMultiMap;
import org.deephacks.westty.cluster.EntryEvent;
import org.vertx.java.core.AsyncResult;
import org.vertx.java.core.AsyncResultHandler;
import org.vertx.java.core.eventbus.impl.ServerIDs;
import org.vertx.java.core.eventbus.impl.SubsMap;
import org.vertx.java.core.eventbus.impl.hazelcast.HazelcastServerID;
import org.vertx.java.core.impl.BlockingAction;
import org.vertx.java.core.impl.VertxInternal;
import org.vertx.java.core.net.impl.ServerID;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
// Merge them
prev.merge(sids);
sids = prev;
}
sids.setInitialised();
sresult = new AsyncResult<>(sids);
} else {
sresult = new AsyncResult<>(result.exception);
}
completionHandler.handle(sresult);
}
}) {
public Collection<HazelcastServerID> action() throws Exception {
return map.get(subName);
}
}.run();
}
}
@Override
public void remove(final String subName, final ServerID serverID,
final AsyncResultHandler<Boolean> completionHandler) {
new BlockingAction<Boolean>(vertx, completionHandler) {
public Boolean action() throws Exception {
return map.remove(subName, new HazelcastServerID(serverID));
}
}.run();
}
@Override | public void entryAdded(EntryEvent<String, HazelcastServerID> entry) { |
deephacks/westty | westty-job/src/main/java/org/deephacks/westty/internal/job/Rescheduler.java | // Path: westty-job/src/main/java/org/deephacks/westty/job/Job.java
// public interface Job {
// public void execute(JobData map);
// }
//
// Path: westty-job/src/main/java/org/deephacks/westty/job/JobData.java
// public interface JobData {
// public void put(String key, String value);
//
// public String get(String key);
// }
| import org.deephacks.westty.job.Job;
import org.deephacks.westty.job.JobData;
import org.deephacks.westty.job.Schedule;
import javax.inject.Inject; | /**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.deephacks.westty.internal.job;
@Schedule("*/10 * * * * ?")
class Rescheduler implements Job {
@Inject
private JobSchedulerBootstrap scheduler;
@Override | // Path: westty-job/src/main/java/org/deephacks/westty/job/Job.java
// public interface Job {
// public void execute(JobData map);
// }
//
// Path: westty-job/src/main/java/org/deephacks/westty/job/JobData.java
// public interface JobData {
// public void put(String key, String value);
//
// public String get(String key);
// }
// Path: westty-job/src/main/java/org/deephacks/westty/internal/job/Rescheduler.java
import org.deephacks.westty.job.Job;
import org.deephacks.westty.job.JobData;
import org.deephacks.westty.job.Schedule;
import javax.inject.Inject;
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.deephacks.westty.internal.job;
@Schedule("*/10 * * * * ?")
class Rescheduler implements Job {
@Inject
private JobSchedulerBootstrap scheduler;
@Override | public void execute(JobData map) { |
deephacks/westty | westty-job/src/main/java/org/deephacks/westty/internal/job/JobExtension.java | // Path: westty-job/src/main/java/org/deephacks/westty/job/Job.java
// public interface Job {
// public void execute(JobData map);
// }
| import java.util.HashSet;
import java.util.Set;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.spi.AfterBeanDiscovery;
import javax.enterprise.inject.spi.AnnotatedType;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.Extension;
import javax.enterprise.inject.spi.ProcessAnnotatedType;
import org.deephacks.westty.job.Job;
import org.deephacks.westty.job.Schedule; | package org.deephacks.westty.internal.job;
class JobExtension implements Extension {
private static BeanManager bm; | // Path: westty-job/src/main/java/org/deephacks/westty/job/Job.java
// public interface Job {
// public void execute(JobData map);
// }
// Path: westty-job/src/main/java/org/deephacks/westty/internal/job/JobExtension.java
import java.util.HashSet;
import java.util.Set;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.spi.AfterBeanDiscovery;
import javax.enterprise.inject.spi.AnnotatedType;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.Extension;
import javax.enterprise.inject.spi.ProcessAnnotatedType;
import org.deephacks.westty.job.Job;
import org.deephacks.westty.job.Schedule;
package org.deephacks.westty.internal.job;
class JobExtension implements Extension {
private static BeanManager bm; | private static final Set<Class<? extends Job>> jobs = new HashSet<Class<? extends Job>>(); |
deephacks/westty | westty-core/src/main/java/org/deephacks/westty/internal/core/http/HttpUpstreamHandler.java | // Path: westty-core/src/main/java/org/deephacks/westty/internal/core/http/HttpDecoder.java
// public final static class WesttyHttpMessage extends DefaultHttpRequest {
// private HttpHandler handler;
//
// public WesttyHttpMessage(HttpVersion version, HttpMethod method, String uri,
// HttpHandler handler) {
// super(version, method, uri);
// this.handler = handler;
// }
//
// public HttpHandler getHandler() {
// return handler;
// }
// }
| import org.deephacks.westty.internal.core.http.HttpDecoder.WesttyHttpMessage;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.handler.codec.frame.TooLongFrameException;
import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.jboss.netty.handler.codec.http.HttpVersion.HTTP_1_1; | /**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.deephacks.westty.internal.core.http;
class HttpUpstreamHandler extends SimpleChannelUpstreamHandler {
private final static Logger log = LoggerFactory.getLogger(HttpUpstreamHandler.class);
private ChannelGroup clients = new DefaultChannelGroup("connected-clients");
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
clients.add(ctx.getChannel());
super.channelConnected(ctx, e);
}
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
clients.remove(ctx.getChannel());
super.channelClosed(ctx, e);
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { | // Path: westty-core/src/main/java/org/deephacks/westty/internal/core/http/HttpDecoder.java
// public final static class WesttyHttpMessage extends DefaultHttpRequest {
// private HttpHandler handler;
//
// public WesttyHttpMessage(HttpVersion version, HttpMethod method, String uri,
// HttpHandler handler) {
// super(version, method, uri);
// this.handler = handler;
// }
//
// public HttpHandler getHandler() {
// return handler;
// }
// }
// Path: westty-core/src/main/java/org/deephacks/westty/internal/core/http/HttpUpstreamHandler.java
import org.deephacks.westty.internal.core.http.HttpDecoder.WesttyHttpMessage;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;
import org.jboss.netty.handler.codec.frame.TooLongFrameException;
import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.jboss.netty.handler.codec.http.HttpVersion.HTTP_1_1;
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.deephacks.westty.internal.core.http;
class HttpUpstreamHandler extends SimpleChannelUpstreamHandler {
private final static Logger log = LoggerFactory.getLogger(HttpUpstreamHandler.class);
private ChannelGroup clients = new DefaultChannelGroup("connected-clients");
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
clients.add(ctx.getChannel());
super.channelConnected(ctx, e);
}
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
clients.remove(ctx.getChannel());
super.channelClosed(ctx, e);
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { | if (e.getMessage() instanceof WesttyHttpMessage) { |
deephacks/westty | westty-core/src/test/java/org/deephacks/westty/test/WesttyJUnit4Runner.java | // Path: westty-api/src/main/java/org/deephacks/westty/Westty.java
// public class Westty {
// private static final String WESTTY_CORE = "org.deephacks.westty.internal.core.WesttyCore";
// private static Object WESTTY;
// private String serverName;
// public static void main(String[] args) throws Throwable {
// Westty westty = new Westty();
// westty.startup();
// }
// public Westty() {
// if (WESTTY == null) {
// ClassLoader cl = Thread.currentThread().getContextClassLoader();
// try {
// WESTTY = cl.loadClass(WESTTY_CORE).newInstance();
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// }
//
// public Westty(String serverName){
// this();
// this.serverName = serverName;
// }
//
// public synchronized void startup() throws Throwable {
// if(serverName != null){
// call("setServerName", serverName);
// }
// call("startup");
// }
//
// public synchronized void shutdown() throws Throwable {
// call("shutdown");
// }
//
// public synchronized <V> V getInstance(Class<V> cls) throws Throwable {
// return (V) call("getInstance", cls);
// }
//
// public synchronized void stop() throws Throwable {
// call("shutdown");
// }
//
// private Object call(String method, Object... args) throws Throwable {
// try {
// Class<?> cls = WESTTY.getClass();
// if (args == null || args.length == 0) {
// return cls.getMethod(method).invoke(WESTTY);
// } else {
// Class<?>[] classes = new Class<?>[args.length];
// for (int i = 0; i < args.length; i++) {
// classes[i] = args[i].getClass();
// }
// Method m = cls.getMethod(method, classes);
// return m.invoke(WESTTY, args);
// }
// } catch (InvocationTargetException e) {
// Throwable t = e.getTargetException();
// if (t instanceof ExceptionInInitializerError) {
// ExceptionInInitializerError err = (ExceptionInInitializerError) t;
// throw err.getCause();
// }
// throw t;
//
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// }
| import org.deephacks.westty.Westty;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier; | package org.deephacks.westty.test;
public class WesttyJUnit4Runner extends BlockJUnit4ClassRunner {
private final Class<?> cls; | // Path: westty-api/src/main/java/org/deephacks/westty/Westty.java
// public class Westty {
// private static final String WESTTY_CORE = "org.deephacks.westty.internal.core.WesttyCore";
// private static Object WESTTY;
// private String serverName;
// public static void main(String[] args) throws Throwable {
// Westty westty = new Westty();
// westty.startup();
// }
// public Westty() {
// if (WESTTY == null) {
// ClassLoader cl = Thread.currentThread().getContextClassLoader();
// try {
// WESTTY = cl.loadClass(WESTTY_CORE).newInstance();
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// }
//
// public Westty(String serverName){
// this();
// this.serverName = serverName;
// }
//
// public synchronized void startup() throws Throwable {
// if(serverName != null){
// call("setServerName", serverName);
// }
// call("startup");
// }
//
// public synchronized void shutdown() throws Throwable {
// call("shutdown");
// }
//
// public synchronized <V> V getInstance(Class<V> cls) throws Throwable {
// return (V) call("getInstance", cls);
// }
//
// public synchronized void stop() throws Throwable {
// call("shutdown");
// }
//
// private Object call(String method, Object... args) throws Throwable {
// try {
// Class<?> cls = WESTTY.getClass();
// if (args == null || args.length == 0) {
// return cls.getMethod(method).invoke(WESTTY);
// } else {
// Class<?>[] classes = new Class<?>[args.length];
// for (int i = 0; i < args.length; i++) {
// classes[i] = args[i].getClass();
// }
// Method m = cls.getMethod(method, classes);
// return m.invoke(WESTTY, args);
// }
// } catch (InvocationTargetException e) {
// Throwable t = e.getTargetException();
// if (t instanceof ExceptionInInitializerError) {
// ExceptionInInitializerError err = (ExceptionInInitializerError) t;
// throw err.getCause();
// }
// throw t;
//
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// }
// Path: westty-core/src/test/java/org/deephacks/westty/test/WesttyJUnit4Runner.java
import org.deephacks.westty.Westty;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
package org.deephacks.westty.test;
public class WesttyJUnit4Runner extends BlockJUnit4ClassRunner {
private final Class<?> cls; | private Westty westty; |
deephacks/westty | westty-protobuf/src/main/java/org/deephacks/westty/internal/protobuf/ProtobufExtension.java | // Path: westty-protobuf/src/main/java/org/deephacks/westty/protobuf/ProtobufSerializer.java
// @Alternative
// public class ProtobufSerializer {
// private static final Logger log = LoggerFactory.getLogger(ProtobufSerializer.class);
// private HashMap<Integer, Method> numToMethod = new HashMap<>();
// private HashMap<String, Integer> protoToNum = new HashMap<>();
// private static final String UNRECOGNIZED_PROTOCOL_MSG = "Unrecognized protocol.";
//
// public ProtobufSerializer() {
// registerResource("META-INF/failure.desc");
// registerResource("META-INF/void.desc");
// }
//
// public void register(URL protodesc) {
// try {
// registerDesc(protodesc.getFile(), protodesc.openStream());
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public void register(File protodesc) {
// try {
// registerDesc(protodesc.getName(), new FileInputStream(protodesc));
// } catch (FileNotFoundException e) {
// throw new RuntimeException(e);
// }
// }
//
// public void registerResource(String protodesc) {
// URL url = Thread.currentThread().getContextClassLoader().getResource(protodesc);
// register(url);
// }
//
// private void registerDesc(String name, InputStream in) {
// try {
// FileDescriptorSet descriptorSet = FileDescriptorSet.parseFrom(in);
// for (FileDescriptorProto fdp : descriptorSet.getFileList()) {
// FileDescriptor fd = FileDescriptor.buildFrom(fdp, new FileDescriptor[] {});
//
// for (Descriptor desc : fd.getMessageTypes()) {
// FieldDescriptor fdesc = desc.findFieldByName("protoType");
// if (fdesc == null) {
// throw new IllegalArgumentException(name
// + ".proto file must define protoType field "
// + "with unqiue number that identify proto type");
// }
// String packageName = fdp.getOptions().getJavaPackage();
//
// if (Strings.isNullOrEmpty(packageName)) {
// throw new IllegalArgumentException(name
// + ".proto file must define java_package");
// }
// String simpleClassName = fdp.getOptions().getJavaOuterClassname();
// if (Strings.isNullOrEmpty(simpleClassName)) {
// throw new IllegalArgumentException(name
// + " .proto file must define java_outer_classname");
// }
//
// String className = packageName + "." + simpleClassName + "$" + desc.getName();
// Class<?> cls = Thread.currentThread().getContextClassLoader()
// .loadClass(className);
// protoToNum.put(desc.getFullName(), fdesc.getNumber());
// numToMethod.put(fdesc.getNumber(), cls.getMethod("parseFrom", byte[].class));
// log.debug("Registered protobuf resource {}.", name);
// }
// }
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public Object read(byte[] bytes) throws Exception {
// try {
// ByteBuffer buf = ByteBuffer.wrap(bytes);
// Varint32 vint = new Varint32(buf);
// int protoTypeNum = vint.read();
// buf = vint.getByteBuffer();
// byte[] message = new byte[buf.remaining()];
// buf.get(message);
// Method m = numToMethod.get(protoTypeNum);
// if (m == null) {
// return Failure.newBuilder().setCode(BAD_REQUEST.getCode())
// .setMsg("proto_type=" + protoTypeNum).build();
// }
// return m.invoke(null, message);
// } catch (Exception e) {
// return Failure.newBuilder().setCode(BAD_REQUEST.getCode())
// .setMsg(UNRECOGNIZED_PROTOCOL_MSG).build();
// }
// }
//
// public byte[] write(Object proto) throws IOException {
// Message msg = (Message) proto;
// String protoName = msg.getDescriptorForType().getFullName();
// Integer num = protoToNum.get(protoName);
// if(num == null){
// throw new IllegalArgumentException("Could not find protoType mapping for " + protoName);
// }
// byte[] msgBytes = msg.toByteArray();
// Varint32 vint = new Varint32(num);
// int vsize = vint.getSize();
// byte[] bytes = new byte[vsize + msgBytes.length];
// System.arraycopy(vint.write(), 0, bytes, 0, vsize);
// System.arraycopy(msgBytes, 0, bytes, vsize, msgBytes.length);
// return bytes;
// }
// }
| import org.deephacks.westty.protobuf.Protobuf;
import org.deephacks.westty.protobuf.ProtobufMethod;
import org.deephacks.westty.protobuf.ProtobufSerializer;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.spi.AnnotatedMethod;
import javax.enterprise.inject.spi.AnnotatedType;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.Extension;
import javax.enterprise.inject.spi.ProcessAnnotatedType;
import javax.inject.Singleton; | /**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.deephacks.westty.internal.protobuf;
@Singleton
public class ProtobufExtension implements Extension { | // Path: westty-protobuf/src/main/java/org/deephacks/westty/protobuf/ProtobufSerializer.java
// @Alternative
// public class ProtobufSerializer {
// private static final Logger log = LoggerFactory.getLogger(ProtobufSerializer.class);
// private HashMap<Integer, Method> numToMethod = new HashMap<>();
// private HashMap<String, Integer> protoToNum = new HashMap<>();
// private static final String UNRECOGNIZED_PROTOCOL_MSG = "Unrecognized protocol.";
//
// public ProtobufSerializer() {
// registerResource("META-INF/failure.desc");
// registerResource("META-INF/void.desc");
// }
//
// public void register(URL protodesc) {
// try {
// registerDesc(protodesc.getFile(), protodesc.openStream());
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public void register(File protodesc) {
// try {
// registerDesc(protodesc.getName(), new FileInputStream(protodesc));
// } catch (FileNotFoundException e) {
// throw new RuntimeException(e);
// }
// }
//
// public void registerResource(String protodesc) {
// URL url = Thread.currentThread().getContextClassLoader().getResource(protodesc);
// register(url);
// }
//
// private void registerDesc(String name, InputStream in) {
// try {
// FileDescriptorSet descriptorSet = FileDescriptorSet.parseFrom(in);
// for (FileDescriptorProto fdp : descriptorSet.getFileList()) {
// FileDescriptor fd = FileDescriptor.buildFrom(fdp, new FileDescriptor[] {});
//
// for (Descriptor desc : fd.getMessageTypes()) {
// FieldDescriptor fdesc = desc.findFieldByName("protoType");
// if (fdesc == null) {
// throw new IllegalArgumentException(name
// + ".proto file must define protoType field "
// + "with unqiue number that identify proto type");
// }
// String packageName = fdp.getOptions().getJavaPackage();
//
// if (Strings.isNullOrEmpty(packageName)) {
// throw new IllegalArgumentException(name
// + ".proto file must define java_package");
// }
// String simpleClassName = fdp.getOptions().getJavaOuterClassname();
// if (Strings.isNullOrEmpty(simpleClassName)) {
// throw new IllegalArgumentException(name
// + " .proto file must define java_outer_classname");
// }
//
// String className = packageName + "." + simpleClassName + "$" + desc.getName();
// Class<?> cls = Thread.currentThread().getContextClassLoader()
// .loadClass(className);
// protoToNum.put(desc.getFullName(), fdesc.getNumber());
// numToMethod.put(fdesc.getNumber(), cls.getMethod("parseFrom", byte[].class));
// log.debug("Registered protobuf resource {}.", name);
// }
// }
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// public Object read(byte[] bytes) throws Exception {
// try {
// ByteBuffer buf = ByteBuffer.wrap(bytes);
// Varint32 vint = new Varint32(buf);
// int protoTypeNum = vint.read();
// buf = vint.getByteBuffer();
// byte[] message = new byte[buf.remaining()];
// buf.get(message);
// Method m = numToMethod.get(protoTypeNum);
// if (m == null) {
// return Failure.newBuilder().setCode(BAD_REQUEST.getCode())
// .setMsg("proto_type=" + protoTypeNum).build();
// }
// return m.invoke(null, message);
// } catch (Exception e) {
// return Failure.newBuilder().setCode(BAD_REQUEST.getCode())
// .setMsg(UNRECOGNIZED_PROTOCOL_MSG).build();
// }
// }
//
// public byte[] write(Object proto) throws IOException {
// Message msg = (Message) proto;
// String protoName = msg.getDescriptorForType().getFullName();
// Integer num = protoToNum.get(protoName);
// if(num == null){
// throw new IllegalArgumentException("Could not find protoType mapping for " + protoName);
// }
// byte[] msgBytes = msg.toByteArray();
// Varint32 vint = new Varint32(num);
// int vsize = vint.getSize();
// byte[] bytes = new byte[vsize + msgBytes.length];
// System.arraycopy(vint.write(), 0, bytes, 0, vsize);
// System.arraycopy(msgBytes, 0, bytes, vsize, msgBytes.length);
// return bytes;
// }
// }
// Path: westty-protobuf/src/main/java/org/deephacks/westty/internal/protobuf/ProtobufExtension.java
import org.deephacks.westty.protobuf.Protobuf;
import org.deephacks.westty.protobuf.ProtobufMethod;
import org.deephacks.westty.protobuf.ProtobufSerializer;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.spi.AnnotatedMethod;
import javax.enterprise.inject.spi.AnnotatedType;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.Extension;
import javax.enterprise.inject.spi.ProcessAnnotatedType;
import javax.inject.Singleton;
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.deephacks.westty.internal.protobuf;
@Singleton
public class ProtobufExtension implements Extension { | private ProtobufSerializer serializer = new ProtobufSerializer(); |
deephacks/westty | westty-api/src/main/java/org/deephacks/westty/cluster/EntryEvent.java | // Path: westty-api/src/main/java/org/deephacks/westty/server/Server.java
// public class Server implements Serializable {
//
// private int port;
// private String host;
//
// public Server(String host, int port) {
// this.port = port;
// this.host = host;
// }
//
// public Server() {
// }
//
// public int getPort(){
// return port;
// }
//
// public String getHost(){
// return host;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o)
// return true;
// if (o == null || getClass() != o.getClass())
// return false;
//
// Server server = (Server) o;
//
// if (port != server.port)
// return false;
// if (!host.equals(server.host))
// return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = port;
// result = 31 * result + host.hashCode();
// return result;
// }
//
// public String toString() {
// return host + ":" + port;
// }
//
// }
| import org.deephacks.westty.server.Server; | package org.deephacks.westty.cluster;
public interface EntryEvent<K, V> {
/**
* Returns the key of the entry event
*
* @return the key
*/
public K getKey();
/**
* Returns the old value of the entry event
*
* @return
*/
public V getOldValue();
/**
* Returns the value of the entry event
*
* @return
*/
public V getValue();
/**
* Returns the member fired this event.
*
* @return the member fired this event.
*/ | // Path: westty-api/src/main/java/org/deephacks/westty/server/Server.java
// public class Server implements Serializable {
//
// private int port;
// private String host;
//
// public Server(String host, int port) {
// this.port = port;
// this.host = host;
// }
//
// public Server() {
// }
//
// public int getPort(){
// return port;
// }
//
// public String getHost(){
// return host;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o)
// return true;
// if (o == null || getClass() != o.getClass())
// return false;
//
// Server server = (Server) o;
//
// if (port != server.port)
// return false;
// if (!host.equals(server.host))
// return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = port;
// result = 31 * result + host.hashCode();
// return result;
// }
//
// public String toString() {
// return host + ":" + port;
// }
//
// }
// Path: westty-api/src/main/java/org/deephacks/westty/cluster/EntryEvent.java
import org.deephacks.westty.server.Server;
package org.deephacks.westty.cluster;
public interface EntryEvent<K, V> {
/**
* Returns the key of the entry event
*
* @return the key
*/
public K getKey();
/**
* Returns the old value of the entry event
*
* @return
*/
public V getOldValue();
/**
* Returns the value of the entry event
*
* @return
*/
public V getValue();
/**
* Returns the member fired this event.
*
* @return the member fired this event.
*/ | public Server getMember(); |
deephacks/westty | westty-api/src/main/java/org/deephacks/westty/config/ServerSpecificConfigProxy.java | // Path: westty-api/src/main/java/org/deephacks/westty/server/ServerName.java
// @Alternative
// public class ServerName {
// private String name;
//
// public ServerName(String name){
// this.name = name;
// }
//
// public String getName() {
// return name;
// }
// }
| import com.google.common.base.Optional;
import org.deephacks.confit.ConfigContext;
import org.deephacks.confit.model.AbortRuntimeException;
import org.deephacks.confit.model.Events;
import org.deephacks.westty.server.ServerName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.inject.Inject;
import java.lang.reflect.Constructor;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable; | package org.deephacks.westty.config;
/**
* This class enables injection of configurable classes that have an @Id
* same as the running server instance. This also means that the configurable
* class must have a constructor that takes its id as an argument.
*
* @param <T> configurable class
*/
public class ServerSpecificConfigProxy<T> {
private T config;
private ServerSpecificConfigProxy(T config){
this.config = config;
}
/**
* @return The configurable server specific instance or an empty default
* instance if it does not exist in the configuration bean manager.
*/
public T get(){
return config;
}
static class ServerSpecificConfigProxyProducer<T> {
private static final Logger log = LoggerFactory.getLogger(ServerSpecificConfigProxyProducer.class);
@Inject | // Path: westty-api/src/main/java/org/deephacks/westty/server/ServerName.java
// @Alternative
// public class ServerName {
// private String name;
//
// public ServerName(String name){
// this.name = name;
// }
//
// public String getName() {
// return name;
// }
// }
// Path: westty-api/src/main/java/org/deephacks/westty/config/ServerSpecificConfigProxy.java
import com.google.common.base.Optional;
import org.deephacks.confit.ConfigContext;
import org.deephacks.confit.model.AbortRuntimeException;
import org.deephacks.confit.model.Events;
import org.deephacks.westty.server.ServerName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.inject.Inject;
import java.lang.reflect.Constructor;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
package org.deephacks.westty.config;
/**
* This class enables injection of configurable classes that have an @Id
* same as the running server instance. This also means that the configurable
* class must have a constructor that takes its id as an argument.
*
* @param <T> configurable class
*/
public class ServerSpecificConfigProxy<T> {
private T config;
private ServerSpecificConfigProxy(T config){
this.config = config;
}
/**
* @return The configurable server specific instance or an empty default
* instance if it does not exist in the configuration bean manager.
*/
public T get(){
return config;
}
static class ServerSpecificConfigProxyProducer<T> {
private static final Logger log = LoggerFactory.getLogger(ServerSpecificConfigProxyProducer.class);
@Inject | private ServerName serverName; |
thom-nic/openfire-jboss-clustering | src/main/java/com/enernoc/rnd/openfire/cluster/ClusterPacketRouter.java | // Path: src/main/java/com/enernoc/rnd/openfire/cluster/task/BroadcastTask.java
// public class BroadcastTask extends PacketTask<Message> {
//
// public BroadcastTask() {}
// public BroadcastTask( Message msg ) { super(msg); }
//
// public void run() {
// XMPPServer.getInstance().getRoutingTable().broadcastPacket( packet, true );
// }
//
// @Override
// public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
// packet = new Message( super.readXML(in), true );
// }
//
// @Override
// public void writeExternal(ObjectOutput out) throws IOException {
// ExternalizableUtil.getInstance().writeSafeUTF( out, packet.toXML() );
// }
// }
//
// Path: src/main/java/com/enernoc/rnd/openfire/cluster/task/PacketRouterTask.java
// public class PacketRouterTask extends PacketTask<Packet> {
//
// public PacketRouterTask() {}
// public PacketRouterTask( Packet packet ) {
// super( packet );
// }
//
// public void run() {
// XMPPServer.getInstance().getPacketRouter().route( packet );
// }
// }
| import org.jivesoftware.openfire.RemotePacketRouter;
import org.jivesoftware.util.cache.CacheFactory;
import org.xmpp.packet.JID;
import org.xmpp.packet.Message;
import org.xmpp.packet.Packet;
import com.enernoc.rnd.openfire.cluster.task.BroadcastTask;
import com.enernoc.rnd.openfire.cluster.task.PacketRouterTask; | /**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package com.enernoc.rnd.openfire.cluster;
public class ClusterPacketRouter implements RemotePacketRouter {
public void broadcastPacket( Message packet ) { | // Path: src/main/java/com/enernoc/rnd/openfire/cluster/task/BroadcastTask.java
// public class BroadcastTask extends PacketTask<Message> {
//
// public BroadcastTask() {}
// public BroadcastTask( Message msg ) { super(msg); }
//
// public void run() {
// XMPPServer.getInstance().getRoutingTable().broadcastPacket( packet, true );
// }
//
// @Override
// public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
// packet = new Message( super.readXML(in), true );
// }
//
// @Override
// public void writeExternal(ObjectOutput out) throws IOException {
// ExternalizableUtil.getInstance().writeSafeUTF( out, packet.toXML() );
// }
// }
//
// Path: src/main/java/com/enernoc/rnd/openfire/cluster/task/PacketRouterTask.java
// public class PacketRouterTask extends PacketTask<Packet> {
//
// public PacketRouterTask() {}
// public PacketRouterTask( Packet packet ) {
// super( packet );
// }
//
// public void run() {
// XMPPServer.getInstance().getPacketRouter().route( packet );
// }
// }
// Path: src/main/java/com/enernoc/rnd/openfire/cluster/ClusterPacketRouter.java
import org.jivesoftware.openfire.RemotePacketRouter;
import org.jivesoftware.util.cache.CacheFactory;
import org.xmpp.packet.JID;
import org.xmpp.packet.Message;
import org.xmpp.packet.Packet;
import com.enernoc.rnd.openfire.cluster.task.BroadcastTask;
import com.enernoc.rnd.openfire.cluster.task.PacketRouterTask;
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package com.enernoc.rnd.openfire.cluster;
public class ClusterPacketRouter implements RemotePacketRouter {
public void broadcastPacket( Message packet ) { | CacheFactory.doClusterTask( new BroadcastTask(packet) ); |
thom-nic/openfire-jboss-clustering | src/main/java/com/enernoc/rnd/openfire/cluster/ClusterPacketRouter.java | // Path: src/main/java/com/enernoc/rnd/openfire/cluster/task/BroadcastTask.java
// public class BroadcastTask extends PacketTask<Message> {
//
// public BroadcastTask() {}
// public BroadcastTask( Message msg ) { super(msg); }
//
// public void run() {
// XMPPServer.getInstance().getRoutingTable().broadcastPacket( packet, true );
// }
//
// @Override
// public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
// packet = new Message( super.readXML(in), true );
// }
//
// @Override
// public void writeExternal(ObjectOutput out) throws IOException {
// ExternalizableUtil.getInstance().writeSafeUTF( out, packet.toXML() );
// }
// }
//
// Path: src/main/java/com/enernoc/rnd/openfire/cluster/task/PacketRouterTask.java
// public class PacketRouterTask extends PacketTask<Packet> {
//
// public PacketRouterTask() {}
// public PacketRouterTask( Packet packet ) {
// super( packet );
// }
//
// public void run() {
// XMPPServer.getInstance().getPacketRouter().route( packet );
// }
// }
| import org.jivesoftware.openfire.RemotePacketRouter;
import org.jivesoftware.util.cache.CacheFactory;
import org.xmpp.packet.JID;
import org.xmpp.packet.Message;
import org.xmpp.packet.Packet;
import com.enernoc.rnd.openfire.cluster.task.BroadcastTask;
import com.enernoc.rnd.openfire.cluster.task.PacketRouterTask; | /**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package com.enernoc.rnd.openfire.cluster;
public class ClusterPacketRouter implements RemotePacketRouter {
public void broadcastPacket( Message packet ) {
CacheFactory.doClusterTask( new BroadcastTask(packet) );
}
public boolean routePacket( byte[] nodeID, JID receipient, Packet packet ) {
packet.setTo(receipient); | // Path: src/main/java/com/enernoc/rnd/openfire/cluster/task/BroadcastTask.java
// public class BroadcastTask extends PacketTask<Message> {
//
// public BroadcastTask() {}
// public BroadcastTask( Message msg ) { super(msg); }
//
// public void run() {
// XMPPServer.getInstance().getRoutingTable().broadcastPacket( packet, true );
// }
//
// @Override
// public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
// packet = new Message( super.readXML(in), true );
// }
//
// @Override
// public void writeExternal(ObjectOutput out) throws IOException {
// ExternalizableUtil.getInstance().writeSafeUTF( out, packet.toXML() );
// }
// }
//
// Path: src/main/java/com/enernoc/rnd/openfire/cluster/task/PacketRouterTask.java
// public class PacketRouterTask extends PacketTask<Packet> {
//
// public PacketRouterTask() {}
// public PacketRouterTask( Packet packet ) {
// super( packet );
// }
//
// public void run() {
// XMPPServer.getInstance().getPacketRouter().route( packet );
// }
// }
// Path: src/main/java/com/enernoc/rnd/openfire/cluster/ClusterPacketRouter.java
import org.jivesoftware.openfire.RemotePacketRouter;
import org.jivesoftware.util.cache.CacheFactory;
import org.xmpp.packet.JID;
import org.xmpp.packet.Message;
import org.xmpp.packet.Packet;
import com.enernoc.rnd.openfire.cluster.task.BroadcastTask;
import com.enernoc.rnd.openfire.cluster.task.PacketRouterTask;
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package com.enernoc.rnd.openfire.cluster;
public class ClusterPacketRouter implements RemotePacketRouter {
public void broadcastPacket( Message packet ) {
CacheFactory.doClusterTask( new BroadcastTask(packet) );
}
public boolean routePacket( byte[] nodeID, JID receipient, Packet packet ) {
packet.setTo(receipient); | CacheFactory.doClusterTask( new PacketRouterTask(packet), nodeID ); |
thom-nic/openfire-jboss-clustering | src/main/java/com/enernoc/rnd/openfire/cluster/JBossClusterPlugin.java | // Path: src/main/java/com/enernoc/rnd/openfire/cluster/session/ClusteredSessionLocator.java
// public class ClusteredSessionLocator implements RemoteSessionLocator {
//
// public ClusteredClientSession getClientSession( byte[] nodeID, JID address ) {
// return new ClusteredClientSession(address, nodeID);
// }
//
// public ClusterComponentSession getComponentSession(byte[] nodeID, JID address) {
// return (ClusterComponentSession) CacheFactory.doSynchronousClusterTask(
// new GetComponentSessionTask( address ), nodeID);
// }
//
// public ConnectionMultiplexerSession getConnectionMultiplexerSession(
// byte[] nodeID, JID address) {
// return (ConnectionMultiplexerSession) CacheFactory.doSynchronousClusterTask(
// new GetMultiplexerSessionTask( address ), nodeID);
// }
//
// public IncomingServerSession getIncomingServerSession(byte[] nodeID,
// String streamID) {
// XMPPServer xmpp = XMPPServer.getInstance();
// IncomingServerSession s = xmpp.getSessionManager().getIncomingServerSession(streamID);
// if ( s == null ) {
// // xmpp.getSessionManager().createClientSession(conn)
// }
// return s;
// // return (ClusterIncomingSession) CacheFactory.doSynchronousClusterTask(
// // new GetIncomingSessionTask( streamID ), nodeID);
// }
//
// public ClusterOutgoingSession getOutgoingServerSession(byte[] nodeID,
// JID address) {
// return null;
// // return (ClusterOutgoingSession) CacheFactory.doSynchronousClusterTask(
// // new GetOutgoingSessionTask( address ), nodeID);
// }
//
// }
| import java.io.File;
import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.LogManager;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.cluster.ClusterManager;
import org.jivesoftware.openfire.container.Plugin;
import org.jivesoftware.openfire.container.PluginManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.enernoc.rnd.openfire.cluster.session.ClusteredSessionLocator; | /**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package com.enernoc.rnd.openfire.cluster;
public class JBossClusterPlugin implements Plugin {
protected final Logger log = LoggerFactory.getLogger( getClass() );
public static final String CLUSTER_JGROUPS_CONFIG_PROPERTY =
"com.enernoc.clustering.jgroups.config";
public static final String CLUSTER_CACHE_CONFIG_PROPERTY =
"com.enernoc.clustering.cache.config";
public void destroyPlugin() {
log.info("Destroying the plugin");
ClusterManager.shutdown();
// TODO interrupt master listener & node listener?
// TODO destroy all singletons and resources associated with this plugin
}
public void initializePlugin( PluginManager mgr, File pluginDir ) {
try {
log.debug(new String(Inet4Address.getLocalHost().getAddress()));
} catch (UnknownHostException e) {
log.debug("unable to obtain ipaddress for host");
}
LogManager.getLogManager().getLogger("").setLevel(Level.FINE);
Enumeration<String> es = LogManager.getLogManager().getLoggerNames();
while ( es.hasMoreElements() ) log.error( es.nextElement() ); | // Path: src/main/java/com/enernoc/rnd/openfire/cluster/session/ClusteredSessionLocator.java
// public class ClusteredSessionLocator implements RemoteSessionLocator {
//
// public ClusteredClientSession getClientSession( byte[] nodeID, JID address ) {
// return new ClusteredClientSession(address, nodeID);
// }
//
// public ClusterComponentSession getComponentSession(byte[] nodeID, JID address) {
// return (ClusterComponentSession) CacheFactory.doSynchronousClusterTask(
// new GetComponentSessionTask( address ), nodeID);
// }
//
// public ConnectionMultiplexerSession getConnectionMultiplexerSession(
// byte[] nodeID, JID address) {
// return (ConnectionMultiplexerSession) CacheFactory.doSynchronousClusterTask(
// new GetMultiplexerSessionTask( address ), nodeID);
// }
//
// public IncomingServerSession getIncomingServerSession(byte[] nodeID,
// String streamID) {
// XMPPServer xmpp = XMPPServer.getInstance();
// IncomingServerSession s = xmpp.getSessionManager().getIncomingServerSession(streamID);
// if ( s == null ) {
// // xmpp.getSessionManager().createClientSession(conn)
// }
// return s;
// // return (ClusterIncomingSession) CacheFactory.doSynchronousClusterTask(
// // new GetIncomingSessionTask( streamID ), nodeID);
// }
//
// public ClusterOutgoingSession getOutgoingServerSession(byte[] nodeID,
// JID address) {
// return null;
// // return (ClusterOutgoingSession) CacheFactory.doSynchronousClusterTask(
// // new GetOutgoingSessionTask( address ), nodeID);
// }
//
// }
// Path: src/main/java/com/enernoc/rnd/openfire/cluster/JBossClusterPlugin.java
import java.io.File;
import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.LogManager;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.cluster.ClusterManager;
import org.jivesoftware.openfire.container.Plugin;
import org.jivesoftware.openfire.container.PluginManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.enernoc.rnd.openfire.cluster.session.ClusteredSessionLocator;
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package com.enernoc.rnd.openfire.cluster;
public class JBossClusterPlugin implements Plugin {
protected final Logger log = LoggerFactory.getLogger( getClass() );
public static final String CLUSTER_JGROUPS_CONFIG_PROPERTY =
"com.enernoc.clustering.jgroups.config";
public static final String CLUSTER_CACHE_CONFIG_PROPERTY =
"com.enernoc.clustering.cache.config";
public void destroyPlugin() {
log.info("Destroying the plugin");
ClusterManager.shutdown();
// TODO interrupt master listener & node listener?
// TODO destroy all singletons and resources associated with this plugin
}
public void initializePlugin( PluginManager mgr, File pluginDir ) {
try {
log.debug(new String(Inet4Address.getLocalHost().getAddress()));
} catch (UnknownHostException e) {
log.debug("unable to obtain ipaddress for host");
}
LogManager.getLogManager().getLogger("").setLevel(Level.FINE);
Enumeration<String> es = LogManager.getLogManager().getLoggerNames();
while ( es.hasMoreElements() ) log.error( es.nextElement() ); | XMPPServer.getInstance().setRemoteSessionLocator( new ClusteredSessionLocator() ); |
prcaen/external-resources | library/src/main/java/fr/prcaen/externalresources/Downloader.java | // Path: library/src/main/java/fr/prcaen/externalresources/converter/Converter.java
// public interface Converter {
// Resources fromReader(Reader reader) throws IOException;
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/exception/ExternalResourceException.java
// public class ExternalResourceException extends RuntimeException {
//
// public ExternalResourceException(String detailMessage) {
// super(detailMessage);
// }
//
// public ExternalResourceException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ExternalResourceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/exception/ResponseException.java
// public final class ResponseException extends ExternalResourceException {
//
// private final boolean localCacheOnly;
// private final int responseCode;
//
// public ResponseException(String message, @Cache.Policy int networkPolicy, int responseCode) {
// super(message);
//
// this.localCacheOnly = networkPolicy == Cache.POLICY_OFFLINE;
// this.responseCode = responseCode;
// }
//
// public boolean isLocalCacheOnly() {
// return localCacheOnly;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/model/Resources.java
// @SuppressWarnings("unused") public final class Resources {
// protected final ConcurrentHashMap<String, Resource> members;
//
// public Resources() {
// this.members = new ConcurrentHashMap<>();
// }
//
// public Resources(@NonNull ConcurrentHashMap<String, Resource> members) {
// this.members = members;
// }
//
// public static Resources from(Reader reader, Converter converter) throws IOException {
// return converter.fromReader(reader);
// }
//
// public static Resources from(String string, Converter converter) throws IOException {
// return from(new StringReader(string), converter);
// }
//
// public static Resources fromJson(Reader reader) throws IOException {
// return from(reader, new JsonConverter());
// }
//
// public static Resources fromJson(String string) throws IOException {
// return from(string, new JsonConverter());
// }
//
// public static Resources fromJson(InputStream reader) throws IOException {
// return fromJson(new InputStreamReader(reader));
// }
//
// public static Resources fromXml(Reader reader) throws IOException {
// return from(reader, new XmlConverter());
// }
//
// public static Resources fromXml(String string) throws IOException {
// return from(string, new XmlConverter());
// }
//
// public static Resources fromXml(InputStream reader) throws IOException {
// return fromXml(new InputStreamReader(reader));
// }
//
// public Resource add(String key, Resource value) {
// return members.put(key, value);
// }
//
// @NonNull protected Set<Entry<String, Resource>> entrySet() {
// return members.entrySet();
// }
//
// public boolean has(String key) {
// return members.containsKey(key);
// }
//
// public Resource get(String key) {
// return members.get(key);
// }
//
// public Resources merge(Resources resources) {
// members.putAll(resources.members);
//
// return this;
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/url/Url.java
// public interface Url {
//
// void fontScale(float fontScale);
//
// void hardKeyboardHidden(int hardKeyboardHidden);
//
// void keyboard(int keyboard);
//
// void keyboardHidden(int keyboardHidden);
//
// void locale(Locale locale);
//
// void mcc(int mcc);
//
// void mnc(int mnc);
//
// void navigation(int navigation);
//
// void navigationHidden(int navigationHidden);
//
// void orientation(int orientation);
//
// void screenLayout(int screenLayout);
//
// void touchscreen(int touchscreen);
//
// void uiMode(int uiMode);
//
// void densityDpi(int densityDpi);
//
// void screenWidthDp(int screenWidthDp);
//
// void screenHeightDp(int screenHeightDp);
//
// void smallestScreenWidthDp(int smallestScreenWidthDp);
//
// String build();
// }
| import android.content.Context;
import android.content.res.Configuration;
import android.support.annotation.NonNull;
import com.squareup.okhttp.CacheControl;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import fr.prcaen.externalresources.converter.Converter;
import fr.prcaen.externalresources.exception.ExternalResourceException;
import fr.prcaen.externalresources.exception.ResponseException;
import fr.prcaen.externalresources.model.Resources;
import fr.prcaen.externalresources.url.Url;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.HONEYCOMB_MR2;
import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1; | package fr.prcaen.externalresources;
public final class Downloader {
private static final int CONNECT_TIMEOUT_MILLIS = 15 * 1000; // 15s
private static final int READ_TIMEOUT_MILLIS = 20 * 1000; // 20s
private static final int WRITE_TIMEOUT_MILLIS = 20 * 1000; // 20s
@NonNull private final Context context;
@NonNull private final OkHttpClient client; | // Path: library/src/main/java/fr/prcaen/externalresources/converter/Converter.java
// public interface Converter {
// Resources fromReader(Reader reader) throws IOException;
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/exception/ExternalResourceException.java
// public class ExternalResourceException extends RuntimeException {
//
// public ExternalResourceException(String detailMessage) {
// super(detailMessage);
// }
//
// public ExternalResourceException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ExternalResourceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/exception/ResponseException.java
// public final class ResponseException extends ExternalResourceException {
//
// private final boolean localCacheOnly;
// private final int responseCode;
//
// public ResponseException(String message, @Cache.Policy int networkPolicy, int responseCode) {
// super(message);
//
// this.localCacheOnly = networkPolicy == Cache.POLICY_OFFLINE;
// this.responseCode = responseCode;
// }
//
// public boolean isLocalCacheOnly() {
// return localCacheOnly;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/model/Resources.java
// @SuppressWarnings("unused") public final class Resources {
// protected final ConcurrentHashMap<String, Resource> members;
//
// public Resources() {
// this.members = new ConcurrentHashMap<>();
// }
//
// public Resources(@NonNull ConcurrentHashMap<String, Resource> members) {
// this.members = members;
// }
//
// public static Resources from(Reader reader, Converter converter) throws IOException {
// return converter.fromReader(reader);
// }
//
// public static Resources from(String string, Converter converter) throws IOException {
// return from(new StringReader(string), converter);
// }
//
// public static Resources fromJson(Reader reader) throws IOException {
// return from(reader, new JsonConverter());
// }
//
// public static Resources fromJson(String string) throws IOException {
// return from(string, new JsonConverter());
// }
//
// public static Resources fromJson(InputStream reader) throws IOException {
// return fromJson(new InputStreamReader(reader));
// }
//
// public static Resources fromXml(Reader reader) throws IOException {
// return from(reader, new XmlConverter());
// }
//
// public static Resources fromXml(String string) throws IOException {
// return from(string, new XmlConverter());
// }
//
// public static Resources fromXml(InputStream reader) throws IOException {
// return fromXml(new InputStreamReader(reader));
// }
//
// public Resource add(String key, Resource value) {
// return members.put(key, value);
// }
//
// @NonNull protected Set<Entry<String, Resource>> entrySet() {
// return members.entrySet();
// }
//
// public boolean has(String key) {
// return members.containsKey(key);
// }
//
// public Resource get(String key) {
// return members.get(key);
// }
//
// public Resources merge(Resources resources) {
// members.putAll(resources.members);
//
// return this;
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/url/Url.java
// public interface Url {
//
// void fontScale(float fontScale);
//
// void hardKeyboardHidden(int hardKeyboardHidden);
//
// void keyboard(int keyboard);
//
// void keyboardHidden(int keyboardHidden);
//
// void locale(Locale locale);
//
// void mcc(int mcc);
//
// void mnc(int mnc);
//
// void navigation(int navigation);
//
// void navigationHidden(int navigationHidden);
//
// void orientation(int orientation);
//
// void screenLayout(int screenLayout);
//
// void touchscreen(int touchscreen);
//
// void uiMode(int uiMode);
//
// void densityDpi(int densityDpi);
//
// void screenWidthDp(int screenWidthDp);
//
// void screenHeightDp(int screenHeightDp);
//
// void smallestScreenWidthDp(int smallestScreenWidthDp);
//
// String build();
// }
// Path: library/src/main/java/fr/prcaen/externalresources/Downloader.java
import android.content.Context;
import android.content.res.Configuration;
import android.support.annotation.NonNull;
import com.squareup.okhttp.CacheControl;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import fr.prcaen.externalresources.converter.Converter;
import fr.prcaen.externalresources.exception.ExternalResourceException;
import fr.prcaen.externalresources.exception.ResponseException;
import fr.prcaen.externalresources.model.Resources;
import fr.prcaen.externalresources.url.Url;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.HONEYCOMB_MR2;
import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
package fr.prcaen.externalresources;
public final class Downloader {
private static final int CONNECT_TIMEOUT_MILLIS = 15 * 1000; // 15s
private static final int READ_TIMEOUT_MILLIS = 20 * 1000; // 20s
private static final int WRITE_TIMEOUT_MILLIS = 20 * 1000; // 20s
@NonNull private final Context context;
@NonNull private final OkHttpClient client; | @NonNull private final Converter converter; |
prcaen/external-resources | library/src/main/java/fr/prcaen/externalresources/Downloader.java | // Path: library/src/main/java/fr/prcaen/externalresources/converter/Converter.java
// public interface Converter {
// Resources fromReader(Reader reader) throws IOException;
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/exception/ExternalResourceException.java
// public class ExternalResourceException extends RuntimeException {
//
// public ExternalResourceException(String detailMessage) {
// super(detailMessage);
// }
//
// public ExternalResourceException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ExternalResourceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/exception/ResponseException.java
// public final class ResponseException extends ExternalResourceException {
//
// private final boolean localCacheOnly;
// private final int responseCode;
//
// public ResponseException(String message, @Cache.Policy int networkPolicy, int responseCode) {
// super(message);
//
// this.localCacheOnly = networkPolicy == Cache.POLICY_OFFLINE;
// this.responseCode = responseCode;
// }
//
// public boolean isLocalCacheOnly() {
// return localCacheOnly;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/model/Resources.java
// @SuppressWarnings("unused") public final class Resources {
// protected final ConcurrentHashMap<String, Resource> members;
//
// public Resources() {
// this.members = new ConcurrentHashMap<>();
// }
//
// public Resources(@NonNull ConcurrentHashMap<String, Resource> members) {
// this.members = members;
// }
//
// public static Resources from(Reader reader, Converter converter) throws IOException {
// return converter.fromReader(reader);
// }
//
// public static Resources from(String string, Converter converter) throws IOException {
// return from(new StringReader(string), converter);
// }
//
// public static Resources fromJson(Reader reader) throws IOException {
// return from(reader, new JsonConverter());
// }
//
// public static Resources fromJson(String string) throws IOException {
// return from(string, new JsonConverter());
// }
//
// public static Resources fromJson(InputStream reader) throws IOException {
// return fromJson(new InputStreamReader(reader));
// }
//
// public static Resources fromXml(Reader reader) throws IOException {
// return from(reader, new XmlConverter());
// }
//
// public static Resources fromXml(String string) throws IOException {
// return from(string, new XmlConverter());
// }
//
// public static Resources fromXml(InputStream reader) throws IOException {
// return fromXml(new InputStreamReader(reader));
// }
//
// public Resource add(String key, Resource value) {
// return members.put(key, value);
// }
//
// @NonNull protected Set<Entry<String, Resource>> entrySet() {
// return members.entrySet();
// }
//
// public boolean has(String key) {
// return members.containsKey(key);
// }
//
// public Resource get(String key) {
// return members.get(key);
// }
//
// public Resources merge(Resources resources) {
// members.putAll(resources.members);
//
// return this;
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/url/Url.java
// public interface Url {
//
// void fontScale(float fontScale);
//
// void hardKeyboardHidden(int hardKeyboardHidden);
//
// void keyboard(int keyboard);
//
// void keyboardHidden(int keyboardHidden);
//
// void locale(Locale locale);
//
// void mcc(int mcc);
//
// void mnc(int mnc);
//
// void navigation(int navigation);
//
// void navigationHidden(int navigationHidden);
//
// void orientation(int orientation);
//
// void screenLayout(int screenLayout);
//
// void touchscreen(int touchscreen);
//
// void uiMode(int uiMode);
//
// void densityDpi(int densityDpi);
//
// void screenWidthDp(int screenWidthDp);
//
// void screenHeightDp(int screenHeightDp);
//
// void smallestScreenWidthDp(int smallestScreenWidthDp);
//
// String build();
// }
| import android.content.Context;
import android.content.res.Configuration;
import android.support.annotation.NonNull;
import com.squareup.okhttp.CacheControl;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import fr.prcaen.externalresources.converter.Converter;
import fr.prcaen.externalresources.exception.ExternalResourceException;
import fr.prcaen.externalresources.exception.ResponseException;
import fr.prcaen.externalresources.model.Resources;
import fr.prcaen.externalresources.url.Url;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.HONEYCOMB_MR2;
import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1; | package fr.prcaen.externalresources;
public final class Downloader {
private static final int CONNECT_TIMEOUT_MILLIS = 15 * 1000; // 15s
private static final int READ_TIMEOUT_MILLIS = 20 * 1000; // 20s
private static final int WRITE_TIMEOUT_MILLIS = 20 * 1000; // 20s
@NonNull private final Context context;
@NonNull private final OkHttpClient client;
@NonNull private final Converter converter; | // Path: library/src/main/java/fr/prcaen/externalresources/converter/Converter.java
// public interface Converter {
// Resources fromReader(Reader reader) throws IOException;
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/exception/ExternalResourceException.java
// public class ExternalResourceException extends RuntimeException {
//
// public ExternalResourceException(String detailMessage) {
// super(detailMessage);
// }
//
// public ExternalResourceException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ExternalResourceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/exception/ResponseException.java
// public final class ResponseException extends ExternalResourceException {
//
// private final boolean localCacheOnly;
// private final int responseCode;
//
// public ResponseException(String message, @Cache.Policy int networkPolicy, int responseCode) {
// super(message);
//
// this.localCacheOnly = networkPolicy == Cache.POLICY_OFFLINE;
// this.responseCode = responseCode;
// }
//
// public boolean isLocalCacheOnly() {
// return localCacheOnly;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/model/Resources.java
// @SuppressWarnings("unused") public final class Resources {
// protected final ConcurrentHashMap<String, Resource> members;
//
// public Resources() {
// this.members = new ConcurrentHashMap<>();
// }
//
// public Resources(@NonNull ConcurrentHashMap<String, Resource> members) {
// this.members = members;
// }
//
// public static Resources from(Reader reader, Converter converter) throws IOException {
// return converter.fromReader(reader);
// }
//
// public static Resources from(String string, Converter converter) throws IOException {
// return from(new StringReader(string), converter);
// }
//
// public static Resources fromJson(Reader reader) throws IOException {
// return from(reader, new JsonConverter());
// }
//
// public static Resources fromJson(String string) throws IOException {
// return from(string, new JsonConverter());
// }
//
// public static Resources fromJson(InputStream reader) throws IOException {
// return fromJson(new InputStreamReader(reader));
// }
//
// public static Resources fromXml(Reader reader) throws IOException {
// return from(reader, new XmlConverter());
// }
//
// public static Resources fromXml(String string) throws IOException {
// return from(string, new XmlConverter());
// }
//
// public static Resources fromXml(InputStream reader) throws IOException {
// return fromXml(new InputStreamReader(reader));
// }
//
// public Resource add(String key, Resource value) {
// return members.put(key, value);
// }
//
// @NonNull protected Set<Entry<String, Resource>> entrySet() {
// return members.entrySet();
// }
//
// public boolean has(String key) {
// return members.containsKey(key);
// }
//
// public Resource get(String key) {
// return members.get(key);
// }
//
// public Resources merge(Resources resources) {
// members.putAll(resources.members);
//
// return this;
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/url/Url.java
// public interface Url {
//
// void fontScale(float fontScale);
//
// void hardKeyboardHidden(int hardKeyboardHidden);
//
// void keyboard(int keyboard);
//
// void keyboardHidden(int keyboardHidden);
//
// void locale(Locale locale);
//
// void mcc(int mcc);
//
// void mnc(int mnc);
//
// void navigation(int navigation);
//
// void navigationHidden(int navigationHidden);
//
// void orientation(int orientation);
//
// void screenLayout(int screenLayout);
//
// void touchscreen(int touchscreen);
//
// void uiMode(int uiMode);
//
// void densityDpi(int densityDpi);
//
// void screenWidthDp(int screenWidthDp);
//
// void screenHeightDp(int screenHeightDp);
//
// void smallestScreenWidthDp(int smallestScreenWidthDp);
//
// String build();
// }
// Path: library/src/main/java/fr/prcaen/externalresources/Downloader.java
import android.content.Context;
import android.content.res.Configuration;
import android.support.annotation.NonNull;
import com.squareup.okhttp.CacheControl;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import fr.prcaen.externalresources.converter.Converter;
import fr.prcaen.externalresources.exception.ExternalResourceException;
import fr.prcaen.externalresources.exception.ResponseException;
import fr.prcaen.externalresources.model.Resources;
import fr.prcaen.externalresources.url.Url;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.HONEYCOMB_MR2;
import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
package fr.prcaen.externalresources;
public final class Downloader {
private static final int CONNECT_TIMEOUT_MILLIS = 15 * 1000; // 15s
private static final int READ_TIMEOUT_MILLIS = 20 * 1000; // 20s
private static final int WRITE_TIMEOUT_MILLIS = 20 * 1000; // 20s
@NonNull private final Context context;
@NonNull private final OkHttpClient client;
@NonNull private final Converter converter; | @NonNull private final Url url; |
prcaen/external-resources | library/src/main/java/fr/prcaen/externalresources/Downloader.java | // Path: library/src/main/java/fr/prcaen/externalresources/converter/Converter.java
// public interface Converter {
// Resources fromReader(Reader reader) throws IOException;
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/exception/ExternalResourceException.java
// public class ExternalResourceException extends RuntimeException {
//
// public ExternalResourceException(String detailMessage) {
// super(detailMessage);
// }
//
// public ExternalResourceException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ExternalResourceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/exception/ResponseException.java
// public final class ResponseException extends ExternalResourceException {
//
// private final boolean localCacheOnly;
// private final int responseCode;
//
// public ResponseException(String message, @Cache.Policy int networkPolicy, int responseCode) {
// super(message);
//
// this.localCacheOnly = networkPolicy == Cache.POLICY_OFFLINE;
// this.responseCode = responseCode;
// }
//
// public boolean isLocalCacheOnly() {
// return localCacheOnly;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/model/Resources.java
// @SuppressWarnings("unused") public final class Resources {
// protected final ConcurrentHashMap<String, Resource> members;
//
// public Resources() {
// this.members = new ConcurrentHashMap<>();
// }
//
// public Resources(@NonNull ConcurrentHashMap<String, Resource> members) {
// this.members = members;
// }
//
// public static Resources from(Reader reader, Converter converter) throws IOException {
// return converter.fromReader(reader);
// }
//
// public static Resources from(String string, Converter converter) throws IOException {
// return from(new StringReader(string), converter);
// }
//
// public static Resources fromJson(Reader reader) throws IOException {
// return from(reader, new JsonConverter());
// }
//
// public static Resources fromJson(String string) throws IOException {
// return from(string, new JsonConverter());
// }
//
// public static Resources fromJson(InputStream reader) throws IOException {
// return fromJson(new InputStreamReader(reader));
// }
//
// public static Resources fromXml(Reader reader) throws IOException {
// return from(reader, new XmlConverter());
// }
//
// public static Resources fromXml(String string) throws IOException {
// return from(string, new XmlConverter());
// }
//
// public static Resources fromXml(InputStream reader) throws IOException {
// return fromXml(new InputStreamReader(reader));
// }
//
// public Resource add(String key, Resource value) {
// return members.put(key, value);
// }
//
// @NonNull protected Set<Entry<String, Resource>> entrySet() {
// return members.entrySet();
// }
//
// public boolean has(String key) {
// return members.containsKey(key);
// }
//
// public Resource get(String key) {
// return members.get(key);
// }
//
// public Resources merge(Resources resources) {
// members.putAll(resources.members);
//
// return this;
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/url/Url.java
// public interface Url {
//
// void fontScale(float fontScale);
//
// void hardKeyboardHidden(int hardKeyboardHidden);
//
// void keyboard(int keyboard);
//
// void keyboardHidden(int keyboardHidden);
//
// void locale(Locale locale);
//
// void mcc(int mcc);
//
// void mnc(int mnc);
//
// void navigation(int navigation);
//
// void navigationHidden(int navigationHidden);
//
// void orientation(int orientation);
//
// void screenLayout(int screenLayout);
//
// void touchscreen(int touchscreen);
//
// void uiMode(int uiMode);
//
// void densityDpi(int densityDpi);
//
// void screenWidthDp(int screenWidthDp);
//
// void screenHeightDp(int screenHeightDp);
//
// void smallestScreenWidthDp(int smallestScreenWidthDp);
//
// String build();
// }
| import android.content.Context;
import android.content.res.Configuration;
import android.support.annotation.NonNull;
import com.squareup.okhttp.CacheControl;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import fr.prcaen.externalresources.converter.Converter;
import fr.prcaen.externalresources.exception.ExternalResourceException;
import fr.prcaen.externalresources.exception.ResponseException;
import fr.prcaen.externalresources.model.Resources;
import fr.prcaen.externalresources.url.Url;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.HONEYCOMB_MR2;
import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1; | public Resources load(@Cache.Policy int policy) throws ExternalResourceException {
buildUrl();
Logger.i(ExternalResources.TAG, "Load configuration from url: " + url.build());
final CacheControl cacheControl;
switch (policy) {
case Cache.POLICY_NONE:
cacheControl = new CacheControl.Builder().noCache().noStore().build();
break;
case Cache.POLICY_OFFLINE:
cacheControl = CacheControl.FORCE_CACHE;
break;
case Cache.POLICY_ALL:
default:
cacheControl = new CacheControl.Builder().build();
break;
}
Logger.v(ExternalResources.TAG, "CachePolicy: " + policy);
Request request = new Request.Builder().url(url.build()).cacheControl(cacheControl).build();
try {
Response response = client.newCall(request).execute();
int responseCode = response.code();
Logger.d(ExternalResources.TAG, "Response code: " + responseCode);
if (responseCode >= 300) {
response.body().close(); | // Path: library/src/main/java/fr/prcaen/externalresources/converter/Converter.java
// public interface Converter {
// Resources fromReader(Reader reader) throws IOException;
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/exception/ExternalResourceException.java
// public class ExternalResourceException extends RuntimeException {
//
// public ExternalResourceException(String detailMessage) {
// super(detailMessage);
// }
//
// public ExternalResourceException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ExternalResourceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/exception/ResponseException.java
// public final class ResponseException extends ExternalResourceException {
//
// private final boolean localCacheOnly;
// private final int responseCode;
//
// public ResponseException(String message, @Cache.Policy int networkPolicy, int responseCode) {
// super(message);
//
// this.localCacheOnly = networkPolicy == Cache.POLICY_OFFLINE;
// this.responseCode = responseCode;
// }
//
// public boolean isLocalCacheOnly() {
// return localCacheOnly;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/model/Resources.java
// @SuppressWarnings("unused") public final class Resources {
// protected final ConcurrentHashMap<String, Resource> members;
//
// public Resources() {
// this.members = new ConcurrentHashMap<>();
// }
//
// public Resources(@NonNull ConcurrentHashMap<String, Resource> members) {
// this.members = members;
// }
//
// public static Resources from(Reader reader, Converter converter) throws IOException {
// return converter.fromReader(reader);
// }
//
// public static Resources from(String string, Converter converter) throws IOException {
// return from(new StringReader(string), converter);
// }
//
// public static Resources fromJson(Reader reader) throws IOException {
// return from(reader, new JsonConverter());
// }
//
// public static Resources fromJson(String string) throws IOException {
// return from(string, new JsonConverter());
// }
//
// public static Resources fromJson(InputStream reader) throws IOException {
// return fromJson(new InputStreamReader(reader));
// }
//
// public static Resources fromXml(Reader reader) throws IOException {
// return from(reader, new XmlConverter());
// }
//
// public static Resources fromXml(String string) throws IOException {
// return from(string, new XmlConverter());
// }
//
// public static Resources fromXml(InputStream reader) throws IOException {
// return fromXml(new InputStreamReader(reader));
// }
//
// public Resource add(String key, Resource value) {
// return members.put(key, value);
// }
//
// @NonNull protected Set<Entry<String, Resource>> entrySet() {
// return members.entrySet();
// }
//
// public boolean has(String key) {
// return members.containsKey(key);
// }
//
// public Resource get(String key) {
// return members.get(key);
// }
//
// public Resources merge(Resources resources) {
// members.putAll(resources.members);
//
// return this;
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/url/Url.java
// public interface Url {
//
// void fontScale(float fontScale);
//
// void hardKeyboardHidden(int hardKeyboardHidden);
//
// void keyboard(int keyboard);
//
// void keyboardHidden(int keyboardHidden);
//
// void locale(Locale locale);
//
// void mcc(int mcc);
//
// void mnc(int mnc);
//
// void navigation(int navigation);
//
// void navigationHidden(int navigationHidden);
//
// void orientation(int orientation);
//
// void screenLayout(int screenLayout);
//
// void touchscreen(int touchscreen);
//
// void uiMode(int uiMode);
//
// void densityDpi(int densityDpi);
//
// void screenWidthDp(int screenWidthDp);
//
// void screenHeightDp(int screenHeightDp);
//
// void smallestScreenWidthDp(int smallestScreenWidthDp);
//
// String build();
// }
// Path: library/src/main/java/fr/prcaen/externalresources/Downloader.java
import android.content.Context;
import android.content.res.Configuration;
import android.support.annotation.NonNull;
import com.squareup.okhttp.CacheControl;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import fr.prcaen.externalresources.converter.Converter;
import fr.prcaen.externalresources.exception.ExternalResourceException;
import fr.prcaen.externalresources.exception.ResponseException;
import fr.prcaen.externalresources.model.Resources;
import fr.prcaen.externalresources.url.Url;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.HONEYCOMB_MR2;
import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
public Resources load(@Cache.Policy int policy) throws ExternalResourceException {
buildUrl();
Logger.i(ExternalResources.TAG, "Load configuration from url: " + url.build());
final CacheControl cacheControl;
switch (policy) {
case Cache.POLICY_NONE:
cacheControl = new CacheControl.Builder().noCache().noStore().build();
break;
case Cache.POLICY_OFFLINE:
cacheControl = CacheControl.FORCE_CACHE;
break;
case Cache.POLICY_ALL:
default:
cacheControl = new CacheControl.Builder().build();
break;
}
Logger.v(ExternalResources.TAG, "CachePolicy: " + policy);
Request request = new Request.Builder().url(url.build()).cacheControl(cacheControl).build();
try {
Response response = client.newCall(request).execute();
int responseCode = response.code();
Logger.d(ExternalResources.TAG, "Response code: " + responseCode);
if (responseCode >= 300) {
response.body().close(); | throw new ResponseException(responseCode + " " + response.message(), policy, responseCode); |
prcaen/external-resources | library/src/main/java/fr/prcaen/externalresources/exception/ResponseException.java | // Path: library/src/main/java/fr/prcaen/externalresources/Cache.java
// public final class Cache {
// public static final int POLICY_NONE = 0;
// public static final int POLICY_OFFLINE = 1;
// public static final int POLICY_ALL = 2;
// protected static final int MIN_DISK_CACHE_SIZE = 5 * 1024 * 1024; // 5MB
// protected static final int MAX_DISK_CACHE_SIZE = 50 * 1024 * 1024; // 50MB
// private static final String EXTERNAL_RESOURCES_FILE_NAME_CACHE = "external-resources-cache";
// private final File cacheDir;
// private final long cacheSize;
//
// @Retention(RetentionPolicy.SOURCE) @IntDef({
// POLICY_NONE, POLICY_OFFLINE, POLICY_ALL
// }) public @interface Policy {
// }
//
// public Cache(Context context) {
// this.cacheDir = createDefaultCacheDir(context.getApplicationContext());
// this.cacheSize = calculateDiskCacheSize(cacheDir);
// }
//
// private static File createDefaultCacheDir(Context context) {
// File cache = new File(context.getCacheDir(), EXTERNAL_RESOURCES_FILE_NAME_CACHE);
//
// if (!cache.exists()) {
// //noinspection ResultOfMethodCallIgnored
// cache.mkdirs();
// }
//
// return cache;
// }
//
// @SuppressWarnings("deprecation") public static long calculateDiskCacheSize(File dir) {
// long size = MIN_DISK_CACHE_SIZE;
//
// try {
// StatFs statFs = new StatFs(dir.getAbsolutePath());
// final long available;
//
// if (SDK_INT < JELLY_BEAN_MR2) {
// available = ((long) statFs.getBlockCount()) * statFs.getBlockSize();
// } else {
// available = statFs.getBlockCountLong() * statFs.getBlockSizeLong();
// }
//
// size = available / 50;
// } catch (IllegalArgumentException ignored) {
// }
//
// return Math.max(Math.min(size, MAX_DISK_CACHE_SIZE), MIN_DISK_CACHE_SIZE);
// }
//
// public File getCacheDir() {
// return cacheDir;
// }
//
// public long getCacheSize() {
// return cacheSize;
// }
// }
| import fr.prcaen.externalresources.Cache; | package fr.prcaen.externalresources.exception;
public final class ResponseException extends ExternalResourceException {
private final boolean localCacheOnly;
private final int responseCode;
| // Path: library/src/main/java/fr/prcaen/externalresources/Cache.java
// public final class Cache {
// public static final int POLICY_NONE = 0;
// public static final int POLICY_OFFLINE = 1;
// public static final int POLICY_ALL = 2;
// protected static final int MIN_DISK_CACHE_SIZE = 5 * 1024 * 1024; // 5MB
// protected static final int MAX_DISK_CACHE_SIZE = 50 * 1024 * 1024; // 50MB
// private static final String EXTERNAL_RESOURCES_FILE_NAME_CACHE = "external-resources-cache";
// private final File cacheDir;
// private final long cacheSize;
//
// @Retention(RetentionPolicy.SOURCE) @IntDef({
// POLICY_NONE, POLICY_OFFLINE, POLICY_ALL
// }) public @interface Policy {
// }
//
// public Cache(Context context) {
// this.cacheDir = createDefaultCacheDir(context.getApplicationContext());
// this.cacheSize = calculateDiskCacheSize(cacheDir);
// }
//
// private static File createDefaultCacheDir(Context context) {
// File cache = new File(context.getCacheDir(), EXTERNAL_RESOURCES_FILE_NAME_CACHE);
//
// if (!cache.exists()) {
// //noinspection ResultOfMethodCallIgnored
// cache.mkdirs();
// }
//
// return cache;
// }
//
// @SuppressWarnings("deprecation") public static long calculateDiskCacheSize(File dir) {
// long size = MIN_DISK_CACHE_SIZE;
//
// try {
// StatFs statFs = new StatFs(dir.getAbsolutePath());
// final long available;
//
// if (SDK_INT < JELLY_BEAN_MR2) {
// available = ((long) statFs.getBlockCount()) * statFs.getBlockSize();
// } else {
// available = statFs.getBlockCountLong() * statFs.getBlockSizeLong();
// }
//
// size = available / 50;
// } catch (IllegalArgumentException ignored) {
// }
//
// return Math.max(Math.min(size, MAX_DISK_CACHE_SIZE), MIN_DISK_CACHE_SIZE);
// }
//
// public File getCacheDir() {
// return cacheDir;
// }
//
// public long getCacheSize() {
// return cacheSize;
// }
// }
// Path: library/src/main/java/fr/prcaen/externalresources/exception/ResponseException.java
import fr.prcaen.externalresources.Cache;
package fr.prcaen.externalresources.exception;
public final class ResponseException extends ExternalResourceException {
private final boolean localCacheOnly;
private final int responseCode;
| public ResponseException(String message, @Cache.Policy int networkPolicy, int responseCode) { |
prcaen/external-resources | library/src/main/java/fr/prcaen/externalresources/ResourcesRunnable.java | // Path: library/src/main/java/fr/prcaen/externalresources/exception/ExternalResourceException.java
// public class ExternalResourceException extends RuntimeException {
//
// public ExternalResourceException(String detailMessage) {
// super(detailMessage);
// }
//
// public ExternalResourceException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ExternalResourceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/exception/ResponseException.java
// public final class ResponseException extends ExternalResourceException {
//
// private final boolean localCacheOnly;
// private final int responseCode;
//
// public ResponseException(String message, @Cache.Policy int networkPolicy, int responseCode) {
// super(message);
//
// this.localCacheOnly = networkPolicy == Cache.POLICY_OFFLINE;
// this.responseCode = responseCode;
// }
//
// public boolean isLocalCacheOnly() {
// return localCacheOnly;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/model/Resources.java
// @SuppressWarnings("unused") public final class Resources {
// protected final ConcurrentHashMap<String, Resource> members;
//
// public Resources() {
// this.members = new ConcurrentHashMap<>();
// }
//
// public Resources(@NonNull ConcurrentHashMap<String, Resource> members) {
// this.members = members;
// }
//
// public static Resources from(Reader reader, Converter converter) throws IOException {
// return converter.fromReader(reader);
// }
//
// public static Resources from(String string, Converter converter) throws IOException {
// return from(new StringReader(string), converter);
// }
//
// public static Resources fromJson(Reader reader) throws IOException {
// return from(reader, new JsonConverter());
// }
//
// public static Resources fromJson(String string) throws IOException {
// return from(string, new JsonConverter());
// }
//
// public static Resources fromJson(InputStream reader) throws IOException {
// return fromJson(new InputStreamReader(reader));
// }
//
// public static Resources fromXml(Reader reader) throws IOException {
// return from(reader, new XmlConverter());
// }
//
// public static Resources fromXml(String string) throws IOException {
// return from(string, new XmlConverter());
// }
//
// public static Resources fromXml(InputStream reader) throws IOException {
// return fromXml(new InputStreamReader(reader));
// }
//
// public Resource add(String key, Resource value) {
// return members.put(key, value);
// }
//
// @NonNull protected Set<Entry<String, Resource>> entrySet() {
// return members.entrySet();
// }
//
// public boolean has(String key) {
// return members.containsKey(key);
// }
//
// public Resource get(String key) {
// return members.get(key);
// }
//
// public Resources merge(Resources resources) {
// members.putAll(resources.members);
//
// return this;
// }
// }
| import android.support.annotation.NonNull;
import fr.prcaen.externalresources.exception.ExternalResourceException;
import fr.prcaen.externalresources.exception.ResponseException;
import fr.prcaen.externalresources.model.Resources; | package fr.prcaen.externalresources;
public final class ResourcesRunnable implements Runnable {
public static final int RETRY_COUNT = 2;
private static final String THREAD_NAME_SUFFIX = "-external-resources";
private final Downloader downloader;
private final Dispatcher dispatcher;
@Cache.Policy private final int cachePolicy;
private int retryCount;
public ResourcesRunnable(@NonNull Downloader downloader, @NonNull Dispatcher dispatcher,
@Cache.Policy int policy) {
this.downloader = downloader;
this.dispatcher = dispatcher;
this.cachePolicy = policy;
this.retryCount = RETRY_COUNT;
}
@Override public void run() {
Thread.currentThread().setName(Thread.currentThread().getId() + THREAD_NAME_SUFFIX);
try { | // Path: library/src/main/java/fr/prcaen/externalresources/exception/ExternalResourceException.java
// public class ExternalResourceException extends RuntimeException {
//
// public ExternalResourceException(String detailMessage) {
// super(detailMessage);
// }
//
// public ExternalResourceException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ExternalResourceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/exception/ResponseException.java
// public final class ResponseException extends ExternalResourceException {
//
// private final boolean localCacheOnly;
// private final int responseCode;
//
// public ResponseException(String message, @Cache.Policy int networkPolicy, int responseCode) {
// super(message);
//
// this.localCacheOnly = networkPolicy == Cache.POLICY_OFFLINE;
// this.responseCode = responseCode;
// }
//
// public boolean isLocalCacheOnly() {
// return localCacheOnly;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/model/Resources.java
// @SuppressWarnings("unused") public final class Resources {
// protected final ConcurrentHashMap<String, Resource> members;
//
// public Resources() {
// this.members = new ConcurrentHashMap<>();
// }
//
// public Resources(@NonNull ConcurrentHashMap<String, Resource> members) {
// this.members = members;
// }
//
// public static Resources from(Reader reader, Converter converter) throws IOException {
// return converter.fromReader(reader);
// }
//
// public static Resources from(String string, Converter converter) throws IOException {
// return from(new StringReader(string), converter);
// }
//
// public static Resources fromJson(Reader reader) throws IOException {
// return from(reader, new JsonConverter());
// }
//
// public static Resources fromJson(String string) throws IOException {
// return from(string, new JsonConverter());
// }
//
// public static Resources fromJson(InputStream reader) throws IOException {
// return fromJson(new InputStreamReader(reader));
// }
//
// public static Resources fromXml(Reader reader) throws IOException {
// return from(reader, new XmlConverter());
// }
//
// public static Resources fromXml(String string) throws IOException {
// return from(string, new XmlConverter());
// }
//
// public static Resources fromXml(InputStream reader) throws IOException {
// return fromXml(new InputStreamReader(reader));
// }
//
// public Resource add(String key, Resource value) {
// return members.put(key, value);
// }
//
// @NonNull protected Set<Entry<String, Resource>> entrySet() {
// return members.entrySet();
// }
//
// public boolean has(String key) {
// return members.containsKey(key);
// }
//
// public Resource get(String key) {
// return members.get(key);
// }
//
// public Resources merge(Resources resources) {
// members.putAll(resources.members);
//
// return this;
// }
// }
// Path: library/src/main/java/fr/prcaen/externalresources/ResourcesRunnable.java
import android.support.annotation.NonNull;
import fr.prcaen.externalresources.exception.ExternalResourceException;
import fr.prcaen.externalresources.exception.ResponseException;
import fr.prcaen.externalresources.model.Resources;
package fr.prcaen.externalresources;
public final class ResourcesRunnable implements Runnable {
public static final int RETRY_COUNT = 2;
private static final String THREAD_NAME_SUFFIX = "-external-resources";
private final Downloader downloader;
private final Dispatcher dispatcher;
@Cache.Policy private final int cachePolicy;
private int retryCount;
public ResourcesRunnable(@NonNull Downloader downloader, @NonNull Dispatcher dispatcher,
@Cache.Policy int policy) {
this.downloader = downloader;
this.dispatcher = dispatcher;
this.cachePolicy = policy;
this.retryCount = RETRY_COUNT;
}
@Override public void run() {
Thread.currentThread().setName(Thread.currentThread().getId() + THREAD_NAME_SUFFIX);
try { | Resources resources = downloader.load(cachePolicy); |
prcaen/external-resources | library/src/main/java/fr/prcaen/externalresources/ResourcesRunnable.java | // Path: library/src/main/java/fr/prcaen/externalresources/exception/ExternalResourceException.java
// public class ExternalResourceException extends RuntimeException {
//
// public ExternalResourceException(String detailMessage) {
// super(detailMessage);
// }
//
// public ExternalResourceException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ExternalResourceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/exception/ResponseException.java
// public final class ResponseException extends ExternalResourceException {
//
// private final boolean localCacheOnly;
// private final int responseCode;
//
// public ResponseException(String message, @Cache.Policy int networkPolicy, int responseCode) {
// super(message);
//
// this.localCacheOnly = networkPolicy == Cache.POLICY_OFFLINE;
// this.responseCode = responseCode;
// }
//
// public boolean isLocalCacheOnly() {
// return localCacheOnly;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/model/Resources.java
// @SuppressWarnings("unused") public final class Resources {
// protected final ConcurrentHashMap<String, Resource> members;
//
// public Resources() {
// this.members = new ConcurrentHashMap<>();
// }
//
// public Resources(@NonNull ConcurrentHashMap<String, Resource> members) {
// this.members = members;
// }
//
// public static Resources from(Reader reader, Converter converter) throws IOException {
// return converter.fromReader(reader);
// }
//
// public static Resources from(String string, Converter converter) throws IOException {
// return from(new StringReader(string), converter);
// }
//
// public static Resources fromJson(Reader reader) throws IOException {
// return from(reader, new JsonConverter());
// }
//
// public static Resources fromJson(String string) throws IOException {
// return from(string, new JsonConverter());
// }
//
// public static Resources fromJson(InputStream reader) throws IOException {
// return fromJson(new InputStreamReader(reader));
// }
//
// public static Resources fromXml(Reader reader) throws IOException {
// return from(reader, new XmlConverter());
// }
//
// public static Resources fromXml(String string) throws IOException {
// return from(string, new XmlConverter());
// }
//
// public static Resources fromXml(InputStream reader) throws IOException {
// return fromXml(new InputStreamReader(reader));
// }
//
// public Resource add(String key, Resource value) {
// return members.put(key, value);
// }
//
// @NonNull protected Set<Entry<String, Resource>> entrySet() {
// return members.entrySet();
// }
//
// public boolean has(String key) {
// return members.containsKey(key);
// }
//
// public Resource get(String key) {
// return members.get(key);
// }
//
// public Resources merge(Resources resources) {
// members.putAll(resources.members);
//
// return this;
// }
// }
| import android.support.annotation.NonNull;
import fr.prcaen.externalresources.exception.ExternalResourceException;
import fr.prcaen.externalresources.exception.ResponseException;
import fr.prcaen.externalresources.model.Resources; | package fr.prcaen.externalresources;
public final class ResourcesRunnable implements Runnable {
public static final int RETRY_COUNT = 2;
private static final String THREAD_NAME_SUFFIX = "-external-resources";
private final Downloader downloader;
private final Dispatcher dispatcher;
@Cache.Policy private final int cachePolicy;
private int retryCount;
public ResourcesRunnable(@NonNull Downloader downloader, @NonNull Dispatcher dispatcher,
@Cache.Policy int policy) {
this.downloader = downloader;
this.dispatcher = dispatcher;
this.cachePolicy = policy;
this.retryCount = RETRY_COUNT;
}
@Override public void run() {
Thread.currentThread().setName(Thread.currentThread().getId() + THREAD_NAME_SUFFIX);
try {
Resources resources = downloader.load(cachePolicy);
if (null != resources) {
dispatcher.dispatchDone(resources);
} else { | // Path: library/src/main/java/fr/prcaen/externalresources/exception/ExternalResourceException.java
// public class ExternalResourceException extends RuntimeException {
//
// public ExternalResourceException(String detailMessage) {
// super(detailMessage);
// }
//
// public ExternalResourceException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ExternalResourceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/exception/ResponseException.java
// public final class ResponseException extends ExternalResourceException {
//
// private final boolean localCacheOnly;
// private final int responseCode;
//
// public ResponseException(String message, @Cache.Policy int networkPolicy, int responseCode) {
// super(message);
//
// this.localCacheOnly = networkPolicy == Cache.POLICY_OFFLINE;
// this.responseCode = responseCode;
// }
//
// public boolean isLocalCacheOnly() {
// return localCacheOnly;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/model/Resources.java
// @SuppressWarnings("unused") public final class Resources {
// protected final ConcurrentHashMap<String, Resource> members;
//
// public Resources() {
// this.members = new ConcurrentHashMap<>();
// }
//
// public Resources(@NonNull ConcurrentHashMap<String, Resource> members) {
// this.members = members;
// }
//
// public static Resources from(Reader reader, Converter converter) throws IOException {
// return converter.fromReader(reader);
// }
//
// public static Resources from(String string, Converter converter) throws IOException {
// return from(new StringReader(string), converter);
// }
//
// public static Resources fromJson(Reader reader) throws IOException {
// return from(reader, new JsonConverter());
// }
//
// public static Resources fromJson(String string) throws IOException {
// return from(string, new JsonConverter());
// }
//
// public static Resources fromJson(InputStream reader) throws IOException {
// return fromJson(new InputStreamReader(reader));
// }
//
// public static Resources fromXml(Reader reader) throws IOException {
// return from(reader, new XmlConverter());
// }
//
// public static Resources fromXml(String string) throws IOException {
// return from(string, new XmlConverter());
// }
//
// public static Resources fromXml(InputStream reader) throws IOException {
// return fromXml(new InputStreamReader(reader));
// }
//
// public Resource add(String key, Resource value) {
// return members.put(key, value);
// }
//
// @NonNull protected Set<Entry<String, Resource>> entrySet() {
// return members.entrySet();
// }
//
// public boolean has(String key) {
// return members.containsKey(key);
// }
//
// public Resource get(String key) {
// return members.get(key);
// }
//
// public Resources merge(Resources resources) {
// members.putAll(resources.members);
//
// return this;
// }
// }
// Path: library/src/main/java/fr/prcaen/externalresources/ResourcesRunnable.java
import android.support.annotation.NonNull;
import fr.prcaen.externalresources.exception.ExternalResourceException;
import fr.prcaen.externalresources.exception.ResponseException;
import fr.prcaen.externalresources.model.Resources;
package fr.prcaen.externalresources;
public final class ResourcesRunnable implements Runnable {
public static final int RETRY_COUNT = 2;
private static final String THREAD_NAME_SUFFIX = "-external-resources";
private final Downloader downloader;
private final Dispatcher dispatcher;
@Cache.Policy private final int cachePolicy;
private int retryCount;
public ResourcesRunnable(@NonNull Downloader downloader, @NonNull Dispatcher dispatcher,
@Cache.Policy int policy) {
this.downloader = downloader;
this.dispatcher = dispatcher;
this.cachePolicy = policy;
this.retryCount = RETRY_COUNT;
}
@Override public void run() {
Thread.currentThread().setName(Thread.currentThread().getId() + THREAD_NAME_SUFFIX);
try {
Resources resources = downloader.load(cachePolicy);
if (null != resources) {
dispatcher.dispatchDone(resources);
} else { | dispatcher.dispatchFailed(new ExternalResourceException("Resources are null.")); |
prcaen/external-resources | library/src/main/java/fr/prcaen/externalresources/ResourcesRunnable.java | // Path: library/src/main/java/fr/prcaen/externalresources/exception/ExternalResourceException.java
// public class ExternalResourceException extends RuntimeException {
//
// public ExternalResourceException(String detailMessage) {
// super(detailMessage);
// }
//
// public ExternalResourceException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ExternalResourceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/exception/ResponseException.java
// public final class ResponseException extends ExternalResourceException {
//
// private final boolean localCacheOnly;
// private final int responseCode;
//
// public ResponseException(String message, @Cache.Policy int networkPolicy, int responseCode) {
// super(message);
//
// this.localCacheOnly = networkPolicy == Cache.POLICY_OFFLINE;
// this.responseCode = responseCode;
// }
//
// public boolean isLocalCacheOnly() {
// return localCacheOnly;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/model/Resources.java
// @SuppressWarnings("unused") public final class Resources {
// protected final ConcurrentHashMap<String, Resource> members;
//
// public Resources() {
// this.members = new ConcurrentHashMap<>();
// }
//
// public Resources(@NonNull ConcurrentHashMap<String, Resource> members) {
// this.members = members;
// }
//
// public static Resources from(Reader reader, Converter converter) throws IOException {
// return converter.fromReader(reader);
// }
//
// public static Resources from(String string, Converter converter) throws IOException {
// return from(new StringReader(string), converter);
// }
//
// public static Resources fromJson(Reader reader) throws IOException {
// return from(reader, new JsonConverter());
// }
//
// public static Resources fromJson(String string) throws IOException {
// return from(string, new JsonConverter());
// }
//
// public static Resources fromJson(InputStream reader) throws IOException {
// return fromJson(new InputStreamReader(reader));
// }
//
// public static Resources fromXml(Reader reader) throws IOException {
// return from(reader, new XmlConverter());
// }
//
// public static Resources fromXml(String string) throws IOException {
// return from(string, new XmlConverter());
// }
//
// public static Resources fromXml(InputStream reader) throws IOException {
// return fromXml(new InputStreamReader(reader));
// }
//
// public Resource add(String key, Resource value) {
// return members.put(key, value);
// }
//
// @NonNull protected Set<Entry<String, Resource>> entrySet() {
// return members.entrySet();
// }
//
// public boolean has(String key) {
// return members.containsKey(key);
// }
//
// public Resource get(String key) {
// return members.get(key);
// }
//
// public Resources merge(Resources resources) {
// members.putAll(resources.members);
//
// return this;
// }
// }
| import android.support.annotation.NonNull;
import fr.prcaen.externalresources.exception.ExternalResourceException;
import fr.prcaen.externalresources.exception.ResponseException;
import fr.prcaen.externalresources.model.Resources; | package fr.prcaen.externalresources;
public final class ResourcesRunnable implements Runnable {
public static final int RETRY_COUNT = 2;
private static final String THREAD_NAME_SUFFIX = "-external-resources";
private final Downloader downloader;
private final Dispatcher dispatcher;
@Cache.Policy private final int cachePolicy;
private int retryCount;
public ResourcesRunnable(@NonNull Downloader downloader, @NonNull Dispatcher dispatcher,
@Cache.Policy int policy) {
this.downloader = downloader;
this.dispatcher = dispatcher;
this.cachePolicy = policy;
this.retryCount = RETRY_COUNT;
}
@Override public void run() {
Thread.currentThread().setName(Thread.currentThread().getId() + THREAD_NAME_SUFFIX);
try {
Resources resources = downloader.load(cachePolicy);
if (null != resources) {
dispatcher.dispatchDone(resources);
} else {
dispatcher.dispatchFailed(new ExternalResourceException("Resources are null."));
} | // Path: library/src/main/java/fr/prcaen/externalresources/exception/ExternalResourceException.java
// public class ExternalResourceException extends RuntimeException {
//
// public ExternalResourceException(String detailMessage) {
// super(detailMessage);
// }
//
// public ExternalResourceException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ExternalResourceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/exception/ResponseException.java
// public final class ResponseException extends ExternalResourceException {
//
// private final boolean localCacheOnly;
// private final int responseCode;
//
// public ResponseException(String message, @Cache.Policy int networkPolicy, int responseCode) {
// super(message);
//
// this.localCacheOnly = networkPolicy == Cache.POLICY_OFFLINE;
// this.responseCode = responseCode;
// }
//
// public boolean isLocalCacheOnly() {
// return localCacheOnly;
// }
//
// public int getResponseCode() {
// return responseCode;
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/model/Resources.java
// @SuppressWarnings("unused") public final class Resources {
// protected final ConcurrentHashMap<String, Resource> members;
//
// public Resources() {
// this.members = new ConcurrentHashMap<>();
// }
//
// public Resources(@NonNull ConcurrentHashMap<String, Resource> members) {
// this.members = members;
// }
//
// public static Resources from(Reader reader, Converter converter) throws IOException {
// return converter.fromReader(reader);
// }
//
// public static Resources from(String string, Converter converter) throws IOException {
// return from(new StringReader(string), converter);
// }
//
// public static Resources fromJson(Reader reader) throws IOException {
// return from(reader, new JsonConverter());
// }
//
// public static Resources fromJson(String string) throws IOException {
// return from(string, new JsonConverter());
// }
//
// public static Resources fromJson(InputStream reader) throws IOException {
// return fromJson(new InputStreamReader(reader));
// }
//
// public static Resources fromXml(Reader reader) throws IOException {
// return from(reader, new XmlConverter());
// }
//
// public static Resources fromXml(String string) throws IOException {
// return from(string, new XmlConverter());
// }
//
// public static Resources fromXml(InputStream reader) throws IOException {
// return fromXml(new InputStreamReader(reader));
// }
//
// public Resource add(String key, Resource value) {
// return members.put(key, value);
// }
//
// @NonNull protected Set<Entry<String, Resource>> entrySet() {
// return members.entrySet();
// }
//
// public boolean has(String key) {
// return members.containsKey(key);
// }
//
// public Resource get(String key) {
// return members.get(key);
// }
//
// public Resources merge(Resources resources) {
// members.putAll(resources.members);
//
// return this;
// }
// }
// Path: library/src/main/java/fr/prcaen/externalresources/ResourcesRunnable.java
import android.support.annotation.NonNull;
import fr.prcaen.externalresources.exception.ExternalResourceException;
import fr.prcaen.externalresources.exception.ResponseException;
import fr.prcaen.externalresources.model.Resources;
package fr.prcaen.externalresources;
public final class ResourcesRunnable implements Runnable {
public static final int RETRY_COUNT = 2;
private static final String THREAD_NAME_SUFFIX = "-external-resources";
private final Downloader downloader;
private final Dispatcher dispatcher;
@Cache.Policy private final int cachePolicy;
private int retryCount;
public ResourcesRunnable(@NonNull Downloader downloader, @NonNull Dispatcher dispatcher,
@Cache.Policy int policy) {
this.downloader = downloader;
this.dispatcher = dispatcher;
this.cachePolicy = policy;
this.retryCount = RETRY_COUNT;
}
@Override public void run() {
Thread.currentThread().setName(Thread.currentThread().getId() + THREAD_NAME_SUFFIX);
try {
Resources resources = downloader.load(cachePolicy);
if (null != resources) {
dispatcher.dispatchDone(resources);
} else {
dispatcher.dispatchFailed(new ExternalResourceException("Resources are null."));
} | } catch (ResponseException e) { |
prcaen/external-resources | library/src/main/java/fr/prcaen/externalresources/Dispatcher.java | // Path: library/src/main/java/fr/prcaen/externalresources/exception/ExternalResourceException.java
// public class ExternalResourceException extends RuntimeException {
//
// public ExternalResourceException(String detailMessage) {
// super(detailMessage);
// }
//
// public ExternalResourceException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ExternalResourceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/model/Resources.java
// @SuppressWarnings("unused") public final class Resources {
// protected final ConcurrentHashMap<String, Resource> members;
//
// public Resources() {
// this.members = new ConcurrentHashMap<>();
// }
//
// public Resources(@NonNull ConcurrentHashMap<String, Resource> members) {
// this.members = members;
// }
//
// public static Resources from(Reader reader, Converter converter) throws IOException {
// return converter.fromReader(reader);
// }
//
// public static Resources from(String string, Converter converter) throws IOException {
// return from(new StringReader(string), converter);
// }
//
// public static Resources fromJson(Reader reader) throws IOException {
// return from(reader, new JsonConverter());
// }
//
// public static Resources fromJson(String string) throws IOException {
// return from(string, new JsonConverter());
// }
//
// public static Resources fromJson(InputStream reader) throws IOException {
// return fromJson(new InputStreamReader(reader));
// }
//
// public static Resources fromXml(Reader reader) throws IOException {
// return from(reader, new XmlConverter());
// }
//
// public static Resources fromXml(String string) throws IOException {
// return from(string, new XmlConverter());
// }
//
// public static Resources fromXml(InputStream reader) throws IOException {
// return fromXml(new InputStreamReader(reader));
// }
//
// public Resource add(String key, Resource value) {
// return members.put(key, value);
// }
//
// @NonNull protected Set<Entry<String, Resource>> entrySet() {
// return members.entrySet();
// }
//
// public boolean has(String key) {
// return members.containsKey(key);
// }
//
// public Resource get(String key) {
// return members.get(key);
// }
//
// public Resources merge(Resources resources) {
// members.putAll(resources.members);
//
// return this;
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/ResourcesRunnable.java
// public static final int RETRY_COUNT = 2;
| import android.content.Context;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import fr.prcaen.externalresources.exception.ExternalResourceException;
import fr.prcaen.externalresources.model.Resources;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static fr.prcaen.externalresources.ResourcesRunnable.RETRY_COUNT; | this.context = context;
this.service = Executors.newSingleThreadExecutor();
this.dispatcherThread = new DispatcherThread();
this.dispatcherThread.start();
this.mainHandler = mainHandler;
this.handler = new DispatcherHandler(dispatcherThread.getLooper(), this);
this.networkBroadcastReceiver = new NetworkBroadcastReceiver(context, this);
this.networkBroadcastReceiver.register();
this.networkInfo = Utils.getActiveNetworkInfo(context);
this.airPlaneMode = Utils.isAirplaneModeOn(context);
this.resourcesRunnable = new ResourcesRunnable(downloader, this, cachePolicy);
}
public void stop() {
service.shutdown();
dispatcherThread.quit();
networkBroadcastReceiver.unregister();
}
public void dispatchLaunch() {
Logger.v(ExternalResources.TAG, "dispatch launch");
handler.sendMessage(handler.obtainMessage(REQUEST_LAUNCH));
}
public void dispatchRetry() {
Logger.v(ExternalResources.TAG, "dispatch retry");
handler.sendMessageDelayed(handler.obtainMessage(REQUEST_RETRY), RETRY_DELAY);
}
| // Path: library/src/main/java/fr/prcaen/externalresources/exception/ExternalResourceException.java
// public class ExternalResourceException extends RuntimeException {
//
// public ExternalResourceException(String detailMessage) {
// super(detailMessage);
// }
//
// public ExternalResourceException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ExternalResourceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/model/Resources.java
// @SuppressWarnings("unused") public final class Resources {
// protected final ConcurrentHashMap<String, Resource> members;
//
// public Resources() {
// this.members = new ConcurrentHashMap<>();
// }
//
// public Resources(@NonNull ConcurrentHashMap<String, Resource> members) {
// this.members = members;
// }
//
// public static Resources from(Reader reader, Converter converter) throws IOException {
// return converter.fromReader(reader);
// }
//
// public static Resources from(String string, Converter converter) throws IOException {
// return from(new StringReader(string), converter);
// }
//
// public static Resources fromJson(Reader reader) throws IOException {
// return from(reader, new JsonConverter());
// }
//
// public static Resources fromJson(String string) throws IOException {
// return from(string, new JsonConverter());
// }
//
// public static Resources fromJson(InputStream reader) throws IOException {
// return fromJson(new InputStreamReader(reader));
// }
//
// public static Resources fromXml(Reader reader) throws IOException {
// return from(reader, new XmlConverter());
// }
//
// public static Resources fromXml(String string) throws IOException {
// return from(string, new XmlConverter());
// }
//
// public static Resources fromXml(InputStream reader) throws IOException {
// return fromXml(new InputStreamReader(reader));
// }
//
// public Resource add(String key, Resource value) {
// return members.put(key, value);
// }
//
// @NonNull protected Set<Entry<String, Resource>> entrySet() {
// return members.entrySet();
// }
//
// public boolean has(String key) {
// return members.containsKey(key);
// }
//
// public Resource get(String key) {
// return members.get(key);
// }
//
// public Resources merge(Resources resources) {
// members.putAll(resources.members);
//
// return this;
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/ResourcesRunnable.java
// public static final int RETRY_COUNT = 2;
// Path: library/src/main/java/fr/prcaen/externalresources/Dispatcher.java
import android.content.Context;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import fr.prcaen.externalresources.exception.ExternalResourceException;
import fr.prcaen.externalresources.model.Resources;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static fr.prcaen.externalresources.ResourcesRunnable.RETRY_COUNT;
this.context = context;
this.service = Executors.newSingleThreadExecutor();
this.dispatcherThread = new DispatcherThread();
this.dispatcherThread.start();
this.mainHandler = mainHandler;
this.handler = new DispatcherHandler(dispatcherThread.getLooper(), this);
this.networkBroadcastReceiver = new NetworkBroadcastReceiver(context, this);
this.networkBroadcastReceiver.register();
this.networkInfo = Utils.getActiveNetworkInfo(context);
this.airPlaneMode = Utils.isAirplaneModeOn(context);
this.resourcesRunnable = new ResourcesRunnable(downloader, this, cachePolicy);
}
public void stop() {
service.shutdown();
dispatcherThread.quit();
networkBroadcastReceiver.unregister();
}
public void dispatchLaunch() {
Logger.v(ExternalResources.TAG, "dispatch launch");
handler.sendMessage(handler.obtainMessage(REQUEST_LAUNCH));
}
public void dispatchRetry() {
Logger.v(ExternalResources.TAG, "dispatch retry");
handler.sendMessageDelayed(handler.obtainMessage(REQUEST_RETRY), RETRY_DELAY);
}
| public void dispatchFailed(ExternalResourceException e) { |
prcaen/external-resources | library/src/main/java/fr/prcaen/externalresources/Dispatcher.java | // Path: library/src/main/java/fr/prcaen/externalresources/exception/ExternalResourceException.java
// public class ExternalResourceException extends RuntimeException {
//
// public ExternalResourceException(String detailMessage) {
// super(detailMessage);
// }
//
// public ExternalResourceException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ExternalResourceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/model/Resources.java
// @SuppressWarnings("unused") public final class Resources {
// protected final ConcurrentHashMap<String, Resource> members;
//
// public Resources() {
// this.members = new ConcurrentHashMap<>();
// }
//
// public Resources(@NonNull ConcurrentHashMap<String, Resource> members) {
// this.members = members;
// }
//
// public static Resources from(Reader reader, Converter converter) throws IOException {
// return converter.fromReader(reader);
// }
//
// public static Resources from(String string, Converter converter) throws IOException {
// return from(new StringReader(string), converter);
// }
//
// public static Resources fromJson(Reader reader) throws IOException {
// return from(reader, new JsonConverter());
// }
//
// public static Resources fromJson(String string) throws IOException {
// return from(string, new JsonConverter());
// }
//
// public static Resources fromJson(InputStream reader) throws IOException {
// return fromJson(new InputStreamReader(reader));
// }
//
// public static Resources fromXml(Reader reader) throws IOException {
// return from(reader, new XmlConverter());
// }
//
// public static Resources fromXml(String string) throws IOException {
// return from(string, new XmlConverter());
// }
//
// public static Resources fromXml(InputStream reader) throws IOException {
// return fromXml(new InputStreamReader(reader));
// }
//
// public Resource add(String key, Resource value) {
// return members.put(key, value);
// }
//
// @NonNull protected Set<Entry<String, Resource>> entrySet() {
// return members.entrySet();
// }
//
// public boolean has(String key) {
// return members.containsKey(key);
// }
//
// public Resource get(String key) {
// return members.get(key);
// }
//
// public Resources merge(Resources resources) {
// members.putAll(resources.members);
//
// return this;
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/ResourcesRunnable.java
// public static final int RETRY_COUNT = 2;
| import android.content.Context;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import fr.prcaen.externalresources.exception.ExternalResourceException;
import fr.prcaen.externalresources.model.Resources;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static fr.prcaen.externalresources.ResourcesRunnable.RETRY_COUNT; | this.handler = new DispatcherHandler(dispatcherThread.getLooper(), this);
this.networkBroadcastReceiver = new NetworkBroadcastReceiver(context, this);
this.networkBroadcastReceiver.register();
this.networkInfo = Utils.getActiveNetworkInfo(context);
this.airPlaneMode = Utils.isAirplaneModeOn(context);
this.resourcesRunnable = new ResourcesRunnable(downloader, this, cachePolicy);
}
public void stop() {
service.shutdown();
dispatcherThread.quit();
networkBroadcastReceiver.unregister();
}
public void dispatchLaunch() {
Logger.v(ExternalResources.TAG, "dispatch launch");
handler.sendMessage(handler.obtainMessage(REQUEST_LAUNCH));
}
public void dispatchRetry() {
Logger.v(ExternalResources.TAG, "dispatch retry");
handler.sendMessageDelayed(handler.obtainMessage(REQUEST_RETRY), RETRY_DELAY);
}
public void dispatchFailed(ExternalResourceException e) {
Logger.v(ExternalResources.TAG, "dispatch failed");
mainHandler.sendMessage(mainHandler.obtainMessage(REQUEST_FAILED, e));
}
| // Path: library/src/main/java/fr/prcaen/externalresources/exception/ExternalResourceException.java
// public class ExternalResourceException extends RuntimeException {
//
// public ExternalResourceException(String detailMessage) {
// super(detailMessage);
// }
//
// public ExternalResourceException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ExternalResourceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/model/Resources.java
// @SuppressWarnings("unused") public final class Resources {
// protected final ConcurrentHashMap<String, Resource> members;
//
// public Resources() {
// this.members = new ConcurrentHashMap<>();
// }
//
// public Resources(@NonNull ConcurrentHashMap<String, Resource> members) {
// this.members = members;
// }
//
// public static Resources from(Reader reader, Converter converter) throws IOException {
// return converter.fromReader(reader);
// }
//
// public static Resources from(String string, Converter converter) throws IOException {
// return from(new StringReader(string), converter);
// }
//
// public static Resources fromJson(Reader reader) throws IOException {
// return from(reader, new JsonConverter());
// }
//
// public static Resources fromJson(String string) throws IOException {
// return from(string, new JsonConverter());
// }
//
// public static Resources fromJson(InputStream reader) throws IOException {
// return fromJson(new InputStreamReader(reader));
// }
//
// public static Resources fromXml(Reader reader) throws IOException {
// return from(reader, new XmlConverter());
// }
//
// public static Resources fromXml(String string) throws IOException {
// return from(string, new XmlConverter());
// }
//
// public static Resources fromXml(InputStream reader) throws IOException {
// return fromXml(new InputStreamReader(reader));
// }
//
// public Resource add(String key, Resource value) {
// return members.put(key, value);
// }
//
// @NonNull protected Set<Entry<String, Resource>> entrySet() {
// return members.entrySet();
// }
//
// public boolean has(String key) {
// return members.containsKey(key);
// }
//
// public Resource get(String key) {
// return members.get(key);
// }
//
// public Resources merge(Resources resources) {
// members.putAll(resources.members);
//
// return this;
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/ResourcesRunnable.java
// public static final int RETRY_COUNT = 2;
// Path: library/src/main/java/fr/prcaen/externalresources/Dispatcher.java
import android.content.Context;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import fr.prcaen.externalresources.exception.ExternalResourceException;
import fr.prcaen.externalresources.model.Resources;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static fr.prcaen.externalresources.ResourcesRunnable.RETRY_COUNT;
this.handler = new DispatcherHandler(dispatcherThread.getLooper(), this);
this.networkBroadcastReceiver = new NetworkBroadcastReceiver(context, this);
this.networkBroadcastReceiver.register();
this.networkInfo = Utils.getActiveNetworkInfo(context);
this.airPlaneMode = Utils.isAirplaneModeOn(context);
this.resourcesRunnable = new ResourcesRunnable(downloader, this, cachePolicy);
}
public void stop() {
service.shutdown();
dispatcherThread.quit();
networkBroadcastReceiver.unregister();
}
public void dispatchLaunch() {
Logger.v(ExternalResources.TAG, "dispatch launch");
handler.sendMessage(handler.obtainMessage(REQUEST_LAUNCH));
}
public void dispatchRetry() {
Logger.v(ExternalResources.TAG, "dispatch retry");
handler.sendMessageDelayed(handler.obtainMessage(REQUEST_RETRY), RETRY_DELAY);
}
public void dispatchFailed(ExternalResourceException e) {
Logger.v(ExternalResources.TAG, "dispatch failed");
mainHandler.sendMessage(mainHandler.obtainMessage(REQUEST_FAILED, e));
}
| public void dispatchDone(Resources resources) { |
prcaen/external-resources | library/src/main/java/fr/prcaen/externalresources/Dispatcher.java | // Path: library/src/main/java/fr/prcaen/externalresources/exception/ExternalResourceException.java
// public class ExternalResourceException extends RuntimeException {
//
// public ExternalResourceException(String detailMessage) {
// super(detailMessage);
// }
//
// public ExternalResourceException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ExternalResourceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/model/Resources.java
// @SuppressWarnings("unused") public final class Resources {
// protected final ConcurrentHashMap<String, Resource> members;
//
// public Resources() {
// this.members = new ConcurrentHashMap<>();
// }
//
// public Resources(@NonNull ConcurrentHashMap<String, Resource> members) {
// this.members = members;
// }
//
// public static Resources from(Reader reader, Converter converter) throws IOException {
// return converter.fromReader(reader);
// }
//
// public static Resources from(String string, Converter converter) throws IOException {
// return from(new StringReader(string), converter);
// }
//
// public static Resources fromJson(Reader reader) throws IOException {
// return from(reader, new JsonConverter());
// }
//
// public static Resources fromJson(String string) throws IOException {
// return from(string, new JsonConverter());
// }
//
// public static Resources fromJson(InputStream reader) throws IOException {
// return fromJson(new InputStreamReader(reader));
// }
//
// public static Resources fromXml(Reader reader) throws IOException {
// return from(reader, new XmlConverter());
// }
//
// public static Resources fromXml(String string) throws IOException {
// return from(string, new XmlConverter());
// }
//
// public static Resources fromXml(InputStream reader) throws IOException {
// return fromXml(new InputStreamReader(reader));
// }
//
// public Resource add(String key, Resource value) {
// return members.put(key, value);
// }
//
// @NonNull protected Set<Entry<String, Resource>> entrySet() {
// return members.entrySet();
// }
//
// public boolean has(String key) {
// return members.containsKey(key);
// }
//
// public Resource get(String key) {
// return members.get(key);
// }
//
// public Resources merge(Resources resources) {
// members.putAll(resources.members);
//
// return this;
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/ResourcesRunnable.java
// public static final int RETRY_COUNT = 2;
| import android.content.Context;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import fr.prcaen.externalresources.exception.ExternalResourceException;
import fr.prcaen.externalresources.model.Resources;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static fr.prcaen.externalresources.ResourcesRunnable.RETRY_COUNT; | handler.sendMessage(handler.obtainMessage(AIRPLANE_MODE_CHANGE, airPlaneMode));
}
public void dispatchNetworkStateChange(@NonNull NetworkInfo networkInfo) {
handler.sendMessage(handler.obtainMessage(NETWORK_STATE_CHANGE, networkInfo));
}
private void performLaunch() {
boolean canRetryConnectivity = null == networkInfo || networkInfo.isConnected();
if (!airPlaneMode && canRetryConnectivity) {
Logger.v(ExternalResources.TAG, "perform launch");
service.submit(resourcesRunnable);
} else {
Logger.v(ExternalResources.TAG, "wait until connectivity");
this.needReplay = true;
}
}
private void performRetry() {
boolean canRetryConnectivity = null == networkInfo || networkInfo.isConnected();
if (resourcesRunnable.canRetry() && !airPlaneMode && canRetryConnectivity) {
Logger.v(ExternalResources.TAG, "perform retry");
resourcesRunnable.decreaseRetryCount();
service.submit(resourcesRunnable);
} else if (resourcesRunnable.canRetry()) {
Logger.v(ExternalResources.TAG, "wait until connectivity");
this.needReplay = true;
} else { | // Path: library/src/main/java/fr/prcaen/externalresources/exception/ExternalResourceException.java
// public class ExternalResourceException extends RuntimeException {
//
// public ExternalResourceException(String detailMessage) {
// super(detailMessage);
// }
//
// public ExternalResourceException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ExternalResourceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/model/Resources.java
// @SuppressWarnings("unused") public final class Resources {
// protected final ConcurrentHashMap<String, Resource> members;
//
// public Resources() {
// this.members = new ConcurrentHashMap<>();
// }
//
// public Resources(@NonNull ConcurrentHashMap<String, Resource> members) {
// this.members = members;
// }
//
// public static Resources from(Reader reader, Converter converter) throws IOException {
// return converter.fromReader(reader);
// }
//
// public static Resources from(String string, Converter converter) throws IOException {
// return from(new StringReader(string), converter);
// }
//
// public static Resources fromJson(Reader reader) throws IOException {
// return from(reader, new JsonConverter());
// }
//
// public static Resources fromJson(String string) throws IOException {
// return from(string, new JsonConverter());
// }
//
// public static Resources fromJson(InputStream reader) throws IOException {
// return fromJson(new InputStreamReader(reader));
// }
//
// public static Resources fromXml(Reader reader) throws IOException {
// return from(reader, new XmlConverter());
// }
//
// public static Resources fromXml(String string) throws IOException {
// return from(string, new XmlConverter());
// }
//
// public static Resources fromXml(InputStream reader) throws IOException {
// return fromXml(new InputStreamReader(reader));
// }
//
// public Resource add(String key, Resource value) {
// return members.put(key, value);
// }
//
// @NonNull protected Set<Entry<String, Resource>> entrySet() {
// return members.entrySet();
// }
//
// public boolean has(String key) {
// return members.containsKey(key);
// }
//
// public Resource get(String key) {
// return members.get(key);
// }
//
// public Resources merge(Resources resources) {
// members.putAll(resources.members);
//
// return this;
// }
// }
//
// Path: library/src/main/java/fr/prcaen/externalresources/ResourcesRunnable.java
// public static final int RETRY_COUNT = 2;
// Path: library/src/main/java/fr/prcaen/externalresources/Dispatcher.java
import android.content.Context;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import fr.prcaen.externalresources.exception.ExternalResourceException;
import fr.prcaen.externalresources.model.Resources;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static fr.prcaen.externalresources.ResourcesRunnable.RETRY_COUNT;
handler.sendMessage(handler.obtainMessage(AIRPLANE_MODE_CHANGE, airPlaneMode));
}
public void dispatchNetworkStateChange(@NonNull NetworkInfo networkInfo) {
handler.sendMessage(handler.obtainMessage(NETWORK_STATE_CHANGE, networkInfo));
}
private void performLaunch() {
boolean canRetryConnectivity = null == networkInfo || networkInfo.isConnected();
if (!airPlaneMode && canRetryConnectivity) {
Logger.v(ExternalResources.TAG, "perform launch");
service.submit(resourcesRunnable);
} else {
Logger.v(ExternalResources.TAG, "wait until connectivity");
this.needReplay = true;
}
}
private void performRetry() {
boolean canRetryConnectivity = null == networkInfo || networkInfo.isConnected();
if (resourcesRunnable.canRetry() && !airPlaneMode && canRetryConnectivity) {
Logger.v(ExternalResources.TAG, "perform retry");
resourcesRunnable.decreaseRetryCount();
service.submit(resourcesRunnable);
} else if (resourcesRunnable.canRetry()) {
Logger.v(ExternalResources.TAG, "wait until connectivity");
this.needReplay = true;
} else { | dispatchFailed(new ExternalResourceException("Perform retry failed after " + RETRY_COUNT)); |
prcaen/external-resources | library/src/test/java/fr/prcaen/externalresources/converter/JsonConverterTest.java | // Path: library/src/main/java/fr/prcaen/externalresources/model/Resources.java
// @SuppressWarnings("unused") public final class Resources {
// protected final ConcurrentHashMap<String, Resource> members;
//
// public Resources() {
// this.members = new ConcurrentHashMap<>();
// }
//
// public Resources(@NonNull ConcurrentHashMap<String, Resource> members) {
// this.members = members;
// }
//
// public static Resources from(Reader reader, Converter converter) throws IOException {
// return converter.fromReader(reader);
// }
//
// public static Resources from(String string, Converter converter) throws IOException {
// return from(new StringReader(string), converter);
// }
//
// public static Resources fromJson(Reader reader) throws IOException {
// return from(reader, new JsonConverter());
// }
//
// public static Resources fromJson(String string) throws IOException {
// return from(string, new JsonConverter());
// }
//
// public static Resources fromJson(InputStream reader) throws IOException {
// return fromJson(new InputStreamReader(reader));
// }
//
// public static Resources fromXml(Reader reader) throws IOException {
// return from(reader, new XmlConverter());
// }
//
// public static Resources fromXml(String string) throws IOException {
// return from(string, new XmlConverter());
// }
//
// public static Resources fromXml(InputStream reader) throws IOException {
// return fromXml(new InputStreamReader(reader));
// }
//
// public Resource add(String key, Resource value) {
// return members.put(key, value);
// }
//
// @NonNull protected Set<Entry<String, Resource>> entrySet() {
// return members.entrySet();
// }
//
// public boolean has(String key) {
// return members.containsKey(key);
// }
//
// public Resource get(String key) {
// return members.get(key);
// }
//
// public Resources merge(Resources resources) {
// members.putAll(resources.members);
//
// return this;
// }
// }
| import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import fr.prcaen.externalresources.model.Resources;
import java.io.IOException;
import java.io.InputStreamReader;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue; | package fr.prcaen.externalresources.converter;
public class JsonConverterTest {
private final InputStreamReader resourcesSteamReader;
private final JsonConverter.ResourceJsonDeserializer deserializer;
public JsonConverterTest() throws IOException {
this.resourcesSteamReader = new InputStreamReader(getClass().getResourceAsStream("/test.json"));
this.deserializer = new JsonConverter.ResourceJsonDeserializer();
}
@SuppressWarnings("ConstantConditions") @Test public void testFromReader() throws Exception { | // Path: library/src/main/java/fr/prcaen/externalresources/model/Resources.java
// @SuppressWarnings("unused") public final class Resources {
// protected final ConcurrentHashMap<String, Resource> members;
//
// public Resources() {
// this.members = new ConcurrentHashMap<>();
// }
//
// public Resources(@NonNull ConcurrentHashMap<String, Resource> members) {
// this.members = members;
// }
//
// public static Resources from(Reader reader, Converter converter) throws IOException {
// return converter.fromReader(reader);
// }
//
// public static Resources from(String string, Converter converter) throws IOException {
// return from(new StringReader(string), converter);
// }
//
// public static Resources fromJson(Reader reader) throws IOException {
// return from(reader, new JsonConverter());
// }
//
// public static Resources fromJson(String string) throws IOException {
// return from(string, new JsonConverter());
// }
//
// public static Resources fromJson(InputStream reader) throws IOException {
// return fromJson(new InputStreamReader(reader));
// }
//
// public static Resources fromXml(Reader reader) throws IOException {
// return from(reader, new XmlConverter());
// }
//
// public static Resources fromXml(String string) throws IOException {
// return from(string, new XmlConverter());
// }
//
// public static Resources fromXml(InputStream reader) throws IOException {
// return fromXml(new InputStreamReader(reader));
// }
//
// public Resource add(String key, Resource value) {
// return members.put(key, value);
// }
//
// @NonNull protected Set<Entry<String, Resource>> entrySet() {
// return members.entrySet();
// }
//
// public boolean has(String key) {
// return members.containsKey(key);
// }
//
// public Resource get(String key) {
// return members.get(key);
// }
//
// public Resources merge(Resources resources) {
// members.putAll(resources.members);
//
// return this;
// }
// }
// Path: library/src/test/java/fr/prcaen/externalresources/converter/JsonConverterTest.java
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import fr.prcaen.externalresources.model.Resources;
import java.io.IOException;
import java.io.InputStreamReader;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
package fr.prcaen.externalresources.converter;
public class JsonConverterTest {
private final InputStreamReader resourcesSteamReader;
private final JsonConverter.ResourceJsonDeserializer deserializer;
public JsonConverterTest() throws IOException {
this.resourcesSteamReader = new InputStreamReader(getClass().getResourceAsStream("/test.json"));
this.deserializer = new JsonConverter.ResourceJsonDeserializer();
}
@SuppressWarnings("ConstantConditions") @Test public void testFromReader() throws Exception { | Resources resources = new JsonConverter().fromReader(resourcesSteamReader); |
ukwa/wren | wren/src/main/java/uk/bl/wa/wren/render/PhantomJSCliRenderer.java | // Path: wren/src/main/java/uk/bl/wa/wren/model/CrawlURL.java
// public class CrawlURL implements Serializable {
//
// private static final long serialVersionUID = 7452432417457114150L;
//
// public String url = "";
//
// public String method;
//
// public String httpVersion;
//
// public List<String> cookies = new ArrayList<String>();
//
// public Map<String, String> headers = new HashMap<String, String>();
//
// public String parentUrl = "";
//
// public String pathFromSeed = "S";
//
// public boolean forceFetch = false;
//
// public boolean isSeed = false;
//
// @JsonProperty
// public ParentUrlMetadata parentUrlMetadata = new ParentUrlMetadata();
//
// public CrawlURL toParent() {
// CrawlURL nurl = new CrawlURL();
// nurl.parentUrl = this.url;
// nurl.parentUrlMetadata.pathFromSeed = this.pathFromSeed;
// return nurl;
// }
//
// public String toJson() throws JsonProcessingException {
// ObjectMapper mapper = new ObjectMapper();
// mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
// return mapper.writeValueAsString(this);
// }
//
// public static CrawlURL fromJson(String json) throws JsonParseException, JsonMappingException, IOException {
// ObjectMapper mapper = new ObjectMapper();
// return mapper.readValue(json, CrawlURL.class);
// }
//
// public static CrawlURL fromCrawlURI(CrawlURI curi) {
// CrawlURL nurl = new CrawlURL();
// nurl.url = curi.getURI();
// nurl.method = "GET";
// nurl.httpVersion = "1.0";
// nurl.pathFromSeed = curi.getPathFromSeed();
// nurl.forceFetch = curi.forceFetch();
// nurl.isSeed = curi.isSeed();
// return nurl;
// }
//
// public static CrawlURI toCrawlURI(CrawlURL curi) throws URIException {
// UURI uuri = UURIFactory.getInstance(curi.url);
// CrawlURI nuri = new CrawlURI(uuri, curi.pathFromSeed, null,
// LinkContext.NAVLINK_MISC);
// nuri.setSeed(curi.isSeed);
// nuri.setForceFetch(curi.forceFetch);
// return nuri;
// }
// }
| import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.bl.wa.wren.model.CrawlURL; | /**
*
*/
package uk.bl.wa.wren.render;
/**
*
* Renders URLs through PhantomJS via the command-line API.
*
* TODO Make location of harRenderScript more sensible/not hardcoded.
*
* TODO optionally point to an archiving proxy. --proxy=192.168.1.42:8080
*
* @see http://phantomjs.org/api/command-line.html
*
* @author Andrew Jackson <[email protected]>
*
*/
public class PhantomJSCliRenderer {
private static final Logger LOG = LoggerFactory.getLogger(PhantomJSCliRenderer.class);
private String phantomjsPath = "phantomjs";
private String harRenderScript = "/Users/andy/Documents/workspace/wren/wren/src/main/resources/resources/netsniff-rasterize.js";
private List<String> selectors = Arrays.asList(new String[] { ":root" });
| // Path: wren/src/main/java/uk/bl/wa/wren/model/CrawlURL.java
// public class CrawlURL implements Serializable {
//
// private static final long serialVersionUID = 7452432417457114150L;
//
// public String url = "";
//
// public String method;
//
// public String httpVersion;
//
// public List<String> cookies = new ArrayList<String>();
//
// public Map<String, String> headers = new HashMap<String, String>();
//
// public String parentUrl = "";
//
// public String pathFromSeed = "S";
//
// public boolean forceFetch = false;
//
// public boolean isSeed = false;
//
// @JsonProperty
// public ParentUrlMetadata parentUrlMetadata = new ParentUrlMetadata();
//
// public CrawlURL toParent() {
// CrawlURL nurl = new CrawlURL();
// nurl.parentUrl = this.url;
// nurl.parentUrlMetadata.pathFromSeed = this.pathFromSeed;
// return nurl;
// }
//
// public String toJson() throws JsonProcessingException {
// ObjectMapper mapper = new ObjectMapper();
// mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
// return mapper.writeValueAsString(this);
// }
//
// public static CrawlURL fromJson(String json) throws JsonParseException, JsonMappingException, IOException {
// ObjectMapper mapper = new ObjectMapper();
// return mapper.readValue(json, CrawlURL.class);
// }
//
// public static CrawlURL fromCrawlURI(CrawlURI curi) {
// CrawlURL nurl = new CrawlURL();
// nurl.url = curi.getURI();
// nurl.method = "GET";
// nurl.httpVersion = "1.0";
// nurl.pathFromSeed = curi.getPathFromSeed();
// nurl.forceFetch = curi.forceFetch();
// nurl.isSeed = curi.isSeed();
// return nurl;
// }
//
// public static CrawlURI toCrawlURI(CrawlURL curi) throws URIException {
// UURI uuri = UURIFactory.getInstance(curi.url);
// CrawlURI nuri = new CrawlURI(uuri, curi.pathFromSeed, null,
// LinkContext.NAVLINK_MISC);
// nuri.setSeed(curi.isSeed);
// nuri.setForceFetch(curi.forceFetch);
// return nuri;
// }
// }
// Path: wren/src/main/java/uk/bl/wa/wren/render/PhantomJSCliRenderer.java
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.bl.wa.wren.model.CrawlURL;
/**
*
*/
package uk.bl.wa.wren.render;
/**
*
* Renders URLs through PhantomJS via the command-line API.
*
* TODO Make location of harRenderScript more sensible/not hardcoded.
*
* TODO optionally point to an archiving proxy. --proxy=192.168.1.42:8080
*
* @see http://phantomjs.org/api/command-line.html
*
* @author Andrew Jackson <[email protected]>
*
*/
public class PhantomJSCliRenderer {
private static final Logger LOG = LoggerFactory.getLogger(PhantomJSCliRenderer.class);
private String phantomjsPath = "phantomjs";
private String harRenderScript = "/Users/andy/Documents/workspace/wren/wren/src/main/resources/resources/netsniff-rasterize.js";
private List<String> selectors = Arrays.asList(new String[] { ":root" });
| public String renderToHar(CrawlURL url) throws IOException, InterruptedException { |
ukwa/wren | wren/src/main/java/uk/bl/wa/wren/bolt/HarToWARCWriterBolt.java | // Path: wren/src/main/java/uk/bl/wa/wren/model/CrawlURL.java
// public class CrawlURL implements Serializable {
//
// private static final long serialVersionUID = 7452432417457114150L;
//
// public String url = "";
//
// public String method;
//
// public String httpVersion;
//
// public List<String> cookies = new ArrayList<String>();
//
// public Map<String, String> headers = new HashMap<String, String>();
//
// public String parentUrl = "";
//
// public String pathFromSeed = "S";
//
// public boolean forceFetch = false;
//
// public boolean isSeed = false;
//
// @JsonProperty
// public ParentUrlMetadata parentUrlMetadata = new ParentUrlMetadata();
//
// public CrawlURL toParent() {
// CrawlURL nurl = new CrawlURL();
// nurl.parentUrl = this.url;
// nurl.parentUrlMetadata.pathFromSeed = this.pathFromSeed;
// return nurl;
// }
//
// public String toJson() throws JsonProcessingException {
// ObjectMapper mapper = new ObjectMapper();
// mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
// return mapper.writeValueAsString(this);
// }
//
// public static CrawlURL fromJson(String json) throws JsonParseException, JsonMappingException, IOException {
// ObjectMapper mapper = new ObjectMapper();
// return mapper.readValue(json, CrawlURL.class);
// }
//
// public static CrawlURL fromCrawlURI(CrawlURI curi) {
// CrawlURL nurl = new CrawlURL();
// nurl.url = curi.getURI();
// nurl.method = "GET";
// nurl.httpVersion = "1.0";
// nurl.pathFromSeed = curi.getPathFromSeed();
// nurl.forceFetch = curi.forceFetch();
// nurl.isSeed = curi.isSeed();
// return nurl;
// }
//
// public static CrawlURI toCrawlURI(CrawlURL curi) throws URIException {
// UURI uuri = UURIFactory.getInstance(curi.url);
// CrawlURI nuri = new CrawlURI(uuri, curi.pathFromSeed, null,
// LinkContext.NAVLINK_MISC);
// nuri.setSeed(curi.isSeed);
// nuri.setForceFetch(curi.forceFetch);
// return nuri;
// }
// }
| import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.UUID;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.IRichBolt;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.tuple.Tuple;
import org.jwat.common.Base32;
import org.jwat.common.Base64;
import org.jwat.common.ContentType;
import org.jwat.common.Uri;
import org.jwat.warc.WarcConstants;
import org.jwat.warc.WarcDigest;
import org.jwat.warc.WarcFileNaming;
import org.jwat.warc.WarcFileNamingDefault;
import org.jwat.warc.WarcFileWriter;
import org.jwat.warc.WarcFileWriterConfig;
import org.jwat.warc.WarcHeader;
import org.jwat.warc.WarcRecord;
import org.jwat.warc.WarcWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ibm.icu.util.Calendar;
import uk.bl.wa.wren.model.CrawlURL; | /**
*
*/
package uk.bl.wa.wren.bolt;
/**
* @author Andrew Jackson <[email protected]>
*
*/
public class HarToWARCWriterBolt implements IRichBolt {
private static final long serialVersionUID = 6588071684574175562L;
private static final Logger LOG = LoggerFactory
.getLogger(HarToWARCWriterBolt.class);
private WarcFileWriter writer;
private OutputCollector _collector;
private String outputFolder = "warcs";
private String filePrefix = "BL-TEACUP";
private String hostname = "localhost";
private boolean useBase32 = true;
@Override
public void prepare(Map stormConf, TopologyContext context,
OutputCollector collector) {
// Remember the collector
_collector = collector;
// extend prefix using entity ID to guarentee no collisions:
String componentId = context.getThisComponentId();
int taskId = context.getThisTaskId();
this.filePrefix = this.filePrefix + "-" + componentId + "-" + taskId;
// Set up the writer
WarcFileNaming warcFileNaming = new WarcFileNamingDefault(filePrefix,
null, hostname, null);
WarcFileWriterConfig warcFileConfig = new WarcFileWriterConfig(
new File(outputFolder), true,
WarcFileWriterConfig.DEFAULT_MAX_FILE_SIZE, false);
writer = WarcFileWriter.getWarcWriterInstance(warcFileNaming,
warcFileConfig);
}
@Override
public void execute(Tuple input) { | // Path: wren/src/main/java/uk/bl/wa/wren/model/CrawlURL.java
// public class CrawlURL implements Serializable {
//
// private static final long serialVersionUID = 7452432417457114150L;
//
// public String url = "";
//
// public String method;
//
// public String httpVersion;
//
// public List<String> cookies = new ArrayList<String>();
//
// public Map<String, String> headers = new HashMap<String, String>();
//
// public String parentUrl = "";
//
// public String pathFromSeed = "S";
//
// public boolean forceFetch = false;
//
// public boolean isSeed = false;
//
// @JsonProperty
// public ParentUrlMetadata parentUrlMetadata = new ParentUrlMetadata();
//
// public CrawlURL toParent() {
// CrawlURL nurl = new CrawlURL();
// nurl.parentUrl = this.url;
// nurl.parentUrlMetadata.pathFromSeed = this.pathFromSeed;
// return nurl;
// }
//
// public String toJson() throws JsonProcessingException {
// ObjectMapper mapper = new ObjectMapper();
// mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
// return mapper.writeValueAsString(this);
// }
//
// public static CrawlURL fromJson(String json) throws JsonParseException, JsonMappingException, IOException {
// ObjectMapper mapper = new ObjectMapper();
// return mapper.readValue(json, CrawlURL.class);
// }
//
// public static CrawlURL fromCrawlURI(CrawlURI curi) {
// CrawlURL nurl = new CrawlURL();
// nurl.url = curi.getURI();
// nurl.method = "GET";
// nurl.httpVersion = "1.0";
// nurl.pathFromSeed = curi.getPathFromSeed();
// nurl.forceFetch = curi.forceFetch();
// nurl.isSeed = curi.isSeed();
// return nurl;
// }
//
// public static CrawlURI toCrawlURI(CrawlURL curi) throws URIException {
// UURI uuri = UURIFactory.getInstance(curi.url);
// CrawlURI nuri = new CrawlURI(uuri, curi.pathFromSeed, null,
// LinkContext.NAVLINK_MISC);
// nuri.setSeed(curi.isSeed);
// nuri.setForceFetch(curi.forceFetch);
// return nuri;
// }
// }
// Path: wren/src/main/java/uk/bl/wa/wren/bolt/HarToWARCWriterBolt.java
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.UUID;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.IRichBolt;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.tuple.Tuple;
import org.jwat.common.Base32;
import org.jwat.common.Base64;
import org.jwat.common.ContentType;
import org.jwat.common.Uri;
import org.jwat.warc.WarcConstants;
import org.jwat.warc.WarcDigest;
import org.jwat.warc.WarcFileNaming;
import org.jwat.warc.WarcFileNamingDefault;
import org.jwat.warc.WarcFileWriter;
import org.jwat.warc.WarcFileWriterConfig;
import org.jwat.warc.WarcHeader;
import org.jwat.warc.WarcRecord;
import org.jwat.warc.WarcWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ibm.icu.util.Calendar;
import uk.bl.wa.wren.model.CrawlURL;
/**
*
*/
package uk.bl.wa.wren.bolt;
/**
* @author Andrew Jackson <[email protected]>
*
*/
public class HarToWARCWriterBolt implements IRichBolt {
private static final long serialVersionUID = 6588071684574175562L;
private static final Logger LOG = LoggerFactory
.getLogger(HarToWARCWriterBolt.class);
private WarcFileWriter writer;
private OutputCollector _collector;
private String outputFolder = "warcs";
private String filePrefix = "BL-TEACUP";
private String hostname = "localhost";
private boolean useBase32 = true;
@Override
public void prepare(Map stormConf, TopologyContext context,
OutputCollector collector) {
// Remember the collector
_collector = collector;
// extend prefix using entity ID to guarentee no collisions:
String componentId = context.getThisComponentId();
int taskId = context.getThisTaskId();
this.filePrefix = this.filePrefix + "-" + componentId + "-" + taskId;
// Set up the writer
WarcFileNaming warcFileNaming = new WarcFileNamingDefault(filePrefix,
null, hostname, null);
WarcFileWriterConfig warcFileConfig = new WarcFileWriterConfig(
new File(outputFolder), true,
WarcFileWriterConfig.DEFAULT_MAX_FILE_SIZE, false);
writer = WarcFileWriter.getWarcWriterInstance(warcFileNaming,
warcFileConfig);
}
@Override
public void execute(Tuple input) { | CrawlURL url = (CrawlURL) input.getValueByField("url"); |
ukwa/wren | wren/src/main/java/uk/bl/wa/wren/schemes/CrawlURLScheme.java | // Path: wren/src/main/java/uk/bl/wa/wren/model/CrawlURL.java
// public class CrawlURL implements Serializable {
//
// private static final long serialVersionUID = 7452432417457114150L;
//
// public String url = "";
//
// public String method;
//
// public String httpVersion;
//
// public List<String> cookies = new ArrayList<String>();
//
// public Map<String, String> headers = new HashMap<String, String>();
//
// public String parentUrl = "";
//
// public String pathFromSeed = "S";
//
// public boolean forceFetch = false;
//
// public boolean isSeed = false;
//
// @JsonProperty
// public ParentUrlMetadata parentUrlMetadata = new ParentUrlMetadata();
//
// public CrawlURL toParent() {
// CrawlURL nurl = new CrawlURL();
// nurl.parentUrl = this.url;
// nurl.parentUrlMetadata.pathFromSeed = this.pathFromSeed;
// return nurl;
// }
//
// public String toJson() throws JsonProcessingException {
// ObjectMapper mapper = new ObjectMapper();
// mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
// return mapper.writeValueAsString(this);
// }
//
// public static CrawlURL fromJson(String json) throws JsonParseException, JsonMappingException, IOException {
// ObjectMapper mapper = new ObjectMapper();
// return mapper.readValue(json, CrawlURL.class);
// }
//
// public static CrawlURL fromCrawlURI(CrawlURI curi) {
// CrawlURL nurl = new CrawlURL();
// nurl.url = curi.getURI();
// nurl.method = "GET";
// nurl.httpVersion = "1.0";
// nurl.pathFromSeed = curi.getPathFromSeed();
// nurl.forceFetch = curi.forceFetch();
// nurl.isSeed = curi.isSeed();
// return nurl;
// }
//
// public static CrawlURI toCrawlURI(CrawlURL curi) throws URIException {
// UURI uuri = UURIFactory.getInstance(curi.url);
// CrawlURI nuri = new CrawlURI(uuri, curi.pathFromSeed, null,
// LinkContext.NAVLINK_MISC);
// nuri.setSeed(curi.isSeed);
// nuri.setForceFetch(curi.forceFetch);
// return nuri;
// }
// }
| import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
import org.apache.storm.spout.Scheme;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Values;
import uk.bl.wa.wren.model.CrawlURL; | package uk.bl.wa.wren.schemes;
public class CrawlURLScheme implements Scheme {
private static final long serialVersionUID = 827397701726849709L;
public Fields getOutputFields() {
return new Fields("url");
}
@Override
public List<Object> deserialize(ByteBuffer ser) {
try {
return new Values( | // Path: wren/src/main/java/uk/bl/wa/wren/model/CrawlURL.java
// public class CrawlURL implements Serializable {
//
// private static final long serialVersionUID = 7452432417457114150L;
//
// public String url = "";
//
// public String method;
//
// public String httpVersion;
//
// public List<String> cookies = new ArrayList<String>();
//
// public Map<String, String> headers = new HashMap<String, String>();
//
// public String parentUrl = "";
//
// public String pathFromSeed = "S";
//
// public boolean forceFetch = false;
//
// public boolean isSeed = false;
//
// @JsonProperty
// public ParentUrlMetadata parentUrlMetadata = new ParentUrlMetadata();
//
// public CrawlURL toParent() {
// CrawlURL nurl = new CrawlURL();
// nurl.parentUrl = this.url;
// nurl.parentUrlMetadata.pathFromSeed = this.pathFromSeed;
// return nurl;
// }
//
// public String toJson() throws JsonProcessingException {
// ObjectMapper mapper = new ObjectMapper();
// mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
// return mapper.writeValueAsString(this);
// }
//
// public static CrawlURL fromJson(String json) throws JsonParseException, JsonMappingException, IOException {
// ObjectMapper mapper = new ObjectMapper();
// return mapper.readValue(json, CrawlURL.class);
// }
//
// public static CrawlURL fromCrawlURI(CrawlURI curi) {
// CrawlURL nurl = new CrawlURL();
// nurl.url = curi.getURI();
// nurl.method = "GET";
// nurl.httpVersion = "1.0";
// nurl.pathFromSeed = curi.getPathFromSeed();
// nurl.forceFetch = curi.forceFetch();
// nurl.isSeed = curi.isSeed();
// return nurl;
// }
//
// public static CrawlURI toCrawlURI(CrawlURL curi) throws URIException {
// UURI uuri = UURIFactory.getInstance(curi.url);
// CrawlURI nuri = new CrawlURI(uuri, curi.pathFromSeed, null,
// LinkContext.NAVLINK_MISC);
// nuri.setSeed(curi.isSeed);
// nuri.setForceFetch(curi.forceFetch);
// return nuri;
// }
// }
// Path: wren/src/main/java/uk/bl/wa/wren/schemes/CrawlURLScheme.java
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
import org.apache.storm.spout.Scheme;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Values;
import uk.bl.wa.wren.model.CrawlURL;
package uk.bl.wa.wren.schemes;
public class CrawlURLScheme implements Scheme {
private static final long serialVersionUID = 827397701726849709L;
public Fields getOutputFields() {
return new Fields("url");
}
@Override
public List<Object> deserialize(ByteBuffer ser) {
try {
return new Values( | CrawlURL.fromJson(new String(ser.array(), "UTF-8"))); |
ukwa/wren | wren/src/main/java/uk/bl/wa/wren/queues/UrlTupleToMessage.java | // Path: wren/src/main/java/uk/bl/wa/wren/model/CrawlURL.java
// public class CrawlURL implements Serializable {
//
// private static final long serialVersionUID = 7452432417457114150L;
//
// public String url = "";
//
// public String method;
//
// public String httpVersion;
//
// public List<String> cookies = new ArrayList<String>();
//
// public Map<String, String> headers = new HashMap<String, String>();
//
// public String parentUrl = "";
//
// public String pathFromSeed = "S";
//
// public boolean forceFetch = false;
//
// public boolean isSeed = false;
//
// @JsonProperty
// public ParentUrlMetadata parentUrlMetadata = new ParentUrlMetadata();
//
// public CrawlURL toParent() {
// CrawlURL nurl = new CrawlURL();
// nurl.parentUrl = this.url;
// nurl.parentUrlMetadata.pathFromSeed = this.pathFromSeed;
// return nurl;
// }
//
// public String toJson() throws JsonProcessingException {
// ObjectMapper mapper = new ObjectMapper();
// mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
// return mapper.writeValueAsString(this);
// }
//
// public static CrawlURL fromJson(String json) throws JsonParseException, JsonMappingException, IOException {
// ObjectMapper mapper = new ObjectMapper();
// return mapper.readValue(json, CrawlURL.class);
// }
//
// public static CrawlURL fromCrawlURI(CrawlURI curi) {
// CrawlURL nurl = new CrawlURL();
// nurl.url = curi.getURI();
// nurl.method = "GET";
// nurl.httpVersion = "1.0";
// nurl.pathFromSeed = curi.getPathFromSeed();
// nurl.forceFetch = curi.forceFetch();
// nurl.isSeed = curi.isSeed();
// return nurl;
// }
//
// public static CrawlURI toCrawlURI(CrawlURL curi) throws URIException {
// UURI uuri = UURIFactory.getInstance(curi.url);
// CrawlURI nuri = new CrawlURI(uuri, curi.pathFromSeed, null,
// LinkContext.NAVLINK_MISC);
// nuri.setSeed(curi.isSeed);
// nuri.setForceFetch(curi.forceFetch);
// return nuri;
// }
// }
| import java.io.UnsupportedEncodingException;
import org.apache.storm.tuple.Tuple;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.latent.storm.rabbitmq.TupleToMessage;
import uk.bl.wa.wren.model.CrawlURL; | /**
*
*/
package uk.bl.wa.wren.queues;
/**
* @author Andrew Jackson <[email protected]>
*
*/
public class UrlTupleToMessage extends TupleToMessage {
private static final long serialVersionUID = -949046746396956815L;
@Override
protected byte[] extractBody(Tuple input) { | // Path: wren/src/main/java/uk/bl/wa/wren/model/CrawlURL.java
// public class CrawlURL implements Serializable {
//
// private static final long serialVersionUID = 7452432417457114150L;
//
// public String url = "";
//
// public String method;
//
// public String httpVersion;
//
// public List<String> cookies = new ArrayList<String>();
//
// public Map<String, String> headers = new HashMap<String, String>();
//
// public String parentUrl = "";
//
// public String pathFromSeed = "S";
//
// public boolean forceFetch = false;
//
// public boolean isSeed = false;
//
// @JsonProperty
// public ParentUrlMetadata parentUrlMetadata = new ParentUrlMetadata();
//
// public CrawlURL toParent() {
// CrawlURL nurl = new CrawlURL();
// nurl.parentUrl = this.url;
// nurl.parentUrlMetadata.pathFromSeed = this.pathFromSeed;
// return nurl;
// }
//
// public String toJson() throws JsonProcessingException {
// ObjectMapper mapper = new ObjectMapper();
// mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
// return mapper.writeValueAsString(this);
// }
//
// public static CrawlURL fromJson(String json) throws JsonParseException, JsonMappingException, IOException {
// ObjectMapper mapper = new ObjectMapper();
// return mapper.readValue(json, CrawlURL.class);
// }
//
// public static CrawlURL fromCrawlURI(CrawlURI curi) {
// CrawlURL nurl = new CrawlURL();
// nurl.url = curi.getURI();
// nurl.method = "GET";
// nurl.httpVersion = "1.0";
// nurl.pathFromSeed = curi.getPathFromSeed();
// nurl.forceFetch = curi.forceFetch();
// nurl.isSeed = curi.isSeed();
// return nurl;
// }
//
// public static CrawlURI toCrawlURI(CrawlURL curi) throws URIException {
// UURI uuri = UURIFactory.getInstance(curi.url);
// CrawlURI nuri = new CrawlURI(uuri, curi.pathFromSeed, null,
// LinkContext.NAVLINK_MISC);
// nuri.setSeed(curi.isSeed);
// nuri.setForceFetch(curi.forceFetch);
// return nuri;
// }
// }
// Path: wren/src/main/java/uk/bl/wa/wren/queues/UrlTupleToMessage.java
import java.io.UnsupportedEncodingException;
import org.apache.storm.tuple.Tuple;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.latent.storm.rabbitmq.TupleToMessage;
import uk.bl.wa.wren.model.CrawlURL;
/**
*
*/
package uk.bl.wa.wren.queues;
/**
* @author Andrew Jackson <[email protected]>
*
*/
public class UrlTupleToMessage extends TupleToMessage {
private static final long serialVersionUID = -949046746396956815L;
@Override
protected byte[] extractBody(Tuple input) { | CrawlURL curl = (CrawlURL) input.getValueByField("url"); |
trivago/Mail-Pigeon | pigeon-web/src/main/java/com/trivago/mail/pigeon/web/components/wizard/setup/steps/WizardAddSenderComponent.java | // Path: pigeon-common/src/main/java/com/trivago/mail/pigeon/bean/Sender.java
// public class Sender extends AbstractBean
// {
// public static final String ID = "sender_id";
//
// public static final String NAME = "name";
//
// public static final String FROM_MAIL = "from_mail";
//
// public static final String REPLYTO_MAIL = "reply_to_mail";
//
// public Sender(final Node underlayingNode)
// {
// this.dataNode = underlayingNode;
// }
//
// public Sender(final long senderId)
// {
// dataNode = ConnectionFactory.getSenderIndex().get(IndexTypes.SENDER_ID, senderId).getSingle();
// }
//
// public Sender(final long senderId, final String fromMail, final String replytoMail, final String name)
// {
// dataNode = ConnectionFactory.getSenderIndex().get(IndexTypes.SENDER_ID, senderId).getSingle();
// if (dataNode != null)
// {
// throw new RuntimeException("This sender does already exist");
// }
//
// Transaction tx = ConnectionFactory.getDatabase().beginTx();
// try
// {
// dataNode = ConnectionFactory.getDatabase().createNode();
// writeProperty(ID, senderId);
// writeProperty("type", getClass().getName());
// writeProperty(NAME, name);
// writeProperty(FROM_MAIL, fromMail);
// writeProperty(REPLYTO_MAIL, replytoMail);
//
// ConnectionFactory.getSenderIndex().add(this.dataNode, IndexTypes.SENDER_ID, senderId);
// ConnectionFactory.getSenderIndex().add(this.dataNode, IndexTypes.TYPE, getClass().getName());
// ConnectionFactory.getDatabase().getReferenceNode().createRelationshipTo(dataNode, RelationTypes.SENDER_REFERENCE);
// tx.success();
// }
// catch (Exception e)
// {
// tx.failure();
// }
// finally
// {
// tx.finish();
// }
// }
//
// public Node getDataNode()
// {
// return dataNode;
// }
//
// public long getId()
// {
// return getProperty(Long.class, ID, false);
// }
//
// public String getName()
// {
// return getProperty(String.class, NAME);
// }
//
// public String getFromMail()
// {
// return getProperty(String.class, FROM_MAIL);
// }
//
// public String getReplytoMail()
// {
// return getProperty(String.class, REPLYTO_MAIL);
// }
//
// public void setName(String name)
// {
// writeProperty(NAME, name);
// }
//
// public void setFromMail(String fromMail)
// {
// writeProperty(FROM_MAIL, fromMail);
// }
//
// public void setReplytoMail(String replytoMail)
// {
// writeProperty(REPLYTO_MAIL, replytoMail);
// }
//
// public Relationship addSentMail(Mail mail)
// {
// Transaction tx = ConnectionFactory.getDatabase().beginTx();
// Relationship relation = null;
// try
// {
// Node recipientNode = mail.getDataNode();
// relation = dataNode.createRelationshipTo(recipientNode, RelationTypes.SENT_EMAIL);
// relation.setProperty("date", new Date().getTime());
// tx.success();
// }
// catch (Exception e)
// {
// tx.failure();
// }
// finally
// {
// tx.finish();
// }
// return relation;
// }
//
// public Iterable<Relationship> getSentMails()
// {
// return dataNode.getRelationships(RelationTypes.SENT_EMAIL);
// }
//
// public int getSentMailsCount()
// {
// int count = 0;
// final Iterable<Relationship> sentMails = getSentMails();
// for (Relationship rel : sentMails)
// {
// ++count;
// }
// return count;
// }
//
//
// public static IndexHits<Node> getAll()
// {
// return ConnectionFactory.getSenderIndex().get("type", Sender.class.getName());
// }
// }
| import com.trivago.mail.pigeon.bean.Sender;
import com.vaadin.terminal.UserError;
import com.vaadin.ui.*;
import org.vaadin.teemu.wizards.WizardStep;
import java.util.Date; |
if (tfFromMail.getValue().equals(""))
{
tfFromMail.setComponentError(new UserError("From E-Mail must not be empty"));
}
else
{
tfFromMail.setComponentError(null);
}
if (tfReplyTo.getValue().equals(""))
{
tfReplyTo.setComponentError(new UserError("Reply-To E-Mail must not be empty"));
}
else
{
tfReplyTo.setComponentError(null);
}
if (!tfName.getValue().equals("")
&& !tfFromMail.getValue().equals("")
&& !tfReplyTo.getValue().equals(""))
{
tfName.setComponentError(null);
tfFromMail.setComponentError(null);
tfReplyTo.setComponentError(null);
long senderId = Math.round(new Date().getTime() * Math.random());
try
{ | // Path: pigeon-common/src/main/java/com/trivago/mail/pigeon/bean/Sender.java
// public class Sender extends AbstractBean
// {
// public static final String ID = "sender_id";
//
// public static final String NAME = "name";
//
// public static final String FROM_MAIL = "from_mail";
//
// public static final String REPLYTO_MAIL = "reply_to_mail";
//
// public Sender(final Node underlayingNode)
// {
// this.dataNode = underlayingNode;
// }
//
// public Sender(final long senderId)
// {
// dataNode = ConnectionFactory.getSenderIndex().get(IndexTypes.SENDER_ID, senderId).getSingle();
// }
//
// public Sender(final long senderId, final String fromMail, final String replytoMail, final String name)
// {
// dataNode = ConnectionFactory.getSenderIndex().get(IndexTypes.SENDER_ID, senderId).getSingle();
// if (dataNode != null)
// {
// throw new RuntimeException("This sender does already exist");
// }
//
// Transaction tx = ConnectionFactory.getDatabase().beginTx();
// try
// {
// dataNode = ConnectionFactory.getDatabase().createNode();
// writeProperty(ID, senderId);
// writeProperty("type", getClass().getName());
// writeProperty(NAME, name);
// writeProperty(FROM_MAIL, fromMail);
// writeProperty(REPLYTO_MAIL, replytoMail);
//
// ConnectionFactory.getSenderIndex().add(this.dataNode, IndexTypes.SENDER_ID, senderId);
// ConnectionFactory.getSenderIndex().add(this.dataNode, IndexTypes.TYPE, getClass().getName());
// ConnectionFactory.getDatabase().getReferenceNode().createRelationshipTo(dataNode, RelationTypes.SENDER_REFERENCE);
// tx.success();
// }
// catch (Exception e)
// {
// tx.failure();
// }
// finally
// {
// tx.finish();
// }
// }
//
// public Node getDataNode()
// {
// return dataNode;
// }
//
// public long getId()
// {
// return getProperty(Long.class, ID, false);
// }
//
// public String getName()
// {
// return getProperty(String.class, NAME);
// }
//
// public String getFromMail()
// {
// return getProperty(String.class, FROM_MAIL);
// }
//
// public String getReplytoMail()
// {
// return getProperty(String.class, REPLYTO_MAIL);
// }
//
// public void setName(String name)
// {
// writeProperty(NAME, name);
// }
//
// public void setFromMail(String fromMail)
// {
// writeProperty(FROM_MAIL, fromMail);
// }
//
// public void setReplytoMail(String replytoMail)
// {
// writeProperty(REPLYTO_MAIL, replytoMail);
// }
//
// public Relationship addSentMail(Mail mail)
// {
// Transaction tx = ConnectionFactory.getDatabase().beginTx();
// Relationship relation = null;
// try
// {
// Node recipientNode = mail.getDataNode();
// relation = dataNode.createRelationshipTo(recipientNode, RelationTypes.SENT_EMAIL);
// relation.setProperty("date", new Date().getTime());
// tx.success();
// }
// catch (Exception e)
// {
// tx.failure();
// }
// finally
// {
// tx.finish();
// }
// return relation;
// }
//
// public Iterable<Relationship> getSentMails()
// {
// return dataNode.getRelationships(RelationTypes.SENT_EMAIL);
// }
//
// public int getSentMailsCount()
// {
// int count = 0;
// final Iterable<Relationship> sentMails = getSentMails();
// for (Relationship rel : sentMails)
// {
// ++count;
// }
// return count;
// }
//
//
// public static IndexHits<Node> getAll()
// {
// return ConnectionFactory.getSenderIndex().get("type", Sender.class.getName());
// }
// }
// Path: pigeon-web/src/main/java/com/trivago/mail/pigeon/web/components/wizard/setup/steps/WizardAddSenderComponent.java
import com.trivago.mail.pigeon.bean.Sender;
import com.vaadin.terminal.UserError;
import com.vaadin.ui.*;
import org.vaadin.teemu.wizards.WizardStep;
import java.util.Date;
if (tfFromMail.getValue().equals(""))
{
tfFromMail.setComponentError(new UserError("From E-Mail must not be empty"));
}
else
{
tfFromMail.setComponentError(null);
}
if (tfReplyTo.getValue().equals(""))
{
tfReplyTo.setComponentError(new UserError("Reply-To E-Mail must not be empty"));
}
else
{
tfReplyTo.setComponentError(null);
}
if (!tfName.getValue().equals("")
&& !tfFromMail.getValue().equals("")
&& !tfReplyTo.getValue().equals(""))
{
tfName.setComponentError(null);
tfFromMail.setComponentError(null);
tfReplyTo.setComponentError(null);
long senderId = Math.round(new Date().getTime() * Math.random());
try
{ | Sender s = new Sender(senderId, tfFromMail.getValue().toString(), tfReplyTo.getValue().toString(), tfName.getValue().toString()); |
trivago/Mail-Pigeon | pigeon-web/src/main/java/com/trivago/mail/pigeon/web/components/groups/GroupList.java | // Path: pigeon-common/src/main/java/com/trivago/mail/pigeon/bean/RecipientGroup.java
// public class RecipientGroup extends AbstractBean
// {
// public static final String ID = "group_id";
//
// public static final String NAME = "name";
//
// public static final String DATE = "date";
//
// public RecipientGroup(final Node underlayingNode)
// {
// this.dataNode = underlayingNode;
// }
//
// public RecipientGroup(final long groupId)
// {
// dataNode = ConnectionFactory.getGroupIndex().get(IndexTypes.GROUP_ID, groupId).getSingle();
// if (dataNode == null)
// {
// Transaction tx = ConnectionFactory.getDatabase().beginTx();
// try
// {
// dataNode = ConnectionFactory.getDatabase().createNode();
// writeProperty(ID, groupId);
// writeProperty("type", getClass().getName());
// writeProperty(NAME, "DefaultGroup");
// ConnectionFactory.getGroupIndex().add(this.dataNode, IndexTypes.GROUP_ID, groupId);
// ConnectionFactory.getGroupIndex().add(this.dataNode, IndexTypes.TYPE, getClass().getName());
// ConnectionFactory.getDatabase().getReferenceNode().createRelationshipTo(dataNode, RelationTypes.GROUP_REFERENCE);
//
// tx.success();
// }
// catch (Exception e)
// {
// log.error(e);
// tx.failure();
// }
// finally
// {
// tx.finish();
// }
// }
// }
//
// public RecipientGroup(final long groupId, final String name)
// {
// Transaction tx = ConnectionFactory.getDatabase().beginTx();
// try
// {
// dataNode = ConnectionFactory.getDatabase().createNode();
// writeProperty(ID, groupId);
// writeProperty("type", getClass().getName());
// writeProperty(NAME, name);
// ConnectionFactory.getGroupIndex().add(this.dataNode, IndexTypes.GROUP_ID, groupId);
// ConnectionFactory.getGroupIndex().add(this.dataNode, IndexTypes.TYPE, getClass().getName());
// ConnectionFactory.getDatabase().getReferenceNode().createRelationshipTo(dataNode, RelationTypes.GROUP_REFERENCE);
//
// tx.success();
// }
// catch (Exception e)
// {
// log.error(e);
// tx.failure();
// }
// finally
// {
// tx.finish();
// }
//
// }
//
// public Node getDataNode()
// {
// return dataNode;
// }
//
// public long getId()
// {
// return getProperty(Long.class, ID, false);
// }
//
// public String getName()
// {
// return getProperty(String.class, NAME);
// }
//
// public Relationship addRecipient(Recipient recipient)
// {
// Transaction tx = ConnectionFactory.getDatabase().beginTx();
// Relationship relation = null;
// try
// {
// Node recipientNode = recipient.getDataNode();
// relation = dataNode.createRelationshipTo(recipientNode, RelationTypes.BELONGS_TO_GROUP);
// relation.setProperty(DATE, new Date().getTime());
// tx.success();
//
// }
// catch (Exception e)
// {
// log.error(e);
// tx.failure();
// }
// finally
// {
// tx.finish();
// }
// return relation;
// }
//
// public Iterable<Relationship> getRecipients()
// {
// return dataNode.getRelationships(RelationTypes.BELONGS_TO_GROUP);
// }
//
// public static IndexHits<Node> getAll()
// {
// return ConnectionFactory.getGroupIndex().get("type", RecipientGroup.class.getName());
// }
//
// public void setName(String name)
// {
// writeProperty(NAME, name);
// }
// }
| import com.trivago.mail.pigeon.bean.RecipientGroup;
import com.vaadin.data.util.BeanContainer;
import com.vaadin.terminal.ThemeResource;
import com.vaadin.ui.*;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.index.IndexHits;
import java.util.ArrayList;
import java.util.List; | /**
* Copyright (C) 2011-2012 trivago GmbH <[email protected]>, <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.trivago.mail.pigeon.web.components.groups;
public class GroupList extends CustomComponent
{
private Table viewTable;
| // Path: pigeon-common/src/main/java/com/trivago/mail/pigeon/bean/RecipientGroup.java
// public class RecipientGroup extends AbstractBean
// {
// public static final String ID = "group_id";
//
// public static final String NAME = "name";
//
// public static final String DATE = "date";
//
// public RecipientGroup(final Node underlayingNode)
// {
// this.dataNode = underlayingNode;
// }
//
// public RecipientGroup(final long groupId)
// {
// dataNode = ConnectionFactory.getGroupIndex().get(IndexTypes.GROUP_ID, groupId).getSingle();
// if (dataNode == null)
// {
// Transaction tx = ConnectionFactory.getDatabase().beginTx();
// try
// {
// dataNode = ConnectionFactory.getDatabase().createNode();
// writeProperty(ID, groupId);
// writeProperty("type", getClass().getName());
// writeProperty(NAME, "DefaultGroup");
// ConnectionFactory.getGroupIndex().add(this.dataNode, IndexTypes.GROUP_ID, groupId);
// ConnectionFactory.getGroupIndex().add(this.dataNode, IndexTypes.TYPE, getClass().getName());
// ConnectionFactory.getDatabase().getReferenceNode().createRelationshipTo(dataNode, RelationTypes.GROUP_REFERENCE);
//
// tx.success();
// }
// catch (Exception e)
// {
// log.error(e);
// tx.failure();
// }
// finally
// {
// tx.finish();
// }
// }
// }
//
// public RecipientGroup(final long groupId, final String name)
// {
// Transaction tx = ConnectionFactory.getDatabase().beginTx();
// try
// {
// dataNode = ConnectionFactory.getDatabase().createNode();
// writeProperty(ID, groupId);
// writeProperty("type", getClass().getName());
// writeProperty(NAME, name);
// ConnectionFactory.getGroupIndex().add(this.dataNode, IndexTypes.GROUP_ID, groupId);
// ConnectionFactory.getGroupIndex().add(this.dataNode, IndexTypes.TYPE, getClass().getName());
// ConnectionFactory.getDatabase().getReferenceNode().createRelationshipTo(dataNode, RelationTypes.GROUP_REFERENCE);
//
// tx.success();
// }
// catch (Exception e)
// {
// log.error(e);
// tx.failure();
// }
// finally
// {
// tx.finish();
// }
//
// }
//
// public Node getDataNode()
// {
// return dataNode;
// }
//
// public long getId()
// {
// return getProperty(Long.class, ID, false);
// }
//
// public String getName()
// {
// return getProperty(String.class, NAME);
// }
//
// public Relationship addRecipient(Recipient recipient)
// {
// Transaction tx = ConnectionFactory.getDatabase().beginTx();
// Relationship relation = null;
// try
// {
// Node recipientNode = recipient.getDataNode();
// relation = dataNode.createRelationshipTo(recipientNode, RelationTypes.BELONGS_TO_GROUP);
// relation.setProperty(DATE, new Date().getTime());
// tx.success();
//
// }
// catch (Exception e)
// {
// log.error(e);
// tx.failure();
// }
// finally
// {
// tx.finish();
// }
// return relation;
// }
//
// public Iterable<Relationship> getRecipients()
// {
// return dataNode.getRelationships(RelationTypes.BELONGS_TO_GROUP);
// }
//
// public static IndexHits<Node> getAll()
// {
// return ConnectionFactory.getGroupIndex().get("type", RecipientGroup.class.getName());
// }
//
// public void setName(String name)
// {
// writeProperty(NAME, name);
// }
// }
// Path: pigeon-web/src/main/java/com/trivago/mail/pigeon/web/components/groups/GroupList.java
import com.trivago.mail.pigeon.bean.RecipientGroup;
import com.vaadin.data.util.BeanContainer;
import com.vaadin.terminal.ThemeResource;
import com.vaadin.ui.*;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.index.IndexHits;
import java.util.ArrayList;
import java.util.List;
/**
* Copyright (C) 2011-2012 trivago GmbH <[email protected]>, <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.trivago.mail.pigeon.web.components.groups;
public class GroupList extends CustomComponent
{
private Table viewTable;
| private BeanContainer<Long, RecipientGroup> beanContainer; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.