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
hubrick/vertx-kafka-service
src/test/java/com/hubrick/vertx/kafka/producer/ManualTest.java
// Path: src/main/java/com/hubrick/vertx/kafka/producer/model/ByteKafkaMessage.java // @DataObject(generateConverter = true) // public class ByteKafkaMessage extends AbstractKafkaMessage { // // private Buffer payload; // // public ByteKafkaMessage() { // } // // public ByteKafkaMessage(Buffer payload) { // checkNotNull(payload, "payload must not be null"); // // this.payload = payload; // } // // public ByteKafkaMessage(Buffer payload, String partKey) { // super(partKey); // checkNotNull(payload, "payload must not be null"); // // this.payload = payload; // } // // public ByteKafkaMessage(ByteKafkaMessage byteKafkaMessage) { // super(byteKafkaMessage.getPartKey()); // checkNotNull(payload, "payload must not be null"); // // this.payload = byteKafkaMessage.getPayload(); // } // // public ByteKafkaMessage(JsonObject jsonObject) { // super(jsonObject.getString(PART_KEY)); // this.payload = jsonObject.getBinary(PAYLOAD) != null ? Buffer.buffer(jsonObject.getBinary(PAYLOAD)) : null; // } // // public Buffer getPayload() { // return payload; // } // // public void setPayload(Buffer payload) { // this.payload = payload; // } // // public JsonObject toJson() { // final JsonObject jsonObject = super.asJson(); // if (getPayload() != null) { // jsonObject.put(PAYLOAD, payload != null ? payload.getBytes() : null); // } // return jsonObject; // } // } // // Path: src/main/java/com/hubrick/vertx/kafka/producer/property/KafkaProducerProperties.java // public final class KafkaProducerProperties { // // /* Non-instantiable class */ // private KafkaProducerProperties() {} // // public static final String ADDRESS = "address"; // public static final String BOOTSTRAP_SERVERS = "bootstrapServers"; // public static final String ACKS = "acks"; // public static final String DEFAULT_TOPIC = "defaultTopic"; // public static final String TYPE = "type"; // public static final String MAX_RETRIES = "maxRetries"; // public static final String RETRY_BACKOFF_MS = "retryBackoffMs"; // public static final String BUFFERING_MAX_MS = "bufferingMaxMs"; // public static final String BUFFERING_MAX_MESSAGES = "bufferingMaxMessages"; // public static final String ENQUEUE_TIMEOUT = "enqueueTimeout"; // public static final String BATCH_MESSAGE_NUM = "batchMessageNum"; // public static final String RETRIES = "retries"; // public static final String REQUEST_TIMEOUT_MS = "requestTimeoutMs"; // public static final String MAX_BLOCK_MS = "maxBlockMs"; // public static final String STATSD = "statsD"; // public static final String METRIC_CONSUMER_CLASSES = "metricConsumerClasses"; // public static final String METRIC_DROPWIZARD_REGISTRY_NAME = "metricDropwizardRegistryName"; // // public static final String BOOTSTRAP_SERVERS_DEFAULT = "localhost:9092"; // public static final String ACKS_DEFAULT = "1"; // // public static final int RETRIES_DEFAULT = 0; // public static final int REQUEST_TIMEOUT_MS_DEFAULT = 30000; // public static final int MAX_BLOCK_MS_DEFAULT = 60000; // // }
import com.hubrick.vertx.kafka.producer.model.ByteKafkaMessage; import com.hubrick.vertx.kafka.producer.property.KafkaProducerProperties; import io.vertx.core.DeploymentOptions; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.json.JsonObject;
/** * Copyright (C) 2016 Etaia AS (oss@hubrick.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.hubrick.vertx.kafka.producer; /** * @author Emir Dizdarevic * @since 1.0.0 */ public class ManualTest { public static void main(String[] args) { JsonObject config = new JsonObject(); config.put(KafkaProducerProperties.ADDRESS, "test-address"); config.put(KafkaProducerProperties.BOOTSTRAP_SERVERS, KafkaProducerProperties.BOOTSTRAP_SERVERS_DEFAULT); config.put(KafkaProducerProperties.DEFAULT_TOPIC, "test-topic"); config.put(KafkaProducerProperties.ACKS, KafkaProducerProperties.ACKS_DEFAULT); final Vertx vertx = Vertx.vertx(); final DeploymentOptions deploymentOptions = new DeploymentOptions(); deploymentOptions.setConfig(config); vertx.deployVerticle("service:com.hubrick.services.kafka-producer", deploymentOptions, result -> { System.out.println(result.result()); JsonObject jsonObject = new JsonObject(); jsonObject.put("payload", "your message goes here".getBytes()); final KafkaProducerService kafkaProducerService = KafkaProducerService.createProxy(vertx, "test-address");
// Path: src/main/java/com/hubrick/vertx/kafka/producer/model/ByteKafkaMessage.java // @DataObject(generateConverter = true) // public class ByteKafkaMessage extends AbstractKafkaMessage { // // private Buffer payload; // // public ByteKafkaMessage() { // } // // public ByteKafkaMessage(Buffer payload) { // checkNotNull(payload, "payload must not be null"); // // this.payload = payload; // } // // public ByteKafkaMessage(Buffer payload, String partKey) { // super(partKey); // checkNotNull(payload, "payload must not be null"); // // this.payload = payload; // } // // public ByteKafkaMessage(ByteKafkaMessage byteKafkaMessage) { // super(byteKafkaMessage.getPartKey()); // checkNotNull(payload, "payload must not be null"); // // this.payload = byteKafkaMessage.getPayload(); // } // // public ByteKafkaMessage(JsonObject jsonObject) { // super(jsonObject.getString(PART_KEY)); // this.payload = jsonObject.getBinary(PAYLOAD) != null ? Buffer.buffer(jsonObject.getBinary(PAYLOAD)) : null; // } // // public Buffer getPayload() { // return payload; // } // // public void setPayload(Buffer payload) { // this.payload = payload; // } // // public JsonObject toJson() { // final JsonObject jsonObject = super.asJson(); // if (getPayload() != null) { // jsonObject.put(PAYLOAD, payload != null ? payload.getBytes() : null); // } // return jsonObject; // } // } // // Path: src/main/java/com/hubrick/vertx/kafka/producer/property/KafkaProducerProperties.java // public final class KafkaProducerProperties { // // /* Non-instantiable class */ // private KafkaProducerProperties() {} // // public static final String ADDRESS = "address"; // public static final String BOOTSTRAP_SERVERS = "bootstrapServers"; // public static final String ACKS = "acks"; // public static final String DEFAULT_TOPIC = "defaultTopic"; // public static final String TYPE = "type"; // public static final String MAX_RETRIES = "maxRetries"; // public static final String RETRY_BACKOFF_MS = "retryBackoffMs"; // public static final String BUFFERING_MAX_MS = "bufferingMaxMs"; // public static final String BUFFERING_MAX_MESSAGES = "bufferingMaxMessages"; // public static final String ENQUEUE_TIMEOUT = "enqueueTimeout"; // public static final String BATCH_MESSAGE_NUM = "batchMessageNum"; // public static final String RETRIES = "retries"; // public static final String REQUEST_TIMEOUT_MS = "requestTimeoutMs"; // public static final String MAX_BLOCK_MS = "maxBlockMs"; // public static final String STATSD = "statsD"; // public static final String METRIC_CONSUMER_CLASSES = "metricConsumerClasses"; // public static final String METRIC_DROPWIZARD_REGISTRY_NAME = "metricDropwizardRegistryName"; // // public static final String BOOTSTRAP_SERVERS_DEFAULT = "localhost:9092"; // public static final String ACKS_DEFAULT = "1"; // // public static final int RETRIES_DEFAULT = 0; // public static final int REQUEST_TIMEOUT_MS_DEFAULT = 30000; // public static final int MAX_BLOCK_MS_DEFAULT = 60000; // // } // Path: src/test/java/com/hubrick/vertx/kafka/producer/ManualTest.java import com.hubrick.vertx.kafka.producer.model.ByteKafkaMessage; import com.hubrick.vertx.kafka.producer.property.KafkaProducerProperties; import io.vertx.core.DeploymentOptions; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.json.JsonObject; /** * Copyright (C) 2016 Etaia AS (oss@hubrick.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.hubrick.vertx.kafka.producer; /** * @author Emir Dizdarevic * @since 1.0.0 */ public class ManualTest { public static void main(String[] args) { JsonObject config = new JsonObject(); config.put(KafkaProducerProperties.ADDRESS, "test-address"); config.put(KafkaProducerProperties.BOOTSTRAP_SERVERS, KafkaProducerProperties.BOOTSTRAP_SERVERS_DEFAULT); config.put(KafkaProducerProperties.DEFAULT_TOPIC, "test-topic"); config.put(KafkaProducerProperties.ACKS, KafkaProducerProperties.ACKS_DEFAULT); final Vertx vertx = Vertx.vertx(); final DeploymentOptions deploymentOptions = new DeploymentOptions(); deploymentOptions.setConfig(config); vertx.deployVerticle("service:com.hubrick.services.kafka-producer", deploymentOptions, result -> { System.out.println(result.result()); JsonObject jsonObject = new JsonObject(); jsonObject.put("payload", "your message goes here".getBytes()); final KafkaProducerService kafkaProducerService = KafkaProducerService.createProxy(vertx, "test-address");
kafkaProducerService.sendBytes(new ByteKafkaMessage(Buffer.buffer("your message goes here".getBytes()), "test-partition"), response -> {
hubrick/vertx-kafka-service
src/test/java/com/hubrick/vertx/kafka/producer/KafkaModuleDeployWithStatsdDisabledConfigIntegrationTest.java
// Path: src/main/java/com/hubrick/vertx/kafka/producer/model/StringKafkaMessage.java // @DataObject // public class StringKafkaMessage extends AbstractKafkaMessage { // // private String payload; // // public StringKafkaMessage() { // } // // public StringKafkaMessage(String payload) { // checkNotNull(payload, "payload must not be null"); // // this.payload = payload; // } // // public StringKafkaMessage(String payload, String partKey) { // super(partKey); // checkNotNull(payload, "payload must not be null"); // // this.payload = payload; // } // // public StringKafkaMessage(StringKafkaMessage stringKafkaMessage) { // super(stringKafkaMessage.getPartKey()); // this.payload = stringKafkaMessage.getPayload(); // } // // public StringKafkaMessage(JsonObject jsonObject) { // super(jsonObject.getString(PART_KEY)); // this.payload = jsonObject.getString(PAYLOAD); // } // // public String getPayload() { // return payload; // } // // public void setPayload(String payload) { // this.payload = payload; // } // // public JsonObject toJson() { // final JsonObject jsonObject = super.asJson(); // if (getPayload() != null) { // jsonObject.put(PAYLOAD, getPayload()); // } // return jsonObject; // } // } // // Path: src/main/java/com/hubrick/vertx/kafka/producer/property/KafkaProducerProperties.java // public final class KafkaProducerProperties { // // /* Non-instantiable class */ // private KafkaProducerProperties() {} // // public static final String ADDRESS = "address"; // public static final String BOOTSTRAP_SERVERS = "bootstrapServers"; // public static final String ACKS = "acks"; // public static final String DEFAULT_TOPIC = "defaultTopic"; // public static final String TYPE = "type"; // public static final String MAX_RETRIES = "maxRetries"; // public static final String RETRY_BACKOFF_MS = "retryBackoffMs"; // public static final String BUFFERING_MAX_MS = "bufferingMaxMs"; // public static final String BUFFERING_MAX_MESSAGES = "bufferingMaxMessages"; // public static final String ENQUEUE_TIMEOUT = "enqueueTimeout"; // public static final String BATCH_MESSAGE_NUM = "batchMessageNum"; // public static final String RETRIES = "retries"; // public static final String REQUEST_TIMEOUT_MS = "requestTimeoutMs"; // public static final String MAX_BLOCK_MS = "maxBlockMs"; // public static final String STATSD = "statsD"; // public static final String METRIC_CONSUMER_CLASSES = "metricConsumerClasses"; // public static final String METRIC_DROPWIZARD_REGISTRY_NAME = "metricDropwizardRegistryName"; // // public static final String BOOTSTRAP_SERVERS_DEFAULT = "localhost:9092"; // public static final String ACKS_DEFAULT = "1"; // // public static final int RETRIES_DEFAULT = 0; // public static final int REQUEST_TIMEOUT_MS_DEFAULT = 30000; // public static final int MAX_BLOCK_MS_DEFAULT = 60000; // // }
import com.hubrick.vertx.kafka.producer.model.StringKafkaMessage; import com.hubrick.vertx.kafka.producer.property.KafkaProducerProperties; import io.vertx.core.AsyncResult; import io.vertx.core.DeploymentOptions; import io.vertx.core.Handler; import io.vertx.core.json.JsonObject; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.Test; import org.junit.runner.RunWith;
/** * Copyright (C) 2016 Etaia AS (oss@hubrick.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.hubrick.vertx.kafka.producer; /** * Tests mod-kafka module with disabled StatsD configuration. The deployment should be successfull and * the executor call of StatsD should not fail. * <p/> * This test sends an event to Vert.x EventBus, then registers a handler to handle that event * and send it to Kafka broker, by creating Kafka Producer. It checks that the flow works correctly * until the point, where message is sent to Kafka. */ @RunWith(VertxUnitRunner.class) public class KafkaModuleDeployWithStatsdDisabledConfigIntegrationTest extends AbstractProducerTest { private static final String ADDRESS = "default-address"; private static final String MESSAGE = "Test message from KafkaModuleDeployWithStatsdDisabledConfigIT!"; private static final String TOPIC = "some-topic"; @Test // The deployment should be successfull and StatsD executor call should not fail, but will not do anything public void test(TestContext testContext) throws Exception { JsonObject config = makeDefaultConfig();
// Path: src/main/java/com/hubrick/vertx/kafka/producer/model/StringKafkaMessage.java // @DataObject // public class StringKafkaMessage extends AbstractKafkaMessage { // // private String payload; // // public StringKafkaMessage() { // } // // public StringKafkaMessage(String payload) { // checkNotNull(payload, "payload must not be null"); // // this.payload = payload; // } // // public StringKafkaMessage(String payload, String partKey) { // super(partKey); // checkNotNull(payload, "payload must not be null"); // // this.payload = payload; // } // // public StringKafkaMessage(StringKafkaMessage stringKafkaMessage) { // super(stringKafkaMessage.getPartKey()); // this.payload = stringKafkaMessage.getPayload(); // } // // public StringKafkaMessage(JsonObject jsonObject) { // super(jsonObject.getString(PART_KEY)); // this.payload = jsonObject.getString(PAYLOAD); // } // // public String getPayload() { // return payload; // } // // public void setPayload(String payload) { // this.payload = payload; // } // // public JsonObject toJson() { // final JsonObject jsonObject = super.asJson(); // if (getPayload() != null) { // jsonObject.put(PAYLOAD, getPayload()); // } // return jsonObject; // } // } // // Path: src/main/java/com/hubrick/vertx/kafka/producer/property/KafkaProducerProperties.java // public final class KafkaProducerProperties { // // /* Non-instantiable class */ // private KafkaProducerProperties() {} // // public static final String ADDRESS = "address"; // public static final String BOOTSTRAP_SERVERS = "bootstrapServers"; // public static final String ACKS = "acks"; // public static final String DEFAULT_TOPIC = "defaultTopic"; // public static final String TYPE = "type"; // public static final String MAX_RETRIES = "maxRetries"; // public static final String RETRY_BACKOFF_MS = "retryBackoffMs"; // public static final String BUFFERING_MAX_MS = "bufferingMaxMs"; // public static final String BUFFERING_MAX_MESSAGES = "bufferingMaxMessages"; // public static final String ENQUEUE_TIMEOUT = "enqueueTimeout"; // public static final String BATCH_MESSAGE_NUM = "batchMessageNum"; // public static final String RETRIES = "retries"; // public static final String REQUEST_TIMEOUT_MS = "requestTimeoutMs"; // public static final String MAX_BLOCK_MS = "maxBlockMs"; // public static final String STATSD = "statsD"; // public static final String METRIC_CONSUMER_CLASSES = "metricConsumerClasses"; // public static final String METRIC_DROPWIZARD_REGISTRY_NAME = "metricDropwizardRegistryName"; // // public static final String BOOTSTRAP_SERVERS_DEFAULT = "localhost:9092"; // public static final String ACKS_DEFAULT = "1"; // // public static final int RETRIES_DEFAULT = 0; // public static final int REQUEST_TIMEOUT_MS_DEFAULT = 30000; // public static final int MAX_BLOCK_MS_DEFAULT = 60000; // // } // Path: src/test/java/com/hubrick/vertx/kafka/producer/KafkaModuleDeployWithStatsdDisabledConfigIntegrationTest.java import com.hubrick.vertx.kafka.producer.model.StringKafkaMessage; import com.hubrick.vertx.kafka.producer.property.KafkaProducerProperties; import io.vertx.core.AsyncResult; import io.vertx.core.DeploymentOptions; import io.vertx.core.Handler; import io.vertx.core.json.JsonObject; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.Test; import org.junit.runner.RunWith; /** * Copyright (C) 2016 Etaia AS (oss@hubrick.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.hubrick.vertx.kafka.producer; /** * Tests mod-kafka module with disabled StatsD configuration. The deployment should be successfull and * the executor call of StatsD should not fail. * <p/> * This test sends an event to Vert.x EventBus, then registers a handler to handle that event * and send it to Kafka broker, by creating Kafka Producer. It checks that the flow works correctly * until the point, where message is sent to Kafka. */ @RunWith(VertxUnitRunner.class) public class KafkaModuleDeployWithStatsdDisabledConfigIntegrationTest extends AbstractProducerTest { private static final String ADDRESS = "default-address"; private static final String MESSAGE = "Test message from KafkaModuleDeployWithStatsdDisabledConfigIT!"; private static final String TOPIC = "some-topic"; @Test // The deployment should be successfull and StatsD executor call should not fail, but will not do anything public void test(TestContext testContext) throws Exception { JsonObject config = makeDefaultConfig();
config.put(KafkaProducerProperties.ADDRESS, ADDRESS);
hubrick/vertx-kafka-service
src/test/java/com/hubrick/vertx/kafka/producer/KafkaModuleDeployWithStatsdDisabledConfigIntegrationTest.java
// Path: src/main/java/com/hubrick/vertx/kafka/producer/model/StringKafkaMessage.java // @DataObject // public class StringKafkaMessage extends AbstractKafkaMessage { // // private String payload; // // public StringKafkaMessage() { // } // // public StringKafkaMessage(String payload) { // checkNotNull(payload, "payload must not be null"); // // this.payload = payload; // } // // public StringKafkaMessage(String payload, String partKey) { // super(partKey); // checkNotNull(payload, "payload must not be null"); // // this.payload = payload; // } // // public StringKafkaMessage(StringKafkaMessage stringKafkaMessage) { // super(stringKafkaMessage.getPartKey()); // this.payload = stringKafkaMessage.getPayload(); // } // // public StringKafkaMessage(JsonObject jsonObject) { // super(jsonObject.getString(PART_KEY)); // this.payload = jsonObject.getString(PAYLOAD); // } // // public String getPayload() { // return payload; // } // // public void setPayload(String payload) { // this.payload = payload; // } // // public JsonObject toJson() { // final JsonObject jsonObject = super.asJson(); // if (getPayload() != null) { // jsonObject.put(PAYLOAD, getPayload()); // } // return jsonObject; // } // } // // Path: src/main/java/com/hubrick/vertx/kafka/producer/property/KafkaProducerProperties.java // public final class KafkaProducerProperties { // // /* Non-instantiable class */ // private KafkaProducerProperties() {} // // public static final String ADDRESS = "address"; // public static final String BOOTSTRAP_SERVERS = "bootstrapServers"; // public static final String ACKS = "acks"; // public static final String DEFAULT_TOPIC = "defaultTopic"; // public static final String TYPE = "type"; // public static final String MAX_RETRIES = "maxRetries"; // public static final String RETRY_BACKOFF_MS = "retryBackoffMs"; // public static final String BUFFERING_MAX_MS = "bufferingMaxMs"; // public static final String BUFFERING_MAX_MESSAGES = "bufferingMaxMessages"; // public static final String ENQUEUE_TIMEOUT = "enqueueTimeout"; // public static final String BATCH_MESSAGE_NUM = "batchMessageNum"; // public static final String RETRIES = "retries"; // public static final String REQUEST_TIMEOUT_MS = "requestTimeoutMs"; // public static final String MAX_BLOCK_MS = "maxBlockMs"; // public static final String STATSD = "statsD"; // public static final String METRIC_CONSUMER_CLASSES = "metricConsumerClasses"; // public static final String METRIC_DROPWIZARD_REGISTRY_NAME = "metricDropwizardRegistryName"; // // public static final String BOOTSTRAP_SERVERS_DEFAULT = "localhost:9092"; // public static final String ACKS_DEFAULT = "1"; // // public static final int RETRIES_DEFAULT = 0; // public static final int REQUEST_TIMEOUT_MS_DEFAULT = 30000; // public static final int MAX_BLOCK_MS_DEFAULT = 60000; // // }
import com.hubrick.vertx.kafka.producer.model.StringKafkaMessage; import com.hubrick.vertx.kafka.producer.property.KafkaProducerProperties; import io.vertx.core.AsyncResult; import io.vertx.core.DeploymentOptions; import io.vertx.core.Handler; import io.vertx.core.json.JsonObject; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.Test; import org.junit.runner.RunWith;
/** * Copyright (C) 2016 Etaia AS (oss@hubrick.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.hubrick.vertx.kafka.producer; /** * Tests mod-kafka module with disabled StatsD configuration. The deployment should be successfull and * the executor call of StatsD should not fail. * <p/> * This test sends an event to Vert.x EventBus, then registers a handler to handle that event * and send it to Kafka broker, by creating Kafka Producer. It checks that the flow works correctly * until the point, where message is sent to Kafka. */ @RunWith(VertxUnitRunner.class) public class KafkaModuleDeployWithStatsdDisabledConfigIntegrationTest extends AbstractProducerTest { private static final String ADDRESS = "default-address"; private static final String MESSAGE = "Test message from KafkaModuleDeployWithStatsdDisabledConfigIT!"; private static final String TOPIC = "some-topic"; @Test // The deployment should be successfull and StatsD executor call should not fail, but will not do anything public void test(TestContext testContext) throws Exception { JsonObject config = makeDefaultConfig(); config.put(KafkaProducerProperties.ADDRESS, ADDRESS); config.put(KafkaProducerProperties.DEFAULT_TOPIC, TOPIC); final DeploymentOptions deploymentOptions = new DeploymentOptions(); deploymentOptions.setConfig(config); deploy(testContext, deploymentOptions); final Async async = testContext.async(); try { final KafkaProducerService kafkaProducerService = KafkaProducerService.createProxy(vertx, ADDRESS);
// Path: src/main/java/com/hubrick/vertx/kafka/producer/model/StringKafkaMessage.java // @DataObject // public class StringKafkaMessage extends AbstractKafkaMessage { // // private String payload; // // public StringKafkaMessage() { // } // // public StringKafkaMessage(String payload) { // checkNotNull(payload, "payload must not be null"); // // this.payload = payload; // } // // public StringKafkaMessage(String payload, String partKey) { // super(partKey); // checkNotNull(payload, "payload must not be null"); // // this.payload = payload; // } // // public StringKafkaMessage(StringKafkaMessage stringKafkaMessage) { // super(stringKafkaMessage.getPartKey()); // this.payload = stringKafkaMessage.getPayload(); // } // // public StringKafkaMessage(JsonObject jsonObject) { // super(jsonObject.getString(PART_KEY)); // this.payload = jsonObject.getString(PAYLOAD); // } // // public String getPayload() { // return payload; // } // // public void setPayload(String payload) { // this.payload = payload; // } // // public JsonObject toJson() { // final JsonObject jsonObject = super.asJson(); // if (getPayload() != null) { // jsonObject.put(PAYLOAD, getPayload()); // } // return jsonObject; // } // } // // Path: src/main/java/com/hubrick/vertx/kafka/producer/property/KafkaProducerProperties.java // public final class KafkaProducerProperties { // // /* Non-instantiable class */ // private KafkaProducerProperties() {} // // public static final String ADDRESS = "address"; // public static final String BOOTSTRAP_SERVERS = "bootstrapServers"; // public static final String ACKS = "acks"; // public static final String DEFAULT_TOPIC = "defaultTopic"; // public static final String TYPE = "type"; // public static final String MAX_RETRIES = "maxRetries"; // public static final String RETRY_BACKOFF_MS = "retryBackoffMs"; // public static final String BUFFERING_MAX_MS = "bufferingMaxMs"; // public static final String BUFFERING_MAX_MESSAGES = "bufferingMaxMessages"; // public static final String ENQUEUE_TIMEOUT = "enqueueTimeout"; // public static final String BATCH_MESSAGE_NUM = "batchMessageNum"; // public static final String RETRIES = "retries"; // public static final String REQUEST_TIMEOUT_MS = "requestTimeoutMs"; // public static final String MAX_BLOCK_MS = "maxBlockMs"; // public static final String STATSD = "statsD"; // public static final String METRIC_CONSUMER_CLASSES = "metricConsumerClasses"; // public static final String METRIC_DROPWIZARD_REGISTRY_NAME = "metricDropwizardRegistryName"; // // public static final String BOOTSTRAP_SERVERS_DEFAULT = "localhost:9092"; // public static final String ACKS_DEFAULT = "1"; // // public static final int RETRIES_DEFAULT = 0; // public static final int REQUEST_TIMEOUT_MS_DEFAULT = 30000; // public static final int MAX_BLOCK_MS_DEFAULT = 60000; // // } // Path: src/test/java/com/hubrick/vertx/kafka/producer/KafkaModuleDeployWithStatsdDisabledConfigIntegrationTest.java import com.hubrick.vertx.kafka.producer.model.StringKafkaMessage; import com.hubrick.vertx.kafka.producer.property.KafkaProducerProperties; import io.vertx.core.AsyncResult; import io.vertx.core.DeploymentOptions; import io.vertx.core.Handler; import io.vertx.core.json.JsonObject; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.Test; import org.junit.runner.RunWith; /** * Copyright (C) 2016 Etaia AS (oss@hubrick.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.hubrick.vertx.kafka.producer; /** * Tests mod-kafka module with disabled StatsD configuration. The deployment should be successfull and * the executor call of StatsD should not fail. * <p/> * This test sends an event to Vert.x EventBus, then registers a handler to handle that event * and send it to Kafka broker, by creating Kafka Producer. It checks that the flow works correctly * until the point, where message is sent to Kafka. */ @RunWith(VertxUnitRunner.class) public class KafkaModuleDeployWithStatsdDisabledConfigIntegrationTest extends AbstractProducerTest { private static final String ADDRESS = "default-address"; private static final String MESSAGE = "Test message from KafkaModuleDeployWithStatsdDisabledConfigIT!"; private static final String TOPIC = "some-topic"; @Test // The deployment should be successfull and StatsD executor call should not fail, but will not do anything public void test(TestContext testContext) throws Exception { JsonObject config = makeDefaultConfig(); config.put(KafkaProducerProperties.ADDRESS, ADDRESS); config.put(KafkaProducerProperties.DEFAULT_TOPIC, TOPIC); final DeploymentOptions deploymentOptions = new DeploymentOptions(); deploymentOptions.setConfig(config); deploy(testContext, deploymentOptions); final Async async = testContext.async(); try { final KafkaProducerService kafkaProducerService = KafkaProducerService.createProxy(vertx, ADDRESS);
kafkaProducerService.sendString(new StringKafkaMessage(MESSAGE), (Handler<AsyncResult<Void>>) message -> {
hubrick/vertx-kafka-service
src/test/java/com/hubrick/vertx/kafka/producer/StringSerializerIntegrationTest.java
// Path: src/main/java/com/hubrick/vertx/kafka/producer/model/StringKafkaMessage.java // @DataObject // public class StringKafkaMessage extends AbstractKafkaMessage { // // private String payload; // // public StringKafkaMessage() { // } // // public StringKafkaMessage(String payload) { // checkNotNull(payload, "payload must not be null"); // // this.payload = payload; // } // // public StringKafkaMessage(String payload, String partKey) { // super(partKey); // checkNotNull(payload, "payload must not be null"); // // this.payload = payload; // } // // public StringKafkaMessage(StringKafkaMessage stringKafkaMessage) { // super(stringKafkaMessage.getPartKey()); // this.payload = stringKafkaMessage.getPayload(); // } // // public StringKafkaMessage(JsonObject jsonObject) { // super(jsonObject.getString(PART_KEY)); // this.payload = jsonObject.getString(PAYLOAD); // } // // public String getPayload() { // return payload; // } // // public void setPayload(String payload) { // this.payload = payload; // } // // public JsonObject toJson() { // final JsonObject jsonObject = super.asJson(); // if (getPayload() != null) { // jsonObject.put(PAYLOAD, getPayload()); // } // return jsonObject; // } // } // // Path: src/main/java/com/hubrick/vertx/kafka/producer/property/KafkaProducerProperties.java // public final class KafkaProducerProperties { // // /* Non-instantiable class */ // private KafkaProducerProperties() {} // // public static final String ADDRESS = "address"; // public static final String BOOTSTRAP_SERVERS = "bootstrapServers"; // public static final String ACKS = "acks"; // public static final String DEFAULT_TOPIC = "defaultTopic"; // public static final String TYPE = "type"; // public static final String MAX_RETRIES = "maxRetries"; // public static final String RETRY_BACKOFF_MS = "retryBackoffMs"; // public static final String BUFFERING_MAX_MS = "bufferingMaxMs"; // public static final String BUFFERING_MAX_MESSAGES = "bufferingMaxMessages"; // public static final String ENQUEUE_TIMEOUT = "enqueueTimeout"; // public static final String BATCH_MESSAGE_NUM = "batchMessageNum"; // public static final String RETRIES = "retries"; // public static final String REQUEST_TIMEOUT_MS = "requestTimeoutMs"; // public static final String MAX_BLOCK_MS = "maxBlockMs"; // public static final String STATSD = "statsD"; // public static final String METRIC_CONSUMER_CLASSES = "metricConsumerClasses"; // public static final String METRIC_DROPWIZARD_REGISTRY_NAME = "metricDropwizardRegistryName"; // // public static final String BOOTSTRAP_SERVERS_DEFAULT = "localhost:9092"; // public static final String ACKS_DEFAULT = "1"; // // public static final int RETRIES_DEFAULT = 0; // public static final int REQUEST_TIMEOUT_MS_DEFAULT = 30000; // public static final int MAX_BLOCK_MS_DEFAULT = 60000; // // }
import com.hubrick.vertx.kafka.producer.model.StringKafkaMessage; import com.hubrick.vertx.kafka.producer.property.KafkaProducerProperties; import io.vertx.core.AsyncResult; import io.vertx.core.DeploymentOptions; import io.vertx.core.Handler; import io.vertx.core.json.JsonObject; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.Test; import org.junit.runner.RunWith;
/** * Copyright (C) 2016 Etaia AS (oss@hubrick.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.hubrick.vertx.kafka.producer; /** * Tests mod-kafka module with String serializer configuration. */ @RunWith(VertxUnitRunner.class) public class StringSerializerIntegrationTest extends AbstractProducerTest { private static final String ADDRESS = "default-address"; private static final String TOPIC = "some-topic"; private static final String MESSAGE = "Test string message!"; @Test public void test(TestContext testContext) throws Exception { JsonObject config = makeDefaultConfig();
// Path: src/main/java/com/hubrick/vertx/kafka/producer/model/StringKafkaMessage.java // @DataObject // public class StringKafkaMessage extends AbstractKafkaMessage { // // private String payload; // // public StringKafkaMessage() { // } // // public StringKafkaMessage(String payload) { // checkNotNull(payload, "payload must not be null"); // // this.payload = payload; // } // // public StringKafkaMessage(String payload, String partKey) { // super(partKey); // checkNotNull(payload, "payload must not be null"); // // this.payload = payload; // } // // public StringKafkaMessage(StringKafkaMessage stringKafkaMessage) { // super(stringKafkaMessage.getPartKey()); // this.payload = stringKafkaMessage.getPayload(); // } // // public StringKafkaMessage(JsonObject jsonObject) { // super(jsonObject.getString(PART_KEY)); // this.payload = jsonObject.getString(PAYLOAD); // } // // public String getPayload() { // return payload; // } // // public void setPayload(String payload) { // this.payload = payload; // } // // public JsonObject toJson() { // final JsonObject jsonObject = super.asJson(); // if (getPayload() != null) { // jsonObject.put(PAYLOAD, getPayload()); // } // return jsonObject; // } // } // // Path: src/main/java/com/hubrick/vertx/kafka/producer/property/KafkaProducerProperties.java // public final class KafkaProducerProperties { // // /* Non-instantiable class */ // private KafkaProducerProperties() {} // // public static final String ADDRESS = "address"; // public static final String BOOTSTRAP_SERVERS = "bootstrapServers"; // public static final String ACKS = "acks"; // public static final String DEFAULT_TOPIC = "defaultTopic"; // public static final String TYPE = "type"; // public static final String MAX_RETRIES = "maxRetries"; // public static final String RETRY_BACKOFF_MS = "retryBackoffMs"; // public static final String BUFFERING_MAX_MS = "bufferingMaxMs"; // public static final String BUFFERING_MAX_MESSAGES = "bufferingMaxMessages"; // public static final String ENQUEUE_TIMEOUT = "enqueueTimeout"; // public static final String BATCH_MESSAGE_NUM = "batchMessageNum"; // public static final String RETRIES = "retries"; // public static final String REQUEST_TIMEOUT_MS = "requestTimeoutMs"; // public static final String MAX_BLOCK_MS = "maxBlockMs"; // public static final String STATSD = "statsD"; // public static final String METRIC_CONSUMER_CLASSES = "metricConsumerClasses"; // public static final String METRIC_DROPWIZARD_REGISTRY_NAME = "metricDropwizardRegistryName"; // // public static final String BOOTSTRAP_SERVERS_DEFAULT = "localhost:9092"; // public static final String ACKS_DEFAULT = "1"; // // public static final int RETRIES_DEFAULT = 0; // public static final int REQUEST_TIMEOUT_MS_DEFAULT = 30000; // public static final int MAX_BLOCK_MS_DEFAULT = 60000; // // } // Path: src/test/java/com/hubrick/vertx/kafka/producer/StringSerializerIntegrationTest.java import com.hubrick.vertx.kafka.producer.model.StringKafkaMessage; import com.hubrick.vertx.kafka.producer.property.KafkaProducerProperties; import io.vertx.core.AsyncResult; import io.vertx.core.DeploymentOptions; import io.vertx.core.Handler; import io.vertx.core.json.JsonObject; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.Test; import org.junit.runner.RunWith; /** * Copyright (C) 2016 Etaia AS (oss@hubrick.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.hubrick.vertx.kafka.producer; /** * Tests mod-kafka module with String serializer configuration. */ @RunWith(VertxUnitRunner.class) public class StringSerializerIntegrationTest extends AbstractProducerTest { private static final String ADDRESS = "default-address"; private static final String TOPIC = "some-topic"; private static final String MESSAGE = "Test string message!"; @Test public void test(TestContext testContext) throws Exception { JsonObject config = makeDefaultConfig();
config.put(KafkaProducerProperties.ADDRESS, ADDRESS);
hubrick/vertx-kafka-service
src/test/java/com/hubrick/vertx/kafka/producer/StringSerializerIntegrationTest.java
// Path: src/main/java/com/hubrick/vertx/kafka/producer/model/StringKafkaMessage.java // @DataObject // public class StringKafkaMessage extends AbstractKafkaMessage { // // private String payload; // // public StringKafkaMessage() { // } // // public StringKafkaMessage(String payload) { // checkNotNull(payload, "payload must not be null"); // // this.payload = payload; // } // // public StringKafkaMessage(String payload, String partKey) { // super(partKey); // checkNotNull(payload, "payload must not be null"); // // this.payload = payload; // } // // public StringKafkaMessage(StringKafkaMessage stringKafkaMessage) { // super(stringKafkaMessage.getPartKey()); // this.payload = stringKafkaMessage.getPayload(); // } // // public StringKafkaMessage(JsonObject jsonObject) { // super(jsonObject.getString(PART_KEY)); // this.payload = jsonObject.getString(PAYLOAD); // } // // public String getPayload() { // return payload; // } // // public void setPayload(String payload) { // this.payload = payload; // } // // public JsonObject toJson() { // final JsonObject jsonObject = super.asJson(); // if (getPayload() != null) { // jsonObject.put(PAYLOAD, getPayload()); // } // return jsonObject; // } // } // // Path: src/main/java/com/hubrick/vertx/kafka/producer/property/KafkaProducerProperties.java // public final class KafkaProducerProperties { // // /* Non-instantiable class */ // private KafkaProducerProperties() {} // // public static final String ADDRESS = "address"; // public static final String BOOTSTRAP_SERVERS = "bootstrapServers"; // public static final String ACKS = "acks"; // public static final String DEFAULT_TOPIC = "defaultTopic"; // public static final String TYPE = "type"; // public static final String MAX_RETRIES = "maxRetries"; // public static final String RETRY_BACKOFF_MS = "retryBackoffMs"; // public static final String BUFFERING_MAX_MS = "bufferingMaxMs"; // public static final String BUFFERING_MAX_MESSAGES = "bufferingMaxMessages"; // public static final String ENQUEUE_TIMEOUT = "enqueueTimeout"; // public static final String BATCH_MESSAGE_NUM = "batchMessageNum"; // public static final String RETRIES = "retries"; // public static final String REQUEST_TIMEOUT_MS = "requestTimeoutMs"; // public static final String MAX_BLOCK_MS = "maxBlockMs"; // public static final String STATSD = "statsD"; // public static final String METRIC_CONSUMER_CLASSES = "metricConsumerClasses"; // public static final String METRIC_DROPWIZARD_REGISTRY_NAME = "metricDropwizardRegistryName"; // // public static final String BOOTSTRAP_SERVERS_DEFAULT = "localhost:9092"; // public static final String ACKS_DEFAULT = "1"; // // public static final int RETRIES_DEFAULT = 0; // public static final int REQUEST_TIMEOUT_MS_DEFAULT = 30000; // public static final int MAX_BLOCK_MS_DEFAULT = 60000; // // }
import com.hubrick.vertx.kafka.producer.model.StringKafkaMessage; import com.hubrick.vertx.kafka.producer.property.KafkaProducerProperties; import io.vertx.core.AsyncResult; import io.vertx.core.DeploymentOptions; import io.vertx.core.Handler; import io.vertx.core.json.JsonObject; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.Test; import org.junit.runner.RunWith;
/** * Copyright (C) 2016 Etaia AS (oss@hubrick.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.hubrick.vertx.kafka.producer; /** * Tests mod-kafka module with String serializer configuration. */ @RunWith(VertxUnitRunner.class) public class StringSerializerIntegrationTest extends AbstractProducerTest { private static final String ADDRESS = "default-address"; private static final String TOPIC = "some-topic"; private static final String MESSAGE = "Test string message!"; @Test public void test(TestContext testContext) throws Exception { JsonObject config = makeDefaultConfig(); config.put(KafkaProducerProperties.ADDRESS, ADDRESS); config.put(KafkaProducerProperties.DEFAULT_TOPIC, TOPIC); final DeploymentOptions deploymentOptions = new DeploymentOptions(); deploymentOptions.setConfig(config); deploy(testContext, deploymentOptions); final Async async = testContext.async(); try { final KafkaProducerService kafkaProducerService = KafkaProducerService.createProxy(vertx, ADDRESS);
// Path: src/main/java/com/hubrick/vertx/kafka/producer/model/StringKafkaMessage.java // @DataObject // public class StringKafkaMessage extends AbstractKafkaMessage { // // private String payload; // // public StringKafkaMessage() { // } // // public StringKafkaMessage(String payload) { // checkNotNull(payload, "payload must not be null"); // // this.payload = payload; // } // // public StringKafkaMessage(String payload, String partKey) { // super(partKey); // checkNotNull(payload, "payload must not be null"); // // this.payload = payload; // } // // public StringKafkaMessage(StringKafkaMessage stringKafkaMessage) { // super(stringKafkaMessage.getPartKey()); // this.payload = stringKafkaMessage.getPayload(); // } // // public StringKafkaMessage(JsonObject jsonObject) { // super(jsonObject.getString(PART_KEY)); // this.payload = jsonObject.getString(PAYLOAD); // } // // public String getPayload() { // return payload; // } // // public void setPayload(String payload) { // this.payload = payload; // } // // public JsonObject toJson() { // final JsonObject jsonObject = super.asJson(); // if (getPayload() != null) { // jsonObject.put(PAYLOAD, getPayload()); // } // return jsonObject; // } // } // // Path: src/main/java/com/hubrick/vertx/kafka/producer/property/KafkaProducerProperties.java // public final class KafkaProducerProperties { // // /* Non-instantiable class */ // private KafkaProducerProperties() {} // // public static final String ADDRESS = "address"; // public static final String BOOTSTRAP_SERVERS = "bootstrapServers"; // public static final String ACKS = "acks"; // public static final String DEFAULT_TOPIC = "defaultTopic"; // public static final String TYPE = "type"; // public static final String MAX_RETRIES = "maxRetries"; // public static final String RETRY_BACKOFF_MS = "retryBackoffMs"; // public static final String BUFFERING_MAX_MS = "bufferingMaxMs"; // public static final String BUFFERING_MAX_MESSAGES = "bufferingMaxMessages"; // public static final String ENQUEUE_TIMEOUT = "enqueueTimeout"; // public static final String BATCH_MESSAGE_NUM = "batchMessageNum"; // public static final String RETRIES = "retries"; // public static final String REQUEST_TIMEOUT_MS = "requestTimeoutMs"; // public static final String MAX_BLOCK_MS = "maxBlockMs"; // public static final String STATSD = "statsD"; // public static final String METRIC_CONSUMER_CLASSES = "metricConsumerClasses"; // public static final String METRIC_DROPWIZARD_REGISTRY_NAME = "metricDropwizardRegistryName"; // // public static final String BOOTSTRAP_SERVERS_DEFAULT = "localhost:9092"; // public static final String ACKS_DEFAULT = "1"; // // public static final int RETRIES_DEFAULT = 0; // public static final int REQUEST_TIMEOUT_MS_DEFAULT = 30000; // public static final int MAX_BLOCK_MS_DEFAULT = 60000; // // } // Path: src/test/java/com/hubrick/vertx/kafka/producer/StringSerializerIntegrationTest.java import com.hubrick.vertx.kafka.producer.model.StringKafkaMessage; import com.hubrick.vertx.kafka.producer.property.KafkaProducerProperties; import io.vertx.core.AsyncResult; import io.vertx.core.DeploymentOptions; import io.vertx.core.Handler; import io.vertx.core.json.JsonObject; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.Test; import org.junit.runner.RunWith; /** * Copyright (C) 2016 Etaia AS (oss@hubrick.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.hubrick.vertx.kafka.producer; /** * Tests mod-kafka module with String serializer configuration. */ @RunWith(VertxUnitRunner.class) public class StringSerializerIntegrationTest extends AbstractProducerTest { private static final String ADDRESS = "default-address"; private static final String TOPIC = "some-topic"; private static final String MESSAGE = "Test string message!"; @Test public void test(TestContext testContext) throws Exception { JsonObject config = makeDefaultConfig(); config.put(KafkaProducerProperties.ADDRESS, ADDRESS); config.put(KafkaProducerProperties.DEFAULT_TOPIC, TOPIC); final DeploymentOptions deploymentOptions = new DeploymentOptions(); deploymentOptions.setConfig(config); deploy(testContext, deploymentOptions); final Async async = testContext.async(); try { final KafkaProducerService kafkaProducerService = KafkaProducerService.createProxy(vertx, ADDRESS);
kafkaProducerService.sendString(new StringKafkaMessage(MESSAGE), (Handler<AsyncResult<Void>>) message -> {
ibrdtn/ibrdtn-android-library
library/src/main/java/de/tubs/ibr/dtn/Services.java
// Path: library/src/main/java/de/tubs/ibr/dtn/api/ServiceNotAvailableException.java // public class ServiceNotAvailableException extends Exception { // // /** // * // */ // private static final long serialVersionUID = 876730276266296815L; // // public ServiceNotAvailableException() {} // // public ServiceNotAvailableException(Exception innerException) { // this.innerException = innerException; // } // // public ServiceNotAvailableException(String what) { // this.what = null; // } // // @Override // public String toString() { // if ((innerException == null) && (what == null)) return super.toString(); // return "ServiceNotAvailableException: " + ((innerException == null) ? what : innerException.toString()); // } // // public Exception innerException = null; // public String what = null; // }
import java.util.List; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.ResolveInfo; import android.content.pm.ServiceInfo; import android.net.Uri; import de.tubs.ibr.dtn.api.ServiceNotAvailableException;
package de.tubs.ibr.dtn; public class Services { /** * Version = 0 (< 1.0) * Version = 1 (>= 1.0) */ public static final Integer VERSION_APPLICATION = 1; /** * Version = 0 (< 1.0) * Version = 1 (>= 1.0) */ public static final Integer VERSION_MANAGER = 1; /** * Version = 0 (< 1.0) * Version = 1 (>= 1.0) */ public static final Integer VERSION_SECURITY = 1; public static final Service SERVICE_APPLICATION = new Service(DTNService.class.getName(), VERSION_APPLICATION); public static final Service SERVICE_MANAGER = new Service(DtnManager.class.getName(), VERSION_MANAGER); public static final Service SERVICE_SECURITY = new Service(SecurityService.class.getName(), VERSION_SECURITY); public static final String EXTRA_VERSION = "de.tubs.ibr.dtn.Service.VERSION"; public static final String EXTRA_NAME = "de.tubs.ibr.dtn.Service.NAME"; public static class Service { private final String mClassName; private final Integer mVersion; private Service(String className, Integer version) { mClassName = className; mVersion = version; } public String getClassName() { return mClassName; } public Integer getVersion() { return mVersion; }
// Path: library/src/main/java/de/tubs/ibr/dtn/api/ServiceNotAvailableException.java // public class ServiceNotAvailableException extends Exception { // // /** // * // */ // private static final long serialVersionUID = 876730276266296815L; // // public ServiceNotAvailableException() {} // // public ServiceNotAvailableException(Exception innerException) { // this.innerException = innerException; // } // // public ServiceNotAvailableException(String what) { // this.what = null; // } // // @Override // public String toString() { // if ((innerException == null) && (what == null)) return super.toString(); // return "ServiceNotAvailableException: " + ((innerException == null) ? what : innerException.toString()); // } // // public Exception innerException = null; // public String what = null; // } // Path: library/src/main/java/de/tubs/ibr/dtn/Services.java import java.util.List; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.ResolveInfo; import android.content.pm.ServiceInfo; import android.net.Uri; import de.tubs.ibr.dtn.api.ServiceNotAvailableException; package de.tubs.ibr.dtn; public class Services { /** * Version = 0 (< 1.0) * Version = 1 (>= 1.0) */ public static final Integer VERSION_APPLICATION = 1; /** * Version = 0 (< 1.0) * Version = 1 (>= 1.0) */ public static final Integer VERSION_MANAGER = 1; /** * Version = 0 (< 1.0) * Version = 1 (>= 1.0) */ public static final Integer VERSION_SECURITY = 1; public static final Service SERVICE_APPLICATION = new Service(DTNService.class.getName(), VERSION_APPLICATION); public static final Service SERVICE_MANAGER = new Service(DtnManager.class.getName(), VERSION_MANAGER); public static final Service SERVICE_SECURITY = new Service(SecurityService.class.getName(), VERSION_SECURITY); public static final String EXTRA_VERSION = "de.tubs.ibr.dtn.Service.VERSION"; public static final String EXTRA_NAME = "de.tubs.ibr.dtn.Service.NAME"; public static class Service { private final String mClassName; private final Integer mVersion; private Service(String className, Integer version) { mClassName = className; mVersion = version; } public String getClassName() { return mClassName; } public Integer getVersion() { return mVersion; }
public Intent getIntent(Context context, String action) throws ServiceNotAvailableException {
ibrdtn/ibrdtn-android-library
library/src/main/java/de/tubs/ibr/dtn/api/DTNClient.java
// Path: library/src/main/java/de/tubs/ibr/dtn/Services.java // public class Services { // /** // * Version = 0 (< 1.0) // * Version = 1 (>= 1.0) // */ // public static final Integer VERSION_APPLICATION = 1; // // /** // * Version = 0 (< 1.0) // * Version = 1 (>= 1.0) // */ // public static final Integer VERSION_MANAGER = 1; // // /** // * Version = 0 (< 1.0) // * Version = 1 (>= 1.0) // */ // public static final Integer VERSION_SECURITY = 1; // // public static final Service SERVICE_APPLICATION = new Service(DTNService.class.getName(), VERSION_APPLICATION); // public static final Service SERVICE_MANAGER = new Service(DtnManager.class.getName(), VERSION_MANAGER); // public static final Service SERVICE_SECURITY = new Service(SecurityService.class.getName(), VERSION_SECURITY); // // public static final String EXTRA_VERSION = "de.tubs.ibr.dtn.Service.VERSION"; // public static final String EXTRA_NAME = "de.tubs.ibr.dtn.Service.NAME"; // // public static class Service { // private final String mClassName; // private final Integer mVersion; // // private Service(String className, Integer version) { // mClassName = className; // mVersion = version; // } // // public String getClassName() { // return mClassName; // } // // public Integer getVersion() { // return mVersion; // } // // public Intent getIntent(Context context, String action) throws ServiceNotAvailableException { // Intent queryIntent = new Intent(mClassName); // List<ResolveInfo> list = context.getPackageManager().queryIntentServices(queryIntent, 0); // if (list.size() == 0) throw new ServiceNotAvailableException(); // // // get the first found service // ServiceInfo serviceInfo = list.get(0).serviceInfo; // // // create bind intent to the first service // Intent intent = new Intent(action); // intent.setClassName(serviceInfo.packageName, serviceInfo.name); // return intent; // } // // public void bind(Context context, ServiceConnection conn, int flags) throws ServiceNotAvailableException { // Intent queryIntent = new Intent(mClassName); // List<ResolveInfo> list = context.getPackageManager().queryIntentServices(queryIntent, 0); // if (list.size() == 0) throw new ServiceNotAvailableException(); // // // get the first found service // ServiceInfo serviceInfo = list.get(0).serviceInfo; // // // create bind intent to the first service // Intent bindIntent = new Intent(mClassName); // bindIntent.putExtra(EXTRA_NAME, mClassName); // bindIntent.putExtra(EXTRA_VERSION, mVersion); // bindIntent.setClassName(serviceInfo.packageName, serviceInfo.name); // // // set class-name and version as data URI to prevent caching conflicts // bindIntent.setData(Uri.fromParts("service", mClassName, mVersion.toString())); // // // bind to the service // context.bindService(bindIntent, conn, flags); // } // // public boolean match(Intent intent) { // // the requested API version // Integer version = intent.getIntExtra(Services.EXTRA_VERSION, 0); // // // the requested service name // String name = intent.getStringExtra(Services.EXTRA_NAME); // // // check old-style API binds // if ((name == null) && (version == 0)) // { // if (mClassName.equals(intent.getAction())) return true; // if (mClassName.equals(DTNService.class.getName())) return true; // return false; // } // // // check if API version matches // if (!mClassName.equals(name)) return false; // // // check if API version matches // if (version != mVersion) return false; // // return true; // } // } // }
import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.IBinder; import android.os.ParcelFileDescriptor; import android.os.Parcelable; import android.os.RemoteException; import android.preference.PreferenceManager; import android.util.Log; import de.tubs.ibr.dtn.DTNService; import de.tubs.ibr.dtn.Services; import java.util.List; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection;
String session_key = intent.getStringExtra("key"); SharedPreferences pm = PreferenceManager.getDefaultSharedPreferences(mContext); Editor edit = pm.edit(); edit.putString(PREF_SESSION_KEY, session_key); // store new hash code edit.putInt("registration_hash", mRegistration.hashCode()); edit.commit(); // initialize the session initializeSession(mRegistration); } } }; private void initializeSession(Registration reg) { Session s = null; try { // do not initialize if the service is not connected if (mService == null) return; s = new Session(mContext, mService); s.initialize(reg); } catch (Exception e) { try {
// Path: library/src/main/java/de/tubs/ibr/dtn/Services.java // public class Services { // /** // * Version = 0 (< 1.0) // * Version = 1 (>= 1.0) // */ // public static final Integer VERSION_APPLICATION = 1; // // /** // * Version = 0 (< 1.0) // * Version = 1 (>= 1.0) // */ // public static final Integer VERSION_MANAGER = 1; // // /** // * Version = 0 (< 1.0) // * Version = 1 (>= 1.0) // */ // public static final Integer VERSION_SECURITY = 1; // // public static final Service SERVICE_APPLICATION = new Service(DTNService.class.getName(), VERSION_APPLICATION); // public static final Service SERVICE_MANAGER = new Service(DtnManager.class.getName(), VERSION_MANAGER); // public static final Service SERVICE_SECURITY = new Service(SecurityService.class.getName(), VERSION_SECURITY); // // public static final String EXTRA_VERSION = "de.tubs.ibr.dtn.Service.VERSION"; // public static final String EXTRA_NAME = "de.tubs.ibr.dtn.Service.NAME"; // // public static class Service { // private final String mClassName; // private final Integer mVersion; // // private Service(String className, Integer version) { // mClassName = className; // mVersion = version; // } // // public String getClassName() { // return mClassName; // } // // public Integer getVersion() { // return mVersion; // } // // public Intent getIntent(Context context, String action) throws ServiceNotAvailableException { // Intent queryIntent = new Intent(mClassName); // List<ResolveInfo> list = context.getPackageManager().queryIntentServices(queryIntent, 0); // if (list.size() == 0) throw new ServiceNotAvailableException(); // // // get the first found service // ServiceInfo serviceInfo = list.get(0).serviceInfo; // // // create bind intent to the first service // Intent intent = new Intent(action); // intent.setClassName(serviceInfo.packageName, serviceInfo.name); // return intent; // } // // public void bind(Context context, ServiceConnection conn, int flags) throws ServiceNotAvailableException { // Intent queryIntent = new Intent(mClassName); // List<ResolveInfo> list = context.getPackageManager().queryIntentServices(queryIntent, 0); // if (list.size() == 0) throw new ServiceNotAvailableException(); // // // get the first found service // ServiceInfo serviceInfo = list.get(0).serviceInfo; // // // create bind intent to the first service // Intent bindIntent = new Intent(mClassName); // bindIntent.putExtra(EXTRA_NAME, mClassName); // bindIntent.putExtra(EXTRA_VERSION, mVersion); // bindIntent.setClassName(serviceInfo.packageName, serviceInfo.name); // // // set class-name and version as data URI to prevent caching conflicts // bindIntent.setData(Uri.fromParts("service", mClassName, mVersion.toString())); // // // bind to the service // context.bindService(bindIntent, conn, flags); // } // // public boolean match(Intent intent) { // // the requested API version // Integer version = intent.getIntExtra(Services.EXTRA_VERSION, 0); // // // the requested service name // String name = intent.getStringExtra(Services.EXTRA_NAME); // // // check old-style API binds // if ((name == null) && (version == 0)) // { // if (mClassName.equals(intent.getAction())) return true; // if (mClassName.equals(DTNService.class.getName())) return true; // return false; // } // // // check if API version matches // if (!mClassName.equals(name)) return false; // // // check if API version matches // if (version != mVersion) return false; // // return true; // } // } // } // Path: library/src/main/java/de/tubs/ibr/dtn/api/DTNClient.java import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.IBinder; import android.os.ParcelFileDescriptor; import android.os.Parcelable; import android.os.RemoteException; import android.preference.PreferenceManager; import android.util.Log; import de.tubs.ibr.dtn.DTNService; import de.tubs.ibr.dtn.Services; import java.util.List; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; String session_key = intent.getStringExtra("key"); SharedPreferences pm = PreferenceManager.getDefaultSharedPreferences(mContext); Editor edit = pm.edit(); edit.putString(PREF_SESSION_KEY, session_key); // store new hash code edit.putInt("registration_hash", mRegistration.hashCode()); edit.commit(); // initialize the session initializeSession(mRegistration); } } }; private void initializeSession(Registration reg) { Session s = null; try { // do not initialize if the service is not connected if (mService == null) return; s = new Session(mContext, mService); s.initialize(reg); } catch (Exception e) { try {
Intent registrationIntent = Services.SERVICE_APPLICATION.getIntent(mContext, de.tubs.ibr.dtn.Intent.REGISTER);
ibrdtn/ibrdtn-android-library
library/src/main/java/de/tubs/ibr/dtn/api/BundleID.java
// Path: library/src/main/java/de/tubs/ibr/dtn/api/Bundle.java // public enum ProcFlags { // FRAGMENT(1 << 0x00), // APPDATA_IS_ADMRECORD(1 << 0x01), // DONT_FRAGMENT(1 << 0x02), // CUSTODY_REQUESTED(1 << 0x03), // DESTINATION_IS_SINGLETON(1 << 0x04), // ACKOFAPP_REQUESTED(1 << 0x05), // RESERVED_6(1 << 0x06), // PRIORITY_BIT1(1 << 0x07), // PRIORITY_BIT2(1 << 0x08), // CLASSOFSERVICE_9(1 << 0x09), // CLASSOFSERVICE_10(1 << 0x0A), // CLASSOFSERVICE_11(1 << 0x0B), // CLASSOFSERVICE_12(1 << 0x0C), // CLASSOFSERVICE_13(1 << 0x0D), // REQUEST_REPORT_OF_BUNDLE_RECEPTION(1 << 0x0E), // REQUEST_REPORT_OF_CUSTODY_ACCEPTANCE(1 << 0x0F), // REQUEST_REPORT_OF_BUNDLE_FORWARDING(1 << 0x10), // REQUEST_REPORT_OF_BUNDLE_DELIVERY(1 << 0x11), // REQUEST_REPORT_OF_BUNDLE_DELETION(1 << 0x12), // STATUS_REPORT_REQUEST_19(1 << 0x13), // STATUS_REPORT_REQUEST_20(1 << 0x14), // // // DTNSEC FLAGS (these are customized flags and not written down in any draft) // DTNSEC_REQUEST_SIGN(1 << 0x1A), // DTNSEC_REQUEST_ENCRYPT(1 << 0x1B), // DTNSEC_STATUS_VERIFIED(1 << 0x1C), // DTNSEC_STATUS_CONFIDENTIAL(1 << 0x1D), // DTNSEC_STATUS_AUTHENTICATED(1 << 0x1E), // IBRDTN_REQUEST_COMPRESSION(1 << 0x1F); // // private int value = 0; // // private ProcFlags(int i) { // this.value = i; // } // // public int getValue() { // return this.value; // } // };
import android.os.Parcel; import android.os.Parcelable; import de.tubs.ibr.dtn.api.Bundle.ProcFlags; import java.util.StringTokenizer;
/* * Block.java * * Copyright (C) 2011 IBR, TU Braunschweig * * Written-by: Johannes Morgenroth <morgenroth@ibr.cs.tu-bs.de> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package de.tubs.ibr.dtn.api; public class BundleID implements Parcelable, Comparable<BundleID> { private SingletonEndpoint source = null; private Timestamp timestamp = null; private Long sequencenumber = null; private boolean fragment = false; private Long fragment_offset = 0L; private Long fragment_payload = 0L; public BundleID() { } public BundleID(Bundle b) { this.source = b.getSource(); this.timestamp = b.getTimestamp(); this.sequencenumber = b.getSequencenumber();
// Path: library/src/main/java/de/tubs/ibr/dtn/api/Bundle.java // public enum ProcFlags { // FRAGMENT(1 << 0x00), // APPDATA_IS_ADMRECORD(1 << 0x01), // DONT_FRAGMENT(1 << 0x02), // CUSTODY_REQUESTED(1 << 0x03), // DESTINATION_IS_SINGLETON(1 << 0x04), // ACKOFAPP_REQUESTED(1 << 0x05), // RESERVED_6(1 << 0x06), // PRIORITY_BIT1(1 << 0x07), // PRIORITY_BIT2(1 << 0x08), // CLASSOFSERVICE_9(1 << 0x09), // CLASSOFSERVICE_10(1 << 0x0A), // CLASSOFSERVICE_11(1 << 0x0B), // CLASSOFSERVICE_12(1 << 0x0C), // CLASSOFSERVICE_13(1 << 0x0D), // REQUEST_REPORT_OF_BUNDLE_RECEPTION(1 << 0x0E), // REQUEST_REPORT_OF_CUSTODY_ACCEPTANCE(1 << 0x0F), // REQUEST_REPORT_OF_BUNDLE_FORWARDING(1 << 0x10), // REQUEST_REPORT_OF_BUNDLE_DELIVERY(1 << 0x11), // REQUEST_REPORT_OF_BUNDLE_DELETION(1 << 0x12), // STATUS_REPORT_REQUEST_19(1 << 0x13), // STATUS_REPORT_REQUEST_20(1 << 0x14), // // // DTNSEC FLAGS (these are customized flags and not written down in any draft) // DTNSEC_REQUEST_SIGN(1 << 0x1A), // DTNSEC_REQUEST_ENCRYPT(1 << 0x1B), // DTNSEC_STATUS_VERIFIED(1 << 0x1C), // DTNSEC_STATUS_CONFIDENTIAL(1 << 0x1D), // DTNSEC_STATUS_AUTHENTICATED(1 << 0x1E), // IBRDTN_REQUEST_COMPRESSION(1 << 0x1F); // // private int value = 0; // // private ProcFlags(int i) { // this.value = i; // } // // public int getValue() { // return this.value; // } // }; // Path: library/src/main/java/de/tubs/ibr/dtn/api/BundleID.java import android.os.Parcel; import android.os.Parcelable; import de.tubs.ibr.dtn.api.Bundle.ProcFlags; import java.util.StringTokenizer; /* * Block.java * * Copyright (C) 2011 IBR, TU Braunschweig * * Written-by: Johannes Morgenroth <morgenroth@ibr.cs.tu-bs.de> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package de.tubs.ibr.dtn.api; public class BundleID implements Parcelable, Comparable<BundleID> { private SingletonEndpoint source = null; private Timestamp timestamp = null; private Long sequencenumber = null; private boolean fragment = false; private Long fragment_offset = 0L; private Long fragment_payload = 0L; public BundleID() { } public BundleID(Bundle b) { this.source = b.getSource(); this.timestamp = b.getTimestamp(); this.sequencenumber = b.getSequencenumber();
this.fragment = b.get(ProcFlags.FRAGMENT);
h2r/burlapcraft
src/main/java/edu/brown/cs/h2r/burlapcraft/block/BlockBurlapStone.java
// Path: src/main/java/edu/brown/cs/h2r/burlapcraft/BurlapCraft.java // @Mod(modid = BurlapCraft.MODID, version = BurlapCraft.VERSION) // public class BurlapCraft { // // // mod information // public static final String MODID = "burlapcraftmod"; // public static final String VERSION = "1.1"; // // // items // // // blocks // public static Block burlapStone; // public static Block redRock; // public static Block blueRock; // public static Block greenRock; // public static Block orangeRock; // public static Block mineableRedRock; // public static Block mineableBlueRock; // public static Block mineableGreenRock; // public static Block mineableOrangeRock; // // // event handlers // HandlerDungeonGeneration genHandler = new HandlerDungeonGeneration(); // HandlerEvents eventHandler = new HandlerEvents(); // // public static Dungeon currentDungeon; // public static List<Dungeon> dungeons = new ArrayList<Dungeon>(); // public static Map<String, Dungeon> dungeonMap = new HashMap<String, Dungeon>(); // // public static void registerDungeon(Dungeon d) { // dungeons.add(d); // dungeonMap.put(d.getName(), d); // } // // @EventHandler // public void preInit(FMLPreInitializationEvent event) { // // // burlapStone = new BlockBurlapStone(); // redRock = new BlockRedRock(); // blueRock = new BlockBlueRock(); // orangeRock = new BlockOrangeRock(); // greenRock = new BlockGreenRock(); // mineableRedRock = new BlockMineableRedRock(); // mineableOrangeRock = new BlockMineableOrangeRock(); // mineableGreenRock = new BlockMineableGreenRock(); // mineableBlueRock = new BlockMineableBlueRock(); // // // make sure minecraft knows // GameRegistry.registerBlock(burlapStone, "burlapstone"); // GameRegistry.registerBlock(redRock, "redrock"); // GameRegistry.registerBlock(blueRock, "bluerock"); // GameRegistry.registerBlock(greenRock, "greenrock"); // GameRegistry.registerBlock(orangeRock, "orangerock"); // GameRegistry.registerBlock(mineableRedRock, "mineableRedRock"); // GameRegistry.registerBlock(mineableGreenRock, "mineableGreenRock"); // GameRegistry.registerBlock(mineableBlueRock, "mineableBlueRock"); // GameRegistry.registerBlock(mineableOrangeRock, "mineableOrangeRock"); // GameRegistry.registerWorldGenerator(genHandler, 0); // // MinecraftForge.EVENT_BUS.register(eventHandler); // // FMLCommonHandler.instance().bus().register(fmlHandler); // // } // // @EventHandler // public void serverLoad(FMLServerStartingEvent event) // { // // register server commands // event.registerServerCommand(new CommandTeleport()); // event.registerServerCommand(new CommandSmoothMove()); // event.registerServerCommand(new CommandAStar()); // event.registerServerCommand(new CommandBFS()); // event.registerServerCommand(new CommandVI()); // event.registerServerCommand(new CommandRMax()); // event.registerServerCommand(new CommandCreateDungeons()); // event.registerServerCommand(new CommandInventory()); // event.registerServerCommand(new CommandCheckState()); // event.registerServerCommand(new CommandResetDungeon()); // event.registerServerCommand(new CommandCheckProps()); // event.registerServerCommand(new CommandTest()); // event.registerServerCommand(new CommandTerminalExplore()); // event.registerServerCommand(new CommandCurrentPath()); // event.registerServerCommand(new CommandReachable()); // // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // // } // // }
import java.util.Random; import edu.brown.cs.h2r.burlapcraft.BurlapCraft; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; import net.minecraft.item.Item;
package edu.brown.cs.h2r.burlapcraft.block; public class BlockBurlapStone extends Block { // name of block private String name = "burlapstone"; public BlockBurlapStone() { super(Material.rock);
// Path: src/main/java/edu/brown/cs/h2r/burlapcraft/BurlapCraft.java // @Mod(modid = BurlapCraft.MODID, version = BurlapCraft.VERSION) // public class BurlapCraft { // // // mod information // public static final String MODID = "burlapcraftmod"; // public static final String VERSION = "1.1"; // // // items // // // blocks // public static Block burlapStone; // public static Block redRock; // public static Block blueRock; // public static Block greenRock; // public static Block orangeRock; // public static Block mineableRedRock; // public static Block mineableBlueRock; // public static Block mineableGreenRock; // public static Block mineableOrangeRock; // // // event handlers // HandlerDungeonGeneration genHandler = new HandlerDungeonGeneration(); // HandlerEvents eventHandler = new HandlerEvents(); // // public static Dungeon currentDungeon; // public static List<Dungeon> dungeons = new ArrayList<Dungeon>(); // public static Map<String, Dungeon> dungeonMap = new HashMap<String, Dungeon>(); // // public static void registerDungeon(Dungeon d) { // dungeons.add(d); // dungeonMap.put(d.getName(), d); // } // // @EventHandler // public void preInit(FMLPreInitializationEvent event) { // // // burlapStone = new BlockBurlapStone(); // redRock = new BlockRedRock(); // blueRock = new BlockBlueRock(); // orangeRock = new BlockOrangeRock(); // greenRock = new BlockGreenRock(); // mineableRedRock = new BlockMineableRedRock(); // mineableOrangeRock = new BlockMineableOrangeRock(); // mineableGreenRock = new BlockMineableGreenRock(); // mineableBlueRock = new BlockMineableBlueRock(); // // // make sure minecraft knows // GameRegistry.registerBlock(burlapStone, "burlapstone"); // GameRegistry.registerBlock(redRock, "redrock"); // GameRegistry.registerBlock(blueRock, "bluerock"); // GameRegistry.registerBlock(greenRock, "greenrock"); // GameRegistry.registerBlock(orangeRock, "orangerock"); // GameRegistry.registerBlock(mineableRedRock, "mineableRedRock"); // GameRegistry.registerBlock(mineableGreenRock, "mineableGreenRock"); // GameRegistry.registerBlock(mineableBlueRock, "mineableBlueRock"); // GameRegistry.registerBlock(mineableOrangeRock, "mineableOrangeRock"); // GameRegistry.registerWorldGenerator(genHandler, 0); // // MinecraftForge.EVENT_BUS.register(eventHandler); // // FMLCommonHandler.instance().bus().register(fmlHandler); // // } // // @EventHandler // public void serverLoad(FMLServerStartingEvent event) // { // // register server commands // event.registerServerCommand(new CommandTeleport()); // event.registerServerCommand(new CommandSmoothMove()); // event.registerServerCommand(new CommandAStar()); // event.registerServerCommand(new CommandBFS()); // event.registerServerCommand(new CommandVI()); // event.registerServerCommand(new CommandRMax()); // event.registerServerCommand(new CommandCreateDungeons()); // event.registerServerCommand(new CommandInventory()); // event.registerServerCommand(new CommandCheckState()); // event.registerServerCommand(new CommandResetDungeon()); // event.registerServerCommand(new CommandCheckProps()); // event.registerServerCommand(new CommandTest()); // event.registerServerCommand(new CommandTerminalExplore()); // event.registerServerCommand(new CommandCurrentPath()); // event.registerServerCommand(new CommandReachable()); // // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // // } // // } // Path: src/main/java/edu/brown/cs/h2r/burlapcraft/block/BlockBurlapStone.java import java.util.Random; import edu.brown.cs.h2r.burlapcraft.BurlapCraft; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; import net.minecraft.item.Item; package edu.brown.cs.h2r.burlapcraft.block; public class BlockBurlapStone extends Block { // name of block private String name = "burlapstone"; public BlockBurlapStone() { super(Material.rock);
setBlockName(BurlapCraft.MODID + "_" + name);
h2r/burlapcraft
src/main/java/edu/brown/cs/h2r/burlapcraft/block/BlockOrangeRock.java
// Path: src/main/java/edu/brown/cs/h2r/burlapcraft/BurlapCraft.java // @Mod(modid = BurlapCraft.MODID, version = BurlapCraft.VERSION) // public class BurlapCraft { // // // mod information // public static final String MODID = "burlapcraftmod"; // public static final String VERSION = "1.1"; // // // items // // // blocks // public static Block burlapStone; // public static Block redRock; // public static Block blueRock; // public static Block greenRock; // public static Block orangeRock; // public static Block mineableRedRock; // public static Block mineableBlueRock; // public static Block mineableGreenRock; // public static Block mineableOrangeRock; // // // event handlers // HandlerDungeonGeneration genHandler = new HandlerDungeonGeneration(); // HandlerEvents eventHandler = new HandlerEvents(); // // public static Dungeon currentDungeon; // public static List<Dungeon> dungeons = new ArrayList<Dungeon>(); // public static Map<String, Dungeon> dungeonMap = new HashMap<String, Dungeon>(); // // public static void registerDungeon(Dungeon d) { // dungeons.add(d); // dungeonMap.put(d.getName(), d); // } // // @EventHandler // public void preInit(FMLPreInitializationEvent event) { // // // burlapStone = new BlockBurlapStone(); // redRock = new BlockRedRock(); // blueRock = new BlockBlueRock(); // orangeRock = new BlockOrangeRock(); // greenRock = new BlockGreenRock(); // mineableRedRock = new BlockMineableRedRock(); // mineableOrangeRock = new BlockMineableOrangeRock(); // mineableGreenRock = new BlockMineableGreenRock(); // mineableBlueRock = new BlockMineableBlueRock(); // // // make sure minecraft knows // GameRegistry.registerBlock(burlapStone, "burlapstone"); // GameRegistry.registerBlock(redRock, "redrock"); // GameRegistry.registerBlock(blueRock, "bluerock"); // GameRegistry.registerBlock(greenRock, "greenrock"); // GameRegistry.registerBlock(orangeRock, "orangerock"); // GameRegistry.registerBlock(mineableRedRock, "mineableRedRock"); // GameRegistry.registerBlock(mineableGreenRock, "mineableGreenRock"); // GameRegistry.registerBlock(mineableBlueRock, "mineableBlueRock"); // GameRegistry.registerBlock(mineableOrangeRock, "mineableOrangeRock"); // GameRegistry.registerWorldGenerator(genHandler, 0); // // MinecraftForge.EVENT_BUS.register(eventHandler); // // FMLCommonHandler.instance().bus().register(fmlHandler); // // } // // @EventHandler // public void serverLoad(FMLServerStartingEvent event) // { // // register server commands // event.registerServerCommand(new CommandTeleport()); // event.registerServerCommand(new CommandSmoothMove()); // event.registerServerCommand(new CommandAStar()); // event.registerServerCommand(new CommandBFS()); // event.registerServerCommand(new CommandVI()); // event.registerServerCommand(new CommandRMax()); // event.registerServerCommand(new CommandCreateDungeons()); // event.registerServerCommand(new CommandInventory()); // event.registerServerCommand(new CommandCheckState()); // event.registerServerCommand(new CommandResetDungeon()); // event.registerServerCommand(new CommandCheckProps()); // event.registerServerCommand(new CommandTest()); // event.registerServerCommand(new CommandTerminalExplore()); // event.registerServerCommand(new CommandCurrentPath()); // event.registerServerCommand(new CommandReachable()); // // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // // } // // }
import edu.brown.cs.h2r.burlapcraft.BurlapCraft; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs;
package edu.brown.cs.h2r.burlapcraft.block; public class BlockOrangeRock extends Block { // name of block private String name = "orangerock"; public BlockOrangeRock() { super(Material.rock);
// Path: src/main/java/edu/brown/cs/h2r/burlapcraft/BurlapCraft.java // @Mod(modid = BurlapCraft.MODID, version = BurlapCraft.VERSION) // public class BurlapCraft { // // // mod information // public static final String MODID = "burlapcraftmod"; // public static final String VERSION = "1.1"; // // // items // // // blocks // public static Block burlapStone; // public static Block redRock; // public static Block blueRock; // public static Block greenRock; // public static Block orangeRock; // public static Block mineableRedRock; // public static Block mineableBlueRock; // public static Block mineableGreenRock; // public static Block mineableOrangeRock; // // // event handlers // HandlerDungeonGeneration genHandler = new HandlerDungeonGeneration(); // HandlerEvents eventHandler = new HandlerEvents(); // // public static Dungeon currentDungeon; // public static List<Dungeon> dungeons = new ArrayList<Dungeon>(); // public static Map<String, Dungeon> dungeonMap = new HashMap<String, Dungeon>(); // // public static void registerDungeon(Dungeon d) { // dungeons.add(d); // dungeonMap.put(d.getName(), d); // } // // @EventHandler // public void preInit(FMLPreInitializationEvent event) { // // // burlapStone = new BlockBurlapStone(); // redRock = new BlockRedRock(); // blueRock = new BlockBlueRock(); // orangeRock = new BlockOrangeRock(); // greenRock = new BlockGreenRock(); // mineableRedRock = new BlockMineableRedRock(); // mineableOrangeRock = new BlockMineableOrangeRock(); // mineableGreenRock = new BlockMineableGreenRock(); // mineableBlueRock = new BlockMineableBlueRock(); // // // make sure minecraft knows // GameRegistry.registerBlock(burlapStone, "burlapstone"); // GameRegistry.registerBlock(redRock, "redrock"); // GameRegistry.registerBlock(blueRock, "bluerock"); // GameRegistry.registerBlock(greenRock, "greenrock"); // GameRegistry.registerBlock(orangeRock, "orangerock"); // GameRegistry.registerBlock(mineableRedRock, "mineableRedRock"); // GameRegistry.registerBlock(mineableGreenRock, "mineableGreenRock"); // GameRegistry.registerBlock(mineableBlueRock, "mineableBlueRock"); // GameRegistry.registerBlock(mineableOrangeRock, "mineableOrangeRock"); // GameRegistry.registerWorldGenerator(genHandler, 0); // // MinecraftForge.EVENT_BUS.register(eventHandler); // // FMLCommonHandler.instance().bus().register(fmlHandler); // // } // // @EventHandler // public void serverLoad(FMLServerStartingEvent event) // { // // register server commands // event.registerServerCommand(new CommandTeleport()); // event.registerServerCommand(new CommandSmoothMove()); // event.registerServerCommand(new CommandAStar()); // event.registerServerCommand(new CommandBFS()); // event.registerServerCommand(new CommandVI()); // event.registerServerCommand(new CommandRMax()); // event.registerServerCommand(new CommandCreateDungeons()); // event.registerServerCommand(new CommandInventory()); // event.registerServerCommand(new CommandCheckState()); // event.registerServerCommand(new CommandResetDungeon()); // event.registerServerCommand(new CommandCheckProps()); // event.registerServerCommand(new CommandTest()); // event.registerServerCommand(new CommandTerminalExplore()); // event.registerServerCommand(new CommandCurrentPath()); // event.registerServerCommand(new CommandReachable()); // // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // // } // // } // Path: src/main/java/edu/brown/cs/h2r/burlapcraft/block/BlockOrangeRock.java import edu.brown.cs.h2r.burlapcraft.BurlapCraft; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; package edu.brown.cs.h2r.burlapcraft.block; public class BlockOrangeRock extends Block { // name of block private String name = "orangerock"; public BlockOrangeRock() { super(Material.rock);
setBlockName(BurlapCraft.MODID + "_" + name);
h2r/burlapcraft
src/main/java/edu/brown/cs/h2r/burlapcraft/state/BCMap.java
// Path: src/main/java/edu/brown/cs/h2r/burlapcraft/helper/HelperNameSpace.java // public static final String CLASS_MAP = "map"; // // Path: src/main/java/edu/brown/cs/h2r/burlapcraft/helper/HelperNameSpace.java // public static final String VAR_MAP = "map";
import burlap.mdp.core.oo.state.ObjectInstance; import burlap.mdp.core.state.annotations.ShallowCopyState; import java.util.Arrays; import java.util.List; import static edu.brown.cs.h2r.burlapcraft.helper.HelperNameSpace.CLASS_MAP; import static edu.brown.cs.h2r.burlapcraft.helper.HelperNameSpace.VAR_MAP;
package edu.brown.cs.h2r.burlapcraft.state; /** * @author James MacGlashan. */ @ShallowCopyState public class BCMap implements ObjectInstance{ public int [][][] map;
// Path: src/main/java/edu/brown/cs/h2r/burlapcraft/helper/HelperNameSpace.java // public static final String CLASS_MAP = "map"; // // Path: src/main/java/edu/brown/cs/h2r/burlapcraft/helper/HelperNameSpace.java // public static final String VAR_MAP = "map"; // Path: src/main/java/edu/brown/cs/h2r/burlapcraft/state/BCMap.java import burlap.mdp.core.oo.state.ObjectInstance; import burlap.mdp.core.state.annotations.ShallowCopyState; import java.util.Arrays; import java.util.List; import static edu.brown.cs.h2r.burlapcraft.helper.HelperNameSpace.CLASS_MAP; import static edu.brown.cs.h2r.burlapcraft.helper.HelperNameSpace.VAR_MAP; package edu.brown.cs.h2r.burlapcraft.state; /** * @author James MacGlashan. */ @ShallowCopyState public class BCMap implements ObjectInstance{ public int [][][] map;
private static final List<Object> keys = Arrays.<Object>asList(VAR_MAP);
h2r/burlapcraft
src/main/java/edu/brown/cs/h2r/burlapcraft/state/BCMap.java
// Path: src/main/java/edu/brown/cs/h2r/burlapcraft/helper/HelperNameSpace.java // public static final String CLASS_MAP = "map"; // // Path: src/main/java/edu/brown/cs/h2r/burlapcraft/helper/HelperNameSpace.java // public static final String VAR_MAP = "map";
import burlap.mdp.core.oo.state.ObjectInstance; import burlap.mdp.core.state.annotations.ShallowCopyState; import java.util.Arrays; import java.util.List; import static edu.brown.cs.h2r.burlapcraft.helper.HelperNameSpace.CLASS_MAP; import static edu.brown.cs.h2r.burlapcraft.helper.HelperNameSpace.VAR_MAP;
package edu.brown.cs.h2r.burlapcraft.state; /** * @author James MacGlashan. */ @ShallowCopyState public class BCMap implements ObjectInstance{ public int [][][] map; private static final List<Object> keys = Arrays.<Object>asList(VAR_MAP); public BCMap() { } public BCMap(int[][][] map) { this.map = map; } @Override public String className() {
// Path: src/main/java/edu/brown/cs/h2r/burlapcraft/helper/HelperNameSpace.java // public static final String CLASS_MAP = "map"; // // Path: src/main/java/edu/brown/cs/h2r/burlapcraft/helper/HelperNameSpace.java // public static final String VAR_MAP = "map"; // Path: src/main/java/edu/brown/cs/h2r/burlapcraft/state/BCMap.java import burlap.mdp.core.oo.state.ObjectInstance; import burlap.mdp.core.state.annotations.ShallowCopyState; import java.util.Arrays; import java.util.List; import static edu.brown.cs.h2r.burlapcraft.helper.HelperNameSpace.CLASS_MAP; import static edu.brown.cs.h2r.burlapcraft.helper.HelperNameSpace.VAR_MAP; package edu.brown.cs.h2r.burlapcraft.state; /** * @author James MacGlashan. */ @ShallowCopyState public class BCMap implements ObjectInstance{ public int [][][] map; private static final List<Object> keys = Arrays.<Object>asList(VAR_MAP); public BCMap() { } public BCMap(int[][][] map) { this.map = map; } @Override public String className() {
return CLASS_MAP;
h2r/burlapcraft
src/main/java/edu/brown/cs/h2r/burlapcraft/domaingenerator/propositionalfunction/PFAgentOnBlock.java
// Path: src/main/java/edu/brown/cs/h2r/burlapcraft/state/BCAgent.java // @DeepCopyState // public class BCAgent implements ObjectInstance { // // public int x; // public int y; // public int z; // public int rdir; // public int vdir; // public int selected; // // private static final List<Object> keys = Arrays.<Object>asList(VAR_X, VAR_Y, VAR_Z, VAR_R_DIR, VAR_V_DIR, VAR_SEL); // // public BCAgent() { // } // // public BCAgent(int x, int y, int z, int rdir, int vdir, int selected) { // this.x = x; // this.y = y; // this.z = z; // this.rdir = rdir; // this.vdir = vdir; // this.selected = selected; // } // // @Override // public List<Object> variableKeys() { // return keys; // } // // @Override // public Object get(Object variableKey) { // if(variableKey.equals(VAR_X)){ // return x; // } // else if(variableKey.equals(VAR_Y)){ // return y; // } // else if(variableKey.equals(VAR_Z)){ // return z; // } // else if(variableKey.equals(VAR_R_DIR)){ // return rdir; // } // else if(variableKey.equals(VAR_V_DIR)){ // return vdir; // } // else if(variableKey.equals(VAR_SEL)){ // return selected; // } // throw new UnknownKeyException(variableKey); // } // // @Override // public String className() { // return CLASS_AGENT; // } // // @Override // public String name() { // return CLASS_AGENT; // } // // @Override // public BCAgent copyWithName(String objectName) { // if(!objectName.equals(CLASS_AGENT)){ // throw new RuntimeException("Agent object must be named " + CLASS_AGENT); // } // return copy(); // } // // @Override // public BCAgent copy() { // return new BCAgent(x, y, z, rdir, vdir, selected); // } // // @Override // public String toString() { // return OOStateUtilities.objectInstanceToString(this); // } // } // // Path: src/main/java/edu/brown/cs/h2r/burlapcraft/state/BCBlock.java // @DeepCopyState // public class BCBlock implements ObjectInstance { // // public int x; // public int y; // public int z; // public int type; // // protected String name; // // private static final List<Object> keys = Arrays.<Object>asList(VAR_X, VAR_Y, VAR_Z, VAR_BT); // // public BCBlock() { // } // // public BCBlock(int x, int y, int z, int type, String name) { // this.x = x; // this.y = y; // this.z = z; // this.type = type; // this.name = name; // } // // @Override // public String className() { // return CLASS_BLOCK; // } // // @Override // public String name() { // return name; // } // // @Override // public BCBlock copyWithName(String objectName) { // return new BCBlock(x, y, z, type, objectName); // } // // @Override // public List<Object> variableKeys() { // return keys; // } // // @Override // public Object get(Object variableKey) { // if(variableKey.equals(VAR_X)){ // return x; // } // else if(variableKey.equals(VAR_Y)){ // return y; // } // else if(variableKey.equals(VAR_Z)){ // return z; // } // else if(variableKey.equals(VAR_BT)){ // return type; // } // throw new UnknownKeyException(variableKey); // } // // @Override // public BCBlock copy() { // return new BCBlock(x, y, z, type, name); // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return OOStateUtilities.objectInstanceToString(this); // } // }
import burlap.mdp.core.oo.propositional.PropositionalFunction; import burlap.mdp.core.oo.state.OOState; import edu.brown.cs.h2r.burlapcraft.state.BCAgent; import edu.brown.cs.h2r.burlapcraft.state.BCBlock;
package edu.brown.cs.h2r.burlapcraft.domaingenerator.propositionalfunction; public class PFAgentOnBlock extends PropositionalFunction { public PFAgentOnBlock(String name, String[] parameterClasses) { super(name, parameterClasses); } @Override public boolean isTrue(OOState s, String... params) {
// Path: src/main/java/edu/brown/cs/h2r/burlapcraft/state/BCAgent.java // @DeepCopyState // public class BCAgent implements ObjectInstance { // // public int x; // public int y; // public int z; // public int rdir; // public int vdir; // public int selected; // // private static final List<Object> keys = Arrays.<Object>asList(VAR_X, VAR_Y, VAR_Z, VAR_R_DIR, VAR_V_DIR, VAR_SEL); // // public BCAgent() { // } // // public BCAgent(int x, int y, int z, int rdir, int vdir, int selected) { // this.x = x; // this.y = y; // this.z = z; // this.rdir = rdir; // this.vdir = vdir; // this.selected = selected; // } // // @Override // public List<Object> variableKeys() { // return keys; // } // // @Override // public Object get(Object variableKey) { // if(variableKey.equals(VAR_X)){ // return x; // } // else if(variableKey.equals(VAR_Y)){ // return y; // } // else if(variableKey.equals(VAR_Z)){ // return z; // } // else if(variableKey.equals(VAR_R_DIR)){ // return rdir; // } // else if(variableKey.equals(VAR_V_DIR)){ // return vdir; // } // else if(variableKey.equals(VAR_SEL)){ // return selected; // } // throw new UnknownKeyException(variableKey); // } // // @Override // public String className() { // return CLASS_AGENT; // } // // @Override // public String name() { // return CLASS_AGENT; // } // // @Override // public BCAgent copyWithName(String objectName) { // if(!objectName.equals(CLASS_AGENT)){ // throw new RuntimeException("Agent object must be named " + CLASS_AGENT); // } // return copy(); // } // // @Override // public BCAgent copy() { // return new BCAgent(x, y, z, rdir, vdir, selected); // } // // @Override // public String toString() { // return OOStateUtilities.objectInstanceToString(this); // } // } // // Path: src/main/java/edu/brown/cs/h2r/burlapcraft/state/BCBlock.java // @DeepCopyState // public class BCBlock implements ObjectInstance { // // public int x; // public int y; // public int z; // public int type; // // protected String name; // // private static final List<Object> keys = Arrays.<Object>asList(VAR_X, VAR_Y, VAR_Z, VAR_BT); // // public BCBlock() { // } // // public BCBlock(int x, int y, int z, int type, String name) { // this.x = x; // this.y = y; // this.z = z; // this.type = type; // this.name = name; // } // // @Override // public String className() { // return CLASS_BLOCK; // } // // @Override // public String name() { // return name; // } // // @Override // public BCBlock copyWithName(String objectName) { // return new BCBlock(x, y, z, type, objectName); // } // // @Override // public List<Object> variableKeys() { // return keys; // } // // @Override // public Object get(Object variableKey) { // if(variableKey.equals(VAR_X)){ // return x; // } // else if(variableKey.equals(VAR_Y)){ // return y; // } // else if(variableKey.equals(VAR_Z)){ // return z; // } // else if(variableKey.equals(VAR_BT)){ // return type; // } // throw new UnknownKeyException(variableKey); // } // // @Override // public BCBlock copy() { // return new BCBlock(x, y, z, type, name); // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return OOStateUtilities.objectInstanceToString(this); // } // } // Path: src/main/java/edu/brown/cs/h2r/burlapcraft/domaingenerator/propositionalfunction/PFAgentOnBlock.java import burlap.mdp.core.oo.propositional.PropositionalFunction; import burlap.mdp.core.oo.state.OOState; import edu.brown.cs.h2r.burlapcraft.state.BCAgent; import edu.brown.cs.h2r.burlapcraft.state.BCBlock; package edu.brown.cs.h2r.burlapcraft.domaingenerator.propositionalfunction; public class PFAgentOnBlock extends PropositionalFunction { public PFAgentOnBlock(String name, String[] parameterClasses) { super(name, parameterClasses); } @Override public boolean isTrue(OOState s, String... params) {
BCAgent a = (BCAgent)s.object(params[0]);
h2r/burlapcraft
src/main/java/edu/brown/cs/h2r/burlapcraft/domaingenerator/propositionalfunction/PFAgentOnBlock.java
// Path: src/main/java/edu/brown/cs/h2r/burlapcraft/state/BCAgent.java // @DeepCopyState // public class BCAgent implements ObjectInstance { // // public int x; // public int y; // public int z; // public int rdir; // public int vdir; // public int selected; // // private static final List<Object> keys = Arrays.<Object>asList(VAR_X, VAR_Y, VAR_Z, VAR_R_DIR, VAR_V_DIR, VAR_SEL); // // public BCAgent() { // } // // public BCAgent(int x, int y, int z, int rdir, int vdir, int selected) { // this.x = x; // this.y = y; // this.z = z; // this.rdir = rdir; // this.vdir = vdir; // this.selected = selected; // } // // @Override // public List<Object> variableKeys() { // return keys; // } // // @Override // public Object get(Object variableKey) { // if(variableKey.equals(VAR_X)){ // return x; // } // else if(variableKey.equals(VAR_Y)){ // return y; // } // else if(variableKey.equals(VAR_Z)){ // return z; // } // else if(variableKey.equals(VAR_R_DIR)){ // return rdir; // } // else if(variableKey.equals(VAR_V_DIR)){ // return vdir; // } // else if(variableKey.equals(VAR_SEL)){ // return selected; // } // throw new UnknownKeyException(variableKey); // } // // @Override // public String className() { // return CLASS_AGENT; // } // // @Override // public String name() { // return CLASS_AGENT; // } // // @Override // public BCAgent copyWithName(String objectName) { // if(!objectName.equals(CLASS_AGENT)){ // throw new RuntimeException("Agent object must be named " + CLASS_AGENT); // } // return copy(); // } // // @Override // public BCAgent copy() { // return new BCAgent(x, y, z, rdir, vdir, selected); // } // // @Override // public String toString() { // return OOStateUtilities.objectInstanceToString(this); // } // } // // Path: src/main/java/edu/brown/cs/h2r/burlapcraft/state/BCBlock.java // @DeepCopyState // public class BCBlock implements ObjectInstance { // // public int x; // public int y; // public int z; // public int type; // // protected String name; // // private static final List<Object> keys = Arrays.<Object>asList(VAR_X, VAR_Y, VAR_Z, VAR_BT); // // public BCBlock() { // } // // public BCBlock(int x, int y, int z, int type, String name) { // this.x = x; // this.y = y; // this.z = z; // this.type = type; // this.name = name; // } // // @Override // public String className() { // return CLASS_BLOCK; // } // // @Override // public String name() { // return name; // } // // @Override // public BCBlock copyWithName(String objectName) { // return new BCBlock(x, y, z, type, objectName); // } // // @Override // public List<Object> variableKeys() { // return keys; // } // // @Override // public Object get(Object variableKey) { // if(variableKey.equals(VAR_X)){ // return x; // } // else if(variableKey.equals(VAR_Y)){ // return y; // } // else if(variableKey.equals(VAR_Z)){ // return z; // } // else if(variableKey.equals(VAR_BT)){ // return type; // } // throw new UnknownKeyException(variableKey); // } // // @Override // public BCBlock copy() { // return new BCBlock(x, y, z, type, name); // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return OOStateUtilities.objectInstanceToString(this); // } // }
import burlap.mdp.core.oo.propositional.PropositionalFunction; import burlap.mdp.core.oo.state.OOState; import edu.brown.cs.h2r.burlapcraft.state.BCAgent; import edu.brown.cs.h2r.burlapcraft.state.BCBlock;
package edu.brown.cs.h2r.burlapcraft.domaingenerator.propositionalfunction; public class PFAgentOnBlock extends PropositionalFunction { public PFAgentOnBlock(String name, String[] parameterClasses) { super(name, parameterClasses); } @Override public boolean isTrue(OOState s, String... params) { BCAgent a = (BCAgent)s.object(params[0]);
// Path: src/main/java/edu/brown/cs/h2r/burlapcraft/state/BCAgent.java // @DeepCopyState // public class BCAgent implements ObjectInstance { // // public int x; // public int y; // public int z; // public int rdir; // public int vdir; // public int selected; // // private static final List<Object> keys = Arrays.<Object>asList(VAR_X, VAR_Y, VAR_Z, VAR_R_DIR, VAR_V_DIR, VAR_SEL); // // public BCAgent() { // } // // public BCAgent(int x, int y, int z, int rdir, int vdir, int selected) { // this.x = x; // this.y = y; // this.z = z; // this.rdir = rdir; // this.vdir = vdir; // this.selected = selected; // } // // @Override // public List<Object> variableKeys() { // return keys; // } // // @Override // public Object get(Object variableKey) { // if(variableKey.equals(VAR_X)){ // return x; // } // else if(variableKey.equals(VAR_Y)){ // return y; // } // else if(variableKey.equals(VAR_Z)){ // return z; // } // else if(variableKey.equals(VAR_R_DIR)){ // return rdir; // } // else if(variableKey.equals(VAR_V_DIR)){ // return vdir; // } // else if(variableKey.equals(VAR_SEL)){ // return selected; // } // throw new UnknownKeyException(variableKey); // } // // @Override // public String className() { // return CLASS_AGENT; // } // // @Override // public String name() { // return CLASS_AGENT; // } // // @Override // public BCAgent copyWithName(String objectName) { // if(!objectName.equals(CLASS_AGENT)){ // throw new RuntimeException("Agent object must be named " + CLASS_AGENT); // } // return copy(); // } // // @Override // public BCAgent copy() { // return new BCAgent(x, y, z, rdir, vdir, selected); // } // // @Override // public String toString() { // return OOStateUtilities.objectInstanceToString(this); // } // } // // Path: src/main/java/edu/brown/cs/h2r/burlapcraft/state/BCBlock.java // @DeepCopyState // public class BCBlock implements ObjectInstance { // // public int x; // public int y; // public int z; // public int type; // // protected String name; // // private static final List<Object> keys = Arrays.<Object>asList(VAR_X, VAR_Y, VAR_Z, VAR_BT); // // public BCBlock() { // } // // public BCBlock(int x, int y, int z, int type, String name) { // this.x = x; // this.y = y; // this.z = z; // this.type = type; // this.name = name; // } // // @Override // public String className() { // return CLASS_BLOCK; // } // // @Override // public String name() { // return name; // } // // @Override // public BCBlock copyWithName(String objectName) { // return new BCBlock(x, y, z, type, objectName); // } // // @Override // public List<Object> variableKeys() { // return keys; // } // // @Override // public Object get(Object variableKey) { // if(variableKey.equals(VAR_X)){ // return x; // } // else if(variableKey.equals(VAR_Y)){ // return y; // } // else if(variableKey.equals(VAR_Z)){ // return z; // } // else if(variableKey.equals(VAR_BT)){ // return type; // } // throw new UnknownKeyException(variableKey); // } // // @Override // public BCBlock copy() { // return new BCBlock(x, y, z, type, name); // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return OOStateUtilities.objectInstanceToString(this); // } // } // Path: src/main/java/edu/brown/cs/h2r/burlapcraft/domaingenerator/propositionalfunction/PFAgentOnBlock.java import burlap.mdp.core.oo.propositional.PropositionalFunction; import burlap.mdp.core.oo.state.OOState; import edu.brown.cs.h2r.burlapcraft.state.BCAgent; import edu.brown.cs.h2r.burlapcraft.state.BCBlock; package edu.brown.cs.h2r.burlapcraft.domaingenerator.propositionalfunction; public class PFAgentOnBlock extends PropositionalFunction { public PFAgentOnBlock(String name, String[] parameterClasses) { super(name, parameterClasses); } @Override public boolean isTrue(OOState s, String... params) { BCAgent a = (BCAgent)s.object(params[0]);
BCBlock b = (BCBlock)s.object(params[1]);
h2r/burlapcraft
src/main/java/edu/brown/cs/h2r/burlapcraft/domaingenerator/propositionalfunction/PFBlockIsType.java
// Path: src/main/java/edu/brown/cs/h2r/burlapcraft/state/BCBlock.java // @DeepCopyState // public class BCBlock implements ObjectInstance { // // public int x; // public int y; // public int z; // public int type; // // protected String name; // // private static final List<Object> keys = Arrays.<Object>asList(VAR_X, VAR_Y, VAR_Z, VAR_BT); // // public BCBlock() { // } // // public BCBlock(int x, int y, int z, int type, String name) { // this.x = x; // this.y = y; // this.z = z; // this.type = type; // this.name = name; // } // // @Override // public String className() { // return CLASS_BLOCK; // } // // @Override // public String name() { // return name; // } // // @Override // public BCBlock copyWithName(String objectName) { // return new BCBlock(x, y, z, type, objectName); // } // // @Override // public List<Object> variableKeys() { // return keys; // } // // @Override // public Object get(Object variableKey) { // if(variableKey.equals(VAR_X)){ // return x; // } // else if(variableKey.equals(VAR_Y)){ // return y; // } // else if(variableKey.equals(VAR_Z)){ // return z; // } // else if(variableKey.equals(VAR_BT)){ // return type; // } // throw new UnknownKeyException(variableKey); // } // // @Override // public BCBlock copy() { // return new BCBlock(x, y, z, type, name); // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return OOStateUtilities.objectInstanceToString(this); // } // }
import burlap.mdp.core.oo.propositional.PropositionalFunction; import burlap.mdp.core.oo.state.OOState; import edu.brown.cs.h2r.burlapcraft.state.BCBlock;
package edu.brown.cs.h2r.burlapcraft.domaingenerator.propositionalfunction; public class PFBlockIsType extends PropositionalFunction { protected int type; public PFBlockIsType(String name, String[] parameterClasses, int type) { super(name, parameterClasses); this.type = type; } @Override public boolean isTrue(OOState s, String... params) {
// Path: src/main/java/edu/brown/cs/h2r/burlapcraft/state/BCBlock.java // @DeepCopyState // public class BCBlock implements ObjectInstance { // // public int x; // public int y; // public int z; // public int type; // // protected String name; // // private static final List<Object> keys = Arrays.<Object>asList(VAR_X, VAR_Y, VAR_Z, VAR_BT); // // public BCBlock() { // } // // public BCBlock(int x, int y, int z, int type, String name) { // this.x = x; // this.y = y; // this.z = z; // this.type = type; // this.name = name; // } // // @Override // public String className() { // return CLASS_BLOCK; // } // // @Override // public String name() { // return name; // } // // @Override // public BCBlock copyWithName(String objectName) { // return new BCBlock(x, y, z, type, objectName); // } // // @Override // public List<Object> variableKeys() { // return keys; // } // // @Override // public Object get(Object variableKey) { // if(variableKey.equals(VAR_X)){ // return x; // } // else if(variableKey.equals(VAR_Y)){ // return y; // } // else if(variableKey.equals(VAR_Z)){ // return z; // } // else if(variableKey.equals(VAR_BT)){ // return type; // } // throw new UnknownKeyException(variableKey); // } // // @Override // public BCBlock copy() { // return new BCBlock(x, y, z, type, name); // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return OOStateUtilities.objectInstanceToString(this); // } // } // Path: src/main/java/edu/brown/cs/h2r/burlapcraft/domaingenerator/propositionalfunction/PFBlockIsType.java import burlap.mdp.core.oo.propositional.PropositionalFunction; import burlap.mdp.core.oo.state.OOState; import edu.brown.cs.h2r.burlapcraft.state.BCBlock; package edu.brown.cs.h2r.burlapcraft.domaingenerator.propositionalfunction; public class PFBlockIsType extends PropositionalFunction { protected int type; public PFBlockIsType(String name, String[] parameterClasses, int type) { super(name, parameterClasses); this.type = type; } @Override public boolean isTrue(OOState s, String... params) {
BCBlock block = (BCBlock)s.object(params[0]);
h2r/burlapcraft
src/main/java/edu/brown/cs/h2r/burlapcraft/state/BCInventory.java
// Path: src/main/java/edu/brown/cs/h2r/burlapcraft/helper/HelperNameSpace.java // public class HelperNameSpace { // // //-------------ATTRIBUTE STRINGS--------------------- // public static final String VAR_X = "x"; // public static final String VAR_Y = "y"; // public static final String VAR_Z = "z"; // public static final String VAR_BT = "blockType"; // public static final String VAR_R_DIR = "rotationalDirection"; // public static final String VAR_V_DIR = "verticalDirection"; // public static final String VAR_INV_NUM = "inventoryBlockQuantity"; // public static final String VAR_SEL = "selectedItemID"; // public static final String VAR_MAP = "map"; // // //-------------BURLAP OBJECTCLASS STRINGS------------- // public static final String CLASS_AGENT = "agent"; // public static final String CLASS_BLOCK = "block"; // public static final String CLASS_MAP = "map"; // public static final String CLASS_INVENTORY = "inventory"; // // //-------------ACTIONS STRINGS------------- // public static final String ACTION_MOVE = "moveForward"; // public static final String ACTION_ROTATE_RIGHT = "rotateRight"; // public static final String ACTION_ROTATE_LEFT = "rotateLeft"; // public static final String ACTION_DEST_BLOCK = "destroyBlock"; // public static final String ACTION_PLACE_BLOCK = "placeBlock"; // public static final String ACTION_AHEAD = "lookAhead"; // public static final String ACTION_DOWN_ONE = "lookDown"; // public static final String ACTION_CHANGE_ITEM = "changeItem"; // // //-------------PROPOSITIONAL FUNCTION STRINGS------------- // public static final String PF_AGENT_HAS_BLOCK = "agentHasBlock"; // public static final String PF_AGENT_ON_BLOCK = "agentOnBlock"; // // public static final String PF_BLOCK_BASE = "blockIs"; // public static final String PF_BLOCK_IS_TYPE = PF_BLOCK_BASE + "TYPE"; // // // //-------------ENUMS------------- // public enum RotDirection { // NORTH(2), EAST(3), SOUTH(0), WEST(1); // public static final int size = RotDirection.values().length; // private final int intVal; // // RotDirection(int i) { // this.intVal = i; // } // // public int toInt() { // return this.intVal; // } // // public static RotDirection fromInt(int i) { // switch (i) { // case 2: // return NORTH; // case 0: // return SOUTH; // case 3: // return EAST; // case 1: // return WEST; // // } // return null; // } // // } // // public enum VertDirection { // AHEAD(0), DOWN(1); // public static final int size = VertDirection.values().length; // private final int intVal; // // VertDirection(int i) { // this.intVal = i; // } // // public int toInt() { // return this.intVal; // } // // public static VertDirection fromInt(int i) { // switch (i) { // case 1: // return DOWN; // case 0: // return AHEAD; // // } // return null; // } // } // // } // // Path: src/main/java/edu/brown/cs/h2r/burlapcraft/helper/HelperNameSpace.java // public static final String CLASS_INVENTORY = "inventory";
import burlap.mdp.core.oo.state.ObjectInstance; import burlap.mdp.core.state.annotations.ShallowCopyState; import edu.brown.cs.h2r.burlapcraft.helper.HelperNameSpace; import java.util.Arrays; import java.util.List; import static edu.brown.cs.h2r.burlapcraft.helper.HelperNameSpace.CLASS_INVENTORY;
package edu.brown.cs.h2r.burlapcraft.state; /** * @author James MacGlashan. */ @ShallowCopyState public class BCInventory implements ObjectInstance { public BCIStack[] inv = new BCIStack[9];
// Path: src/main/java/edu/brown/cs/h2r/burlapcraft/helper/HelperNameSpace.java // public class HelperNameSpace { // // //-------------ATTRIBUTE STRINGS--------------------- // public static final String VAR_X = "x"; // public static final String VAR_Y = "y"; // public static final String VAR_Z = "z"; // public static final String VAR_BT = "blockType"; // public static final String VAR_R_DIR = "rotationalDirection"; // public static final String VAR_V_DIR = "verticalDirection"; // public static final String VAR_INV_NUM = "inventoryBlockQuantity"; // public static final String VAR_SEL = "selectedItemID"; // public static final String VAR_MAP = "map"; // // //-------------BURLAP OBJECTCLASS STRINGS------------- // public static final String CLASS_AGENT = "agent"; // public static final String CLASS_BLOCK = "block"; // public static final String CLASS_MAP = "map"; // public static final String CLASS_INVENTORY = "inventory"; // // //-------------ACTIONS STRINGS------------- // public static final String ACTION_MOVE = "moveForward"; // public static final String ACTION_ROTATE_RIGHT = "rotateRight"; // public static final String ACTION_ROTATE_LEFT = "rotateLeft"; // public static final String ACTION_DEST_BLOCK = "destroyBlock"; // public static final String ACTION_PLACE_BLOCK = "placeBlock"; // public static final String ACTION_AHEAD = "lookAhead"; // public static final String ACTION_DOWN_ONE = "lookDown"; // public static final String ACTION_CHANGE_ITEM = "changeItem"; // // //-------------PROPOSITIONAL FUNCTION STRINGS------------- // public static final String PF_AGENT_HAS_BLOCK = "agentHasBlock"; // public static final String PF_AGENT_ON_BLOCK = "agentOnBlock"; // // public static final String PF_BLOCK_BASE = "blockIs"; // public static final String PF_BLOCK_IS_TYPE = PF_BLOCK_BASE + "TYPE"; // // // //-------------ENUMS------------- // public enum RotDirection { // NORTH(2), EAST(3), SOUTH(0), WEST(1); // public static final int size = RotDirection.values().length; // private final int intVal; // // RotDirection(int i) { // this.intVal = i; // } // // public int toInt() { // return this.intVal; // } // // public static RotDirection fromInt(int i) { // switch (i) { // case 2: // return NORTH; // case 0: // return SOUTH; // case 3: // return EAST; // case 1: // return WEST; // // } // return null; // } // // } // // public enum VertDirection { // AHEAD(0), DOWN(1); // public static final int size = VertDirection.values().length; // private final int intVal; // // VertDirection(int i) { // this.intVal = i; // } // // public int toInt() { // return this.intVal; // } // // public static VertDirection fromInt(int i) { // switch (i) { // case 1: // return DOWN; // case 0: // return AHEAD; // // } // return null; // } // } // // } // // Path: src/main/java/edu/brown/cs/h2r/burlapcraft/helper/HelperNameSpace.java // public static final String CLASS_INVENTORY = "inventory"; // Path: src/main/java/edu/brown/cs/h2r/burlapcraft/state/BCInventory.java import burlap.mdp.core.oo.state.ObjectInstance; import burlap.mdp.core.state.annotations.ShallowCopyState; import edu.brown.cs.h2r.burlapcraft.helper.HelperNameSpace; import java.util.Arrays; import java.util.List; import static edu.brown.cs.h2r.burlapcraft.helper.HelperNameSpace.CLASS_INVENTORY; package edu.brown.cs.h2r.burlapcraft.state; /** * @author James MacGlashan. */ @ShallowCopyState public class BCInventory implements ObjectInstance { public BCIStack[] inv = new BCIStack[9];
private static List<Object> keys = Arrays.<Object>asList(HelperNameSpace.VAR_INV_NUM);
h2r/burlapcraft
src/main/java/edu/brown/cs/h2r/burlapcraft/state/BCInventory.java
// Path: src/main/java/edu/brown/cs/h2r/burlapcraft/helper/HelperNameSpace.java // public class HelperNameSpace { // // //-------------ATTRIBUTE STRINGS--------------------- // public static final String VAR_X = "x"; // public static final String VAR_Y = "y"; // public static final String VAR_Z = "z"; // public static final String VAR_BT = "blockType"; // public static final String VAR_R_DIR = "rotationalDirection"; // public static final String VAR_V_DIR = "verticalDirection"; // public static final String VAR_INV_NUM = "inventoryBlockQuantity"; // public static final String VAR_SEL = "selectedItemID"; // public static final String VAR_MAP = "map"; // // //-------------BURLAP OBJECTCLASS STRINGS------------- // public static final String CLASS_AGENT = "agent"; // public static final String CLASS_BLOCK = "block"; // public static final String CLASS_MAP = "map"; // public static final String CLASS_INVENTORY = "inventory"; // // //-------------ACTIONS STRINGS------------- // public static final String ACTION_MOVE = "moveForward"; // public static final String ACTION_ROTATE_RIGHT = "rotateRight"; // public static final String ACTION_ROTATE_LEFT = "rotateLeft"; // public static final String ACTION_DEST_BLOCK = "destroyBlock"; // public static final String ACTION_PLACE_BLOCK = "placeBlock"; // public static final String ACTION_AHEAD = "lookAhead"; // public static final String ACTION_DOWN_ONE = "lookDown"; // public static final String ACTION_CHANGE_ITEM = "changeItem"; // // //-------------PROPOSITIONAL FUNCTION STRINGS------------- // public static final String PF_AGENT_HAS_BLOCK = "agentHasBlock"; // public static final String PF_AGENT_ON_BLOCK = "agentOnBlock"; // // public static final String PF_BLOCK_BASE = "blockIs"; // public static final String PF_BLOCK_IS_TYPE = PF_BLOCK_BASE + "TYPE"; // // // //-------------ENUMS------------- // public enum RotDirection { // NORTH(2), EAST(3), SOUTH(0), WEST(1); // public static final int size = RotDirection.values().length; // private final int intVal; // // RotDirection(int i) { // this.intVal = i; // } // // public int toInt() { // return this.intVal; // } // // public static RotDirection fromInt(int i) { // switch (i) { // case 2: // return NORTH; // case 0: // return SOUTH; // case 3: // return EAST; // case 1: // return WEST; // // } // return null; // } // // } // // public enum VertDirection { // AHEAD(0), DOWN(1); // public static final int size = VertDirection.values().length; // private final int intVal; // // VertDirection(int i) { // this.intVal = i; // } // // public int toInt() { // return this.intVal; // } // // public static VertDirection fromInt(int i) { // switch (i) { // case 1: // return DOWN; // case 0: // return AHEAD; // // } // return null; // } // } // // } // // Path: src/main/java/edu/brown/cs/h2r/burlapcraft/helper/HelperNameSpace.java // public static final String CLASS_INVENTORY = "inventory";
import burlap.mdp.core.oo.state.ObjectInstance; import burlap.mdp.core.state.annotations.ShallowCopyState; import edu.brown.cs.h2r.burlapcraft.helper.HelperNameSpace; import java.util.Arrays; import java.util.List; import static edu.brown.cs.h2r.burlapcraft.helper.HelperNameSpace.CLASS_INVENTORY;
package edu.brown.cs.h2r.burlapcraft.state; /** * @author James MacGlashan. */ @ShallowCopyState public class BCInventory implements ObjectInstance { public BCIStack[] inv = new BCIStack[9]; private static List<Object> keys = Arrays.<Object>asList(HelperNameSpace.VAR_INV_NUM); public BCInventory() { } public BCInventory(BCIStack[] inv) { this.inv = inv; } @Override public String className() {
// Path: src/main/java/edu/brown/cs/h2r/burlapcraft/helper/HelperNameSpace.java // public class HelperNameSpace { // // //-------------ATTRIBUTE STRINGS--------------------- // public static final String VAR_X = "x"; // public static final String VAR_Y = "y"; // public static final String VAR_Z = "z"; // public static final String VAR_BT = "blockType"; // public static final String VAR_R_DIR = "rotationalDirection"; // public static final String VAR_V_DIR = "verticalDirection"; // public static final String VAR_INV_NUM = "inventoryBlockQuantity"; // public static final String VAR_SEL = "selectedItemID"; // public static final String VAR_MAP = "map"; // // //-------------BURLAP OBJECTCLASS STRINGS------------- // public static final String CLASS_AGENT = "agent"; // public static final String CLASS_BLOCK = "block"; // public static final String CLASS_MAP = "map"; // public static final String CLASS_INVENTORY = "inventory"; // // //-------------ACTIONS STRINGS------------- // public static final String ACTION_MOVE = "moveForward"; // public static final String ACTION_ROTATE_RIGHT = "rotateRight"; // public static final String ACTION_ROTATE_LEFT = "rotateLeft"; // public static final String ACTION_DEST_BLOCK = "destroyBlock"; // public static final String ACTION_PLACE_BLOCK = "placeBlock"; // public static final String ACTION_AHEAD = "lookAhead"; // public static final String ACTION_DOWN_ONE = "lookDown"; // public static final String ACTION_CHANGE_ITEM = "changeItem"; // // //-------------PROPOSITIONAL FUNCTION STRINGS------------- // public static final String PF_AGENT_HAS_BLOCK = "agentHasBlock"; // public static final String PF_AGENT_ON_BLOCK = "agentOnBlock"; // // public static final String PF_BLOCK_BASE = "blockIs"; // public static final String PF_BLOCK_IS_TYPE = PF_BLOCK_BASE + "TYPE"; // // // //-------------ENUMS------------- // public enum RotDirection { // NORTH(2), EAST(3), SOUTH(0), WEST(1); // public static final int size = RotDirection.values().length; // private final int intVal; // // RotDirection(int i) { // this.intVal = i; // } // // public int toInt() { // return this.intVal; // } // // public static RotDirection fromInt(int i) { // switch (i) { // case 2: // return NORTH; // case 0: // return SOUTH; // case 3: // return EAST; // case 1: // return WEST; // // } // return null; // } // // } // // public enum VertDirection { // AHEAD(0), DOWN(1); // public static final int size = VertDirection.values().length; // private final int intVal; // // VertDirection(int i) { // this.intVal = i; // } // // public int toInt() { // return this.intVal; // } // // public static VertDirection fromInt(int i) { // switch (i) { // case 1: // return DOWN; // case 0: // return AHEAD; // // } // return null; // } // } // // } // // Path: src/main/java/edu/brown/cs/h2r/burlapcraft/helper/HelperNameSpace.java // public static final String CLASS_INVENTORY = "inventory"; // Path: src/main/java/edu/brown/cs/h2r/burlapcraft/state/BCInventory.java import burlap.mdp.core.oo.state.ObjectInstance; import burlap.mdp.core.state.annotations.ShallowCopyState; import edu.brown.cs.h2r.burlapcraft.helper.HelperNameSpace; import java.util.Arrays; import java.util.List; import static edu.brown.cs.h2r.burlapcraft.helper.HelperNameSpace.CLASS_INVENTORY; package edu.brown.cs.h2r.burlapcraft.state; /** * @author James MacGlashan. */ @ShallowCopyState public class BCInventory implements ObjectInstance { public BCIStack[] inv = new BCIStack[9]; private static List<Object> keys = Arrays.<Object>asList(HelperNameSpace.VAR_INV_NUM); public BCInventory() { } public BCInventory(BCIStack[] inv) { this.inv = inv; } @Override public String className() {
return CLASS_INVENTORY;
h2r/burlapcraft
src/main/java/edu/brown/cs/h2r/burlapcraft/block/BlockGreenRock.java
// Path: src/main/java/edu/brown/cs/h2r/burlapcraft/BurlapCraft.java // @Mod(modid = BurlapCraft.MODID, version = BurlapCraft.VERSION) // public class BurlapCraft { // // // mod information // public static final String MODID = "burlapcraftmod"; // public static final String VERSION = "1.1"; // // // items // // // blocks // public static Block burlapStone; // public static Block redRock; // public static Block blueRock; // public static Block greenRock; // public static Block orangeRock; // public static Block mineableRedRock; // public static Block mineableBlueRock; // public static Block mineableGreenRock; // public static Block mineableOrangeRock; // // // event handlers // HandlerDungeonGeneration genHandler = new HandlerDungeonGeneration(); // HandlerEvents eventHandler = new HandlerEvents(); // // public static Dungeon currentDungeon; // public static List<Dungeon> dungeons = new ArrayList<Dungeon>(); // public static Map<String, Dungeon> dungeonMap = new HashMap<String, Dungeon>(); // // public static void registerDungeon(Dungeon d) { // dungeons.add(d); // dungeonMap.put(d.getName(), d); // } // // @EventHandler // public void preInit(FMLPreInitializationEvent event) { // // // burlapStone = new BlockBurlapStone(); // redRock = new BlockRedRock(); // blueRock = new BlockBlueRock(); // orangeRock = new BlockOrangeRock(); // greenRock = new BlockGreenRock(); // mineableRedRock = new BlockMineableRedRock(); // mineableOrangeRock = new BlockMineableOrangeRock(); // mineableGreenRock = new BlockMineableGreenRock(); // mineableBlueRock = new BlockMineableBlueRock(); // // // make sure minecraft knows // GameRegistry.registerBlock(burlapStone, "burlapstone"); // GameRegistry.registerBlock(redRock, "redrock"); // GameRegistry.registerBlock(blueRock, "bluerock"); // GameRegistry.registerBlock(greenRock, "greenrock"); // GameRegistry.registerBlock(orangeRock, "orangerock"); // GameRegistry.registerBlock(mineableRedRock, "mineableRedRock"); // GameRegistry.registerBlock(mineableGreenRock, "mineableGreenRock"); // GameRegistry.registerBlock(mineableBlueRock, "mineableBlueRock"); // GameRegistry.registerBlock(mineableOrangeRock, "mineableOrangeRock"); // GameRegistry.registerWorldGenerator(genHandler, 0); // // MinecraftForge.EVENT_BUS.register(eventHandler); // // FMLCommonHandler.instance().bus().register(fmlHandler); // // } // // @EventHandler // public void serverLoad(FMLServerStartingEvent event) // { // // register server commands // event.registerServerCommand(new CommandTeleport()); // event.registerServerCommand(new CommandSmoothMove()); // event.registerServerCommand(new CommandAStar()); // event.registerServerCommand(new CommandBFS()); // event.registerServerCommand(new CommandVI()); // event.registerServerCommand(new CommandRMax()); // event.registerServerCommand(new CommandCreateDungeons()); // event.registerServerCommand(new CommandInventory()); // event.registerServerCommand(new CommandCheckState()); // event.registerServerCommand(new CommandResetDungeon()); // event.registerServerCommand(new CommandCheckProps()); // event.registerServerCommand(new CommandTest()); // event.registerServerCommand(new CommandTerminalExplore()); // event.registerServerCommand(new CommandCurrentPath()); // event.registerServerCommand(new CommandReachable()); // // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // // } // // }
import edu.brown.cs.h2r.burlapcraft.BurlapCraft; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs;
package edu.brown.cs.h2r.burlapcraft.block; public class BlockGreenRock extends Block { // name of block private String name = "greenrock"; public BlockGreenRock() { super(Material.rock);
// Path: src/main/java/edu/brown/cs/h2r/burlapcraft/BurlapCraft.java // @Mod(modid = BurlapCraft.MODID, version = BurlapCraft.VERSION) // public class BurlapCraft { // // // mod information // public static final String MODID = "burlapcraftmod"; // public static final String VERSION = "1.1"; // // // items // // // blocks // public static Block burlapStone; // public static Block redRock; // public static Block blueRock; // public static Block greenRock; // public static Block orangeRock; // public static Block mineableRedRock; // public static Block mineableBlueRock; // public static Block mineableGreenRock; // public static Block mineableOrangeRock; // // // event handlers // HandlerDungeonGeneration genHandler = new HandlerDungeonGeneration(); // HandlerEvents eventHandler = new HandlerEvents(); // // public static Dungeon currentDungeon; // public static List<Dungeon> dungeons = new ArrayList<Dungeon>(); // public static Map<String, Dungeon> dungeonMap = new HashMap<String, Dungeon>(); // // public static void registerDungeon(Dungeon d) { // dungeons.add(d); // dungeonMap.put(d.getName(), d); // } // // @EventHandler // public void preInit(FMLPreInitializationEvent event) { // // // burlapStone = new BlockBurlapStone(); // redRock = new BlockRedRock(); // blueRock = new BlockBlueRock(); // orangeRock = new BlockOrangeRock(); // greenRock = new BlockGreenRock(); // mineableRedRock = new BlockMineableRedRock(); // mineableOrangeRock = new BlockMineableOrangeRock(); // mineableGreenRock = new BlockMineableGreenRock(); // mineableBlueRock = new BlockMineableBlueRock(); // // // make sure minecraft knows // GameRegistry.registerBlock(burlapStone, "burlapstone"); // GameRegistry.registerBlock(redRock, "redrock"); // GameRegistry.registerBlock(blueRock, "bluerock"); // GameRegistry.registerBlock(greenRock, "greenrock"); // GameRegistry.registerBlock(orangeRock, "orangerock"); // GameRegistry.registerBlock(mineableRedRock, "mineableRedRock"); // GameRegistry.registerBlock(mineableGreenRock, "mineableGreenRock"); // GameRegistry.registerBlock(mineableBlueRock, "mineableBlueRock"); // GameRegistry.registerBlock(mineableOrangeRock, "mineableOrangeRock"); // GameRegistry.registerWorldGenerator(genHandler, 0); // // MinecraftForge.EVENT_BUS.register(eventHandler); // // FMLCommonHandler.instance().bus().register(fmlHandler); // // } // // @EventHandler // public void serverLoad(FMLServerStartingEvent event) // { // // register server commands // event.registerServerCommand(new CommandTeleport()); // event.registerServerCommand(new CommandSmoothMove()); // event.registerServerCommand(new CommandAStar()); // event.registerServerCommand(new CommandBFS()); // event.registerServerCommand(new CommandVI()); // event.registerServerCommand(new CommandRMax()); // event.registerServerCommand(new CommandCreateDungeons()); // event.registerServerCommand(new CommandInventory()); // event.registerServerCommand(new CommandCheckState()); // event.registerServerCommand(new CommandResetDungeon()); // event.registerServerCommand(new CommandCheckProps()); // event.registerServerCommand(new CommandTest()); // event.registerServerCommand(new CommandTerminalExplore()); // event.registerServerCommand(new CommandCurrentPath()); // event.registerServerCommand(new CommandReachable()); // // } // // @EventHandler // public void init(FMLInitializationEvent event) // { // // } // // @EventHandler // public void postInit(FMLPostInitializationEvent event) // { // // } // // } // Path: src/main/java/edu/brown/cs/h2r/burlapcraft/block/BlockGreenRock.java import edu.brown.cs.h2r.burlapcraft.BurlapCraft; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; package edu.brown.cs.h2r.burlapcraft.block; public class BlockGreenRock extends Block { // name of block private String name = "greenrock"; public BlockGreenRock() { super(Material.rock);
setBlockName(BurlapCraft.MODID + "_" + name);
sanity/LastCalc
src/main/java/com/lastcalc/Tokenizer.java
// Path: src/main/java/com/lastcalc/parsers/math/Radix.java // public class Radix implements Serializable { // private static final long serialVersionUID = 6793205833102927654L; // public final long integer; // public final int radix; // // public static Radix parse(final String value) { // if (value.startsWith("0x")) // return new Radix(Long.parseLong(value.substring(2), 16), 16); // else if (value.startsWith("0b")) // return new Radix(Long.parseLong(value.substring(2), 2), 2); // else if (value.startsWith("0o")) // return new Radix(Long.parseLong(value.substring(2), 8), 8); // else // return null; // } // // public Radix(final long integer, final int radix) { // this.integer = integer; // this.radix = radix; // } // // @Override // public String toString() { // String prefix; // if (radix == 2) { // prefix = "0b"; // } else if (radix == 8) { // prefix = "0o"; // } else { // prefix = "0x"; // } // return prefix + Long.toString(integer, radix); // } // }
import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.lastcalc.parsers.math.Radix; import org.jscience.mathematics.number.LargeInteger; import org.jscience.mathematics.number.Rational; import java.io.Serializable; import java.util.ArrayList; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern;
for (final Entry<String, String> e : tokenMatchers.entrySet()) { matchers.put(e.getKey(), Pattern.compile("^" + e.getValue() + "$")); } Tokenizer.anyMatcher = Pattern.compile(anyMatcher); } public static TokenList tokenize(final String orig) { final Matcher m = anyMatcher.matcher(orig); final ArrayList<Object> ret = Lists.newArrayList(); while (m.find()) { final String found = m.group(); if (matchers.get("float").matcher(found).find()) { final int dotPos = found.indexOf("."); final long intPart = Long.parseLong(found.substring(0, dotPos)); final String fracPart = found.substring(dotPos + 1, found.length()); final long num = intPart * (long) Math.pow(10, fracPart.length()) + (intPart >= 0 ? 1 : -1) * Long.parseLong(fracPart); final long denom = (long) Math.pow(10, fracPart.length()); ret.add(Rational.valueOf(num, denom)); } else if (matchers.get("integer").matcher(found).find()){ ret.add(LargeInteger.valueOf(found)); } else if (found.startsWith("\"") && found.endsWith("\"")) { final String quoted = found.substring(1, found.length() - 1).replace("\\\"", "\""); ret.add(new QuotedString(quoted)); } else { // Is it a radix?
// Path: src/main/java/com/lastcalc/parsers/math/Radix.java // public class Radix implements Serializable { // private static final long serialVersionUID = 6793205833102927654L; // public final long integer; // public final int radix; // // public static Radix parse(final String value) { // if (value.startsWith("0x")) // return new Radix(Long.parseLong(value.substring(2), 16), 16); // else if (value.startsWith("0b")) // return new Radix(Long.parseLong(value.substring(2), 2), 2); // else if (value.startsWith("0o")) // return new Radix(Long.parseLong(value.substring(2), 8), 8); // else // return null; // } // // public Radix(final long integer, final int radix) { // this.integer = integer; // this.radix = radix; // } // // @Override // public String toString() { // String prefix; // if (radix == 2) { // prefix = "0b"; // } else if (radix == 8) { // prefix = "0o"; // } else { // prefix = "0x"; // } // return prefix + Long.toString(integer, radix); // } // } // Path: src/main/java/com/lastcalc/Tokenizer.java import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.lastcalc.parsers.math.Radix; import org.jscience.mathematics.number.LargeInteger; import org.jscience.mathematics.number.Rational; import java.io.Serializable; import java.util.ArrayList; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; for (final Entry<String, String> e : tokenMatchers.entrySet()) { matchers.put(e.getKey(), Pattern.compile("^" + e.getValue() + "$")); } Tokenizer.anyMatcher = Pattern.compile(anyMatcher); } public static TokenList tokenize(final String orig) { final Matcher m = anyMatcher.matcher(orig); final ArrayList<Object> ret = Lists.newArrayList(); while (m.find()) { final String found = m.group(); if (matchers.get("float").matcher(found).find()) { final int dotPos = found.indexOf("."); final long intPart = Long.parseLong(found.substring(0, dotPos)); final String fracPart = found.substring(dotPos + 1, found.length()); final long num = intPart * (long) Math.pow(10, fracPart.length()) + (intPart >= 0 ? 1 : -1) * Long.parseLong(fracPart); final long denom = (long) Math.pow(10, fracPart.length()); ret.add(Rational.valueOf(num, denom)); } else if (matchers.get("integer").matcher(found).find()){ ret.add(LargeInteger.valueOf(found)); } else if (found.startsWith("\"") && found.endsWith("\"")) { final String quoted = found.substring(1, found.length() - 1).replace("\\\"", "\""); ret.add(new QuotedString(quoted)); } else { // Is it a radix?
final Radix radix = Radix.parse(found);
sanity/LastCalc
src/main/java/com/lastcalc/servlets/HelpServlet.java
// Path: src/main/java/com/lastcalc/lessons/Help.java // public class Help { // private static final Logger log = Logger.getLogger(Help.class.getName()); // // public static Map<String, Lesson> lessons; // // public static String helpDocAsString; // // static { // lessons = Maps.newHashMap(); // try { // final Document helpDoc = createHelpDoc(); // // helpDocAsString = helpDoc.toString(); // // for (final Element lessonElement : helpDoc.body().select("div.lesson")) { // final Lesson lesson = new Lesson(lessonElement); // lessons.put(lesson.id, lesson); // } // } catch (final Exception e) { // log.warning("Exception while processing tutorial.html " + e); // e.printStackTrace(); // } // } // // private static Document cachedHelpDoc; // // public static Document getHelpDoc() throws IOException { // if (cachedHelpDoc == null || environment.value() == SystemProperty.Environment.Value.Development) { // cachedHelpDoc = createHelpDoc(); // } // return cachedHelpDoc; // } // // private static Document createHelpDoc() throws IOException { // final Document helpDoc = Jsoup.parse(Help.class.getResourceAsStream("help.html"), "UTF-8", "/"); // // helpDoc.outputSettings().charset(Charset.forName("UTF-8")); // helpDoc.head().appendElement("meta").attr("charset", "UTF-8"); // helpDoc.head().appendElement("meta").attr("http-equiv", "Content-Type") // .attr("content", "text/html; charset=UTF-8"); // // // Process calculations // // final SequentialParser sp = SequentialParser.create(); // // for (final Element oldQuestion : helpDoc.select("div.question")) { // final String questionText = oldQuestion.text(); // oldQuestion.text(""); // oldQuestion.removeClass("question"); // oldQuestion.addClass("helpline").addClass("firstLine"); // final Element line = oldQuestion; // final TokenList tokenizedQuestion = Tokenizer.tokenize(questionText); // final TokenList answer = sp.parseNext(tokenizedQuestion); // // Important to render the question after we've calculated the // // answer so that variables are lighlighted in the line they are // // created in // final String questionAsHtml = Renderers.toHtml("/", tokenizedQuestion, sp.getUserDefinedKeywordMap()) // .toString(); // final TokenList strippedAnswer = sp.stripUDF(answer); // final AnswerType answerType = WorksheetServlet.getAnswerType(strippedAnswer); // line.appendElement("div").addClass("helpquestion").html(questionAsHtml); // if (answerType.equals(AnswerType.NORMAL)) { // line.appendElement("div").attr("class", "equals").text("="); // line.appendElement("div").attr("class", "answer") // .html(Renderers.toHtml("/", strippedAnswer).toString()); // } else { // line.appendElement("div").attr("class", "equals") // .html("<span style=\"font-size:10pt;\">&#10003</span>"); // line.appendElement("div").attr("class", "answer"); // } // } // // // Create menu // // final Element menuUl = helpDoc.select("ul#menu").first(); // for (final Element header : helpDoc.select("div.section h1")) { // final String headerText = header.text(); // final String anchor = headerText.toLowerCase().replace(' ', '-'); // header.html("<a name=\"" + anchor + "\">" + headerText + "</a>"); // menuUl.appendElement("li").attr("data-section", anchor).text(headerText); // } // return helpDoc; // } // // public static class Lesson { // public Lesson(final Element lesson) { // id = lesson.id(); // explanation = lesson.select("div.explanation").first(); // requires = Sets.newHashSet(); // for (final Element li : lesson.select("div.requires li")) { // requires.add(li.text()); // } // } // // public String id; // // public Element explanation; // // public Set<String> requires; // } // }
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.*; import com.lastcalc.lessons.Help;
/******************************************************************************* * LastCalc - The last calculator you'll ever need * Copyright (C) 2011, 2012 Uprizer Labs LLC * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU Affero General Public License for more * details. ******************************************************************************/ package com.lastcalc.servlets; public class HelpServlet extends HttpServlet { private static final long serialVersionUID = -7706942563225877578L; @Override public void init() throws javax.servlet.ServletException { // Force static initialization
// Path: src/main/java/com/lastcalc/lessons/Help.java // public class Help { // private static final Logger log = Logger.getLogger(Help.class.getName()); // // public static Map<String, Lesson> lessons; // // public static String helpDocAsString; // // static { // lessons = Maps.newHashMap(); // try { // final Document helpDoc = createHelpDoc(); // // helpDocAsString = helpDoc.toString(); // // for (final Element lessonElement : helpDoc.body().select("div.lesson")) { // final Lesson lesson = new Lesson(lessonElement); // lessons.put(lesson.id, lesson); // } // } catch (final Exception e) { // log.warning("Exception while processing tutorial.html " + e); // e.printStackTrace(); // } // } // // private static Document cachedHelpDoc; // // public static Document getHelpDoc() throws IOException { // if (cachedHelpDoc == null || environment.value() == SystemProperty.Environment.Value.Development) { // cachedHelpDoc = createHelpDoc(); // } // return cachedHelpDoc; // } // // private static Document createHelpDoc() throws IOException { // final Document helpDoc = Jsoup.parse(Help.class.getResourceAsStream("help.html"), "UTF-8", "/"); // // helpDoc.outputSettings().charset(Charset.forName("UTF-8")); // helpDoc.head().appendElement("meta").attr("charset", "UTF-8"); // helpDoc.head().appendElement("meta").attr("http-equiv", "Content-Type") // .attr("content", "text/html; charset=UTF-8"); // // // Process calculations // // final SequentialParser sp = SequentialParser.create(); // // for (final Element oldQuestion : helpDoc.select("div.question")) { // final String questionText = oldQuestion.text(); // oldQuestion.text(""); // oldQuestion.removeClass("question"); // oldQuestion.addClass("helpline").addClass("firstLine"); // final Element line = oldQuestion; // final TokenList tokenizedQuestion = Tokenizer.tokenize(questionText); // final TokenList answer = sp.parseNext(tokenizedQuestion); // // Important to render the question after we've calculated the // // answer so that variables are lighlighted in the line they are // // created in // final String questionAsHtml = Renderers.toHtml("/", tokenizedQuestion, sp.getUserDefinedKeywordMap()) // .toString(); // final TokenList strippedAnswer = sp.stripUDF(answer); // final AnswerType answerType = WorksheetServlet.getAnswerType(strippedAnswer); // line.appendElement("div").addClass("helpquestion").html(questionAsHtml); // if (answerType.equals(AnswerType.NORMAL)) { // line.appendElement("div").attr("class", "equals").text("="); // line.appendElement("div").attr("class", "answer") // .html(Renderers.toHtml("/", strippedAnswer).toString()); // } else { // line.appendElement("div").attr("class", "equals") // .html("<span style=\"font-size:10pt;\">&#10003</span>"); // line.appendElement("div").attr("class", "answer"); // } // } // // // Create menu // // final Element menuUl = helpDoc.select("ul#menu").first(); // for (final Element header : helpDoc.select("div.section h1")) { // final String headerText = header.text(); // final String anchor = headerText.toLowerCase().replace(' ', '-'); // header.html("<a name=\"" + anchor + "\">" + headerText + "</a>"); // menuUl.appendElement("li").attr("data-section", anchor).text(headerText); // } // return helpDoc; // } // // public static class Lesson { // public Lesson(final Element lesson) { // id = lesson.id(); // explanation = lesson.select("div.explanation").first(); // requires = Sets.newHashSet(); // for (final Element li : lesson.select("div.requires li")) { // requires.add(li.text()); // } // } // // public String id; // // public Element explanation; // // public Set<String> requires; // } // } // Path: src/main/java/com/lastcalc/servlets/HelpServlet.java import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.*; import com.lastcalc.lessons.Help; /******************************************************************************* * LastCalc - The last calculator you'll ever need * Copyright (C) 2011, 2012 Uprizer Labs LLC * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU Affero General Public License for more * details. ******************************************************************************/ package com.lastcalc.servlets; public class HelpServlet extends HttpServlet { private static final long serialVersionUID = -7706942563225877578L; @Override public void init() throws javax.servlet.ServletException { // Force static initialization
Help.lessons.size();
sanity/LastCalc
src/main/java/com/lastcalc/lessons/Help.java
// Path: src/main/java/com/lastcalc/servlets/WorksheetServlet.java // public enum AnswerType { // NORMAL, FUNCTION, ERROR // }
import static com.google.appengine.api.utils.SystemProperty.environment; import java.io.IOException; import java.nio.charset.Charset; import java.util.*; import java.util.logging.Logger; import com.google.common.collect.*; import org.jsoup.Jsoup; import org.jsoup.nodes.*; import com.google.appengine.api.utils.SystemProperty; import com.lastcalc.*; import com.lastcalc.servlets.*; import com.lastcalc.servlets.WorksheetServlet.AnswerType;
} return cachedHelpDoc; } private static Document createHelpDoc() throws IOException { final Document helpDoc = Jsoup.parse(Help.class.getResourceAsStream("help.html"), "UTF-8", "/"); helpDoc.outputSettings().charset(Charset.forName("UTF-8")); helpDoc.head().appendElement("meta").attr("charset", "UTF-8"); helpDoc.head().appendElement("meta").attr("http-equiv", "Content-Type") .attr("content", "text/html; charset=UTF-8"); // Process calculations final SequentialParser sp = SequentialParser.create(); for (final Element oldQuestion : helpDoc.select("div.question")) { final String questionText = oldQuestion.text(); oldQuestion.text(""); oldQuestion.removeClass("question"); oldQuestion.addClass("helpline").addClass("firstLine"); final Element line = oldQuestion; final TokenList tokenizedQuestion = Tokenizer.tokenize(questionText); final TokenList answer = sp.parseNext(tokenizedQuestion); // Important to render the question after we've calculated the // answer so that variables are lighlighted in the line they are // created in final String questionAsHtml = Renderers.toHtml("/", tokenizedQuestion, sp.getUserDefinedKeywordMap()) .toString(); final TokenList strippedAnswer = sp.stripUDF(answer);
// Path: src/main/java/com/lastcalc/servlets/WorksheetServlet.java // public enum AnswerType { // NORMAL, FUNCTION, ERROR // } // Path: src/main/java/com/lastcalc/lessons/Help.java import static com.google.appengine.api.utils.SystemProperty.environment; import java.io.IOException; import java.nio.charset.Charset; import java.util.*; import java.util.logging.Logger; import com.google.common.collect.*; import org.jsoup.Jsoup; import org.jsoup.nodes.*; import com.google.appengine.api.utils.SystemProperty; import com.lastcalc.*; import com.lastcalc.servlets.*; import com.lastcalc.servlets.WorksheetServlet.AnswerType; } return cachedHelpDoc; } private static Document createHelpDoc() throws IOException { final Document helpDoc = Jsoup.parse(Help.class.getResourceAsStream("help.html"), "UTF-8", "/"); helpDoc.outputSettings().charset(Charset.forName("UTF-8")); helpDoc.head().appendElement("meta").attr("charset", "UTF-8"); helpDoc.head().appendElement("meta").attr("http-equiv", "Content-Type") .attr("content", "text/html; charset=UTF-8"); // Process calculations final SequentialParser sp = SequentialParser.create(); for (final Element oldQuestion : helpDoc.select("div.question")) { final String questionText = oldQuestion.text(); oldQuestion.text(""); oldQuestion.removeClass("question"); oldQuestion.addClass("helpline").addClass("firstLine"); final Element line = oldQuestion; final TokenList tokenizedQuestion = Tokenizer.tokenize(questionText); final TokenList answer = sp.parseNext(tokenizedQuestion); // Important to render the question after we've calculated the // answer so that variables are lighlighted in the line they are // created in final String questionAsHtml = Renderers.toHtml("/", tokenizedQuestion, sp.getUserDefinedKeywordMap()) .toString(); final TokenList strippedAnswer = sp.stripUDF(answer);
final AnswerType answerType = WorksheetServlet.getAnswerType(strippedAnswer);
sanity/LastCalc
src/main/java/com/lastcalc/parsers/meta/ImportParser.java
// Path: src/main/java/com/lastcalc/Tokenizer.java // public static class QuotedString implements Serializable { // private static final long serialVersionUID = 8125107374281852751L; // public final String value; // // public QuotedString(final String value) { // this.value = value; // } // // @Override // public String toString() { // return "\"" + value + "\""; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((value == null) ? 0 : value.hashCode()); // return result; // } // // @Override // public boolean equals(final Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof QuotedString)) // return false; // final QuotedString other = (QuotedString) obj; // if (value == null) { // if (other.value != null) // return false; // } else if (!value.equals(other.value)) // return false; // return true; // } // } // // Path: src/main/java/com/lastcalc/cache/ObjectCache.java // public class ObjectCache { // private static final Logger log = Logger.getLogger(ObjectCache.class.getName()); // // static Map<Integer, CachedObject> softMap = new MapMaker().softValues().makeMap(); // // public static <T> T getFast(final long oldestAllowed, final Object... key) { // return getFastWithHash(oldestAllowed, Arrays.hashCode(key)); // } // // @SuppressWarnings("unchecked") // private static <T> T getFastWithHash(final long oldestAllowed, final int hash) { // final CachedObject co = softMap.get(hash); // if (co == null) // return null; // if (System.currentTimeMillis() - oldestAllowed > co.cacheTime) // return (T) co.object; // else // return null; // } // // @SuppressWarnings("unchecked") // public static <T> T getSlow(final long oldestAllowed, final Object... key) { // final int keyHash = Arrays.hashCode(key); // final T o = getFastWithHash(oldestAllowed, keyHash); // if (o != null) { // log.info("Got from local RAM"); // return o; // } // else { // CacheFactory cacheFactory; // try { // cacheFactory = CacheManager.getInstance().getCacheFactory(); // final Cache memcache = cacheFactory.createCache(Collections.emptyMap()); // final CachedObject co = (CachedObject) memcache.get(keyHash); // if (co != null) { // log.info("Got from memcache"); // return (T) co.object; // } // else // return null; // } catch (final CacheException e) { // log.warning("Exception retrieving object from cache: " + e); // return null; // } // } // } // // @SuppressWarnings("unchecked") // public static void put(final long expirationDelta, final Object value, final Object... key) { // final int keyHash = Arrays.hashCode(key); // final CachedObject co = new CachedObject(value); // softMap.put(keyHash, co); // CacheFactory cacheFactory; // try { // cacheFactory = CacheManager.getInstance().getCacheFactory(); // final Map<Object, Object> props = Maps.newHashMap(); // props.put(GCacheFactory.EXPIRATION_DELTA, 3600); // final Cache memcache = cacheFactory.createCache(props); // memcache.put(keyHash, co); // } catch (final CacheException e) { // log.warning("Exception retrieving object from cache: " + e); // } // } // // public static class CachedObject implements Serializable { // /** // * // */ // private static final long serialVersionUID = 2851269118906160513L; // // public final long cacheTime; // // public final Object object; // // public CachedObject(final Object object) { // this.object = object; // cacheTime = System.currentTimeMillis(); // } // } // }
import java.io.*; import java.net.*; import java.util.Collection; import com.lastcalc.*; import com.lastcalc.Tokenizer.QuotedString; import com.lastcalc.cache.ObjectCache; import com.lastcalc.parsers.*;
package com.lastcalc.parsers.meta; public class ImportParser extends Parser { private static TokenList template = TokenList.createD("import", QuotedString.class); @Override public TokenList getTemplate() { return template; } @Override public ParseResult parse(final TokenList tokens, final int templatePos, final ParserContext context) { if (context.importDepth > 5) return ParseResult.fail(); URL url; try { url = new URL(((QuotedString) tokens.get(templatePos + 1)).value); } catch (final MalformedURLException e) { return ParseResult.fail(); }
// Path: src/main/java/com/lastcalc/Tokenizer.java // public static class QuotedString implements Serializable { // private static final long serialVersionUID = 8125107374281852751L; // public final String value; // // public QuotedString(final String value) { // this.value = value; // } // // @Override // public String toString() { // return "\"" + value + "\""; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((value == null) ? 0 : value.hashCode()); // return result; // } // // @Override // public boolean equals(final Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof QuotedString)) // return false; // final QuotedString other = (QuotedString) obj; // if (value == null) { // if (other.value != null) // return false; // } else if (!value.equals(other.value)) // return false; // return true; // } // } // // Path: src/main/java/com/lastcalc/cache/ObjectCache.java // public class ObjectCache { // private static final Logger log = Logger.getLogger(ObjectCache.class.getName()); // // static Map<Integer, CachedObject> softMap = new MapMaker().softValues().makeMap(); // // public static <T> T getFast(final long oldestAllowed, final Object... key) { // return getFastWithHash(oldestAllowed, Arrays.hashCode(key)); // } // // @SuppressWarnings("unchecked") // private static <T> T getFastWithHash(final long oldestAllowed, final int hash) { // final CachedObject co = softMap.get(hash); // if (co == null) // return null; // if (System.currentTimeMillis() - oldestAllowed > co.cacheTime) // return (T) co.object; // else // return null; // } // // @SuppressWarnings("unchecked") // public static <T> T getSlow(final long oldestAllowed, final Object... key) { // final int keyHash = Arrays.hashCode(key); // final T o = getFastWithHash(oldestAllowed, keyHash); // if (o != null) { // log.info("Got from local RAM"); // return o; // } // else { // CacheFactory cacheFactory; // try { // cacheFactory = CacheManager.getInstance().getCacheFactory(); // final Cache memcache = cacheFactory.createCache(Collections.emptyMap()); // final CachedObject co = (CachedObject) memcache.get(keyHash); // if (co != null) { // log.info("Got from memcache"); // return (T) co.object; // } // else // return null; // } catch (final CacheException e) { // log.warning("Exception retrieving object from cache: " + e); // return null; // } // } // } // // @SuppressWarnings("unchecked") // public static void put(final long expirationDelta, final Object value, final Object... key) { // final int keyHash = Arrays.hashCode(key); // final CachedObject co = new CachedObject(value); // softMap.put(keyHash, co); // CacheFactory cacheFactory; // try { // cacheFactory = CacheManager.getInstance().getCacheFactory(); // final Map<Object, Object> props = Maps.newHashMap(); // props.put(GCacheFactory.EXPIRATION_DELTA, 3600); // final Cache memcache = cacheFactory.createCache(props); // memcache.put(keyHash, co); // } catch (final CacheException e) { // log.warning("Exception retrieving object from cache: " + e); // } // } // // public static class CachedObject implements Serializable { // /** // * // */ // private static final long serialVersionUID = 2851269118906160513L; // // public final long cacheTime; // // public final Object object; // // public CachedObject(final Object object) { // this.object = object; // cacheTime = System.currentTimeMillis(); // } // } // } // Path: src/main/java/com/lastcalc/parsers/meta/ImportParser.java import java.io.*; import java.net.*; import java.util.Collection; import com.lastcalc.*; import com.lastcalc.Tokenizer.QuotedString; import com.lastcalc.cache.ObjectCache; import com.lastcalc.parsers.*; package com.lastcalc.parsers.meta; public class ImportParser extends Parser { private static TokenList template = TokenList.createD("import", QuotedString.class); @Override public TokenList getTemplate() { return template; } @Override public ParseResult parse(final TokenList tokens, final int templatePos, final ParserContext context) { if (context.importDepth > 5) return ParseResult.fail(); URL url; try { url = new URL(((QuotedString) tokens.get(templatePos + 1)).value); } catch (final MalformedURLException e) { return ParseResult.fail(); }
CachedImport cached = ObjectCache.getSlow(1000l * 60l * 60l * 24l, url);
sanity/LastCalc
src/main/java/com/lastcalc/parsers/Interpret.java
// Path: src/main/java/com/lastcalc/Tokenizer.java // public static class QuotedString implements Serializable { // private static final long serialVersionUID = 8125107374281852751L; // public final String value; // // public QuotedString(final String value) { // this.value = value; // } // // @Override // public String toString() { // return "\"" + value + "\""; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((value == null) ? 0 : value.hashCode()); // return result; // } // // @Override // public boolean equals(final Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof QuotedString)) // return false; // final QuotedString other = (QuotedString) obj; // if (value == null) { // if (other.value != null) // return false; // } else if (!value.equals(other.value)) // return false; // return true; // } // }
import com.lastcalc.*; import com.lastcalc.Tokenizer.QuotedString;
/******************************************************************************* * LastCalc - The last calculator you'll ever need * Copyright (C) 2011, 2012 Uprizer Labs LLC * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU Affero General Public License for more * details. ******************************************************************************/ package com.lastcalc.parsers; public class Interpret extends Parser { private static final long serialVersionUID = 4507416694168613210L;
// Path: src/main/java/com/lastcalc/Tokenizer.java // public static class QuotedString implements Serializable { // private static final long serialVersionUID = 8125107374281852751L; // public final String value; // // public QuotedString(final String value) { // this.value = value; // } // // @Override // public String toString() { // return "\"" + value + "\""; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((value == null) ? 0 : value.hashCode()); // return result; // } // // @Override // public boolean equals(final Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof QuotedString)) // return false; // final QuotedString other = (QuotedString) obj; // if (value == null) { // if (other.value != null) // return false; // } else if (!value.equals(other.value)) // return false; // return true; // } // } // Path: src/main/java/com/lastcalc/parsers/Interpret.java import com.lastcalc.*; import com.lastcalc.Tokenizer.QuotedString; /******************************************************************************* * LastCalc - The last calculator you'll ever need * Copyright (C) 2011, 2012 Uprizer Labs LLC * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU Affero General Public License for more * details. ******************************************************************************/ package com.lastcalc.parsers; public class Interpret extends Parser { private static final long serialVersionUID = 4507416694168613210L;
private static TokenList template = TokenList.createD("interpret", Tokenizer.QuotedString.class);
sanity/LastCalc
src/main/java/com/lastcalc/parsers/web/HttpRetriever.java
// Path: src/main/java/com/lastcalc/Tokenizer.java // public static class QuotedString implements Serializable { // private static final long serialVersionUID = 8125107374281852751L; // public final String value; // // public QuotedString(final String value) { // this.value = value; // } // // @Override // public String toString() { // return "\"" + value + "\""; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((value == null) ? 0 : value.hashCode()); // return result; // } // // @Override // public boolean equals(final Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof QuotedString)) // return false; // final QuotedString other = (QuotedString) obj; // if (value == null) { // if (other.value != null) // return false; // } else if (!value.equals(other.value)) // return false; // return true; // } // }
import java.io.IOException; import java.net.*; import org.jsoup.Jsoup; import com.lastcalc.*; import com.lastcalc.Tokenizer.QuotedString; import com.lastcalc.cache.*; import com.lastcalc.parsers.*;
/******************************************************************************* * LastCalc - The last calculator you'll ever need * Copyright (C) 2011, 2012 Uprizer Labs LLC * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU Affero General Public License for more * details. ******************************************************************************/ package com.lastcalc.parsers.web; public class HttpRetriever extends Parser { private static final long serialVersionUID = 429169446256736079L;
// Path: src/main/java/com/lastcalc/Tokenizer.java // public static class QuotedString implements Serializable { // private static final long serialVersionUID = 8125107374281852751L; // public final String value; // // public QuotedString(final String value) { // this.value = value; // } // // @Override // public String toString() { // return "\"" + value + "\""; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((value == null) ? 0 : value.hashCode()); // return result; // } // // @Override // public boolean equals(final Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof QuotedString)) // return false; // final QuotedString other = (QuotedString) obj; // if (value == null) { // if (other.value != null) // return false; // } else if (!value.equals(other.value)) // return false; // return true; // } // } // Path: src/main/java/com/lastcalc/parsers/web/HttpRetriever.java import java.io.IOException; import java.net.*; import org.jsoup.Jsoup; import com.lastcalc.*; import com.lastcalc.Tokenizer.QuotedString; import com.lastcalc.cache.*; import com.lastcalc.parsers.*; /******************************************************************************* * LastCalc - The last calculator you'll ever need * Copyright (C) 2011, 2012 Uprizer Labs LLC * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU Affero General Public License for more * details. ******************************************************************************/ package com.lastcalc.parsers.web; public class HttpRetriever extends Parser { private static final long serialVersionUID = 429169446256736079L;
private static TokenList template = TokenList.createD("retrieve", QuotedString.class);
sanity/LastCalc
src/main/java/com/lastcalc/engines/ParserSet.java
// Path: src/main/java/com/lastcalc/parsers/UserDefinedParserParser.java // public static class UserDefinedParser extends Parser { // private static final long serialVersionUID = -4928516936219533258L; // // public final TokenList after; // // private final TokenList template; // // private final TokenList before; // // public final Set<String> variables; // // public UserDefinedParser(final TokenList before, final TokenList after, final Set<String> variables) { // this.before = before; // this.after = after; // this.variables = variables; // final List<Object> tpl = Lists.newArrayList(); // // for (final Object o : before) { // if (variables.contains(o)) { // final String var = (String) o; // if (var.endsWith("List")) { // tpl.add(List.class); // } else if (var.endsWith("Map")) { // tpl.add(Map.class); // } else if (var.endsWith("Num") || var.endsWith("Number")) { // tpl.add(Number.class); // } else if (var.endsWith("Bool") || var.endsWith("Boolean")) { // tpl.add(Boolean.class); // } else if (var.endsWith("Amount")) { // tpl.add(Amount.class); // } else if (var.endsWith("Fun") || var.endsWith("Function")) { // tpl.add(UserDefinedParser.class); // tpl.add(Amount.class); // } else { // tpl.add(Object.class); // } // } else if (o instanceof String) { // tpl.add(o); // } else if (o instanceof MapWithTail || o instanceof Map) { // tpl.add(Map.class); // } else if (o instanceof ListWithTail || o instanceof List) { // tpl.add(List.class); // } else { // tpl.add(o.getClass()); // } // } // template = TokenList.create(tpl); // // } // // @Override // public ParseResult parse(final TokenList tokens, final int templatePos, final ParserContext context) { // if (tokens.get(PreParser.findEdgeOrObjectBackwards(tokens, templatePos, "then")).equals("then")) // return ParseResult.fail(); // // final List<Object> result = Lists.newArrayListWithCapacity(after.size() + 2); // final boolean useBrackets = tokens.size() > template.size(); // if (useBrackets) { // result.add("("); // } // final TokenList input = tokens.subList(templatePos, templatePos + template.size()); // final Map<String, Object> varMap = Maps.newHashMapWithExpectedSize(variables.size()); // try { // bind(before, input, variables, varMap); // for (final Object o : after) { // final Object val = varMap.get(o); // if (val != null) { // result.add(val); // } else { // result.add(o); // } // } // } catch (final BindException e) { // return ParseResult.fail(); // } // if (useBrackets) { // result.add(")"); // } // final TokenList resultTL = TokenList.create(result); // final TokenList flattened = PreParser.flatten(resultTL); // return ParseResult.success( // tokens.replaceWithTokenList(templatePos, templatePos + template.size(), flattened), // Math.min(0, -flattened.size()) // ); // } // // @Override // public TokenList getTemplate() { // return template; // } // // @Override // public String toString() { // return before + " = " + after; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((after == null) ? 0 : after.hashCode()); // result = prime * result + ((before == null) ? 0 : before.hashCode()); // return result; // } // // @Override // public boolean equals(final Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof UserDefinedParser)) // return false; // final UserDefinedParser other = (UserDefinedParser) obj; // if (after == null) { // if (other.after != null) // return false; // } else if (!after.equals(other.after)) // return false; // if (before == null) { // if (other.before != null) // return false; // } else if (!before.equals(other.before)) // return false; // return true; // } // // public boolean hasVariables() { // return !variables.isEmpty(); // } // }
import java.util.*; import com.lastcalc.parsers.*; import com.lastcalc.parsers.UserDefinedParserParser.UserDefinedParser;
package com.lastcalc.engines; /** * A set for parsers where the UserDefinedParser that shortens the token * list most comes first. For use in ParserPickerFactories. * * @author Ian Clarke <ian.clarke@gmail.com> * */ public class ParserSet extends TreeSet<Parser> { private static final long serialVersionUID = -6285593762627218550L; public ParserSet() { super(new Comparator<Parser>() { @Override public int compare(final Parser o1, final Parser o2) {
// Path: src/main/java/com/lastcalc/parsers/UserDefinedParserParser.java // public static class UserDefinedParser extends Parser { // private static final long serialVersionUID = -4928516936219533258L; // // public final TokenList after; // // private final TokenList template; // // private final TokenList before; // // public final Set<String> variables; // // public UserDefinedParser(final TokenList before, final TokenList after, final Set<String> variables) { // this.before = before; // this.after = after; // this.variables = variables; // final List<Object> tpl = Lists.newArrayList(); // // for (final Object o : before) { // if (variables.contains(o)) { // final String var = (String) o; // if (var.endsWith("List")) { // tpl.add(List.class); // } else if (var.endsWith("Map")) { // tpl.add(Map.class); // } else if (var.endsWith("Num") || var.endsWith("Number")) { // tpl.add(Number.class); // } else if (var.endsWith("Bool") || var.endsWith("Boolean")) { // tpl.add(Boolean.class); // } else if (var.endsWith("Amount")) { // tpl.add(Amount.class); // } else if (var.endsWith("Fun") || var.endsWith("Function")) { // tpl.add(UserDefinedParser.class); // tpl.add(Amount.class); // } else { // tpl.add(Object.class); // } // } else if (o instanceof String) { // tpl.add(o); // } else if (o instanceof MapWithTail || o instanceof Map) { // tpl.add(Map.class); // } else if (o instanceof ListWithTail || o instanceof List) { // tpl.add(List.class); // } else { // tpl.add(o.getClass()); // } // } // template = TokenList.create(tpl); // // } // // @Override // public ParseResult parse(final TokenList tokens, final int templatePos, final ParserContext context) { // if (tokens.get(PreParser.findEdgeOrObjectBackwards(tokens, templatePos, "then")).equals("then")) // return ParseResult.fail(); // // final List<Object> result = Lists.newArrayListWithCapacity(after.size() + 2); // final boolean useBrackets = tokens.size() > template.size(); // if (useBrackets) { // result.add("("); // } // final TokenList input = tokens.subList(templatePos, templatePos + template.size()); // final Map<String, Object> varMap = Maps.newHashMapWithExpectedSize(variables.size()); // try { // bind(before, input, variables, varMap); // for (final Object o : after) { // final Object val = varMap.get(o); // if (val != null) { // result.add(val); // } else { // result.add(o); // } // } // } catch (final BindException e) { // return ParseResult.fail(); // } // if (useBrackets) { // result.add(")"); // } // final TokenList resultTL = TokenList.create(result); // final TokenList flattened = PreParser.flatten(resultTL); // return ParseResult.success( // tokens.replaceWithTokenList(templatePos, templatePos + template.size(), flattened), // Math.min(0, -flattened.size()) // ); // } // // @Override // public TokenList getTemplate() { // return template; // } // // @Override // public String toString() { // return before + " = " + after; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((after == null) ? 0 : after.hashCode()); // result = prime * result + ((before == null) ? 0 : before.hashCode()); // return result; // } // // @Override // public boolean equals(final Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (!(obj instanceof UserDefinedParser)) // return false; // final UserDefinedParser other = (UserDefinedParser) obj; // if (after == null) { // if (other.after != null) // return false; // } else if (!after.equals(other.after)) // return false; // if (before == null) { // if (other.before != null) // return false; // } else if (!before.equals(other.before)) // return false; // return true; // } // // public boolean hasVariables() { // return !variables.isEmpty(); // } // } // Path: src/main/java/com/lastcalc/engines/ParserSet.java import java.util.*; import com.lastcalc.parsers.*; import com.lastcalc.parsers.UserDefinedParserParser.UserDefinedParser; package com.lastcalc.engines; /** * A set for parsers where the UserDefinedParser that shortens the token * list most comes first. For use in ParserPickerFactories. * * @author Ian Clarke <ian.clarke@gmail.com> * */ public class ParserSet extends TreeSet<Parser> { private static final long serialVersionUID = -6285593762627218550L; public ParserSet() { super(new Comparator<Parser>() { @Override public int compare(final Parser o1, final Parser o2) {
if (o1 instanceof UserDefinedParser && !(o2 instanceof UserDefinedParser))
shevek/jcpp
src/main/java/org/anarres/cpp/CppReader.java
// Path: src/main/java/org/anarres/cpp/Token.java // public static final int CCOMMENT = 260; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int CPPCOMMENT = 261; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int EOF = 265;
import java.io.Closeable; import java.io.IOException; import java.io.Reader; import javax.annotation.Nonnull; import static org.anarres.cpp.Token.CCOMMENT; import static org.anarres.cpp.Token.CPPCOMMENT; import static org.anarres.cpp.Token.EOF;
/** * Defines the given name as a macro. * * This is a convnience method. */ public void addMacro(@Nonnull String name) throws LexerException { cpp.addMacro(name); } /** * Defines the given name as a macro. * * This is a convnience method. */ public void addMacro(@Nonnull String name, @Nonnull String value) throws LexerException { cpp.addMacro(name, value); } private boolean refill() throws IOException { try { assert cpp != null : "cpp is null : was it closed?"; if (token == null) return false; while (idx >= token.length()) { Token tok = cpp.token(); switch (tok.getType()) {
// Path: src/main/java/org/anarres/cpp/Token.java // public static final int CCOMMENT = 260; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int CPPCOMMENT = 261; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int EOF = 265; // Path: src/main/java/org/anarres/cpp/CppReader.java import java.io.Closeable; import java.io.IOException; import java.io.Reader; import javax.annotation.Nonnull; import static org.anarres.cpp.Token.CCOMMENT; import static org.anarres.cpp.Token.CPPCOMMENT; import static org.anarres.cpp.Token.EOF; /** * Defines the given name as a macro. * * This is a convnience method. */ public void addMacro(@Nonnull String name) throws LexerException { cpp.addMacro(name); } /** * Defines the given name as a macro. * * This is a convnience method. */ public void addMacro(@Nonnull String name, @Nonnull String value) throws LexerException { cpp.addMacro(name, value); } private boolean refill() throws IOException { try { assert cpp != null : "cpp is null : was it closed?"; if (token == null) return false; while (idx >= token.length()) { Token tok = cpp.token(); switch (tok.getType()) {
case EOF:
shevek/jcpp
src/main/java/org/anarres/cpp/CppReader.java
// Path: src/main/java/org/anarres/cpp/Token.java // public static final int CCOMMENT = 260; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int CPPCOMMENT = 261; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int EOF = 265;
import java.io.Closeable; import java.io.IOException; import java.io.Reader; import javax.annotation.Nonnull; import static org.anarres.cpp.Token.CCOMMENT; import static org.anarres.cpp.Token.CPPCOMMENT; import static org.anarres.cpp.Token.EOF;
* * This is a convnience method. */ public void addMacro(@Nonnull String name) throws LexerException { cpp.addMacro(name); } /** * Defines the given name as a macro. * * This is a convnience method. */ public void addMacro(@Nonnull String name, @Nonnull String value) throws LexerException { cpp.addMacro(name, value); } private boolean refill() throws IOException { try { assert cpp != null : "cpp is null : was it closed?"; if (token == null) return false; while (idx >= token.length()) { Token tok = cpp.token(); switch (tok.getType()) { case EOF: token = null; return false;
// Path: src/main/java/org/anarres/cpp/Token.java // public static final int CCOMMENT = 260; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int CPPCOMMENT = 261; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int EOF = 265; // Path: src/main/java/org/anarres/cpp/CppReader.java import java.io.Closeable; import java.io.IOException; import java.io.Reader; import javax.annotation.Nonnull; import static org.anarres.cpp.Token.CCOMMENT; import static org.anarres.cpp.Token.CPPCOMMENT; import static org.anarres.cpp.Token.EOF; * * This is a convnience method. */ public void addMacro(@Nonnull String name) throws LexerException { cpp.addMacro(name); } /** * Defines the given name as a macro. * * This is a convnience method. */ public void addMacro(@Nonnull String name, @Nonnull String value) throws LexerException { cpp.addMacro(name, value); } private boolean refill() throws IOException { try { assert cpp != null : "cpp is null : was it closed?"; if (token == null) return false; while (idx >= token.length()) { Token tok = cpp.token(); switch (tok.getType()) { case EOF: token = null; return false;
case CCOMMENT:
shevek/jcpp
src/main/java/org/anarres/cpp/CppReader.java
// Path: src/main/java/org/anarres/cpp/Token.java // public static final int CCOMMENT = 260; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int CPPCOMMENT = 261; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int EOF = 265;
import java.io.Closeable; import java.io.IOException; import java.io.Reader; import javax.annotation.Nonnull; import static org.anarres.cpp.Token.CCOMMENT; import static org.anarres.cpp.Token.CPPCOMMENT; import static org.anarres.cpp.Token.EOF;
* This is a convnience method. */ public void addMacro(@Nonnull String name) throws LexerException { cpp.addMacro(name); } /** * Defines the given name as a macro. * * This is a convnience method. */ public void addMacro(@Nonnull String name, @Nonnull String value) throws LexerException { cpp.addMacro(name, value); } private boolean refill() throws IOException { try { assert cpp != null : "cpp is null : was it closed?"; if (token == null) return false; while (idx >= token.length()) { Token tok = cpp.token(); switch (tok.getType()) { case EOF: token = null; return false; case CCOMMENT:
// Path: src/main/java/org/anarres/cpp/Token.java // public static final int CCOMMENT = 260; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int CPPCOMMENT = 261; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int EOF = 265; // Path: src/main/java/org/anarres/cpp/CppReader.java import java.io.Closeable; import java.io.IOException; import java.io.Reader; import javax.annotation.Nonnull; import static org.anarres.cpp.Token.CCOMMENT; import static org.anarres.cpp.Token.CPPCOMMENT; import static org.anarres.cpp.Token.EOF; * This is a convnience method. */ public void addMacro(@Nonnull String name) throws LexerException { cpp.addMacro(name); } /** * Defines the given name as a macro. * * This is a convnience method. */ public void addMacro(@Nonnull String name, @Nonnull String value) throws LexerException { cpp.addMacro(name, value); } private boolean refill() throws IOException { try { assert cpp != null : "cpp is null : was it closed?"; if (token == null) return false; while (idx >= token.length()) { Token tok = cpp.token(); switch (tok.getType()) { case EOF: token = null; return false; case CCOMMENT:
case CPPCOMMENT:
shevek/jcpp
src/main/java/org/anarres/cpp/SourceIterator.java
// Path: src/main/java/org/anarres/cpp/Token.java // public static final int EOF = 265;
import java.io.IOException; import java.util.Iterator; import java.util.NoSuchElementException; import javax.annotation.Nonnull; import static org.anarres.cpp.Token.EOF;
/* * Anarres C Preprocessor * Copyright (c) 2007-2015, Shevek * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.anarres.cpp; /** * An Iterator for {@link Source Sources}, * returning {@link Token Tokens}. */ public class SourceIterator implements Iterator<Token> { private final Source source; private Token tok; public SourceIterator(@Nonnull Source s) { this.source = s; this.tok = null; } /** * Rethrows IOException inside IllegalStateException. */ private void advance() { try { if (tok == null) tok = source.token(); } catch (LexerException e) { throw new IllegalStateException(e); } catch (IOException e) { throw new IllegalStateException(e); } } /** * Returns true if the enclosed Source has more tokens. * * The EOF token is never returned by the iterator. * @throws IllegalStateException if the Source * throws a LexerException or IOException */ @Override public boolean hasNext() { advance();
// Path: src/main/java/org/anarres/cpp/Token.java // public static final int EOF = 265; // Path: src/main/java/org/anarres/cpp/SourceIterator.java import java.io.IOException; import java.util.Iterator; import java.util.NoSuchElementException; import javax.annotation.Nonnull; import static org.anarres.cpp.Token.EOF; /* * Anarres C Preprocessor * Copyright (c) 2007-2015, Shevek * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.anarres.cpp; /** * An Iterator for {@link Source Sources}, * returning {@link Token Tokens}. */ public class SourceIterator implements Iterator<Token> { private final Source source; private Token tok; public SourceIterator(@Nonnull Source s) { this.source = s; this.tok = null; } /** * Rethrows IOException inside IllegalStateException. */ private void advance() { try { if (tok == null) tok = source.token(); } catch (LexerException e) { throw new IllegalStateException(e); } catch (IOException e) { throw new IllegalStateException(e); } } /** * Returns true if the enclosed Source has more tokens. * * The EOF token is never returned by the iterator. * @throws IllegalStateException if the Source * throws a LexerException or IOException */ @Override public boolean hasNext() { advance();
return tok.getType() != EOF;
shevek/jcpp
src/main/java/org/anarres/cpp/Source.java
// Path: src/main/java/org/anarres/cpp/Token.java // public static final int CCOMMENT = 260; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int CPPCOMMENT = 261; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int EOF = 265; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int NL = 284; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int WHITESPACE = 294;
import java.io.Closeable; import java.io.IOException; import java.util.Iterator; import javax.annotation.CheckForNull; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import static org.anarres.cpp.Token.CCOMMENT; import static org.anarres.cpp.Token.CPPCOMMENT; import static org.anarres.cpp.Token.EOF; import static org.anarres.cpp.Token.NL; import static org.anarres.cpp.Token.WHITESPACE;
* * @see Token */ @Nonnull public abstract Token token() throws IOException, LexerException; /** * Returns a token iterator for this Source. */ @Override public Iterator<Token> iterator() { return new SourceIterator(this); } /** * Skips tokens until the end of line. * * @param white true if only whitespace is permitted on the * remainder of the line. * @return the NL token. */ @Nonnull public Token skipline(boolean white) throws IOException, LexerException { for (;;) { Token tok = token(); switch (tok.getType()) {
// Path: src/main/java/org/anarres/cpp/Token.java // public static final int CCOMMENT = 260; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int CPPCOMMENT = 261; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int EOF = 265; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int NL = 284; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int WHITESPACE = 294; // Path: src/main/java/org/anarres/cpp/Source.java import java.io.Closeable; import java.io.IOException; import java.util.Iterator; import javax.annotation.CheckForNull; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import static org.anarres.cpp.Token.CCOMMENT; import static org.anarres.cpp.Token.CPPCOMMENT; import static org.anarres.cpp.Token.EOF; import static org.anarres.cpp.Token.NL; import static org.anarres.cpp.Token.WHITESPACE; * * @see Token */ @Nonnull public abstract Token token() throws IOException, LexerException; /** * Returns a token iterator for this Source. */ @Override public Iterator<Token> iterator() { return new SourceIterator(this); } /** * Skips tokens until the end of line. * * @param white true if only whitespace is permitted on the * remainder of the line. * @return the NL token. */ @Nonnull public Token skipline(boolean white) throws IOException, LexerException { for (;;) { Token tok = token(); switch (tok.getType()) {
case EOF:
shevek/jcpp
src/main/java/org/anarres/cpp/Source.java
// Path: src/main/java/org/anarres/cpp/Token.java // public static final int CCOMMENT = 260; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int CPPCOMMENT = 261; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int EOF = 265; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int NL = 284; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int WHITESPACE = 294;
import java.io.Closeable; import java.io.IOException; import java.util.Iterator; import javax.annotation.CheckForNull; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import static org.anarres.cpp.Token.CCOMMENT; import static org.anarres.cpp.Token.CPPCOMMENT; import static org.anarres.cpp.Token.EOF; import static org.anarres.cpp.Token.NL; import static org.anarres.cpp.Token.WHITESPACE;
LexerException; /** * Returns a token iterator for this Source. */ @Override public Iterator<Token> iterator() { return new SourceIterator(this); } /** * Skips tokens until the end of line. * * @param white true if only whitespace is permitted on the * remainder of the line. * @return the NL token. */ @Nonnull public Token skipline(boolean white) throws IOException, LexerException { for (;;) { Token tok = token(); switch (tok.getType()) { case EOF: /* There ought to be a newline before EOF. * At least, in any skipline context. */ /* XXX Are we sure about this? */ warning(tok.getLine(), tok.getColumn(), "No newline before end of file");
// Path: src/main/java/org/anarres/cpp/Token.java // public static final int CCOMMENT = 260; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int CPPCOMMENT = 261; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int EOF = 265; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int NL = 284; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int WHITESPACE = 294; // Path: src/main/java/org/anarres/cpp/Source.java import java.io.Closeable; import java.io.IOException; import java.util.Iterator; import javax.annotation.CheckForNull; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import static org.anarres.cpp.Token.CCOMMENT; import static org.anarres.cpp.Token.CPPCOMMENT; import static org.anarres.cpp.Token.EOF; import static org.anarres.cpp.Token.NL; import static org.anarres.cpp.Token.WHITESPACE; LexerException; /** * Returns a token iterator for this Source. */ @Override public Iterator<Token> iterator() { return new SourceIterator(this); } /** * Skips tokens until the end of line. * * @param white true if only whitespace is permitted on the * remainder of the line. * @return the NL token. */ @Nonnull public Token skipline(boolean white) throws IOException, LexerException { for (;;) { Token tok = token(); switch (tok.getType()) { case EOF: /* There ought to be a newline before EOF. * At least, in any skipline context. */ /* XXX Are we sure about this? */ warning(tok.getLine(), tok.getColumn(), "No newline before end of file");
return new Token(NL,
shevek/jcpp
src/main/java/org/anarres/cpp/Source.java
// Path: src/main/java/org/anarres/cpp/Token.java // public static final int CCOMMENT = 260; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int CPPCOMMENT = 261; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int EOF = 265; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int NL = 284; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int WHITESPACE = 294;
import java.io.Closeable; import java.io.IOException; import java.util.Iterator; import javax.annotation.CheckForNull; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import static org.anarres.cpp.Token.CCOMMENT; import static org.anarres.cpp.Token.CPPCOMMENT; import static org.anarres.cpp.Token.EOF; import static org.anarres.cpp.Token.NL; import static org.anarres.cpp.Token.WHITESPACE;
return new SourceIterator(this); } /** * Skips tokens until the end of line. * * @param white true if only whitespace is permitted on the * remainder of the line. * @return the NL token. */ @Nonnull public Token skipline(boolean white) throws IOException, LexerException { for (;;) { Token tok = token(); switch (tok.getType()) { case EOF: /* There ought to be a newline before EOF. * At least, in any skipline context. */ /* XXX Are we sure about this? */ warning(tok.getLine(), tok.getColumn(), "No newline before end of file"); return new Token(NL, tok.getLine(), tok.getColumn(), "\n"); // return tok; case NL: /* This may contain one or more newlines. */ return tok;
// Path: src/main/java/org/anarres/cpp/Token.java // public static final int CCOMMENT = 260; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int CPPCOMMENT = 261; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int EOF = 265; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int NL = 284; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int WHITESPACE = 294; // Path: src/main/java/org/anarres/cpp/Source.java import java.io.Closeable; import java.io.IOException; import java.util.Iterator; import javax.annotation.CheckForNull; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import static org.anarres.cpp.Token.CCOMMENT; import static org.anarres.cpp.Token.CPPCOMMENT; import static org.anarres.cpp.Token.EOF; import static org.anarres.cpp.Token.NL; import static org.anarres.cpp.Token.WHITESPACE; return new SourceIterator(this); } /** * Skips tokens until the end of line. * * @param white true if only whitespace is permitted on the * remainder of the line. * @return the NL token. */ @Nonnull public Token skipline(boolean white) throws IOException, LexerException { for (;;) { Token tok = token(); switch (tok.getType()) { case EOF: /* There ought to be a newline before EOF. * At least, in any skipline context. */ /* XXX Are we sure about this? */ warning(tok.getLine(), tok.getColumn(), "No newline before end of file"); return new Token(NL, tok.getLine(), tok.getColumn(), "\n"); // return tok; case NL: /* This may contain one or more newlines. */ return tok;
case CCOMMENT:
shevek/jcpp
src/main/java/org/anarres/cpp/Source.java
// Path: src/main/java/org/anarres/cpp/Token.java // public static final int CCOMMENT = 260; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int CPPCOMMENT = 261; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int EOF = 265; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int NL = 284; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int WHITESPACE = 294;
import java.io.Closeable; import java.io.IOException; import java.util.Iterator; import javax.annotation.CheckForNull; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import static org.anarres.cpp.Token.CCOMMENT; import static org.anarres.cpp.Token.CPPCOMMENT; import static org.anarres.cpp.Token.EOF; import static org.anarres.cpp.Token.NL; import static org.anarres.cpp.Token.WHITESPACE;
} /** * Skips tokens until the end of line. * * @param white true if only whitespace is permitted on the * remainder of the line. * @return the NL token. */ @Nonnull public Token skipline(boolean white) throws IOException, LexerException { for (;;) { Token tok = token(); switch (tok.getType()) { case EOF: /* There ought to be a newline before EOF. * At least, in any skipline context. */ /* XXX Are we sure about this? */ warning(tok.getLine(), tok.getColumn(), "No newline before end of file"); return new Token(NL, tok.getLine(), tok.getColumn(), "\n"); // return tok; case NL: /* This may contain one or more newlines. */ return tok; case CCOMMENT:
// Path: src/main/java/org/anarres/cpp/Token.java // public static final int CCOMMENT = 260; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int CPPCOMMENT = 261; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int EOF = 265; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int NL = 284; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int WHITESPACE = 294; // Path: src/main/java/org/anarres/cpp/Source.java import java.io.Closeable; import java.io.IOException; import java.util.Iterator; import javax.annotation.CheckForNull; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import static org.anarres.cpp.Token.CCOMMENT; import static org.anarres.cpp.Token.CPPCOMMENT; import static org.anarres.cpp.Token.EOF; import static org.anarres.cpp.Token.NL; import static org.anarres.cpp.Token.WHITESPACE; } /** * Skips tokens until the end of line. * * @param white true if only whitespace is permitted on the * remainder of the line. * @return the NL token. */ @Nonnull public Token skipline(boolean white) throws IOException, LexerException { for (;;) { Token tok = token(); switch (tok.getType()) { case EOF: /* There ought to be a newline before EOF. * At least, in any skipline context. */ /* XXX Are we sure about this? */ warning(tok.getLine(), tok.getColumn(), "No newline before end of file"); return new Token(NL, tok.getLine(), tok.getColumn(), "\n"); // return tok; case NL: /* This may contain one or more newlines. */ return tok; case CCOMMENT:
case CPPCOMMENT:
shevek/jcpp
src/main/java/org/anarres/cpp/Source.java
// Path: src/main/java/org/anarres/cpp/Token.java // public static final int CCOMMENT = 260; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int CPPCOMMENT = 261; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int EOF = 265; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int NL = 284; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int WHITESPACE = 294;
import java.io.Closeable; import java.io.IOException; import java.util.Iterator; import javax.annotation.CheckForNull; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import static org.anarres.cpp.Token.CCOMMENT; import static org.anarres.cpp.Token.CPPCOMMENT; import static org.anarres.cpp.Token.EOF; import static org.anarres.cpp.Token.NL; import static org.anarres.cpp.Token.WHITESPACE;
/** * Skips tokens until the end of line. * * @param white true if only whitespace is permitted on the * remainder of the line. * @return the NL token. */ @Nonnull public Token skipline(boolean white) throws IOException, LexerException { for (;;) { Token tok = token(); switch (tok.getType()) { case EOF: /* There ought to be a newline before EOF. * At least, in any skipline context. */ /* XXX Are we sure about this? */ warning(tok.getLine(), tok.getColumn(), "No newline before end of file"); return new Token(NL, tok.getLine(), tok.getColumn(), "\n"); // return tok; case NL: /* This may contain one or more newlines. */ return tok; case CCOMMENT: case CPPCOMMENT:
// Path: src/main/java/org/anarres/cpp/Token.java // public static final int CCOMMENT = 260; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int CPPCOMMENT = 261; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int EOF = 265; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int NL = 284; // // Path: src/main/java/org/anarres/cpp/Token.java // public static final int WHITESPACE = 294; // Path: src/main/java/org/anarres/cpp/Source.java import java.io.Closeable; import java.io.IOException; import java.util.Iterator; import javax.annotation.CheckForNull; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import static org.anarres.cpp.Token.CCOMMENT; import static org.anarres.cpp.Token.CPPCOMMENT; import static org.anarres.cpp.Token.EOF; import static org.anarres.cpp.Token.NL; import static org.anarres.cpp.Token.WHITESPACE; /** * Skips tokens until the end of line. * * @param white true if only whitespace is permitted on the * remainder of the line. * @return the NL token. */ @Nonnull public Token skipline(boolean white) throws IOException, LexerException { for (;;) { Token tok = token(); switch (tok.getType()) { case EOF: /* There ought to be a newline before EOF. * At least, in any skipline context. */ /* XXX Are we sure about this? */ warning(tok.getLine(), tok.getColumn(), "No newline before end of file"); return new Token(NL, tok.getLine(), tok.getColumn(), "\n"); // return tok; case NL: /* This may contain one or more newlines. */ return tok; case CCOMMENT: case CPPCOMMENT:
case WHITESPACE:
ivans-innovation-lab/my-company-monolith
src/test/java/com/idugalic/ApplicationIntegrationTest.java
// Path: src/main/java/com/idugalic/commandside/blog/web/CreateBlogPostRequest.java // public class CreateBlogPostRequest { // // @NotNull(message = "Title is mandatory") // @NotBlank(message = "Title is mandatory") // private String title; // @NotNull(message = "rawContent is mandatory") // @NotBlank(message = "rawContent is mandatory") // private String rawContent; // @NotNull(message = "PublicSlug is mandatory") // @NotBlank(message = "PublicSlug is mandatory") // private String publicSlug; // @NotNull // private Boolean draft; // @NotNull // private Boolean broadcast; // @Future(message = "'Publish at' date must be in the future") // @NotNull // private Date publishAt; // @NotNull // private BlogPostCategory category; // // public CreateBlogPostRequest() { // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getRawContent() { // return rawContent; // } // // public void setRawContent(String rawContent) { // this.rawContent = rawContent; // } // // public String getPublicSlug() { // return publicSlug; // } // // public void setPublicSlug(String publicSlug) { // this.publicSlug = publicSlug; // } // // public Boolean getDraft() { // return draft; // } // // public void setDraft(Boolean draft) { // this.draft = draft; // } // // public Boolean getBroadcast() { // return broadcast; // } // // public void setBroadcast(Boolean broadcast) { // this.broadcast = broadcast; // } // // public Date getPublishAt() { // return publishAt; // } // // public void setPublishAt(Date publishAt) { // this.publishAt = publishAt; // } // // public BlogPostCategory getCategory() { // return category; // } // // public void setCategory(BlogPostCategory category) { // this.category = category; // } // // } // // Path: src/main/java/com/idugalic/commandside/project/web/CreateProjectRequest.java // public class CreateProjectRequest { // // private String name; // private String repoUrl; // private String siteUrl; // private String category; // private String description; // // public CreateProjectRequest() { // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getRepoUrl() { // return repoUrl; // } // // public void setRepoUrl(String repoUrl) { // this.repoUrl = repoUrl; // } // // public String getSiteUrl() { // return siteUrl; // } // // public void setSiteUrl(String siteUrl) { // this.siteUrl = siteUrl; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // }
import com.idugalic.commandside.blog.web.CreateBlogPostRequest; import com.idugalic.commandside.project.web.CreateProjectRequest; import com.idugalic.common.blog.model.BlogPostCategory; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext; import org.springframework.security.oauth2.client.OAuth2RestTemplate; import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails; import org.springframework.test.context.junit4.SpringRunner; import java.util.Calendar; import static java.lang.String.format; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat;
package com.idugalic; /** * Integration test for {@link Application} starting on a random port. * * @author idugalic */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class ApplicationIntegrationTest { @Value("${local.server.port}") protected int port; private OAuth2RestTemplate outh2RestTemplate;
// Path: src/main/java/com/idugalic/commandside/blog/web/CreateBlogPostRequest.java // public class CreateBlogPostRequest { // // @NotNull(message = "Title is mandatory") // @NotBlank(message = "Title is mandatory") // private String title; // @NotNull(message = "rawContent is mandatory") // @NotBlank(message = "rawContent is mandatory") // private String rawContent; // @NotNull(message = "PublicSlug is mandatory") // @NotBlank(message = "PublicSlug is mandatory") // private String publicSlug; // @NotNull // private Boolean draft; // @NotNull // private Boolean broadcast; // @Future(message = "'Publish at' date must be in the future") // @NotNull // private Date publishAt; // @NotNull // private BlogPostCategory category; // // public CreateBlogPostRequest() { // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getRawContent() { // return rawContent; // } // // public void setRawContent(String rawContent) { // this.rawContent = rawContent; // } // // public String getPublicSlug() { // return publicSlug; // } // // public void setPublicSlug(String publicSlug) { // this.publicSlug = publicSlug; // } // // public Boolean getDraft() { // return draft; // } // // public void setDraft(Boolean draft) { // this.draft = draft; // } // // public Boolean getBroadcast() { // return broadcast; // } // // public void setBroadcast(Boolean broadcast) { // this.broadcast = broadcast; // } // // public Date getPublishAt() { // return publishAt; // } // // public void setPublishAt(Date publishAt) { // this.publishAt = publishAt; // } // // public BlogPostCategory getCategory() { // return category; // } // // public void setCategory(BlogPostCategory category) { // this.category = category; // } // // } // // Path: src/main/java/com/idugalic/commandside/project/web/CreateProjectRequest.java // public class CreateProjectRequest { // // private String name; // private String repoUrl; // private String siteUrl; // private String category; // private String description; // // public CreateProjectRequest() { // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getRepoUrl() { // return repoUrl; // } // // public void setRepoUrl(String repoUrl) { // this.repoUrl = repoUrl; // } // // public String getSiteUrl() { // return siteUrl; // } // // public void setSiteUrl(String siteUrl) { // this.siteUrl = siteUrl; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // } // Path: src/test/java/com/idugalic/ApplicationIntegrationTest.java import com.idugalic.commandside.blog.web.CreateBlogPostRequest; import com.idugalic.commandside.project.web.CreateProjectRequest; import com.idugalic.common.blog.model.BlogPostCategory; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext; import org.springframework.security.oauth2.client.OAuth2RestTemplate; import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails; import org.springframework.test.context.junit4.SpringRunner; import java.util.Calendar; import static java.lang.String.format; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; package com.idugalic; /** * Integration test for {@link Application} starting on a random port. * * @author idugalic */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class ApplicationIntegrationTest { @Value("${local.server.port}") protected int port; private OAuth2RestTemplate outh2RestTemplate;
private CreateBlogPostRequest createBlogPostRequest;
ivans-innovation-lab/my-company-monolith
src/test/java/com/idugalic/ApplicationIntegrationTest.java
// Path: src/main/java/com/idugalic/commandside/blog/web/CreateBlogPostRequest.java // public class CreateBlogPostRequest { // // @NotNull(message = "Title is mandatory") // @NotBlank(message = "Title is mandatory") // private String title; // @NotNull(message = "rawContent is mandatory") // @NotBlank(message = "rawContent is mandatory") // private String rawContent; // @NotNull(message = "PublicSlug is mandatory") // @NotBlank(message = "PublicSlug is mandatory") // private String publicSlug; // @NotNull // private Boolean draft; // @NotNull // private Boolean broadcast; // @Future(message = "'Publish at' date must be in the future") // @NotNull // private Date publishAt; // @NotNull // private BlogPostCategory category; // // public CreateBlogPostRequest() { // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getRawContent() { // return rawContent; // } // // public void setRawContent(String rawContent) { // this.rawContent = rawContent; // } // // public String getPublicSlug() { // return publicSlug; // } // // public void setPublicSlug(String publicSlug) { // this.publicSlug = publicSlug; // } // // public Boolean getDraft() { // return draft; // } // // public void setDraft(Boolean draft) { // this.draft = draft; // } // // public Boolean getBroadcast() { // return broadcast; // } // // public void setBroadcast(Boolean broadcast) { // this.broadcast = broadcast; // } // // public Date getPublishAt() { // return publishAt; // } // // public void setPublishAt(Date publishAt) { // this.publishAt = publishAt; // } // // public BlogPostCategory getCategory() { // return category; // } // // public void setCategory(BlogPostCategory category) { // this.category = category; // } // // } // // Path: src/main/java/com/idugalic/commandside/project/web/CreateProjectRequest.java // public class CreateProjectRequest { // // private String name; // private String repoUrl; // private String siteUrl; // private String category; // private String description; // // public CreateProjectRequest() { // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getRepoUrl() { // return repoUrl; // } // // public void setRepoUrl(String repoUrl) { // this.repoUrl = repoUrl; // } // // public String getSiteUrl() { // return siteUrl; // } // // public void setSiteUrl(String siteUrl) { // this.siteUrl = siteUrl; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // }
import com.idugalic.commandside.blog.web.CreateBlogPostRequest; import com.idugalic.commandside.project.web.CreateProjectRequest; import com.idugalic.common.blog.model.BlogPostCategory; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext; import org.springframework.security.oauth2.client.OAuth2RestTemplate; import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails; import org.springframework.test.context.junit4.SpringRunner; import java.util.Calendar; import static java.lang.String.format; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat;
package com.idugalic; /** * Integration test for {@link Application} starting on a random port. * * @author idugalic */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class ApplicationIntegrationTest { @Value("${local.server.port}") protected int port; private OAuth2RestTemplate outh2RestTemplate; private CreateBlogPostRequest createBlogPostRequest;
// Path: src/main/java/com/idugalic/commandside/blog/web/CreateBlogPostRequest.java // public class CreateBlogPostRequest { // // @NotNull(message = "Title is mandatory") // @NotBlank(message = "Title is mandatory") // private String title; // @NotNull(message = "rawContent is mandatory") // @NotBlank(message = "rawContent is mandatory") // private String rawContent; // @NotNull(message = "PublicSlug is mandatory") // @NotBlank(message = "PublicSlug is mandatory") // private String publicSlug; // @NotNull // private Boolean draft; // @NotNull // private Boolean broadcast; // @Future(message = "'Publish at' date must be in the future") // @NotNull // private Date publishAt; // @NotNull // private BlogPostCategory category; // // public CreateBlogPostRequest() { // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getRawContent() { // return rawContent; // } // // public void setRawContent(String rawContent) { // this.rawContent = rawContent; // } // // public String getPublicSlug() { // return publicSlug; // } // // public void setPublicSlug(String publicSlug) { // this.publicSlug = publicSlug; // } // // public Boolean getDraft() { // return draft; // } // // public void setDraft(Boolean draft) { // this.draft = draft; // } // // public Boolean getBroadcast() { // return broadcast; // } // // public void setBroadcast(Boolean broadcast) { // this.broadcast = broadcast; // } // // public Date getPublishAt() { // return publishAt; // } // // public void setPublishAt(Date publishAt) { // this.publishAt = publishAt; // } // // public BlogPostCategory getCategory() { // return category; // } // // public void setCategory(BlogPostCategory category) { // this.category = category; // } // // } // // Path: src/main/java/com/idugalic/commandside/project/web/CreateProjectRequest.java // public class CreateProjectRequest { // // private String name; // private String repoUrl; // private String siteUrl; // private String category; // private String description; // // public CreateProjectRequest() { // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getRepoUrl() { // return repoUrl; // } // // public void setRepoUrl(String repoUrl) { // this.repoUrl = repoUrl; // } // // public String getSiteUrl() { // return siteUrl; // } // // public void setSiteUrl(String siteUrl) { // this.siteUrl = siteUrl; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // } // Path: src/test/java/com/idugalic/ApplicationIntegrationTest.java import com.idugalic.commandside.blog.web.CreateBlogPostRequest; import com.idugalic.commandside.project.web.CreateProjectRequest; import com.idugalic.common.blog.model.BlogPostCategory; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext; import org.springframework.security.oauth2.client.OAuth2RestTemplate; import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails; import org.springframework.test.context.junit4.SpringRunner; import java.util.Calendar; import static java.lang.String.format; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; package com.idugalic; /** * Integration test for {@link Application} starting on a random port. * * @author idugalic */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class ApplicationIntegrationTest { @Value("${local.server.port}") protected int port; private OAuth2RestTemplate outh2RestTemplate; private CreateBlogPostRequest createBlogPostRequest;
private CreateProjectRequest createProjectRequest;
ivans-innovation-lab/my-company-monolith
src/main/java/com/idugalic/security/service/impl/MyUserDetailsService.java
// Path: src/main/java/com/idugalic/security/domain/User.java // @Entity // @Table(name = "app_user") // public class User { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "first_name") // private String firstName; // // @Column(name = "last_name") // private String lastName; // // /** // * Roles are being eagerly loaded here because // * they are a fairly small collection of items for this example. // */ // @ManyToMany(fetch = FetchType.EAGER) // @JoinTable(name = "user_role", joinColumns // = @JoinColumn(name = "user_id", // referencedColumnName = "id"), // inverseJoinColumns = @JoinColumn(name = "role_id", // referencedColumnName = "id")) // private List<Role> roles; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public List<Role> getRoles() { // return roles; // } // // public void setRoles(List<Role> roles) { // this.roles = roles; // } // } // // Path: src/main/java/com/idugalic/security/repository/UserRepository.java // @RepositoryRestResource(collectionResourceRel = "users", path = "users") // public interface UserRepository extends CrudRepository<User, Long> { // User findByUsername(String username); // }
import com.idugalic.security.domain.User; import com.idugalic.security.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List;
package com.idugalic.security.service.impl; @Component public class MyUserDetailsService implements UserDetailsService { @Autowired
// Path: src/main/java/com/idugalic/security/domain/User.java // @Entity // @Table(name = "app_user") // public class User { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "first_name") // private String firstName; // // @Column(name = "last_name") // private String lastName; // // /** // * Roles are being eagerly loaded here because // * they are a fairly small collection of items for this example. // */ // @ManyToMany(fetch = FetchType.EAGER) // @JoinTable(name = "user_role", joinColumns // = @JoinColumn(name = "user_id", // referencedColumnName = "id"), // inverseJoinColumns = @JoinColumn(name = "role_id", // referencedColumnName = "id")) // private List<Role> roles; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public List<Role> getRoles() { // return roles; // } // // public void setRoles(List<Role> roles) { // this.roles = roles; // } // } // // Path: src/main/java/com/idugalic/security/repository/UserRepository.java // @RepositoryRestResource(collectionResourceRel = "users", path = "users") // public interface UserRepository extends CrudRepository<User, Long> { // User findByUsername(String username); // } // Path: src/main/java/com/idugalic/security/service/impl/MyUserDetailsService.java import com.idugalic.security.domain.User; import com.idugalic.security.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; package com.idugalic.security.service.impl; @Component public class MyUserDetailsService implements UserDetailsService { @Autowired
private UserRepository userRepository;
ivans-innovation-lab/my-company-monolith
src/main/java/com/idugalic/security/service/impl/MyUserDetailsService.java
// Path: src/main/java/com/idugalic/security/domain/User.java // @Entity // @Table(name = "app_user") // public class User { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "first_name") // private String firstName; // // @Column(name = "last_name") // private String lastName; // // /** // * Roles are being eagerly loaded here because // * they are a fairly small collection of items for this example. // */ // @ManyToMany(fetch = FetchType.EAGER) // @JoinTable(name = "user_role", joinColumns // = @JoinColumn(name = "user_id", // referencedColumnName = "id"), // inverseJoinColumns = @JoinColumn(name = "role_id", // referencedColumnName = "id")) // private List<Role> roles; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public List<Role> getRoles() { // return roles; // } // // public void setRoles(List<Role> roles) { // this.roles = roles; // } // } // // Path: src/main/java/com/idugalic/security/repository/UserRepository.java // @RepositoryRestResource(collectionResourceRel = "users", path = "users") // public interface UserRepository extends CrudRepository<User, Long> { // User findByUsername(String username); // }
import com.idugalic.security.domain.User; import com.idugalic.security.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List;
package com.idugalic.security.service.impl; @Component public class MyUserDetailsService implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
// Path: src/main/java/com/idugalic/security/domain/User.java // @Entity // @Table(name = "app_user") // public class User { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "first_name") // private String firstName; // // @Column(name = "last_name") // private String lastName; // // /** // * Roles are being eagerly loaded here because // * they are a fairly small collection of items for this example. // */ // @ManyToMany(fetch = FetchType.EAGER) // @JoinTable(name = "user_role", joinColumns // = @JoinColumn(name = "user_id", // referencedColumnName = "id"), // inverseJoinColumns = @JoinColumn(name = "role_id", // referencedColumnName = "id")) // private List<Role> roles; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public List<Role> getRoles() { // return roles; // } // // public void setRoles(List<Role> roles) { // this.roles = roles; // } // } // // Path: src/main/java/com/idugalic/security/repository/UserRepository.java // @RepositoryRestResource(collectionResourceRel = "users", path = "users") // public interface UserRepository extends CrudRepository<User, Long> { // User findByUsername(String username); // } // Path: src/main/java/com/idugalic/security/service/impl/MyUserDetailsService.java import com.idugalic.security.domain.User; import com.idugalic.security.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; package com.idugalic.security.service.impl; @Component public class MyUserDetailsService implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
User user = userRepository.findByUsername(s);
ivans-innovation-lab/my-company-monolith
src/main/java/com/idugalic/configuration/RestConfiguration.java
// Path: src/main/java/com/idugalic/security/domain/User.java // @Entity // @Table(name = "app_user") // public class User { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "first_name") // private String firstName; // // @Column(name = "last_name") // private String lastName; // // /** // * Roles are being eagerly loaded here because // * they are a fairly small collection of items for this example. // */ // @ManyToMany(fetch = FetchType.EAGER) // @JoinTable(name = "user_role", joinColumns // = @JoinColumn(name = "user_id", // referencedColumnName = "id"), // inverseJoinColumns = @JoinColumn(name = "role_id", // referencedColumnName = "id")) // private List<Role> roles; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public List<Role> getRoles() { // return roles; // } // // public void setRoles(List<Role> roles) { // this.roles = roles; // } // }
import org.springframework.beans.factory.ObjectFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.core.convert.ConversionService; import org.springframework.data.rest.core.config.RepositoryRestConfiguration; import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter; import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration; import com.idugalic.queryside.blog.domain.BlogPost; import com.idugalic.queryside.project.domain.Project; import com.idugalic.queryside.team.domain.Member; import com.idugalic.queryside.team.domain.Team; import com.idugalic.security.domain.User;
package com.idugalic.configuration; /** * A configuration of rest data respositories for {@link BlogPost} and * {@link Project}. * * @author idugalic * */ @Configuration public class RestConfiguration extends RepositoryRestMvcConfiguration { public RestConfiguration(ApplicationContext context, ObjectFactory<ConversionService> conversionService) { super(context, conversionService); } @Configuration static class RestConfigurationExposeId extends RepositoryRestConfigurerAdapter { @Override public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
// Path: src/main/java/com/idugalic/security/domain/User.java // @Entity // @Table(name = "app_user") // public class User { // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column(name = "id") // private Long id; // // @Column(name = "username") // private String username; // // @Column(name = "password") // private String password; // // @Column(name = "first_name") // private String firstName; // // @Column(name = "last_name") // private String lastName; // // /** // * Roles are being eagerly loaded here because // * they are a fairly small collection of items for this example. // */ // @ManyToMany(fetch = FetchType.EAGER) // @JoinTable(name = "user_role", joinColumns // = @JoinColumn(name = "user_id", // referencedColumnName = "id"), // inverseJoinColumns = @JoinColumn(name = "role_id", // referencedColumnName = "id")) // private List<Role> roles; // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public List<Role> getRoles() { // return roles; // } // // public void setRoles(List<Role> roles) { // this.roles = roles; // } // } // Path: src/main/java/com/idugalic/configuration/RestConfiguration.java import org.springframework.beans.factory.ObjectFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.core.convert.ConversionService; import org.springframework.data.rest.core.config.RepositoryRestConfiguration; import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter; import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration; import com.idugalic.queryside.blog.domain.BlogPost; import com.idugalic.queryside.project.domain.Project; import com.idugalic.queryside.team.domain.Member; import com.idugalic.queryside.team.domain.Team; import com.idugalic.security.domain.User; package com.idugalic.configuration; /** * A configuration of rest data respositories for {@link BlogPost} and * {@link Project}. * * @author idugalic * */ @Configuration public class RestConfiguration extends RepositoryRestMvcConfiguration { public RestConfiguration(ApplicationContext context, ObjectFactory<ConversionService> conversionService) { super(context, conversionService); } @Configuration static class RestConfigurationExposeId extends RepositoryRestConfigurerAdapter { @Override public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.exposeIdsFor(BlogPost.class, Project.class, Team.class, Member.class, User.class);
schibsted/triathlon
src/test/java/com/schibsted/triathlon/main/TriathlonRouterTest.java
// Path: src/main/java/com/schibsted/triathlon/service/impl/TriathlonEndpointImpl.java // public class TriathlonEndpointImpl implements TriathlonEndpoint { // // private static final Logger LOGGER = LoggerFactory.getLogger(TriathlonEndpointImpl.class); // private static TriathlonService triathlonService; // // public TriathlonEndpointImpl() { // Injector injector = Guice.createInjector(new TriathlonModule()); // triathlonService = injector.getInstance(TriathlonService.class); // } // // /** // * This endpoint will forward the post data to the selected marathon server. // * // * TODO: Move logic from here // * // * @param request // * @param response // * @return response to be send to the caller // */ // @Override // public Observable<Void> postApps(HttpServerRequest<ByteBuf> request, HttpServerResponse<ByteBuf> response) { // return triathlonService.parseJson(request.getContent()) // .flatMap(this::matchDataCenter) // .flatMap(content -> { // response.write(content); // return response.close(); // }) // .onErrorResumeNext(throwable -> { // LOGGER.info("Service ERROR"); // response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR); // return response.close(); // }) // .doOnCompleted(() -> response.close(true)); // } // // /** // * Try to find the datacenter specified in the field `datacenter` of the constraints on the info obtained // * from the marathons subscribed on Eureka2. // * If a match is found, build and return {@link MarathonCommand} to // * @param appDefinition object used to serialize the json document // * @return // */ // private Observable<ByteBuf> matchDataCenter(Marathon appDefinition) { // try { // return Observable.from(appDefinition.getConstraints()) // .map(constraint -> { // ConstraintModel cm = null; // try { // cm = ConstraintModel.createConstraintModel(constraint); // } catch (Exception e) { // e.printStackTrace(); // } // return cm; // }) // .filter(constraint -> constraint.getField().equals("datacenter")) // .flatMap(constraint -> { // return this.runConstraint(constraint, appDefinition); // }); // } catch (Exception e) { // LOGGER.error("matchDataCenter error: ", e); // return Observable.error(e); // } // } // // private Observable<ByteBuf> runConstraint(ConstraintModel constraint, Marathon appDefinition) { // return OperatorFactory.build(constraint).apply(appDefinition); // } // }
import com.google.common.collect.Lists; import com.schibsted.triathlon.service.impl.TriathlonEndpointImpl; import io.netty.channel.local.LocalChannel; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; import io.reactivex.netty.protocol.http.server.HttpRequestHeaders; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import netflix.karyon.transport.http.health.HealthCheckEndpoint; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import rx.Observable; import java.util.HashMap; import java.util.List; import java.util.Set; import static org.mockito.Matchers.any; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.*;
/* * Copyright (c) 2015 Schibsted Products and Technology * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.schibsted.triathlon.main; public class TriathlonRouterTest { private HttpServerRequest request; private HttpServerResponse response;
// Path: src/main/java/com/schibsted/triathlon/service/impl/TriathlonEndpointImpl.java // public class TriathlonEndpointImpl implements TriathlonEndpoint { // // private static final Logger LOGGER = LoggerFactory.getLogger(TriathlonEndpointImpl.class); // private static TriathlonService triathlonService; // // public TriathlonEndpointImpl() { // Injector injector = Guice.createInjector(new TriathlonModule()); // triathlonService = injector.getInstance(TriathlonService.class); // } // // /** // * This endpoint will forward the post data to the selected marathon server. // * // * TODO: Move logic from here // * // * @param request // * @param response // * @return response to be send to the caller // */ // @Override // public Observable<Void> postApps(HttpServerRequest<ByteBuf> request, HttpServerResponse<ByteBuf> response) { // return triathlonService.parseJson(request.getContent()) // .flatMap(this::matchDataCenter) // .flatMap(content -> { // response.write(content); // return response.close(); // }) // .onErrorResumeNext(throwable -> { // LOGGER.info("Service ERROR"); // response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR); // return response.close(); // }) // .doOnCompleted(() -> response.close(true)); // } // // /** // * Try to find the datacenter specified in the field `datacenter` of the constraints on the info obtained // * from the marathons subscribed on Eureka2. // * If a match is found, build and return {@link MarathonCommand} to // * @param appDefinition object used to serialize the json document // * @return // */ // private Observable<ByteBuf> matchDataCenter(Marathon appDefinition) { // try { // return Observable.from(appDefinition.getConstraints()) // .map(constraint -> { // ConstraintModel cm = null; // try { // cm = ConstraintModel.createConstraintModel(constraint); // } catch (Exception e) { // e.printStackTrace(); // } // return cm; // }) // .filter(constraint -> constraint.getField().equals("datacenter")) // .flatMap(constraint -> { // return this.runConstraint(constraint, appDefinition); // }); // } catch (Exception e) { // LOGGER.error("matchDataCenter error: ", e); // return Observable.error(e); // } // } // // private Observable<ByteBuf> runConstraint(ConstraintModel constraint, Marathon appDefinition) { // return OperatorFactory.build(constraint).apply(appDefinition); // } // } // Path: src/test/java/com/schibsted/triathlon/main/TriathlonRouterTest.java import com.google.common.collect.Lists; import com.schibsted.triathlon.service.impl.TriathlonEndpointImpl; import io.netty.channel.local.LocalChannel; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; import io.reactivex.netty.protocol.http.server.HttpRequestHeaders; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import netflix.karyon.transport.http.health.HealthCheckEndpoint; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import rx.Observable; import java.util.HashMap; import java.util.List; import java.util.Set; import static org.mockito.Matchers.any; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.*; /* * Copyright (c) 2015 Schibsted Products and Technology * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.schibsted.triathlon.main; public class TriathlonRouterTest { private HttpServerRequest request; private HttpServerResponse response;
private TriathlonEndpointImpl triathlonEndpoint;
schibsted/triathlon
src/main/java/com/schibsted/triathlon/service/TriathlonModule.java
// Path: src/main/java/com/schibsted/triathlon/service/discovery/EurekaService.java // public interface EurekaService { // public void shutdown(); // public Observable<ChangeNotification<InstanceInfo>> subscribeToInterest(String interest); // } // // Path: src/main/java/com/schibsted/triathlon/service/discovery/EurekaServiceImpl.java // public class EurekaServiceImpl implements EurekaService { // // private static final Logger LOGGER = LoggerFactory.getLogger(TriathlonEndpointImpl.class); // // public static final InstanceInfo TRIATHLON = new InstanceInfo.Builder() // .withId("triathlon") // .withApp("Triathlon") // .withAppGroup("Triathlon_1") // .withStatus(InstanceInfo.Status.UP) // .withDataCenterInfo(BasicDataCenterInfo.fromSystemData()) // .build(); // // private final String writeServerHostname; // private final int writeServerRegistrationPort; // private final int writeServerInterestPort; // private final String readServerVip; // // private Subscription subscription; // EurekaRegistrationClient registrationClient; // EurekaInterestClient interestClient; // // /** // * Register the application with Eureka2 // * TODO: Remove this logic from the constructor // */ // public EurekaServiceImpl() { // writeServerHostname = DynamicPropertyFactory.getInstance().getStringProperty("triathlon.writeServerHostname", "localhost").get(); // writeServerRegistrationPort = DynamicPropertyFactory.getInstance().getIntProperty("triathlon.writeServerRegistrationPort", 12102).get(); // writeServerInterestPort = DynamicPropertyFactory.getInstance().getIntProperty("triathlon.writeServerInterestPort", 12103).get(); // readServerVip = DynamicPropertyFactory.getInstance().getStringProperty("triathlon.readServerVip", "eureka-read-cluster").get(); // // registrationClient = Eurekas.newRegistrationClientBuilder() // .withServerResolver(fromHostname(writeServerHostname).withPort(writeServerRegistrationPort)) // .build(); // // BehaviorSubject<InstanceInfo> infoSubject = BehaviorSubject.create(); // subscription = registrationClient.register(infoSubject).subscribe(); // // LOGGER.info("Registering application"); // infoSubject.onNext(TRIATHLON); // // ServerResolver interestClientResolver = // fromEureka( // fromHostname(writeServerHostname).withPort(writeServerInterestPort) // ).forInterest(forVips(readServerVip)); // // interestClient = Eurekas.newInterestClientBuilder() // .withServerResolver(interestClientResolver) // .build(); // } // // /** // * Perform some cleanup tasks. // * TODO: Find a way to run on server shutdown // */ // @Override // public void shutdown() { // subscription.unsubscribe(); // // // Terminate both clients. // LOGGER.info("Shutting down clients"); // registrationClient.shutdown(); // interestClient.shutdown(); // // } // // /** // * Subscribe to an Eureka2 interest // * // * @param interest a regular expression for the interest (i.e. "marathon.*") // * @return // */ // @Override // public Observable<ChangeNotification<InstanceInfo>> subscribeToInterest(String interest) { // LOGGER.info("Subscribing to interest: " + interest); // return interestClient.forInterest(forApplications(Interest.Operator.Like, interest)) // .filter(cn -> cn.getKind().equals(ChangeNotification.Kind.Add)); // } // }
import com.google.inject.AbstractModule; import com.schibsted.triathlon.service.discovery.EurekaService; import com.schibsted.triathlon.service.discovery.EurekaServiceImpl;
/* * Copyright (c) 2015 Schibsted Products and Technology * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.schibsted.triathlon.service; /** * @author Albert Manyà */ public class TriathlonModule extends AbstractModule { @Override protected void configure() { bind(TriathlonService.class).to(TriathlonServiceImpl.class);
// Path: src/main/java/com/schibsted/triathlon/service/discovery/EurekaService.java // public interface EurekaService { // public void shutdown(); // public Observable<ChangeNotification<InstanceInfo>> subscribeToInterest(String interest); // } // // Path: src/main/java/com/schibsted/triathlon/service/discovery/EurekaServiceImpl.java // public class EurekaServiceImpl implements EurekaService { // // private static final Logger LOGGER = LoggerFactory.getLogger(TriathlonEndpointImpl.class); // // public static final InstanceInfo TRIATHLON = new InstanceInfo.Builder() // .withId("triathlon") // .withApp("Triathlon") // .withAppGroup("Triathlon_1") // .withStatus(InstanceInfo.Status.UP) // .withDataCenterInfo(BasicDataCenterInfo.fromSystemData()) // .build(); // // private final String writeServerHostname; // private final int writeServerRegistrationPort; // private final int writeServerInterestPort; // private final String readServerVip; // // private Subscription subscription; // EurekaRegistrationClient registrationClient; // EurekaInterestClient interestClient; // // /** // * Register the application with Eureka2 // * TODO: Remove this logic from the constructor // */ // public EurekaServiceImpl() { // writeServerHostname = DynamicPropertyFactory.getInstance().getStringProperty("triathlon.writeServerHostname", "localhost").get(); // writeServerRegistrationPort = DynamicPropertyFactory.getInstance().getIntProperty("triathlon.writeServerRegistrationPort", 12102).get(); // writeServerInterestPort = DynamicPropertyFactory.getInstance().getIntProperty("triathlon.writeServerInterestPort", 12103).get(); // readServerVip = DynamicPropertyFactory.getInstance().getStringProperty("triathlon.readServerVip", "eureka-read-cluster").get(); // // registrationClient = Eurekas.newRegistrationClientBuilder() // .withServerResolver(fromHostname(writeServerHostname).withPort(writeServerRegistrationPort)) // .build(); // // BehaviorSubject<InstanceInfo> infoSubject = BehaviorSubject.create(); // subscription = registrationClient.register(infoSubject).subscribe(); // // LOGGER.info("Registering application"); // infoSubject.onNext(TRIATHLON); // // ServerResolver interestClientResolver = // fromEureka( // fromHostname(writeServerHostname).withPort(writeServerInterestPort) // ).forInterest(forVips(readServerVip)); // // interestClient = Eurekas.newInterestClientBuilder() // .withServerResolver(interestClientResolver) // .build(); // } // // /** // * Perform some cleanup tasks. // * TODO: Find a way to run on server shutdown // */ // @Override // public void shutdown() { // subscription.unsubscribe(); // // // Terminate both clients. // LOGGER.info("Shutting down clients"); // registrationClient.shutdown(); // interestClient.shutdown(); // // } // // /** // * Subscribe to an Eureka2 interest // * // * @param interest a regular expression for the interest (i.e. "marathon.*") // * @return // */ // @Override // public Observable<ChangeNotification<InstanceInfo>> subscribeToInterest(String interest) { // LOGGER.info("Subscribing to interest: " + interest); // return interestClient.forInterest(forApplications(Interest.Operator.Like, interest)) // .filter(cn -> cn.getKind().equals(ChangeNotification.Kind.Add)); // } // } // Path: src/main/java/com/schibsted/triathlon/service/TriathlonModule.java import com.google.inject.AbstractModule; import com.schibsted.triathlon.service.discovery.EurekaService; import com.schibsted.triathlon.service.discovery.EurekaServiceImpl; /* * Copyright (c) 2015 Schibsted Products and Technology * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.schibsted.triathlon.service; /** * @author Albert Manyà */ public class TriathlonModule extends AbstractModule { @Override protected void configure() { bind(TriathlonService.class).to(TriathlonServiceImpl.class);
bind(EurekaService.class).to(EurekaServiceImpl.class);
schibsted/triathlon
src/main/java/com/schibsted/triathlon/service/TriathlonModule.java
// Path: src/main/java/com/schibsted/triathlon/service/discovery/EurekaService.java // public interface EurekaService { // public void shutdown(); // public Observable<ChangeNotification<InstanceInfo>> subscribeToInterest(String interest); // } // // Path: src/main/java/com/schibsted/triathlon/service/discovery/EurekaServiceImpl.java // public class EurekaServiceImpl implements EurekaService { // // private static final Logger LOGGER = LoggerFactory.getLogger(TriathlonEndpointImpl.class); // // public static final InstanceInfo TRIATHLON = new InstanceInfo.Builder() // .withId("triathlon") // .withApp("Triathlon") // .withAppGroup("Triathlon_1") // .withStatus(InstanceInfo.Status.UP) // .withDataCenterInfo(BasicDataCenterInfo.fromSystemData()) // .build(); // // private final String writeServerHostname; // private final int writeServerRegistrationPort; // private final int writeServerInterestPort; // private final String readServerVip; // // private Subscription subscription; // EurekaRegistrationClient registrationClient; // EurekaInterestClient interestClient; // // /** // * Register the application with Eureka2 // * TODO: Remove this logic from the constructor // */ // public EurekaServiceImpl() { // writeServerHostname = DynamicPropertyFactory.getInstance().getStringProperty("triathlon.writeServerHostname", "localhost").get(); // writeServerRegistrationPort = DynamicPropertyFactory.getInstance().getIntProperty("triathlon.writeServerRegistrationPort", 12102).get(); // writeServerInterestPort = DynamicPropertyFactory.getInstance().getIntProperty("triathlon.writeServerInterestPort", 12103).get(); // readServerVip = DynamicPropertyFactory.getInstance().getStringProperty("triathlon.readServerVip", "eureka-read-cluster").get(); // // registrationClient = Eurekas.newRegistrationClientBuilder() // .withServerResolver(fromHostname(writeServerHostname).withPort(writeServerRegistrationPort)) // .build(); // // BehaviorSubject<InstanceInfo> infoSubject = BehaviorSubject.create(); // subscription = registrationClient.register(infoSubject).subscribe(); // // LOGGER.info("Registering application"); // infoSubject.onNext(TRIATHLON); // // ServerResolver interestClientResolver = // fromEureka( // fromHostname(writeServerHostname).withPort(writeServerInterestPort) // ).forInterest(forVips(readServerVip)); // // interestClient = Eurekas.newInterestClientBuilder() // .withServerResolver(interestClientResolver) // .build(); // } // // /** // * Perform some cleanup tasks. // * TODO: Find a way to run on server shutdown // */ // @Override // public void shutdown() { // subscription.unsubscribe(); // // // Terminate both clients. // LOGGER.info("Shutting down clients"); // registrationClient.shutdown(); // interestClient.shutdown(); // // } // // /** // * Subscribe to an Eureka2 interest // * // * @param interest a regular expression for the interest (i.e. "marathon.*") // * @return // */ // @Override // public Observable<ChangeNotification<InstanceInfo>> subscribeToInterest(String interest) { // LOGGER.info("Subscribing to interest: " + interest); // return interestClient.forInterest(forApplications(Interest.Operator.Like, interest)) // .filter(cn -> cn.getKind().equals(ChangeNotification.Kind.Add)); // } // }
import com.google.inject.AbstractModule; import com.schibsted.triathlon.service.discovery.EurekaService; import com.schibsted.triathlon.service.discovery.EurekaServiceImpl;
/* * Copyright (c) 2015 Schibsted Products and Technology * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.schibsted.triathlon.service; /** * @author Albert Manyà */ public class TriathlonModule extends AbstractModule { @Override protected void configure() { bind(TriathlonService.class).to(TriathlonServiceImpl.class);
// Path: src/main/java/com/schibsted/triathlon/service/discovery/EurekaService.java // public interface EurekaService { // public void shutdown(); // public Observable<ChangeNotification<InstanceInfo>> subscribeToInterest(String interest); // } // // Path: src/main/java/com/schibsted/triathlon/service/discovery/EurekaServiceImpl.java // public class EurekaServiceImpl implements EurekaService { // // private static final Logger LOGGER = LoggerFactory.getLogger(TriathlonEndpointImpl.class); // // public static final InstanceInfo TRIATHLON = new InstanceInfo.Builder() // .withId("triathlon") // .withApp("Triathlon") // .withAppGroup("Triathlon_1") // .withStatus(InstanceInfo.Status.UP) // .withDataCenterInfo(BasicDataCenterInfo.fromSystemData()) // .build(); // // private final String writeServerHostname; // private final int writeServerRegistrationPort; // private final int writeServerInterestPort; // private final String readServerVip; // // private Subscription subscription; // EurekaRegistrationClient registrationClient; // EurekaInterestClient interestClient; // // /** // * Register the application with Eureka2 // * TODO: Remove this logic from the constructor // */ // public EurekaServiceImpl() { // writeServerHostname = DynamicPropertyFactory.getInstance().getStringProperty("triathlon.writeServerHostname", "localhost").get(); // writeServerRegistrationPort = DynamicPropertyFactory.getInstance().getIntProperty("triathlon.writeServerRegistrationPort", 12102).get(); // writeServerInterestPort = DynamicPropertyFactory.getInstance().getIntProperty("triathlon.writeServerInterestPort", 12103).get(); // readServerVip = DynamicPropertyFactory.getInstance().getStringProperty("triathlon.readServerVip", "eureka-read-cluster").get(); // // registrationClient = Eurekas.newRegistrationClientBuilder() // .withServerResolver(fromHostname(writeServerHostname).withPort(writeServerRegistrationPort)) // .build(); // // BehaviorSubject<InstanceInfo> infoSubject = BehaviorSubject.create(); // subscription = registrationClient.register(infoSubject).subscribe(); // // LOGGER.info("Registering application"); // infoSubject.onNext(TRIATHLON); // // ServerResolver interestClientResolver = // fromEureka( // fromHostname(writeServerHostname).withPort(writeServerInterestPort) // ).forInterest(forVips(readServerVip)); // // interestClient = Eurekas.newInterestClientBuilder() // .withServerResolver(interestClientResolver) // .build(); // } // // /** // * Perform some cleanup tasks. // * TODO: Find a way to run on server shutdown // */ // @Override // public void shutdown() { // subscription.unsubscribe(); // // // Terminate both clients. // LOGGER.info("Shutting down clients"); // registrationClient.shutdown(); // interestClient.shutdown(); // // } // // /** // * Subscribe to an Eureka2 interest // * // * @param interest a regular expression for the interest (i.e. "marathon.*") // * @return // */ // @Override // public Observable<ChangeNotification<InstanceInfo>> subscribeToInterest(String interest) { // LOGGER.info("Subscribing to interest: " + interest); // return interestClient.forInterest(forApplications(Interest.Operator.Like, interest)) // .filter(cn -> cn.getKind().equals(ChangeNotification.Kind.Add)); // } // } // Path: src/main/java/com/schibsted/triathlon/service/TriathlonModule.java import com.google.inject.AbstractModule; import com.schibsted.triathlon.service.discovery.EurekaService; import com.schibsted.triathlon.service.discovery.EurekaServiceImpl; /* * Copyright (c) 2015 Schibsted Products and Technology * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.schibsted.triathlon.service; /** * @author Albert Manyà */ public class TriathlonModule extends AbstractModule { @Override protected void configure() { bind(TriathlonService.class).to(TriathlonServiceImpl.class);
bind(EurekaService.class).to(EurekaServiceImpl.class);
schibsted/triathlon
src/test/java/com/schibsted/triathlon/service/InstanceInfoModelTest.java
// Path: src/main/java/com/schibsted/triathlon/model/InstanceInfoModel.java // public class InstanceInfoModel { // private static HashMap<String, InstanceInfo> instanceInfo = new HashMap<>(); // private static final Logger LOGGER = LoggerFactory.getLogger(InstanceInfoModel.class); // // public static void clear() { // // Added for cleaning the class for tests // // p.s. god forgive me // instanceInfo = new HashMap<>(); // } // // /** // * Stores {@link ChangeNotification} from Eureka2. // * // * @param cn // */ // public synchronized static void interestSubscriber(ChangeNotification<InstanceInfo> cn) { // String id = cn.getData().getId(); // // instanceInfo.put(id, cn.getData()); // } // // /** // * Return the stored information. // * // * @return // */ // public synchronized static HashMap<String, InstanceInfo> getInstanceInfo() { // return instanceInfo; // } // // }
import com.netflix.eureka2.interests.ChangeNotification; import com.netflix.eureka2.registry.datacenter.BasicDataCenterInfo; import com.netflix.eureka2.registry.datacenter.DataCenterInfo; import com.netflix.eureka2.registry.instance.InstanceInfo; import com.netflix.eureka2.registry.instance.NetworkAddress; import com.schibsted.triathlon.model.InstanceInfoModel; import org.junit.Test; import java.util.Collections; import java.util.List;
/* * Copyright (c) 2015 Schibsted Products and Technology * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.schibsted.triathlon.service; /** * Created by amanya on 07/08/15 */ public class InstanceInfoModelTest { @Test public void testInterestSubscriber() throws Exception { List<NetworkAddress> na = Collections.singletonList(new NetworkAddress("public", NetworkAddress.ProtocolType.IPv4, "192.168.0.1", "myHost")); DataCenterInfo myDataCenter = new BasicDataCenterInfo("TestDataCenter", na); InstanceInfo ii = new InstanceInfo.Builder() .withId("testDataCenterInfo") .withDataCenterInfo(myDataCenter) .build(); ChangeNotification<InstanceInfo> cn = new ChangeNotification<>(ChangeNotification.Kind.Add, ii);
// Path: src/main/java/com/schibsted/triathlon/model/InstanceInfoModel.java // public class InstanceInfoModel { // private static HashMap<String, InstanceInfo> instanceInfo = new HashMap<>(); // private static final Logger LOGGER = LoggerFactory.getLogger(InstanceInfoModel.class); // // public static void clear() { // // Added for cleaning the class for tests // // p.s. god forgive me // instanceInfo = new HashMap<>(); // } // // /** // * Stores {@link ChangeNotification} from Eureka2. // * // * @param cn // */ // public synchronized static void interestSubscriber(ChangeNotification<InstanceInfo> cn) { // String id = cn.getData().getId(); // // instanceInfo.put(id, cn.getData()); // } // // /** // * Return the stored information. // * // * @return // */ // public synchronized static HashMap<String, InstanceInfo> getInstanceInfo() { // return instanceInfo; // } // // } // Path: src/test/java/com/schibsted/triathlon/service/InstanceInfoModelTest.java import com.netflix.eureka2.interests.ChangeNotification; import com.netflix.eureka2.registry.datacenter.BasicDataCenterInfo; import com.netflix.eureka2.registry.datacenter.DataCenterInfo; import com.netflix.eureka2.registry.instance.InstanceInfo; import com.netflix.eureka2.registry.instance.NetworkAddress; import com.schibsted.triathlon.model.InstanceInfoModel; import org.junit.Test; import java.util.Collections; import java.util.List; /* * Copyright (c) 2015 Schibsted Products and Technology * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.schibsted.triathlon.service; /** * Created by amanya on 07/08/15 */ public class InstanceInfoModelTest { @Test public void testInterestSubscriber() throws Exception { List<NetworkAddress> na = Collections.singletonList(new NetworkAddress("public", NetworkAddress.ProtocolType.IPv4, "192.168.0.1", "myHost")); DataCenterInfo myDataCenter = new BasicDataCenterInfo("TestDataCenter", na); InstanceInfo ii = new InstanceInfo.Builder() .withId("testDataCenterInfo") .withDataCenterInfo(myDataCenter) .build(); ChangeNotification<InstanceInfo> cn = new ChangeNotification<>(ChangeNotification.Kind.Add, ii);
InstanceInfoModel.interestSubscriber(cn);
schibsted/triathlon
src/test/java/com/schibsted/triathlon/service/commands/MarathonCommandTest.java
// Path: src/test/java/com/schibsted/triathlon/service/RxTestServer.java // public class RxTestServer { // public static final int DEFAULT_PORT = 8088; // // private final int port; // // private HttpServer<ByteBuf, ByteBuf> server; // // public RxTestServer(int port) { // this.port = port; // } // // public HttpServer<ByteBuf, ByteBuf> createServer() { // HttpServer<ByteBuf, ByteBuf> server = RxNetty.newHttpServerBuilder(port, new RequestHandler<ByteBuf, ByteBuf>() { // @Override // public Observable<Void> handle(HttpServerRequest<ByteBuf> request, final HttpServerResponse<ByteBuf> response) { // if (request.getPath().contains("/v2/apps")) { // if (request.getHttpMethod().equals(HttpMethod.POST)) { // return handleTest(request, response); // } // } // response.setStatus(HttpResponseStatus.NOT_FOUND); // return response.close(); // } // }).pipelineConfigurator(PipelineConfigurators.<ByteBuf, ByteBuf>httpServerConfigurator()).enableWireLogging(LogLevel.ERROR).build(); // // System.out.println("RxTetstServer server started..."); // return server; // } // // private Observable<Void> handleTest(HttpServerRequest<ByteBuf> request, final HttpServerResponse<ByteBuf> response) { // response.setStatus(HttpResponseStatus.OK); // // ByteBuf byteBuf = UnpooledByteBufAllocator.DEFAULT.buffer(); // byteBuf.writeBytes("test".getBytes(Charset.defaultCharset())); // // response.write(byteBuf); // return response.close(); // } // // public void start(){ // server = createServer(); // server.start(); // } // // public void shutdown(){ // try { // server.shutdown(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // // public static void main(final String[] args) { // new RxTestServer(DEFAULT_PORT).createServer().startAndWait(); // } // // }
import com.netflix.eureka2.registry.datacenter.BasicDataCenterInfo; import com.netflix.eureka2.registry.datacenter.DataCenterInfo; import com.netflix.eureka2.registry.instance.InstanceInfo; import com.netflix.eureka2.registry.instance.NetworkAddress; import com.netflix.eureka2.registry.instance.ServicePort; import com.schibsted.triathlon.service.RxTestServer; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpResponseStatus; import io.reactivex.netty.RxNetty; import io.reactivex.netty.protocol.http.AbstractHttpContentHolder; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import io.reactivex.netty.protocol.http.client.HttpClientResponse; import io.reactivex.netty.protocol.http.server.HttpServer; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import io.reactivex.netty.protocol.http.server.RequestHandler; import io.reactivex.netty.server.RxServer; import netflix.karyon.transport.http.SimpleUriRouter; import org.junit.After; import org.junit.Before; import org.junit.Test; import rx.Observable; import java.nio.charset.Charset; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; import static rx.Observable.using;
/* * Copyright (c) 2015 Schibsted Products and Technology * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.schibsted.triathlon.service.commands; /** * @author Albert Manyà */ public class MarathonCommandTest { private InstanceInfo ii;
// Path: src/test/java/com/schibsted/triathlon/service/RxTestServer.java // public class RxTestServer { // public static final int DEFAULT_PORT = 8088; // // private final int port; // // private HttpServer<ByteBuf, ByteBuf> server; // // public RxTestServer(int port) { // this.port = port; // } // // public HttpServer<ByteBuf, ByteBuf> createServer() { // HttpServer<ByteBuf, ByteBuf> server = RxNetty.newHttpServerBuilder(port, new RequestHandler<ByteBuf, ByteBuf>() { // @Override // public Observable<Void> handle(HttpServerRequest<ByteBuf> request, final HttpServerResponse<ByteBuf> response) { // if (request.getPath().contains("/v2/apps")) { // if (request.getHttpMethod().equals(HttpMethod.POST)) { // return handleTest(request, response); // } // } // response.setStatus(HttpResponseStatus.NOT_FOUND); // return response.close(); // } // }).pipelineConfigurator(PipelineConfigurators.<ByteBuf, ByteBuf>httpServerConfigurator()).enableWireLogging(LogLevel.ERROR).build(); // // System.out.println("RxTetstServer server started..."); // return server; // } // // private Observable<Void> handleTest(HttpServerRequest<ByteBuf> request, final HttpServerResponse<ByteBuf> response) { // response.setStatus(HttpResponseStatus.OK); // // ByteBuf byteBuf = UnpooledByteBufAllocator.DEFAULT.buffer(); // byteBuf.writeBytes("test".getBytes(Charset.defaultCharset())); // // response.write(byteBuf); // return response.close(); // } // // public void start(){ // server = createServer(); // server.start(); // } // // public void shutdown(){ // try { // server.shutdown(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // // public static void main(final String[] args) { // new RxTestServer(DEFAULT_PORT).createServer().startAndWait(); // } // // } // Path: src/test/java/com/schibsted/triathlon/service/commands/MarathonCommandTest.java import com.netflix.eureka2.registry.datacenter.BasicDataCenterInfo; import com.netflix.eureka2.registry.datacenter.DataCenterInfo; import com.netflix.eureka2.registry.instance.InstanceInfo; import com.netflix.eureka2.registry.instance.NetworkAddress; import com.netflix.eureka2.registry.instance.ServicePort; import com.schibsted.triathlon.service.RxTestServer; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpResponseStatus; import io.reactivex.netty.RxNetty; import io.reactivex.netty.protocol.http.AbstractHttpContentHolder; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import io.reactivex.netty.protocol.http.client.HttpClientResponse; import io.reactivex.netty.protocol.http.server.HttpServer; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import io.reactivex.netty.protocol.http.server.RequestHandler; import io.reactivex.netty.server.RxServer; import netflix.karyon.transport.http.SimpleUriRouter; import org.junit.After; import org.junit.Before; import org.junit.Test; import rx.Observable; import java.nio.charset.Charset; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; import static rx.Observable.using; /* * Copyright (c) 2015 Schibsted Products and Technology * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.schibsted.triathlon.service.commands; /** * @author Albert Manyà */ public class MarathonCommandTest { private InstanceInfo ii;
private static RxTestServer testServer = new RxTestServer(8088);
schibsted/triathlon
src/main/java/com/schibsted/triathlon/operators/OperatorFactory.java
// Path: src/main/java/com/schibsted/triathlon/model/ConstraintModel.java // public class ConstraintModel { // static List<String> VALID_OPERATORS = new ArrayList<String>() {{ // add("UNIQUE"); // add("CLUSTER"); // add("GROUP_BY"); // add("LIKE"); // add("UNLIKE"); // }}; // // public String getField() { // return field; // } // // public String getOperator() { // return operator; // } // // public String getParameter() { // return parameter; // } // // private final String field; // private final String operator; // private final String parameter; // // private ConstraintModel(List<String> constraint) { // String param = null; // this.field = constraint.get(0); // this.operator = constraint.get(1); // if (constraint.size() == 3) { // param = constraint.get(2); // } // this.parameter = param; // } // // public static ConstraintModel createConstraintModel(List<String> constraint) throws Exception { // if (!validateConstraint(constraint)) { // throw new Exception("Invalid constraint"); // } // return new ConstraintModel(constraint); // } // // private static boolean validateConstraint(List<String> constraint) { // return !(constraint.size() < 2 || constraint.size() > 3) && VALID_OPERATORS.contains(constraint.get(1)); // } // } // // Path: src/main/java/com/schibsted/triathlon/service/TriathlonModule.java // public class TriathlonModule extends AbstractModule { // @Override // protected void configure() { // bind(TriathlonService.class).to(TriathlonServiceImpl.class); // bind(EurekaService.class).to(EurekaServiceImpl.class); // } // } // // Path: src/main/java/com/schibsted/triathlon/service/TriathlonService.java // public interface TriathlonService { // public Observable<Marathon> parseJson(Observable<ByteBuf> byteBufs); // public String serializeMarathon(Marathon marathon) throws IOException; // }
import com.google.inject.Guice; import com.google.inject.Injector; import com.schibsted.triathlon.model.ConstraintModel; import com.schibsted.triathlon.service.TriathlonModule; import com.schibsted.triathlon.service.TriathlonService;
/* * Copyright (c) 2015 Schibsted Products and Technology * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.schibsted.triathlon.operators; /** * @author Albert Manyà */ public class OperatorFactory { private static TriathlonService triathlonService;
// Path: src/main/java/com/schibsted/triathlon/model/ConstraintModel.java // public class ConstraintModel { // static List<String> VALID_OPERATORS = new ArrayList<String>() {{ // add("UNIQUE"); // add("CLUSTER"); // add("GROUP_BY"); // add("LIKE"); // add("UNLIKE"); // }}; // // public String getField() { // return field; // } // // public String getOperator() { // return operator; // } // // public String getParameter() { // return parameter; // } // // private final String field; // private final String operator; // private final String parameter; // // private ConstraintModel(List<String> constraint) { // String param = null; // this.field = constraint.get(0); // this.operator = constraint.get(1); // if (constraint.size() == 3) { // param = constraint.get(2); // } // this.parameter = param; // } // // public static ConstraintModel createConstraintModel(List<String> constraint) throws Exception { // if (!validateConstraint(constraint)) { // throw new Exception("Invalid constraint"); // } // return new ConstraintModel(constraint); // } // // private static boolean validateConstraint(List<String> constraint) { // return !(constraint.size() < 2 || constraint.size() > 3) && VALID_OPERATORS.contains(constraint.get(1)); // } // } // // Path: src/main/java/com/schibsted/triathlon/service/TriathlonModule.java // public class TriathlonModule extends AbstractModule { // @Override // protected void configure() { // bind(TriathlonService.class).to(TriathlonServiceImpl.class); // bind(EurekaService.class).to(EurekaServiceImpl.class); // } // } // // Path: src/main/java/com/schibsted/triathlon/service/TriathlonService.java // public interface TriathlonService { // public Observable<Marathon> parseJson(Observable<ByteBuf> byteBufs); // public String serializeMarathon(Marathon marathon) throws IOException; // } // Path: src/main/java/com/schibsted/triathlon/operators/OperatorFactory.java import com.google.inject.Guice; import com.google.inject.Injector; import com.schibsted.triathlon.model.ConstraintModel; import com.schibsted.triathlon.service.TriathlonModule; import com.schibsted.triathlon.service.TriathlonService; /* * Copyright (c) 2015 Schibsted Products and Technology * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.schibsted.triathlon.operators; /** * @author Albert Manyà */ public class OperatorFactory { private static TriathlonService triathlonService;
public static Operator build(ConstraintModel constraint) {
schibsted/triathlon
src/main/java/com/schibsted/triathlon/operators/OperatorFactory.java
// Path: src/main/java/com/schibsted/triathlon/model/ConstraintModel.java // public class ConstraintModel { // static List<String> VALID_OPERATORS = new ArrayList<String>() {{ // add("UNIQUE"); // add("CLUSTER"); // add("GROUP_BY"); // add("LIKE"); // add("UNLIKE"); // }}; // // public String getField() { // return field; // } // // public String getOperator() { // return operator; // } // // public String getParameter() { // return parameter; // } // // private final String field; // private final String operator; // private final String parameter; // // private ConstraintModel(List<String> constraint) { // String param = null; // this.field = constraint.get(0); // this.operator = constraint.get(1); // if (constraint.size() == 3) { // param = constraint.get(2); // } // this.parameter = param; // } // // public static ConstraintModel createConstraintModel(List<String> constraint) throws Exception { // if (!validateConstraint(constraint)) { // throw new Exception("Invalid constraint"); // } // return new ConstraintModel(constraint); // } // // private static boolean validateConstraint(List<String> constraint) { // return !(constraint.size() < 2 || constraint.size() > 3) && VALID_OPERATORS.contains(constraint.get(1)); // } // } // // Path: src/main/java/com/schibsted/triathlon/service/TriathlonModule.java // public class TriathlonModule extends AbstractModule { // @Override // protected void configure() { // bind(TriathlonService.class).to(TriathlonServiceImpl.class); // bind(EurekaService.class).to(EurekaServiceImpl.class); // } // } // // Path: src/main/java/com/schibsted/triathlon/service/TriathlonService.java // public interface TriathlonService { // public Observable<Marathon> parseJson(Observable<ByteBuf> byteBufs); // public String serializeMarathon(Marathon marathon) throws IOException; // }
import com.google.inject.Guice; import com.google.inject.Injector; import com.schibsted.triathlon.model.ConstraintModel; import com.schibsted.triathlon.service.TriathlonModule; import com.schibsted.triathlon.service.TriathlonService;
/* * Copyright (c) 2015 Schibsted Products and Technology * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.schibsted.triathlon.operators; /** * @author Albert Manyà */ public class OperatorFactory { private static TriathlonService triathlonService; public static Operator build(ConstraintModel constraint) {
// Path: src/main/java/com/schibsted/triathlon/model/ConstraintModel.java // public class ConstraintModel { // static List<String> VALID_OPERATORS = new ArrayList<String>() {{ // add("UNIQUE"); // add("CLUSTER"); // add("GROUP_BY"); // add("LIKE"); // add("UNLIKE"); // }}; // // public String getField() { // return field; // } // // public String getOperator() { // return operator; // } // // public String getParameter() { // return parameter; // } // // private final String field; // private final String operator; // private final String parameter; // // private ConstraintModel(List<String> constraint) { // String param = null; // this.field = constraint.get(0); // this.operator = constraint.get(1); // if (constraint.size() == 3) { // param = constraint.get(2); // } // this.parameter = param; // } // // public static ConstraintModel createConstraintModel(List<String> constraint) throws Exception { // if (!validateConstraint(constraint)) { // throw new Exception("Invalid constraint"); // } // return new ConstraintModel(constraint); // } // // private static boolean validateConstraint(List<String> constraint) { // return !(constraint.size() < 2 || constraint.size() > 3) && VALID_OPERATORS.contains(constraint.get(1)); // } // } // // Path: src/main/java/com/schibsted/triathlon/service/TriathlonModule.java // public class TriathlonModule extends AbstractModule { // @Override // protected void configure() { // bind(TriathlonService.class).to(TriathlonServiceImpl.class); // bind(EurekaService.class).to(EurekaServiceImpl.class); // } // } // // Path: src/main/java/com/schibsted/triathlon/service/TriathlonService.java // public interface TriathlonService { // public Observable<Marathon> parseJson(Observable<ByteBuf> byteBufs); // public String serializeMarathon(Marathon marathon) throws IOException; // } // Path: src/main/java/com/schibsted/triathlon/operators/OperatorFactory.java import com.google.inject.Guice; import com.google.inject.Injector; import com.schibsted.triathlon.model.ConstraintModel; import com.schibsted.triathlon.service.TriathlonModule; import com.schibsted.triathlon.service.TriathlonService; /* * Copyright (c) 2015 Schibsted Products and Technology * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.schibsted.triathlon.operators; /** * @author Albert Manyà */ public class OperatorFactory { private static TriathlonService triathlonService; public static Operator build(ConstraintModel constraint) {
Injector injector = Guice.createInjector(new TriathlonModule());
schibsted/triathlon
src/main/java/com/schibsted/triathlon/main/TriathlonRouter.java
// Path: src/main/java/com/schibsted/triathlon/service/impl/TriathlonEndpointImpl.java // public class TriathlonEndpointImpl implements TriathlonEndpoint { // // private static final Logger LOGGER = LoggerFactory.getLogger(TriathlonEndpointImpl.class); // private static TriathlonService triathlonService; // // public TriathlonEndpointImpl() { // Injector injector = Guice.createInjector(new TriathlonModule()); // triathlonService = injector.getInstance(TriathlonService.class); // } // // /** // * This endpoint will forward the post data to the selected marathon server. // * // * TODO: Move logic from here // * // * @param request // * @param response // * @return response to be send to the caller // */ // @Override // public Observable<Void> postApps(HttpServerRequest<ByteBuf> request, HttpServerResponse<ByteBuf> response) { // return triathlonService.parseJson(request.getContent()) // .flatMap(this::matchDataCenter) // .flatMap(content -> { // response.write(content); // return response.close(); // }) // .onErrorResumeNext(throwable -> { // LOGGER.info("Service ERROR"); // response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR); // return response.close(); // }) // .doOnCompleted(() -> response.close(true)); // } // // /** // * Try to find the datacenter specified in the field `datacenter` of the constraints on the info obtained // * from the marathons subscribed on Eureka2. // * If a match is found, build and return {@link MarathonCommand} to // * @param appDefinition object used to serialize the json document // * @return // */ // private Observable<ByteBuf> matchDataCenter(Marathon appDefinition) { // try { // return Observable.from(appDefinition.getConstraints()) // .map(constraint -> { // ConstraintModel cm = null; // try { // cm = ConstraintModel.createConstraintModel(constraint); // } catch (Exception e) { // e.printStackTrace(); // } // return cm; // }) // .filter(constraint -> constraint.getField().equals("datacenter")) // .flatMap(constraint -> { // return this.runConstraint(constraint, appDefinition); // }); // } catch (Exception e) { // LOGGER.error("matchDataCenter error: ", e); // return Observable.error(e); // } // } // // private Observable<ByteBuf> runConstraint(ConstraintModel constraint, Marathon appDefinition) { // return OperatorFactory.build(constraint).apply(appDefinition); // } // }
import com.schibsted.triathlon.service.impl.TriathlonEndpointImpl; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpMethod; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import io.reactivex.netty.protocol.http.server.RequestHandler; import netflix.karyon.transport.http.SimpleUriRouter; import netflix.karyon.transport.http.health.HealthCheckEndpoint; import rx.Observable;
/* * Copyright (c) 2015 Schibsted Products and Technology * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.schibsted.triathlon.main; /** * A {@link RequestHandler} implementation for Triathlon. */ public class TriathlonRouter implements RequestHandler<ByteBuf, ByteBuf> { private final SimpleUriRouter<ByteBuf, ByteBuf> delegate;
// Path: src/main/java/com/schibsted/triathlon/service/impl/TriathlonEndpointImpl.java // public class TriathlonEndpointImpl implements TriathlonEndpoint { // // private static final Logger LOGGER = LoggerFactory.getLogger(TriathlonEndpointImpl.class); // private static TriathlonService triathlonService; // // public TriathlonEndpointImpl() { // Injector injector = Guice.createInjector(new TriathlonModule()); // triathlonService = injector.getInstance(TriathlonService.class); // } // // /** // * This endpoint will forward the post data to the selected marathon server. // * // * TODO: Move logic from here // * // * @param request // * @param response // * @return response to be send to the caller // */ // @Override // public Observable<Void> postApps(HttpServerRequest<ByteBuf> request, HttpServerResponse<ByteBuf> response) { // return triathlonService.parseJson(request.getContent()) // .flatMap(this::matchDataCenter) // .flatMap(content -> { // response.write(content); // return response.close(); // }) // .onErrorResumeNext(throwable -> { // LOGGER.info("Service ERROR"); // response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR); // return response.close(); // }) // .doOnCompleted(() -> response.close(true)); // } // // /** // * Try to find the datacenter specified in the field `datacenter` of the constraints on the info obtained // * from the marathons subscribed on Eureka2. // * If a match is found, build and return {@link MarathonCommand} to // * @param appDefinition object used to serialize the json document // * @return // */ // private Observable<ByteBuf> matchDataCenter(Marathon appDefinition) { // try { // return Observable.from(appDefinition.getConstraints()) // .map(constraint -> { // ConstraintModel cm = null; // try { // cm = ConstraintModel.createConstraintModel(constraint); // } catch (Exception e) { // e.printStackTrace(); // } // return cm; // }) // .filter(constraint -> constraint.getField().equals("datacenter")) // .flatMap(constraint -> { // return this.runConstraint(constraint, appDefinition); // }); // } catch (Exception e) { // LOGGER.error("matchDataCenter error: ", e); // return Observable.error(e); // } // } // // private Observable<ByteBuf> runConstraint(ConstraintModel constraint, Marathon appDefinition) { // return OperatorFactory.build(constraint).apply(appDefinition); // } // } // Path: src/main/java/com/schibsted/triathlon/main/TriathlonRouter.java import com.schibsted.triathlon.service.impl.TriathlonEndpointImpl; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpMethod; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import io.reactivex.netty.protocol.http.server.RequestHandler; import netflix.karyon.transport.http.SimpleUriRouter; import netflix.karyon.transport.http.health.HealthCheckEndpoint; import rx.Observable; /* * Copyright (c) 2015 Schibsted Products and Technology * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.schibsted.triathlon.main; /** * A {@link RequestHandler} implementation for Triathlon. */ public class TriathlonRouter implements RequestHandler<ByteBuf, ByteBuf> { private final SimpleUriRouter<ByteBuf, ByteBuf> delegate;
public TriathlonRouter(HealthCheckEndpoint healthCheckEndpoint, TriathlonEndpointImpl triathlonEndpoint) {
conveyal/gtfs-editor
app/models/transit/Route.java
// Path: app/models/transit/RouteType.java // public class RouteType extends Model implements Serializable { // public static final long serialVersionUID = 1; // // public String localizedVehicleType; // public String description; // // public GtfsRouteType gtfsRouteType; // // public HvtRouteType hvtRouteType; // // /* // @JsonCreator // public static RouteType factory(long id) { // return RouteType.findById(id); // } // // @JsonCreator // public static RouteType factory(String id) { // return RouteType.findById(Long.parseLong(id)); // } // */ // // // }
import java.io.Serializable; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import models.Model; import models.transit.RouteType; import org.hibernate.annotations.Type; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.vividsolutions.jts.geom.MultiLineString; import datastore.AgencyTx; import datastore.GlobalTx; import play.Logger;
package models.transit; public class Route extends Model implements Cloneable, Serializable { public static final long serialVersionUID = 1; public String gtfsRouteId; public String routeShortName; public String routeLongName; public String routeDesc; public String routeTypeId; public String routeUrl; public String routeColor; public String routeTextColor; // Custom Fields public String comments; public StatusType status; public Boolean publiclyVisible; public String agencyId; //public GisRoute gisRoute; //public GisUpload gisUpload; public AttributeAvailabilityType wheelchairBoarding; /** on which days does this route have service? Derived from calendars on render */ public transient Boolean monday, tuesday, wednesday, thursday, friday, saturday, sunday; // add getters so Jackson will serialize @JsonProperty("monday") public Boolean jsonGetMonday() { return monday; } @JsonProperty("tuesday") public Boolean jsonGetTuesday() { return tuesday; } @JsonProperty("wednesday") public Boolean jsonGetWednesday() { return wednesday; } @JsonProperty("thursday") public Boolean jsonGetThursday() { return thursday; } @JsonProperty("friday") public Boolean jsonGetFriday() { return friday; } @JsonProperty("saturday") public Boolean jsonGetSaturday() { return saturday; } @JsonProperty("sunday") public Boolean jsonGetSunday() { return sunday; } public Route () {} public Route(com.conveyal.gtfs.model.Route route, Agency agency, String routeTypeId) { this.gtfsRouteId = route.route_id; this.routeShortName = route.route_short_name; this.routeLongName = route.route_long_name; this.routeDesc = route.route_desc; this.routeTypeId = routeTypeId; this.routeUrl = route.route_url != null ? route.route_url.toString() : null; this.routeColor = route.route_color; this.routeTextColor = route.route_text_color; this.agencyId = agency.id; }
// Path: app/models/transit/RouteType.java // public class RouteType extends Model implements Serializable { // public static final long serialVersionUID = 1; // // public String localizedVehicleType; // public String description; // // public GtfsRouteType gtfsRouteType; // // public HvtRouteType hvtRouteType; // // /* // @JsonCreator // public static RouteType factory(long id) { // return RouteType.findById(id); // } // // @JsonCreator // public static RouteType factory(String id) { // return RouteType.findById(Long.parseLong(id)); // } // */ // // // } // Path: app/models/transit/Route.java import java.io.Serializable; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import models.Model; import models.transit.RouteType; import org.hibernate.annotations.Type; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.vividsolutions.jts.geom.MultiLineString; import datastore.AgencyTx; import datastore.GlobalTx; import play.Logger; package models.transit; public class Route extends Model implements Cloneable, Serializable { public static final long serialVersionUID = 1; public String gtfsRouteId; public String routeShortName; public String routeLongName; public String routeDesc; public String routeTypeId; public String routeUrl; public String routeColor; public String routeTextColor; // Custom Fields public String comments; public StatusType status; public Boolean publiclyVisible; public String agencyId; //public GisRoute gisRoute; //public GisUpload gisUpload; public AttributeAvailabilityType wheelchairBoarding; /** on which days does this route have service? Derived from calendars on render */ public transient Boolean monday, tuesday, wednesday, thursday, friday, saturday, sunday; // add getters so Jackson will serialize @JsonProperty("monday") public Boolean jsonGetMonday() { return monday; } @JsonProperty("tuesday") public Boolean jsonGetTuesday() { return tuesday; } @JsonProperty("wednesday") public Boolean jsonGetWednesday() { return wednesday; } @JsonProperty("thursday") public Boolean jsonGetThursday() { return thursday; } @JsonProperty("friday") public Boolean jsonGetFriday() { return friday; } @JsonProperty("saturday") public Boolean jsonGetSaturday() { return saturday; } @JsonProperty("sunday") public Boolean jsonGetSunday() { return sunday; } public Route () {} public Route(com.conveyal.gtfs.model.Route route, Agency agency, String routeTypeId) { this.gtfsRouteId = route.route_id; this.routeShortName = route.route_short_name; this.routeLongName = route.route_long_name; this.routeDesc = route.route_desc; this.routeTypeId = routeTypeId; this.routeUrl = route.route_url != null ? route.route_url.toString() : null; this.routeColor = route.route_color; this.routeTextColor = route.route_text_color; this.agencyId = agency.id; }
public Route(String routeShortName, String routeLongName, RouteType routeType, String routeDescription, Agency agency) {
hehonghui/simpledb
database/src/main/java/com/simple/database/upgrade/SqlParser.java
// Path: database/src/main/java/com/simple/database/utils/IOUtils.java // public final class IOUtils { // // /** // * 关闭Closeable对象 // * @param closeable 要关闭的closeable // */ // public static void closeSilently(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (Exception e) { // e.printStackTrace(); // } // } // } // // /** // * 关闭cursor对象, 在api 16之前Cursor对象没有实现 Closeable 接口 !!!! // * @param cursor 要关闭的cursor // */ // public static void closeCursor(Cursor cursor) { // if (cursor != null) { // try { // cursor.close(); // } catch (Exception e) { // e.printStackTrace(); // } // } // } // }
import com.simple.database.utils.IOUtils; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List;
} else if (state == STATE_NONE && tokenizer.skip("--")) { state = STATE_COMMENT; continue; } else if (state == STATE_NONE && c == ';') { final String command = sb.toString().trim(); commands.add(command); sb.setLength(0); continue; } else if (state == STATE_NONE && c == '\'') { state = STATE_STRING; } else if (state == STATE_STRING && c == '\'') { state = STATE_NONE; } if (state == STATE_NONE || state == STATE_STRING) { if (state == STATE_NONE && isWhitespace(c)) { if (sb.length() > 0 && sb.charAt(sb.length() - 1) != ' ') { sb.append(' '); } } else { sb.append(c); } } } } finally {
// Path: database/src/main/java/com/simple/database/utils/IOUtils.java // public final class IOUtils { // // /** // * 关闭Closeable对象 // * @param closeable 要关闭的closeable // */ // public static void closeSilently(Closeable closeable) { // if (closeable != null) { // try { // closeable.close(); // } catch (Exception e) { // e.printStackTrace(); // } // } // } // // /** // * 关闭cursor对象, 在api 16之前Cursor对象没有实现 Closeable 接口 !!!! // * @param cursor 要关闭的cursor // */ // public static void closeCursor(Cursor cursor) { // if (cursor != null) { // try { // cursor.close(); // } catch (Exception e) { // e.printStackTrace(); // } // } // } // } // Path: database/src/main/java/com/simple/database/upgrade/SqlParser.java import com.simple.database.utils.IOUtils; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; } else if (state == STATE_NONE && tokenizer.skip("--")) { state = STATE_COMMENT; continue; } else if (state == STATE_NONE && c == ';') { final String command = sb.toString().trim(); commands.add(command); sb.setLength(0); continue; } else if (state == STATE_NONE && c == '\'') { state = STATE_STRING; } else if (state == STATE_STRING && c == '\'') { state = STATE_NONE; } if (state == STATE_NONE || state == STATE_STRING) { if (state == STATE_NONE && isWhitespace(c)) { if (sb.length() > 0 && sb.charAt(sb.length() - 1) != ' ') { sb.append(' '); } } else { sb.append(c); } } } } finally {
IOUtils.closeSilently(buffer);
hehonghui/simpledb
database/src/main/java/com/simple/database/crud/QueryBuilder.java
// Path: database/src/main/java/com/simple/database/crud/base/WhereBuilder.java // public abstract class WhereBuilder<T> extends BaseSQLBuilder<T> { // protected String selection = null; // protected String[] selectionArgs = null; // // /** // * @param daoClass 同步的dao类,用于构建异步的dao类 // */ // public WhereBuilder(Class daoClass) { // super(daoClass); // } // // /** // * where 查询条件 // * // * @param selection // * @param selectionArgs // * @return // */ // public WhereBuilder where(String selection, String[] selectionArgs) { // this.selection = selection; // this.selectionArgs = selectionArgs; // return this; // } // } // // Path: database/src/main/java/com/simple/database/listeners/DbListener.java // public interface DbListener<T> { // void onComplete(T result); // }
import com.simple.database.crud.base.WhereBuilder; import com.simple.database.listeners.DbListener; import java.util.List;
package com.simple.database.crud; /** * 查询数据的Builder, 能设置 where 、orderBy、limit参数. * * @param <T> 要返回的数据类型 */ public class QueryBuilder<T> extends WhereBuilder { private String orderBy = null; private String limit = null;
// Path: database/src/main/java/com/simple/database/crud/base/WhereBuilder.java // public abstract class WhereBuilder<T> extends BaseSQLBuilder<T> { // protected String selection = null; // protected String[] selectionArgs = null; // // /** // * @param daoClass 同步的dao类,用于构建异步的dao类 // */ // public WhereBuilder(Class daoClass) { // super(daoClass); // } // // /** // * where 查询条件 // * // * @param selection // * @param selectionArgs // * @return // */ // public WhereBuilder where(String selection, String[] selectionArgs) { // this.selection = selection; // this.selectionArgs = selectionArgs; // return this; // } // } // // Path: database/src/main/java/com/simple/database/listeners/DbListener.java // public interface DbListener<T> { // void onComplete(T result); // } // Path: database/src/main/java/com/simple/database/crud/QueryBuilder.java import com.simple.database.crud.base.WhereBuilder; import com.simple.database.listeners.DbListener; import java.util.List; package com.simple.database.crud; /** * 查询数据的Builder, 能设置 where 、orderBy、limit参数. * * @param <T> 要返回的数据类型 */ public class QueryBuilder<T> extends WhereBuilder { private String orderBy = null; private String limit = null;
private DbListener<List<T>> mDbListListener;
hehonghui/simpledb
app/src/main/java/com/simple/simpledatabase/model/BookModel.java
// Path: database/src/main/java/com/simple/database/listeners/DbListener.java // public interface DbListener<T> { // void onComplete(T result); // } // // Path: app/src/main/java/com/simple/simpledatabase/dao/BookDao.java // public class BookDao extends AbsDAO<Book> { // // public BookDao() { // super("books"); // } // // @Override // protected ContentValues convert(Book item) { // ContentValues newValues = new ContentValues(); // newValues.put("id", item.id); // newValues.put("name", item.name); // return newValues; // } // // // @Override // protected Book parseOneItem(Cursor cursor) { // Book item = new Book(); // item.id = cursor.getString(0); // item.name = cursor.getString(1) ; // return item; // } // // } // // Path: app/src/main/java/com/simple/simpledatabase/domain/Book.java // public class Book { // public String id ; // public String name ; // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> DeleteBuilder<T> deleteFrom(Class<? extends AbsDAO<T>> daoClass) { // return new DeleteBuilder<>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> InsertBuilder<T> insertInto(Class<? extends AbsDAO<T>> daoClass) { // return new InsertBuilder<T>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> QueryBuilder<T> selectFrom(Class<? extends AbsDAO<T>> daoClass) { // return new QueryBuilder<>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> UpdateBuilder<T> updateFrom(Class<? extends AbsDAO<T>> daoClass) { // return new UpdateBuilder<>(daoClass); // }
import com.simple.database.listeners.DbListener; import com.simple.simpledatabase.dao.BookDao; import com.simple.simpledatabase.domain.Book; import java.util.List; import static com.simple.database.DatabaseHelper.deleteFrom; import static com.simple.database.DatabaseHelper.insertInto; import static com.simple.database.DatabaseHelper.selectFrom; import static com.simple.database.DatabaseHelper.updateFrom;
package com.simple.simpledatabase.model; /** * 接口使用 * Created by mrsimple on 13/8/16. */ public class BookModel { /** * 插入数据 * * @param aBook */ public void insertBook(Book aBook) {
// Path: database/src/main/java/com/simple/database/listeners/DbListener.java // public interface DbListener<T> { // void onComplete(T result); // } // // Path: app/src/main/java/com/simple/simpledatabase/dao/BookDao.java // public class BookDao extends AbsDAO<Book> { // // public BookDao() { // super("books"); // } // // @Override // protected ContentValues convert(Book item) { // ContentValues newValues = new ContentValues(); // newValues.put("id", item.id); // newValues.put("name", item.name); // return newValues; // } // // // @Override // protected Book parseOneItem(Cursor cursor) { // Book item = new Book(); // item.id = cursor.getString(0); // item.name = cursor.getString(1) ; // return item; // } // // } // // Path: app/src/main/java/com/simple/simpledatabase/domain/Book.java // public class Book { // public String id ; // public String name ; // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> DeleteBuilder<T> deleteFrom(Class<? extends AbsDAO<T>> daoClass) { // return new DeleteBuilder<>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> InsertBuilder<T> insertInto(Class<? extends AbsDAO<T>> daoClass) { // return new InsertBuilder<T>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> QueryBuilder<T> selectFrom(Class<? extends AbsDAO<T>> daoClass) { // return new QueryBuilder<>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> UpdateBuilder<T> updateFrom(Class<? extends AbsDAO<T>> daoClass) { // return new UpdateBuilder<>(daoClass); // } // Path: app/src/main/java/com/simple/simpledatabase/model/BookModel.java import com.simple.database.listeners.DbListener; import com.simple.simpledatabase.dao.BookDao; import com.simple.simpledatabase.domain.Book; import java.util.List; import static com.simple.database.DatabaseHelper.deleteFrom; import static com.simple.database.DatabaseHelper.insertInto; import static com.simple.database.DatabaseHelper.selectFrom; import static com.simple.database.DatabaseHelper.updateFrom; package com.simple.simpledatabase.model; /** * 接口使用 * Created by mrsimple on 13/8/16. */ public class BookModel { /** * 插入数据 * * @param aBook */ public void insertBook(Book aBook) {
insertInto(BookDao.class).withItem(aBook).execute();
hehonghui/simpledb
app/src/main/java/com/simple/simpledatabase/model/BookModel.java
// Path: database/src/main/java/com/simple/database/listeners/DbListener.java // public interface DbListener<T> { // void onComplete(T result); // } // // Path: app/src/main/java/com/simple/simpledatabase/dao/BookDao.java // public class BookDao extends AbsDAO<Book> { // // public BookDao() { // super("books"); // } // // @Override // protected ContentValues convert(Book item) { // ContentValues newValues = new ContentValues(); // newValues.put("id", item.id); // newValues.put("name", item.name); // return newValues; // } // // // @Override // protected Book parseOneItem(Cursor cursor) { // Book item = new Book(); // item.id = cursor.getString(0); // item.name = cursor.getString(1) ; // return item; // } // // } // // Path: app/src/main/java/com/simple/simpledatabase/domain/Book.java // public class Book { // public String id ; // public String name ; // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> DeleteBuilder<T> deleteFrom(Class<? extends AbsDAO<T>> daoClass) { // return new DeleteBuilder<>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> InsertBuilder<T> insertInto(Class<? extends AbsDAO<T>> daoClass) { // return new InsertBuilder<T>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> QueryBuilder<T> selectFrom(Class<? extends AbsDAO<T>> daoClass) { // return new QueryBuilder<>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> UpdateBuilder<T> updateFrom(Class<? extends AbsDAO<T>> daoClass) { // return new UpdateBuilder<>(daoClass); // }
import com.simple.database.listeners.DbListener; import com.simple.simpledatabase.dao.BookDao; import com.simple.simpledatabase.domain.Book; import java.util.List; import static com.simple.database.DatabaseHelper.deleteFrom; import static com.simple.database.DatabaseHelper.insertInto; import static com.simple.database.DatabaseHelper.selectFrom; import static com.simple.database.DatabaseHelper.updateFrom;
package com.simple.simpledatabase.model; /** * 接口使用 * Created by mrsimple on 13/8/16. */ public class BookModel { /** * 插入数据 * * @param aBook */ public void insertBook(Book aBook) {
// Path: database/src/main/java/com/simple/database/listeners/DbListener.java // public interface DbListener<T> { // void onComplete(T result); // } // // Path: app/src/main/java/com/simple/simpledatabase/dao/BookDao.java // public class BookDao extends AbsDAO<Book> { // // public BookDao() { // super("books"); // } // // @Override // protected ContentValues convert(Book item) { // ContentValues newValues = new ContentValues(); // newValues.put("id", item.id); // newValues.put("name", item.name); // return newValues; // } // // // @Override // protected Book parseOneItem(Cursor cursor) { // Book item = new Book(); // item.id = cursor.getString(0); // item.name = cursor.getString(1) ; // return item; // } // // } // // Path: app/src/main/java/com/simple/simpledatabase/domain/Book.java // public class Book { // public String id ; // public String name ; // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> DeleteBuilder<T> deleteFrom(Class<? extends AbsDAO<T>> daoClass) { // return new DeleteBuilder<>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> InsertBuilder<T> insertInto(Class<? extends AbsDAO<T>> daoClass) { // return new InsertBuilder<T>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> QueryBuilder<T> selectFrom(Class<? extends AbsDAO<T>> daoClass) { // return new QueryBuilder<>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> UpdateBuilder<T> updateFrom(Class<? extends AbsDAO<T>> daoClass) { // return new UpdateBuilder<>(daoClass); // } // Path: app/src/main/java/com/simple/simpledatabase/model/BookModel.java import com.simple.database.listeners.DbListener; import com.simple.simpledatabase.dao.BookDao; import com.simple.simpledatabase.domain.Book; import java.util.List; import static com.simple.database.DatabaseHelper.deleteFrom; import static com.simple.database.DatabaseHelper.insertInto; import static com.simple.database.DatabaseHelper.selectFrom; import static com.simple.database.DatabaseHelper.updateFrom; package com.simple.simpledatabase.model; /** * 接口使用 * Created by mrsimple on 13/8/16. */ public class BookModel { /** * 插入数据 * * @param aBook */ public void insertBook(Book aBook) {
insertInto(BookDao.class).withItem(aBook).execute();
hehonghui/simpledb
app/src/main/java/com/simple/simpledatabase/model/BookModel.java
// Path: database/src/main/java/com/simple/database/listeners/DbListener.java // public interface DbListener<T> { // void onComplete(T result); // } // // Path: app/src/main/java/com/simple/simpledatabase/dao/BookDao.java // public class BookDao extends AbsDAO<Book> { // // public BookDao() { // super("books"); // } // // @Override // protected ContentValues convert(Book item) { // ContentValues newValues = new ContentValues(); // newValues.put("id", item.id); // newValues.put("name", item.name); // return newValues; // } // // // @Override // protected Book parseOneItem(Cursor cursor) { // Book item = new Book(); // item.id = cursor.getString(0); // item.name = cursor.getString(1) ; // return item; // } // // } // // Path: app/src/main/java/com/simple/simpledatabase/domain/Book.java // public class Book { // public String id ; // public String name ; // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> DeleteBuilder<T> deleteFrom(Class<? extends AbsDAO<T>> daoClass) { // return new DeleteBuilder<>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> InsertBuilder<T> insertInto(Class<? extends AbsDAO<T>> daoClass) { // return new InsertBuilder<T>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> QueryBuilder<T> selectFrom(Class<? extends AbsDAO<T>> daoClass) { // return new QueryBuilder<>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> UpdateBuilder<T> updateFrom(Class<? extends AbsDAO<T>> daoClass) { // return new UpdateBuilder<>(daoClass); // }
import com.simple.database.listeners.DbListener; import com.simple.simpledatabase.dao.BookDao; import com.simple.simpledatabase.domain.Book; import java.util.List; import static com.simple.database.DatabaseHelper.deleteFrom; import static com.simple.database.DatabaseHelper.insertInto; import static com.simple.database.DatabaseHelper.selectFrom; import static com.simple.database.DatabaseHelper.updateFrom;
package com.simple.simpledatabase.model; /** * 接口使用 * Created by mrsimple on 13/8/16. */ public class BookModel { /** * 插入数据 * * @param aBook */ public void insertBook(Book aBook) { insertInto(BookDao.class).withItem(aBook).execute(); } /** * 删除图书 * * @param aBook */ public void deleteBook(Book aBook) { // 根据Id 删除图书
// Path: database/src/main/java/com/simple/database/listeners/DbListener.java // public interface DbListener<T> { // void onComplete(T result); // } // // Path: app/src/main/java/com/simple/simpledatabase/dao/BookDao.java // public class BookDao extends AbsDAO<Book> { // // public BookDao() { // super("books"); // } // // @Override // protected ContentValues convert(Book item) { // ContentValues newValues = new ContentValues(); // newValues.put("id", item.id); // newValues.put("name", item.name); // return newValues; // } // // // @Override // protected Book parseOneItem(Cursor cursor) { // Book item = new Book(); // item.id = cursor.getString(0); // item.name = cursor.getString(1) ; // return item; // } // // } // // Path: app/src/main/java/com/simple/simpledatabase/domain/Book.java // public class Book { // public String id ; // public String name ; // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> DeleteBuilder<T> deleteFrom(Class<? extends AbsDAO<T>> daoClass) { // return new DeleteBuilder<>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> InsertBuilder<T> insertInto(Class<? extends AbsDAO<T>> daoClass) { // return new InsertBuilder<T>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> QueryBuilder<T> selectFrom(Class<? extends AbsDAO<T>> daoClass) { // return new QueryBuilder<>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> UpdateBuilder<T> updateFrom(Class<? extends AbsDAO<T>> daoClass) { // return new UpdateBuilder<>(daoClass); // } // Path: app/src/main/java/com/simple/simpledatabase/model/BookModel.java import com.simple.database.listeners.DbListener; import com.simple.simpledatabase.dao.BookDao; import com.simple.simpledatabase.domain.Book; import java.util.List; import static com.simple.database.DatabaseHelper.deleteFrom; import static com.simple.database.DatabaseHelper.insertInto; import static com.simple.database.DatabaseHelper.selectFrom; import static com.simple.database.DatabaseHelper.updateFrom; package com.simple.simpledatabase.model; /** * 接口使用 * Created by mrsimple on 13/8/16. */ public class BookModel { /** * 插入数据 * * @param aBook */ public void insertBook(Book aBook) { insertInto(BookDao.class).withItem(aBook).execute(); } /** * 删除图书 * * @param aBook */ public void deleteBook(Book aBook) { // 根据Id 删除图书
deleteFrom(BookDao.class).where("id=?", new String[]{aBook.id}).execute();
hehonghui/simpledb
app/src/main/java/com/simple/simpledatabase/model/BookModel.java
// Path: database/src/main/java/com/simple/database/listeners/DbListener.java // public interface DbListener<T> { // void onComplete(T result); // } // // Path: app/src/main/java/com/simple/simpledatabase/dao/BookDao.java // public class BookDao extends AbsDAO<Book> { // // public BookDao() { // super("books"); // } // // @Override // protected ContentValues convert(Book item) { // ContentValues newValues = new ContentValues(); // newValues.put("id", item.id); // newValues.put("name", item.name); // return newValues; // } // // // @Override // protected Book parseOneItem(Cursor cursor) { // Book item = new Book(); // item.id = cursor.getString(0); // item.name = cursor.getString(1) ; // return item; // } // // } // // Path: app/src/main/java/com/simple/simpledatabase/domain/Book.java // public class Book { // public String id ; // public String name ; // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> DeleteBuilder<T> deleteFrom(Class<? extends AbsDAO<T>> daoClass) { // return new DeleteBuilder<>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> InsertBuilder<T> insertInto(Class<? extends AbsDAO<T>> daoClass) { // return new InsertBuilder<T>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> QueryBuilder<T> selectFrom(Class<? extends AbsDAO<T>> daoClass) { // return new QueryBuilder<>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> UpdateBuilder<T> updateFrom(Class<? extends AbsDAO<T>> daoClass) { // return new UpdateBuilder<>(daoClass); // }
import com.simple.database.listeners.DbListener; import com.simple.simpledatabase.dao.BookDao; import com.simple.simpledatabase.domain.Book; import java.util.List; import static com.simple.database.DatabaseHelper.deleteFrom; import static com.simple.database.DatabaseHelper.insertInto; import static com.simple.database.DatabaseHelper.selectFrom; import static com.simple.database.DatabaseHelper.updateFrom;
package com.simple.simpledatabase.model; /** * 接口使用 * Created by mrsimple on 13/8/16. */ public class BookModel { /** * 插入数据 * * @param aBook */ public void insertBook(Book aBook) { insertInto(BookDao.class).withItem(aBook).execute(); } /** * 删除图书 * * @param aBook */ public void deleteBook(Book aBook) { // 根据Id 删除图书 deleteFrom(BookDao.class).where("id=?", new String[]{aBook.id}).execute(); } public void updateBook(Book aBook) { // 更新数据
// Path: database/src/main/java/com/simple/database/listeners/DbListener.java // public interface DbListener<T> { // void onComplete(T result); // } // // Path: app/src/main/java/com/simple/simpledatabase/dao/BookDao.java // public class BookDao extends AbsDAO<Book> { // // public BookDao() { // super("books"); // } // // @Override // protected ContentValues convert(Book item) { // ContentValues newValues = new ContentValues(); // newValues.put("id", item.id); // newValues.put("name", item.name); // return newValues; // } // // // @Override // protected Book parseOneItem(Cursor cursor) { // Book item = new Book(); // item.id = cursor.getString(0); // item.name = cursor.getString(1) ; // return item; // } // // } // // Path: app/src/main/java/com/simple/simpledatabase/domain/Book.java // public class Book { // public String id ; // public String name ; // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> DeleteBuilder<T> deleteFrom(Class<? extends AbsDAO<T>> daoClass) { // return new DeleteBuilder<>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> InsertBuilder<T> insertInto(Class<? extends AbsDAO<T>> daoClass) { // return new InsertBuilder<T>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> QueryBuilder<T> selectFrom(Class<? extends AbsDAO<T>> daoClass) { // return new QueryBuilder<>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> UpdateBuilder<T> updateFrom(Class<? extends AbsDAO<T>> daoClass) { // return new UpdateBuilder<>(daoClass); // } // Path: app/src/main/java/com/simple/simpledatabase/model/BookModel.java import com.simple.database.listeners.DbListener; import com.simple.simpledatabase.dao.BookDao; import com.simple.simpledatabase.domain.Book; import java.util.List; import static com.simple.database.DatabaseHelper.deleteFrom; import static com.simple.database.DatabaseHelper.insertInto; import static com.simple.database.DatabaseHelper.selectFrom; import static com.simple.database.DatabaseHelper.updateFrom; package com.simple.simpledatabase.model; /** * 接口使用 * Created by mrsimple on 13/8/16. */ public class BookModel { /** * 插入数据 * * @param aBook */ public void insertBook(Book aBook) { insertInto(BookDao.class).withItem(aBook).execute(); } /** * 删除图书 * * @param aBook */ public void deleteBook(Book aBook) { // 根据Id 删除图书 deleteFrom(BookDao.class).where("id=?", new String[]{aBook.id}).execute(); } public void updateBook(Book aBook) { // 更新数据
updateFrom(BookDao.class).withItem(aBook).where("id=?", new String[]{aBook.id});
hehonghui/simpledb
app/src/main/java/com/simple/simpledatabase/model/BookModel.java
// Path: database/src/main/java/com/simple/database/listeners/DbListener.java // public interface DbListener<T> { // void onComplete(T result); // } // // Path: app/src/main/java/com/simple/simpledatabase/dao/BookDao.java // public class BookDao extends AbsDAO<Book> { // // public BookDao() { // super("books"); // } // // @Override // protected ContentValues convert(Book item) { // ContentValues newValues = new ContentValues(); // newValues.put("id", item.id); // newValues.put("name", item.name); // return newValues; // } // // // @Override // protected Book parseOneItem(Cursor cursor) { // Book item = new Book(); // item.id = cursor.getString(0); // item.name = cursor.getString(1) ; // return item; // } // // } // // Path: app/src/main/java/com/simple/simpledatabase/domain/Book.java // public class Book { // public String id ; // public String name ; // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> DeleteBuilder<T> deleteFrom(Class<? extends AbsDAO<T>> daoClass) { // return new DeleteBuilder<>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> InsertBuilder<T> insertInto(Class<? extends AbsDAO<T>> daoClass) { // return new InsertBuilder<T>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> QueryBuilder<T> selectFrom(Class<? extends AbsDAO<T>> daoClass) { // return new QueryBuilder<>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> UpdateBuilder<T> updateFrom(Class<? extends AbsDAO<T>> daoClass) { // return new UpdateBuilder<>(daoClass); // }
import com.simple.database.listeners.DbListener; import com.simple.simpledatabase.dao.BookDao; import com.simple.simpledatabase.domain.Book; import java.util.List; import static com.simple.database.DatabaseHelper.deleteFrom; import static com.simple.database.DatabaseHelper.insertInto; import static com.simple.database.DatabaseHelper.selectFrom; import static com.simple.database.DatabaseHelper.updateFrom;
package com.simple.simpledatabase.model; /** * 接口使用 * Created by mrsimple on 13/8/16. */ public class BookModel { /** * 插入数据 * * @param aBook */ public void insertBook(Book aBook) { insertInto(BookDao.class).withItem(aBook).execute(); } /** * 删除图书 * * @param aBook */ public void deleteBook(Book aBook) { // 根据Id 删除图书 deleteFrom(BookDao.class).where("id=?", new String[]{aBook.id}).execute(); } public void updateBook(Book aBook) { // 更新数据 updateFrom(BookDao.class).withItem(aBook).where("id=?", new String[]{aBook.id}); } /** * 查询所有书籍 * * @param listener */
// Path: database/src/main/java/com/simple/database/listeners/DbListener.java // public interface DbListener<T> { // void onComplete(T result); // } // // Path: app/src/main/java/com/simple/simpledatabase/dao/BookDao.java // public class BookDao extends AbsDAO<Book> { // // public BookDao() { // super("books"); // } // // @Override // protected ContentValues convert(Book item) { // ContentValues newValues = new ContentValues(); // newValues.put("id", item.id); // newValues.put("name", item.name); // return newValues; // } // // // @Override // protected Book parseOneItem(Cursor cursor) { // Book item = new Book(); // item.id = cursor.getString(0); // item.name = cursor.getString(1) ; // return item; // } // // } // // Path: app/src/main/java/com/simple/simpledatabase/domain/Book.java // public class Book { // public String id ; // public String name ; // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> DeleteBuilder<T> deleteFrom(Class<? extends AbsDAO<T>> daoClass) { // return new DeleteBuilder<>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> InsertBuilder<T> insertInto(Class<? extends AbsDAO<T>> daoClass) { // return new InsertBuilder<T>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> QueryBuilder<T> selectFrom(Class<? extends AbsDAO<T>> daoClass) { // return new QueryBuilder<>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> UpdateBuilder<T> updateFrom(Class<? extends AbsDAO<T>> daoClass) { // return new UpdateBuilder<>(daoClass); // } // Path: app/src/main/java/com/simple/simpledatabase/model/BookModel.java import com.simple.database.listeners.DbListener; import com.simple.simpledatabase.dao.BookDao; import com.simple.simpledatabase.domain.Book; import java.util.List; import static com.simple.database.DatabaseHelper.deleteFrom; import static com.simple.database.DatabaseHelper.insertInto; import static com.simple.database.DatabaseHelper.selectFrom; import static com.simple.database.DatabaseHelper.updateFrom; package com.simple.simpledatabase.model; /** * 接口使用 * Created by mrsimple on 13/8/16. */ public class BookModel { /** * 插入数据 * * @param aBook */ public void insertBook(Book aBook) { insertInto(BookDao.class).withItem(aBook).execute(); } /** * 删除图书 * * @param aBook */ public void deleteBook(Book aBook) { // 根据Id 删除图书 deleteFrom(BookDao.class).where("id=?", new String[]{aBook.id}).execute(); } public void updateBook(Book aBook) { // 更新数据 updateFrom(BookDao.class).withItem(aBook).where("id=?", new String[]{aBook.id}); } /** * 查询所有书籍 * * @param listener */
public void queryAllBook(DbListener<List<Book>> listener) {
hehonghui/simpledb
app/src/main/java/com/simple/simpledatabase/model/BookModel.java
// Path: database/src/main/java/com/simple/database/listeners/DbListener.java // public interface DbListener<T> { // void onComplete(T result); // } // // Path: app/src/main/java/com/simple/simpledatabase/dao/BookDao.java // public class BookDao extends AbsDAO<Book> { // // public BookDao() { // super("books"); // } // // @Override // protected ContentValues convert(Book item) { // ContentValues newValues = new ContentValues(); // newValues.put("id", item.id); // newValues.put("name", item.name); // return newValues; // } // // // @Override // protected Book parseOneItem(Cursor cursor) { // Book item = new Book(); // item.id = cursor.getString(0); // item.name = cursor.getString(1) ; // return item; // } // // } // // Path: app/src/main/java/com/simple/simpledatabase/domain/Book.java // public class Book { // public String id ; // public String name ; // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> DeleteBuilder<T> deleteFrom(Class<? extends AbsDAO<T>> daoClass) { // return new DeleteBuilder<>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> InsertBuilder<T> insertInto(Class<? extends AbsDAO<T>> daoClass) { // return new InsertBuilder<T>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> QueryBuilder<T> selectFrom(Class<? extends AbsDAO<T>> daoClass) { // return new QueryBuilder<>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> UpdateBuilder<T> updateFrom(Class<? extends AbsDAO<T>> daoClass) { // return new UpdateBuilder<>(daoClass); // }
import com.simple.database.listeners.DbListener; import com.simple.simpledatabase.dao.BookDao; import com.simple.simpledatabase.domain.Book; import java.util.List; import static com.simple.database.DatabaseHelper.deleteFrom; import static com.simple.database.DatabaseHelper.insertInto; import static com.simple.database.DatabaseHelper.selectFrom; import static com.simple.database.DatabaseHelper.updateFrom;
package com.simple.simpledatabase.model; /** * 接口使用 * Created by mrsimple on 13/8/16. */ public class BookModel { /** * 插入数据 * * @param aBook */ public void insertBook(Book aBook) { insertInto(BookDao.class).withItem(aBook).execute(); } /** * 删除图书 * * @param aBook */ public void deleteBook(Book aBook) { // 根据Id 删除图书 deleteFrom(BookDao.class).where("id=?", new String[]{aBook.id}).execute(); } public void updateBook(Book aBook) { // 更新数据 updateFrom(BookDao.class).withItem(aBook).where("id=?", new String[]{aBook.id}); } /** * 查询所有书籍 * * @param listener */ public void queryAllBook(DbListener<List<Book>> listener) {
// Path: database/src/main/java/com/simple/database/listeners/DbListener.java // public interface DbListener<T> { // void onComplete(T result); // } // // Path: app/src/main/java/com/simple/simpledatabase/dao/BookDao.java // public class BookDao extends AbsDAO<Book> { // // public BookDao() { // super("books"); // } // // @Override // protected ContentValues convert(Book item) { // ContentValues newValues = new ContentValues(); // newValues.put("id", item.id); // newValues.put("name", item.name); // return newValues; // } // // // @Override // protected Book parseOneItem(Cursor cursor) { // Book item = new Book(); // item.id = cursor.getString(0); // item.name = cursor.getString(1) ; // return item; // } // // } // // Path: app/src/main/java/com/simple/simpledatabase/domain/Book.java // public class Book { // public String id ; // public String name ; // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> DeleteBuilder<T> deleteFrom(Class<? extends AbsDAO<T>> daoClass) { // return new DeleteBuilder<>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> InsertBuilder<T> insertInto(Class<? extends AbsDAO<T>> daoClass) { // return new InsertBuilder<T>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> QueryBuilder<T> selectFrom(Class<? extends AbsDAO<T>> daoClass) { // return new QueryBuilder<>(daoClass); // } // // Path: database/src/main/java/com/simple/database/DatabaseHelper.java // public static <T> UpdateBuilder<T> updateFrom(Class<? extends AbsDAO<T>> daoClass) { // return new UpdateBuilder<>(daoClass); // } // Path: app/src/main/java/com/simple/simpledatabase/model/BookModel.java import com.simple.database.listeners.DbListener; import com.simple.simpledatabase.dao.BookDao; import com.simple.simpledatabase.domain.Book; import java.util.List; import static com.simple.database.DatabaseHelper.deleteFrom; import static com.simple.database.DatabaseHelper.insertInto; import static com.simple.database.DatabaseHelper.selectFrom; import static com.simple.database.DatabaseHelper.updateFrom; package com.simple.simpledatabase.model; /** * 接口使用 * Created by mrsimple on 13/8/16. */ public class BookModel { /** * 插入数据 * * @param aBook */ public void insertBook(Book aBook) { insertInto(BookDao.class).withItem(aBook).execute(); } /** * 删除图书 * * @param aBook */ public void deleteBook(Book aBook) { // 根据Id 删除图书 deleteFrom(BookDao.class).where("id=?", new String[]{aBook.id}).execute(); } public void updateBook(Book aBook) { // 更新数据 updateFrom(BookDao.class).withItem(aBook).where("id=?", new String[]{aBook.id}); } /** * 查询所有书籍 * * @param listener */ public void queryAllBook(DbListener<List<Book>> listener) {
selectFrom(BookDao.class).listener(listener).execute();
zhanggh/mtools
mtools/src/main/java/com/mtools/core/plugin/auth/service/imp/RoleServiceImpl.java
// Path: mtools/src/main/java/com/mtools/core/plugin/BasePlugin.java // public class BasePlugin { // // /** // * 尽量使用该日志组件,里面做了特殊字符过滤 // */ // public static Log log=null; // @Autowired // public CoreDao dao; // @Autowired // public MailImpl mailImpl; // @Resource(name = "taskExecutor") // public Executor executor; // public String errorMsg="处理失败"; // @Resource(name = "coreParams") // public CoreParams coreParams; // // public Long getSeq(String seqName){ // return this.dao.getSeq(seqName); // } // // public CoreDao getDao() { // return dao; // } // // public void setDao(CoreDao dao) { // this.dao = dao; // } // // public Executor getExecutor() { // return executor; // } // // public void setExecutor(Executor executor) { // this.executor = executor; // } // // public BasePlugin() { // super(); // if(log==null) // log=LogFactory.getLog(this.getClass()); // } // // } // // Path: mtools/src/main/java/com/mtools/core/plugin/entity/Role.java // public class Role extends BaseDbStruct{ // // /** // * 说明: // * serialVersionUID // */ // private static final long serialVersionUID = -6328054563985222114L; // public static final String TABLE_ALIAS = "rl"; // public static final String TABLE_NAME = "ROLE"; // public static final String[] TABLE_KEYS = { "roleid" }; // // public String roleid; // public String rolename; // // public String getRoleid() { // return roleid; // } // // public void setRoleid(String roleid) { // this.roleid = roleid; // } // // public String getRolename() { // return rolename; // } // // public void setRolename(String rolename) { // this.rolename = rolename; // } // // }
import java.util.List; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.mtools.core.plugin.BasePlugin; import com.mtools.core.plugin.auth.service.RoleService; import com.mtools.core.plugin.entity.Permission; import com.mtools.core.plugin.entity.Role; import com.mtools.core.plugin.entiy.vo.UserVo;
/** * 通联支付-研发中心 * RoleServiceImpl.java * 2014-4-29 */ package com.mtools.core.plugin.auth.service.imp; /** * @author zhang * 功能: * @date 2014-4-29 */ @Service("roleService") public class RoleServiceImpl extends BasePlugin implements RoleService { /** * 功能: */
// Path: mtools/src/main/java/com/mtools/core/plugin/BasePlugin.java // public class BasePlugin { // // /** // * 尽量使用该日志组件,里面做了特殊字符过滤 // */ // public static Log log=null; // @Autowired // public CoreDao dao; // @Autowired // public MailImpl mailImpl; // @Resource(name = "taskExecutor") // public Executor executor; // public String errorMsg="处理失败"; // @Resource(name = "coreParams") // public CoreParams coreParams; // // public Long getSeq(String seqName){ // return this.dao.getSeq(seqName); // } // // public CoreDao getDao() { // return dao; // } // // public void setDao(CoreDao dao) { // this.dao = dao; // } // // public Executor getExecutor() { // return executor; // } // // public void setExecutor(Executor executor) { // this.executor = executor; // } // // public BasePlugin() { // super(); // if(log==null) // log=LogFactory.getLog(this.getClass()); // } // // } // // Path: mtools/src/main/java/com/mtools/core/plugin/entity/Role.java // public class Role extends BaseDbStruct{ // // /** // * 说明: // * serialVersionUID // */ // private static final long serialVersionUID = -6328054563985222114L; // public static final String TABLE_ALIAS = "rl"; // public static final String TABLE_NAME = "ROLE"; // public static final String[] TABLE_KEYS = { "roleid" }; // // public String roleid; // public String rolename; // // public String getRoleid() { // return roleid; // } // // public void setRoleid(String roleid) { // this.roleid = roleid; // } // // public String getRolename() { // return rolename; // } // // public void setRolename(String rolename) { // this.rolename = rolename; // } // // } // Path: mtools/src/main/java/com/mtools/core/plugin/auth/service/imp/RoleServiceImpl.java import java.util.List; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.mtools.core.plugin.BasePlugin; import com.mtools.core.plugin.auth.service.RoleService; import com.mtools.core.plugin.entity.Permission; import com.mtools.core.plugin.entity.Role; import com.mtools.core.plugin.entiy.vo.UserVo; /** * 通联支付-研发中心 * RoleServiceImpl.java * 2014-4-29 */ package com.mtools.core.plugin.auth.service.imp; /** * @author zhang * 功能: * @date 2014-4-29 */ @Service("roleService") public class RoleServiceImpl extends BasePlugin implements RoleService { /** * 功能: */
public List<Role> getRoles(Role role) {
zhanggh/mtools
mtools/src/test/java/com/ztools/security/CoderTest.java
// Path: mtools/src/main/java/com/mtools/core/plugin/security/Coder.java // public abstract class Coder { // public static final String KEY_SHA = "SHA"; // public static final String KEY_MD5 = "MD5"; // // /** // * MAC算法可选以下多种算法 // * // * <pre> // * HmacMD5 // * HmacSHA1 // * HmacSHA256 // * HmacSHA384 // * HmacSHA512 // * </pre> // */ // public static final String KEY_MAC = "HmacMD5"; // // /** // * BASE64解密 // * // * @param key // * @return // * @throws Exception // */ // public static byte[] decryptBASE64(String key) throws Exception { // return (new BASE64Decoder()).decodeBuffer(key); // } // // /** // * BASE64加密 // * // * @param key // * @return // * @throws Exception // */ // public static String encryptBASE64(byte[] key) throws Exception { // return (new BASE64Encoder()).encodeBuffer(key); // } // // /** // * MD5加密 // * // * @param data // * @return // * @throws Exception // */ // public static byte[] encryptMD5(byte[] data) throws Exception { // // MessageDigest md5 = MessageDigest.getInstance(KEY_MD5); // md5.update(data); // // return md5.digest(); // // } // // /** // * SHA加密 // * // * @param data // * @return // * @throws Exception // */ // public static byte[] encryptSHA(byte[] data) throws Exception { // // MessageDigest sha = MessageDigest.getInstance(KEY_SHA); // sha.update(data); // // return sha.digest(); // // } // // /** // * 初始化HMAC密钥 // * // * @return // * @throws Exception // */ // public static String initMacKey() throws Exception { // KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC); // // SecretKey secretKey = keyGenerator.generateKey(); // return encryptBASE64(secretKey.getEncoded()); // } // // /** // * HMAC加密 // * // * @param data // * @param key // * @return // * @throws Exception // */ // public static byte[] encryptHMAC(byte[] data, String key) throws Exception { // // SecretKey secretKey = new SecretKeySpec(decryptBASE64(key), KEY_MAC); // Mac mac = Mac.getInstance(secretKey.getAlgorithm()); // mac.init(secretKey); // // return mac.doFinal(data); // // } // }
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import java.math.BigInteger; import org.junit.Test; import com.mtools.core.plugin.security.Coder;
package com.ztools.security; /** * * @author 梁栋 * @version 1.0 * @since 1.0 */ public class CoderTest { @Test public void test() throws Exception { String inputStr = "简单加密"; System.err.println("原文:\n" + inputStr); byte[] inputData = inputStr.getBytes();
// Path: mtools/src/main/java/com/mtools/core/plugin/security/Coder.java // public abstract class Coder { // public static final String KEY_SHA = "SHA"; // public static final String KEY_MD5 = "MD5"; // // /** // * MAC算法可选以下多种算法 // * // * <pre> // * HmacMD5 // * HmacSHA1 // * HmacSHA256 // * HmacSHA384 // * HmacSHA512 // * </pre> // */ // public static final String KEY_MAC = "HmacMD5"; // // /** // * BASE64解密 // * // * @param key // * @return // * @throws Exception // */ // public static byte[] decryptBASE64(String key) throws Exception { // return (new BASE64Decoder()).decodeBuffer(key); // } // // /** // * BASE64加密 // * // * @param key // * @return // * @throws Exception // */ // public static String encryptBASE64(byte[] key) throws Exception { // return (new BASE64Encoder()).encodeBuffer(key); // } // // /** // * MD5加密 // * // * @param data // * @return // * @throws Exception // */ // public static byte[] encryptMD5(byte[] data) throws Exception { // // MessageDigest md5 = MessageDigest.getInstance(KEY_MD5); // md5.update(data); // // return md5.digest(); // // } // // /** // * SHA加密 // * // * @param data // * @return // * @throws Exception // */ // public static byte[] encryptSHA(byte[] data) throws Exception { // // MessageDigest sha = MessageDigest.getInstance(KEY_SHA); // sha.update(data); // // return sha.digest(); // // } // // /** // * 初始化HMAC密钥 // * // * @return // * @throws Exception // */ // public static String initMacKey() throws Exception { // KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC); // // SecretKey secretKey = keyGenerator.generateKey(); // return encryptBASE64(secretKey.getEncoded()); // } // // /** // * HMAC加密 // * // * @param data // * @param key // * @return // * @throws Exception // */ // public static byte[] encryptHMAC(byte[] data, String key) throws Exception { // // SecretKey secretKey = new SecretKeySpec(decryptBASE64(key), KEY_MAC); // Mac mac = Mac.getInstance(secretKey.getAlgorithm()); // mac.init(secretKey); // // return mac.doFinal(data); // // } // } // Path: mtools/src/test/java/com/ztools/security/CoderTest.java import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import java.math.BigInteger; import org.junit.Test; import com.mtools.core.plugin.security.Coder; package com.ztools.security; /** * * @author 梁栋 * @version 1.0 * @since 1.0 */ public class CoderTest { @Test public void test() throws Exception { String inputStr = "简单加密"; System.err.println("原文:\n" + inputStr); byte[] inputData = inputStr.getBytes();
String code = Coder.encryptBASE64(inputData);
zhanggh/mtools
mtools/src/main/java/com/mtools/core/plugin/web/interceptor/BaseInterceptor.java
// Path: mtools/src/main/java/com/mtools/core/plugin/properties/CoreParams.java // @Component("coreParams") // public class CoreParams { // // @Value("${reloadIndex}") // public String reloadIndex; // @Value("${staticFile}") // public String staticFile; // @Value("${solrUrl}") // public String solrUrl; // @Value("${ssl}") // public String ssl; // @Value("${tranxUri}") // public String tranxUri; // @Value("${tranxUrl}") // public String tranxUrl; // @Value("${db1.isOrcl}") // public String isOrcl; // @Value("${serverName}") // public String serverName; // @Value("${authIp}") // public String authIp; // @Value("${indexpth}") // public String indexpth; // @Value("${fileContxtPth}") // public String fileContxtPth; // @Value("${tomcatEncode}") // public String tomcatEncode; // @Value("${isTest}") // public boolean isTest; // // public String getAuthIp() { // return authIp; // } // // public void setAuthIp(String authIp) { // this.authIp = authIp; // } // // /** // * @return the serverName // */ // public String getServerName() { // return serverName; // } // // /** // * @param serverName the serverName to set // */ // public void setServerName(String serverName) { // this.serverName = serverName; // } // // // /** // * @return the indexpth // */ // public String getIndexpth() { // return indexpth; // } // // /** // * @param indexpth the indexpth to set // */ // public void setIndexpth(String indexpth) { // this.indexpth = indexpth; // } // // /** // * @return the isOrcl // */ // public boolean getIsOrcl() { // return Boolean.parseBoolean(isOrcl); // } // // /** // * @param isOrcl the isOrcl to set // */ // public void setIsOrcl(String isOrcl) { // this.isOrcl = isOrcl; // } // // public String getTranxUrl() { // // return tranxUrl; // } // // public void setTranxUrl(String tranxUrl) { // this.tranxUrl = tranxUrl; // } // // public String getTranxUri() { // return tranxUri; // } // // public void setTranxUri(String tranxUri) { // this.tranxUri = tranxUri; // } // // public String getSolrUrl() { // return solrUrl; // } // // public void setSolrUrl(String solrUrl) { // this.solrUrl = solrUrl; // } // // public String getSsl() { // return ssl; // } // // public void setSsl(String ssl) { // this.ssl = ssl; // } // // /** // * @return the staticFile // */ // public String getStaticFile() { // return staticFile; // } // // /** // * @param staticFile // * the staticFile to set // */ // public void setStaticFile(String staticFile) { // this.staticFile = staticFile; // } // // /** // * @return the reloadIndex // */ // public String getReloadIndex() { // return reloadIndex; // } // // /** // * @param reloadIndex // * the reloadIndex to set // */ // public void setReloadIndex(String reloadIndex) { // this.reloadIndex = reloadIndex; // } // // public String getFileContxtPth() { // return fileContxtPth; // } // // public void setFileContxtPth(String fileContxtPth) { // this.fileContxtPth = fileContxtPth; // } // // public String getTomcatEncode() { // return tomcatEncode; // } // // public void setTomcatEncode(String tomcatEncode) { // this.tomcatEncode = tomcatEncode; // } // // public boolean getIsTest() { // return isTest; // } // // public void setIsTest(boolean isTest) { // this.isTest = isTest; // } // // }
import javax.annotation.Resource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import com.mtools.core.plugin.properties.CoreParams;
/** * BaseInterceptor.java * 2014-4-17 */ package com.mtools.core.plugin.web.interceptor; /** * @author zhang * * 2014-4-17 */ public class BaseInterceptor extends HandlerInterceptorAdapter{ public Log log= LogFactory.getLog(this.getClass()); @Resource(name="coreParams")
// Path: mtools/src/main/java/com/mtools/core/plugin/properties/CoreParams.java // @Component("coreParams") // public class CoreParams { // // @Value("${reloadIndex}") // public String reloadIndex; // @Value("${staticFile}") // public String staticFile; // @Value("${solrUrl}") // public String solrUrl; // @Value("${ssl}") // public String ssl; // @Value("${tranxUri}") // public String tranxUri; // @Value("${tranxUrl}") // public String tranxUrl; // @Value("${db1.isOrcl}") // public String isOrcl; // @Value("${serverName}") // public String serverName; // @Value("${authIp}") // public String authIp; // @Value("${indexpth}") // public String indexpth; // @Value("${fileContxtPth}") // public String fileContxtPth; // @Value("${tomcatEncode}") // public String tomcatEncode; // @Value("${isTest}") // public boolean isTest; // // public String getAuthIp() { // return authIp; // } // // public void setAuthIp(String authIp) { // this.authIp = authIp; // } // // /** // * @return the serverName // */ // public String getServerName() { // return serverName; // } // // /** // * @param serverName the serverName to set // */ // public void setServerName(String serverName) { // this.serverName = serverName; // } // // // /** // * @return the indexpth // */ // public String getIndexpth() { // return indexpth; // } // // /** // * @param indexpth the indexpth to set // */ // public void setIndexpth(String indexpth) { // this.indexpth = indexpth; // } // // /** // * @return the isOrcl // */ // public boolean getIsOrcl() { // return Boolean.parseBoolean(isOrcl); // } // // /** // * @param isOrcl the isOrcl to set // */ // public void setIsOrcl(String isOrcl) { // this.isOrcl = isOrcl; // } // // public String getTranxUrl() { // // return tranxUrl; // } // // public void setTranxUrl(String tranxUrl) { // this.tranxUrl = tranxUrl; // } // // public String getTranxUri() { // return tranxUri; // } // // public void setTranxUri(String tranxUri) { // this.tranxUri = tranxUri; // } // // public String getSolrUrl() { // return solrUrl; // } // // public void setSolrUrl(String solrUrl) { // this.solrUrl = solrUrl; // } // // public String getSsl() { // return ssl; // } // // public void setSsl(String ssl) { // this.ssl = ssl; // } // // /** // * @return the staticFile // */ // public String getStaticFile() { // return staticFile; // } // // /** // * @param staticFile // * the staticFile to set // */ // public void setStaticFile(String staticFile) { // this.staticFile = staticFile; // } // // /** // * @return the reloadIndex // */ // public String getReloadIndex() { // return reloadIndex; // } // // /** // * @param reloadIndex // * the reloadIndex to set // */ // public void setReloadIndex(String reloadIndex) { // this.reloadIndex = reloadIndex; // } // // public String getFileContxtPth() { // return fileContxtPth; // } // // public void setFileContxtPth(String fileContxtPth) { // this.fileContxtPth = fileContxtPth; // } // // public String getTomcatEncode() { // return tomcatEncode; // } // // public void setTomcatEncode(String tomcatEncode) { // this.tomcatEncode = tomcatEncode; // } // // public boolean getIsTest() { // return isTest; // } // // public void setIsTest(boolean isTest) { // this.isTest = isTest; // } // // } // Path: mtools/src/main/java/com/mtools/core/plugin/web/interceptor/BaseInterceptor.java import javax.annotation.Resource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import com.mtools.core.plugin.properties.CoreParams; /** * BaseInterceptor.java * 2014-4-17 */ package com.mtools.core.plugin.web.interceptor; /** * @author zhang * * 2014-4-17 */ public class BaseInterceptor extends HandlerInterceptorAdapter{ public Log log= LogFactory.getLog(this.getClass()); @Resource(name="coreParams")
public CoreParams coreParams;
Netflix/ReactiveLab
reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/clients/VideoMetadataCommand.java
// Path: reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/clients/PersonalizedCatalogCommand.java // public static class Video implements ID { // // private final int id; // // public Video(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // } // // Path: reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/clients/VideoMetadataCommand.java // public static class VideoMetadata { // // private final Map<String, Object> data; // // public VideoMetadata(Map<String, Object> data) { // this.data = data; // } // // public static VideoMetadata fromJson(String json) { // return new VideoMetadata(SimpleJson.jsonToMap(json)); // } // // public int getId() { // return (int) data.get("videoId"); // } // // public String getTitle() { // return (String) data.get("title"); // } // // public Map<String, Object> getDataAsMap() { // return data; // } // // } // // Path: reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/common/SimpleJson.java // public class SimpleJson { // // private static final SimpleJson INSTANCE = new SimpleJson(); // // private SimpleJson() { // // } // // public static Map<String, Object> jsonToMap(String jsonString) { // return INSTANCE._jsonToMap(jsonString); // } // // public static String mapToJson(Map<String, ? extends Object> map) { // return INSTANCE._mapToJson(map); // } // // private final ObjectMapper objectMapper = new ObjectMapper(); // private final ObjectReader objectReader = objectMapper.reader(Map.class); // // private Map<String, Object> _jsonToMap(String jsonString) { // try { // return objectReader.readValue(jsonString); // } catch (IOException e) { // throw new RuntimeException("Unable to parse JSON", e); // } // } // // private final ObjectWriter objectWriter = objectMapper.writerWithType(Map.class); // // private String _mapToJson(Map<String, ? extends Object> map) { // try { // return objectWriter.writeValueAsString(map); // } catch (IOException e) { // throw new RuntimeException("Unable to write JSON", e); // } // } // }
import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixObservableCommand; import io.netty.buffer.ByteBuf; import io.reactivex.lab.gateway.clients.PersonalizedCatalogCommand.Video; import io.reactivex.lab.gateway.clients.VideoMetadataCommand.VideoMetadata; import io.reactivex.lab.gateway.common.SimpleJson; import io.reactivex.lab.gateway.loadbalancer.DiscoveryAndLoadBalancer; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import io.reactivex.netty.protocol.http.sse.ServerSentEvent; import netflix.ocelli.LoadBalancer; import netflix.ocelli.rxnetty.HttpClientHolder; import rx.Observable; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map;
@Override protected Observable<VideoMetadata> construct() { HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/metadata?" + UrlGenerator.generate("videoId", videos)); return loadBalancer.choose() .map(holder -> holder.getClient()) .<VideoMetadata>flatMap(client -> client.submit(request) .flatMap(r -> r.getContent() .map((ServerSentEvent sse) -> VideoMetadata.fromJson(sse.contentAsString())))) .retry(1); } @Override protected Observable<VideoMetadata> resumeWithFallback() { Map<String, Object> video = new HashMap<>(); video.put("videoId", videos.get(0).getId()); video.put("title", "Fallback Video Title"); video.put("other_data", "goes_here"); return Observable.just(new VideoMetadata(video)); } public static class VideoMetadata { private final Map<String, Object> data; public VideoMetadata(Map<String, Object> data) { this.data = data; } public static VideoMetadata fromJson(String json) {
// Path: reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/clients/PersonalizedCatalogCommand.java // public static class Video implements ID { // // private final int id; // // public Video(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // } // // Path: reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/clients/VideoMetadataCommand.java // public static class VideoMetadata { // // private final Map<String, Object> data; // // public VideoMetadata(Map<String, Object> data) { // this.data = data; // } // // public static VideoMetadata fromJson(String json) { // return new VideoMetadata(SimpleJson.jsonToMap(json)); // } // // public int getId() { // return (int) data.get("videoId"); // } // // public String getTitle() { // return (String) data.get("title"); // } // // public Map<String, Object> getDataAsMap() { // return data; // } // // } // // Path: reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/common/SimpleJson.java // public class SimpleJson { // // private static final SimpleJson INSTANCE = new SimpleJson(); // // private SimpleJson() { // // } // // public static Map<String, Object> jsonToMap(String jsonString) { // return INSTANCE._jsonToMap(jsonString); // } // // public static String mapToJson(Map<String, ? extends Object> map) { // return INSTANCE._mapToJson(map); // } // // private final ObjectMapper objectMapper = new ObjectMapper(); // private final ObjectReader objectReader = objectMapper.reader(Map.class); // // private Map<String, Object> _jsonToMap(String jsonString) { // try { // return objectReader.readValue(jsonString); // } catch (IOException e) { // throw new RuntimeException("Unable to parse JSON", e); // } // } // // private final ObjectWriter objectWriter = objectMapper.writerWithType(Map.class); // // private String _mapToJson(Map<String, ? extends Object> map) { // try { // return objectWriter.writeValueAsString(map); // } catch (IOException e) { // throw new RuntimeException("Unable to write JSON", e); // } // } // } // Path: reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/clients/VideoMetadataCommand.java import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixObservableCommand; import io.netty.buffer.ByteBuf; import io.reactivex.lab.gateway.clients.PersonalizedCatalogCommand.Video; import io.reactivex.lab.gateway.clients.VideoMetadataCommand.VideoMetadata; import io.reactivex.lab.gateway.common.SimpleJson; import io.reactivex.lab.gateway.loadbalancer.DiscoveryAndLoadBalancer; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import io.reactivex.netty.protocol.http.sse.ServerSentEvent; import netflix.ocelli.LoadBalancer; import netflix.ocelli.rxnetty.HttpClientHolder; import rx.Observable; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @Override protected Observable<VideoMetadata> construct() { HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/metadata?" + UrlGenerator.generate("videoId", videos)); return loadBalancer.choose() .map(holder -> holder.getClient()) .<VideoMetadata>flatMap(client -> client.submit(request) .flatMap(r -> r.getContent() .map((ServerSentEvent sse) -> VideoMetadata.fromJson(sse.contentAsString())))) .retry(1); } @Override protected Observable<VideoMetadata> resumeWithFallback() { Map<String, Object> video = new HashMap<>(); video.put("videoId", videos.get(0).getId()); video.put("title", "Fallback Video Title"); video.put("other_data", "goes_here"); return Observable.just(new VideoMetadata(video)); } public static class VideoMetadata { private final Map<String, Object> data; public VideoMetadata(Map<String, Object> data) { this.data = data; } public static VideoMetadata fromJson(String json) {
return new VideoMetadata(SimpleJson.jsonToMap(json));
Netflix/ReactiveLab
reactive-lab-services/src/main/java/io/reactivex/lab/services/StartEurekaServer.java
// Path: reactive-lab-services/src/main/java/io/reactivex/lab/services/common/SimpleJson.java // public class SimpleJson { // // private static final SimpleJson INSTANCE = new SimpleJson(); // // private SimpleJson() { // // } // // public static Map<String, Object> jsonToMap(String jsonString) { // return INSTANCE._jsonToMap(jsonString); // } // // public static String mapToJson(Map<String, ?> map) { // return INSTANCE._mapToJson(map); // } // // private final ObjectMapper objectMapper = new ObjectMapper(); // private final ObjectReader objectReader = objectMapper.reader(Map.class); // // private Map<String, Object> _jsonToMap(String jsonString) { // try { // return objectReader.readValue(jsonString); // } catch (IOException e) { // throw new RuntimeException("Unable to parse JSON", e); // } // } // // private final ObjectWriter objectWriter = objectMapper.writerWithType(Map.class); // // private String _mapToJson(Map<String, ?> map) { // try { // return objectWriter.writeValueAsString(map); // } catch (IOException e) { // throw new RuntimeException("Unable to write JSON", e); // } // } // }
import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpResponseStatus; import io.reactivex.lab.services.common.SimpleJson; import io.reactivex.netty.RxNetty; import io.reactivex.netty.protocol.http.server.file.ClassPathFileRequestHandler; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.stream.Collectors; import rx.Observable; import rx.schedulers.Schedulers; import com.netflix.eureka2.client.Eureka; import com.netflix.eureka2.client.EurekaClient; import com.netflix.eureka2.client.resolver.ServerResolver; import com.netflix.eureka2.client.resolver.ServerResolvers; import com.netflix.eureka2.interests.Interests; import com.netflix.eureka2.registry.NetworkAddress.ProtocolType; import com.netflix.eureka2.registry.ServicePort; import com.netflix.eureka2.registry.datacenter.LocalDataCenterInfo; import com.netflix.eureka2.server.EurekaWriteServer; import com.netflix.eureka2.server.WriteServerConfig; import com.netflix.eureka2.transport.EurekaTransports.Codec;
public static class StaticFileHandler extends ClassPathFileRequestHandler { public StaticFileHandler() { super("."); } } private static void startEurekaDashboard(final int port, EurekaClient client) { final StaticFileHandler staticFileHandler = new StaticFileHandler(); RxNetty.createHttpServer(port, (request, response) -> { if (request.getUri().startsWith("/dashboard")) { return staticFileHandler.handle(request, response); } else if (request.getUri().startsWith("/data")) { response.getHeaders().set(HttpHeaders.Names.CONTENT_TYPE, "text/event-stream"); response.getHeaders().set(HttpHeaders.Names.CACHE_CONTROL, "no-cache"); return client.forInterest(Interests.forFullRegistry()) .flatMap(notification -> { ByteBuf data = response.getAllocator().buffer(); data.writeBytes("data: ".getBytes()); Map<String, String> dataAttributes = new HashMap<>(); dataAttributes.put("type", notification.getKind().toString()); dataAttributes.put("instance-id", notification.getData().getId()); dataAttributes.put("vip", notification.getData().getVipAddress()); if (notification.getData().getStatus() != null) { dataAttributes.put("status", notification.getData().getStatus().name()); } HashSet<ServicePort> servicePorts = notification.getData().getPorts(); int port1 = servicePorts.iterator().next().getPort(); dataAttributes.put("port", String.valueOf(port1));
// Path: reactive-lab-services/src/main/java/io/reactivex/lab/services/common/SimpleJson.java // public class SimpleJson { // // private static final SimpleJson INSTANCE = new SimpleJson(); // // private SimpleJson() { // // } // // public static Map<String, Object> jsonToMap(String jsonString) { // return INSTANCE._jsonToMap(jsonString); // } // // public static String mapToJson(Map<String, ?> map) { // return INSTANCE._mapToJson(map); // } // // private final ObjectMapper objectMapper = new ObjectMapper(); // private final ObjectReader objectReader = objectMapper.reader(Map.class); // // private Map<String, Object> _jsonToMap(String jsonString) { // try { // return objectReader.readValue(jsonString); // } catch (IOException e) { // throw new RuntimeException("Unable to parse JSON", e); // } // } // // private final ObjectWriter objectWriter = objectMapper.writerWithType(Map.class); // // private String _mapToJson(Map<String, ?> map) { // try { // return objectWriter.writeValueAsString(map); // } catch (IOException e) { // throw new RuntimeException("Unable to write JSON", e); // } // } // } // Path: reactive-lab-services/src/main/java/io/reactivex/lab/services/StartEurekaServer.java import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpResponseStatus; import io.reactivex.lab.services.common.SimpleJson; import io.reactivex.netty.RxNetty; import io.reactivex.netty.protocol.http.server.file.ClassPathFileRequestHandler; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.stream.Collectors; import rx.Observable; import rx.schedulers.Schedulers; import com.netflix.eureka2.client.Eureka; import com.netflix.eureka2.client.EurekaClient; import com.netflix.eureka2.client.resolver.ServerResolver; import com.netflix.eureka2.client.resolver.ServerResolvers; import com.netflix.eureka2.interests.Interests; import com.netflix.eureka2.registry.NetworkAddress.ProtocolType; import com.netflix.eureka2.registry.ServicePort; import com.netflix.eureka2.registry.datacenter.LocalDataCenterInfo; import com.netflix.eureka2.server.EurekaWriteServer; import com.netflix.eureka2.server.WriteServerConfig; import com.netflix.eureka2.transport.EurekaTransports.Codec; public static class StaticFileHandler extends ClassPathFileRequestHandler { public StaticFileHandler() { super("."); } } private static void startEurekaDashboard(final int port, EurekaClient client) { final StaticFileHandler staticFileHandler = new StaticFileHandler(); RxNetty.createHttpServer(port, (request, response) -> { if (request.getUri().startsWith("/dashboard")) { return staticFileHandler.handle(request, response); } else if (request.getUri().startsWith("/data")) { response.getHeaders().set(HttpHeaders.Names.CONTENT_TYPE, "text/event-stream"); response.getHeaders().set(HttpHeaders.Names.CACHE_CONTROL, "no-cache"); return client.forInterest(Interests.forFullRegistry()) .flatMap(notification -> { ByteBuf data = response.getAllocator().buffer(); data.writeBytes("data: ".getBytes()); Map<String, String> dataAttributes = new HashMap<>(); dataAttributes.put("type", notification.getKind().toString()); dataAttributes.put("instance-id", notification.getData().getId()); dataAttributes.put("vip", notification.getData().getVipAddress()); if (notification.getData().getStatus() != null) { dataAttributes.put("status", notification.getData().getStatus().name()); } HashSet<ServicePort> servicePorts = notification.getData().getPorts(); int port1 = servicePorts.iterator().next().getPort(); dataAttributes.put("port", String.valueOf(port1));
String jsonData = SimpleJson.mapToJson(dataAttributes);
Netflix/ReactiveLab
reactive-lab-services/src/main/java/io/reactivex/lab/services/impls/AbstractMiddleTierService.java
// Path: reactive-lab-services/src/main/java/io/reactivex/lab/services/metrics/HystrixMetricsStreamHandler.java // public class HystrixMetricsStreamHandler<I, O> implements RequestHandler<I, O> { // // public static final String DEFAULT_HYSTRIX_PREFIX = "/hystrix.stream"; // // public static final int DEFAULT_INTERVAL = 2000; // // private static final byte[] HEADER = "data: ".getBytes(Charset.defaultCharset()); // private static final byte[] FOOTER = { 10, 10 }; // private static final int EXTRA_SPACE = HEADER.length + FOOTER.length; // // private final String hystrixPrefix; // private final long interval; // private final RequestHandler<I, O> appHandler; // // private Metrics metrics; // // public HystrixMetricsStreamHandler(Metrics metrics, String hystrixPrefix, long interval, RequestHandler<I, O> appHandler) { // this.metrics = metrics; // this.hystrixPrefix = hystrixPrefix; // this.interval = interval; // this.appHandler = appHandler; // } // // @Override // public Observable<Void> handle(HttpServerRequest<I> request, HttpServerResponse<O> response) { // if (request.getPath().endsWith(hystrixPrefix)) { // return handleHystrixRequest(response); // } // return appHandler.handle(request, response); // } // // private Observable<Void> handleHystrixRequest(final HttpServerResponse<O> response) { // writeHeaders(response); // // final Subject<Void, Void> subject = PublishSubject.create(); // final MultipleAssignmentSubscription subscription = new MultipleAssignmentSubscription(); // Subscription actionSubscription = Observable.timer(0, interval, TimeUnit.MILLISECONDS, Schedulers.computation()) // .subscribe(new Action1<Long>() { // @Override // public void call(Long tick) { // if (!response.getChannel().isOpen()) { // subscription.unsubscribe(); // return; // } // try { // writeMetric(JsonMapper.toJson(metrics), response); // } catch (Exception e) { // subject.onError(e); // } // } // }); // subscription.set(actionSubscription); // return subject; // } // // private void writeHeaders(HttpServerResponse<O> response) { // response.getHeaders().add("Content-Type", "text/event-stream;charset=UTF-8"); // response.getHeaders().add("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate"); // response.getHeaders().add("Pragma", "no-cache"); // } // // @SuppressWarnings("unchecked") // private void writeMetric(String json, HttpServerResponse<O> response) { // byte[] bytes = json.getBytes(Charset.defaultCharset()); // ByteBuf byteBuf = UnpooledByteBufAllocator.DEFAULT.buffer(bytes.length + EXTRA_SPACE); // byteBuf.writeBytes(HEADER); // byteBuf.writeBytes(bytes); // byteBuf.writeBytes(FOOTER); // response.writeAndFlush((O) byteBuf); // } // }
import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpResponseStatus; import io.reactivex.lab.services.metrics.HystrixMetricsStreamHandler; import io.reactivex.lab.services.metrics.Metrics; import io.reactivex.netty.RxNetty; import io.reactivex.netty.pipeline.PipelineConfigurators; import io.reactivex.netty.protocol.http.server.HttpServer; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import io.reactivex.netty.protocol.http.sse.ServerSentEvent; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.UUID; import rx.Observable; import com.netflix.eureka2.client.EurekaClient; import com.netflix.eureka2.registry.InstanceInfo; import com.netflix.eureka2.registry.ServicePort; import com.netflix.eureka2.registry.datacenter.BasicDataCenterInfo;
package io.reactivex.lab.services.impls; /** * Common base for the service impls */ public abstract class AbstractMiddleTierService { private EurekaClient client; private HttpServer<ByteBuf, ServerSentEvent> server; protected final String eurekaVipAddress; private final Metrics metrics; protected AbstractMiddleTierService(String eurekaVipAddress, EurekaClient client) { this.eurekaVipAddress = eurekaVipAddress; this.client = client; this.metrics = new Metrics(eurekaVipAddress); } public HttpServer<ByteBuf, ServerSentEvent> createServer(int port) { System.out.println("Start " + getClass().getSimpleName() + " on port: " + port); // declare handler chain (wrapped in Hystrix) // TODO create a better way of chaining these (related https://github.com/ReactiveX/RxNetty/issues/232 and https://github.com/ReactiveX/RxNetty/issues/202)
// Path: reactive-lab-services/src/main/java/io/reactivex/lab/services/metrics/HystrixMetricsStreamHandler.java // public class HystrixMetricsStreamHandler<I, O> implements RequestHandler<I, O> { // // public static final String DEFAULT_HYSTRIX_PREFIX = "/hystrix.stream"; // // public static final int DEFAULT_INTERVAL = 2000; // // private static final byte[] HEADER = "data: ".getBytes(Charset.defaultCharset()); // private static final byte[] FOOTER = { 10, 10 }; // private static final int EXTRA_SPACE = HEADER.length + FOOTER.length; // // private final String hystrixPrefix; // private final long interval; // private final RequestHandler<I, O> appHandler; // // private Metrics metrics; // // public HystrixMetricsStreamHandler(Metrics metrics, String hystrixPrefix, long interval, RequestHandler<I, O> appHandler) { // this.metrics = metrics; // this.hystrixPrefix = hystrixPrefix; // this.interval = interval; // this.appHandler = appHandler; // } // // @Override // public Observable<Void> handle(HttpServerRequest<I> request, HttpServerResponse<O> response) { // if (request.getPath().endsWith(hystrixPrefix)) { // return handleHystrixRequest(response); // } // return appHandler.handle(request, response); // } // // private Observable<Void> handleHystrixRequest(final HttpServerResponse<O> response) { // writeHeaders(response); // // final Subject<Void, Void> subject = PublishSubject.create(); // final MultipleAssignmentSubscription subscription = new MultipleAssignmentSubscription(); // Subscription actionSubscription = Observable.timer(0, interval, TimeUnit.MILLISECONDS, Schedulers.computation()) // .subscribe(new Action1<Long>() { // @Override // public void call(Long tick) { // if (!response.getChannel().isOpen()) { // subscription.unsubscribe(); // return; // } // try { // writeMetric(JsonMapper.toJson(metrics), response); // } catch (Exception e) { // subject.onError(e); // } // } // }); // subscription.set(actionSubscription); // return subject; // } // // private void writeHeaders(HttpServerResponse<O> response) { // response.getHeaders().add("Content-Type", "text/event-stream;charset=UTF-8"); // response.getHeaders().add("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate"); // response.getHeaders().add("Pragma", "no-cache"); // } // // @SuppressWarnings("unchecked") // private void writeMetric(String json, HttpServerResponse<O> response) { // byte[] bytes = json.getBytes(Charset.defaultCharset()); // ByteBuf byteBuf = UnpooledByteBufAllocator.DEFAULT.buffer(bytes.length + EXTRA_SPACE); // byteBuf.writeBytes(HEADER); // byteBuf.writeBytes(bytes); // byteBuf.writeBytes(FOOTER); // response.writeAndFlush((O) byteBuf); // } // } // Path: reactive-lab-services/src/main/java/io/reactivex/lab/services/impls/AbstractMiddleTierService.java import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.HttpResponseStatus; import io.reactivex.lab.services.metrics.HystrixMetricsStreamHandler; import io.reactivex.lab.services.metrics.Metrics; import io.reactivex.netty.RxNetty; import io.reactivex.netty.pipeline.PipelineConfigurators; import io.reactivex.netty.protocol.http.server.HttpServer; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import io.reactivex.netty.protocol.http.sse.ServerSentEvent; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.UUID; import rx.Observable; import com.netflix.eureka2.client.EurekaClient; import com.netflix.eureka2.registry.InstanceInfo; import com.netflix.eureka2.registry.ServicePort; import com.netflix.eureka2.registry.datacenter.BasicDataCenterInfo; package io.reactivex.lab.services.impls; /** * Common base for the service impls */ public abstract class AbstractMiddleTierService { private EurekaClient client; private HttpServer<ByteBuf, ServerSentEvent> server; protected final String eurekaVipAddress; private final Metrics metrics; protected AbstractMiddleTierService(String eurekaVipAddress, EurekaClient client) { this.eurekaVipAddress = eurekaVipAddress; this.client = client; this.metrics = new Metrics(eurekaVipAddress); } public HttpServer<ByteBuf, ServerSentEvent> createServer(int port) { System.out.println("Start " + getClass().getSimpleName() + " on port: " + port); // declare handler chain (wrapped in Hystrix) // TODO create a better way of chaining these (related https://github.com/ReactiveX/RxNetty/issues/232 and https://github.com/ReactiveX/RxNetty/issues/202)
HystrixMetricsStreamHandler<ByteBuf, ServerSentEvent> handlerChain
Netflix/ReactiveLab
reactive-lab-services/src/main/java/io/reactivex/lab/services/impls/RatingsService.java
// Path: reactive-lab-services/src/main/java/io/reactivex/lab/services/common/SimpleJson.java // public class SimpleJson { // // private static final SimpleJson INSTANCE = new SimpleJson(); // // private SimpleJson() { // // } // // public static Map<String, Object> jsonToMap(String jsonString) { // return INSTANCE._jsonToMap(jsonString); // } // // public static String mapToJson(Map<String, ?> map) { // return INSTANCE._mapToJson(map); // } // // private final ObjectMapper objectMapper = new ObjectMapper(); // private final ObjectReader objectReader = objectMapper.reader(Map.class); // // private Map<String, Object> _jsonToMap(String jsonString) { // try { // return objectReader.readValue(jsonString); // } catch (IOException e) { // throw new RuntimeException("Unable to parse JSON", e); // } // } // // private final ObjectWriter objectWriter = objectMapper.writerWithType(Map.class); // // private String _mapToJson(Map<String, ?> map) { // try { // return objectWriter.writeValueAsString(map); // } catch (IOException e) { // throw new RuntimeException("Unable to write JSON", e); // } // } // }
import com.netflix.eureka2.client.EurekaClient; import io.reactivex.lab.services.common.SimpleJson; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import io.reactivex.netty.protocol.http.sse.ServerSentEvent; import rx.Observable; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit;
package io.reactivex.lab.services.impls; public class RatingsService extends AbstractMiddleTierService { public RatingsService(EurekaClient client) { super("reactive-lab-ratings-service", client); } @Override protected Observable<Void> handleRequest(HttpServerRequest<?> request, HttpServerResponse<ServerSentEvent> response) { List<String> videoIds = request.getQueryParameters().get("videoId"); return Observable.from(videoIds).map(videoId -> { Map<String, Object> video = new HashMap<>(); video.put("videoId", videoId); video.put("estimated_user_rating", 3.5); video.put("actual_user_rating", 4); video.put("average_user_rating", 3.1); return video;
// Path: reactive-lab-services/src/main/java/io/reactivex/lab/services/common/SimpleJson.java // public class SimpleJson { // // private static final SimpleJson INSTANCE = new SimpleJson(); // // private SimpleJson() { // // } // // public static Map<String, Object> jsonToMap(String jsonString) { // return INSTANCE._jsonToMap(jsonString); // } // // public static String mapToJson(Map<String, ?> map) { // return INSTANCE._mapToJson(map); // } // // private final ObjectMapper objectMapper = new ObjectMapper(); // private final ObjectReader objectReader = objectMapper.reader(Map.class); // // private Map<String, Object> _jsonToMap(String jsonString) { // try { // return objectReader.readValue(jsonString); // } catch (IOException e) { // throw new RuntimeException("Unable to parse JSON", e); // } // } // // private final ObjectWriter objectWriter = objectMapper.writerWithType(Map.class); // // private String _mapToJson(Map<String, ?> map) { // try { // return objectWriter.writeValueAsString(map); // } catch (IOException e) { // throw new RuntimeException("Unable to write JSON", e); // } // } // } // Path: reactive-lab-services/src/main/java/io/reactivex/lab/services/impls/RatingsService.java import com.netflix.eureka2.client.EurekaClient; import io.reactivex.lab.services.common.SimpleJson; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import io.reactivex.netty.protocol.http.sse.ServerSentEvent; import rx.Observable; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; package io.reactivex.lab.services.impls; public class RatingsService extends AbstractMiddleTierService { public RatingsService(EurekaClient client) { super("reactive-lab-ratings-service", client); } @Override protected Observable<Void> handleRequest(HttpServerRequest<?> request, HttpServerResponse<ServerSentEvent> response) { List<String> videoIds = request.getQueryParameters().get("videoId"); return Observable.from(videoIds).map(videoId -> { Map<String, Object> video = new HashMap<>(); video.put("videoId", videoId); video.put("estimated_user_rating", 3.5); video.put("actual_user_rating", 4); video.put("average_user_rating", 3.1); return video;
}).flatMap(video -> response.writeStringAndFlush("data: " + SimpleJson.mapToJson(video) + "\n"))
Netflix/ReactiveLab
reactive-lab-services/src/main/java/io/reactivex/lab/services/impls/UserService.java
// Path: reactive-lab-services/src/main/java/io/reactivex/lab/services/common/SimpleJson.java // public class SimpleJson { // // private static final SimpleJson INSTANCE = new SimpleJson(); // // private SimpleJson() { // // } // // public static Map<String, Object> jsonToMap(String jsonString) { // return INSTANCE._jsonToMap(jsonString); // } // // public static String mapToJson(Map<String, ?> map) { // return INSTANCE._mapToJson(map); // } // // private final ObjectMapper objectMapper = new ObjectMapper(); // private final ObjectReader objectReader = objectMapper.reader(Map.class); // // private Map<String, Object> _jsonToMap(String jsonString) { // try { // return objectReader.readValue(jsonString); // } catch (IOException e) { // throw new RuntimeException("Unable to parse JSON", e); // } // } // // private final ObjectWriter objectWriter = objectMapper.writerWithType(Map.class); // // private String _mapToJson(Map<String, ?> map) { // try { // return objectWriter.writeValueAsString(map); // } catch (IOException e) { // throw new RuntimeException("Unable to write JSON", e); // } // } // }
import com.netflix.eureka2.client.EurekaClient; import io.reactivex.lab.services.common.SimpleJson; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import io.reactivex.netty.protocol.http.sse.ServerSentEvent; import rx.Observable; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit;
package io.reactivex.lab.services.impls; public class UserService extends AbstractMiddleTierService { public UserService(EurekaClient client) { super("reactive-lab-user-service", client); } @Override protected Observable<Void> handleRequest(HttpServerRequest<?> request, HttpServerResponse<ServerSentEvent> response) { List<String> userIds = request.getQueryParameters().get("userId"); if (userIds == null || userIds.size() == 0) { return writeError(request, response, "At least one parameter of 'userId' must be included."); } return Observable.from(userIds).map(userId -> { Map<String, Object> user = new HashMap<>(); user.put("userId", userId); user.put("name", "Name Here"); user.put("other_data", "goes_here"); return user;
// Path: reactive-lab-services/src/main/java/io/reactivex/lab/services/common/SimpleJson.java // public class SimpleJson { // // private static final SimpleJson INSTANCE = new SimpleJson(); // // private SimpleJson() { // // } // // public static Map<String, Object> jsonToMap(String jsonString) { // return INSTANCE._jsonToMap(jsonString); // } // // public static String mapToJson(Map<String, ?> map) { // return INSTANCE._mapToJson(map); // } // // private final ObjectMapper objectMapper = new ObjectMapper(); // private final ObjectReader objectReader = objectMapper.reader(Map.class); // // private Map<String, Object> _jsonToMap(String jsonString) { // try { // return objectReader.readValue(jsonString); // } catch (IOException e) { // throw new RuntimeException("Unable to parse JSON", e); // } // } // // private final ObjectWriter objectWriter = objectMapper.writerWithType(Map.class); // // private String _mapToJson(Map<String, ?> map) { // try { // return objectWriter.writeValueAsString(map); // } catch (IOException e) { // throw new RuntimeException("Unable to write JSON", e); // } // } // } // Path: reactive-lab-services/src/main/java/io/reactivex/lab/services/impls/UserService.java import com.netflix.eureka2.client.EurekaClient; import io.reactivex.lab.services.common.SimpleJson; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import io.reactivex.netty.protocol.http.sse.ServerSentEvent; import rx.Observable; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; package io.reactivex.lab.services.impls; public class UserService extends AbstractMiddleTierService { public UserService(EurekaClient client) { super("reactive-lab-user-service", client); } @Override protected Observable<Void> handleRequest(HttpServerRequest<?> request, HttpServerResponse<ServerSentEvent> response) { List<String> userIds = request.getQueryParameters().get("userId"); if (userIds == null || userIds.size() == 0) { return writeError(request, response, "At least one parameter of 'userId' must be included."); } return Observable.from(userIds).map(userId -> { Map<String, Object> user = new HashMap<>(); user.put("userId", userId); user.put("name", "Name Here"); user.put("other_data", "goes_here"); return user;
}).flatMap(user -> response.writeStringAndFlush("data: " + SimpleJson.mapToJson(user) + "\n")
Netflix/ReactiveLab
reactive-lab-services/src/main/java/io/reactivex/lab/services/impls/SocialService.java
// Path: reactive-lab-services/src/main/java/io/reactivex/lab/services/common/SimpleJson.java // public class SimpleJson { // // private static final SimpleJson INSTANCE = new SimpleJson(); // // private SimpleJson() { // // } // // public static Map<String, Object> jsonToMap(String jsonString) { // return INSTANCE._jsonToMap(jsonString); // } // // public static String mapToJson(Map<String, ?> map) { // return INSTANCE._mapToJson(map); // } // // private final ObjectMapper objectMapper = new ObjectMapper(); // private final ObjectReader objectReader = objectMapper.reader(Map.class); // // private Map<String, Object> _jsonToMap(String jsonString) { // try { // return objectReader.readValue(jsonString); // } catch (IOException e) { // throw new RuntimeException("Unable to parse JSON", e); // } // } // // private final ObjectWriter objectWriter = objectMapper.writerWithType(Map.class); // // private String _mapToJson(Map<String, ?> map) { // try { // return objectWriter.writeValueAsString(map); // } catch (IOException e) { // throw new RuntimeException("Unable to write JSON", e); // } // } // }
import com.netflix.eureka2.client.EurekaClient; import io.reactivex.lab.services.common.SimpleJson; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import io.reactivex.netty.protocol.http.sse.ServerSentEvent; import rx.Observable; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit;
package io.reactivex.lab.services.impls; public class SocialService extends AbstractMiddleTierService { public SocialService(EurekaClient client) { super("reactive-lab-social-service", client); } @Override protected Observable<Void> handleRequest(HttpServerRequest<?> request, HttpServerResponse<ServerSentEvent> response) { return Observable.from(request.getQueryParameters().get("userId")).map(userId -> { Map<String, Object> user = new HashMap<>(); user.put("userId", userId); user.put("friends", Arrays.asList(randomUser(), randomUser(), randomUser(), randomUser())); return user;
// Path: reactive-lab-services/src/main/java/io/reactivex/lab/services/common/SimpleJson.java // public class SimpleJson { // // private static final SimpleJson INSTANCE = new SimpleJson(); // // private SimpleJson() { // // } // // public static Map<String, Object> jsonToMap(String jsonString) { // return INSTANCE._jsonToMap(jsonString); // } // // public static String mapToJson(Map<String, ?> map) { // return INSTANCE._mapToJson(map); // } // // private final ObjectMapper objectMapper = new ObjectMapper(); // private final ObjectReader objectReader = objectMapper.reader(Map.class); // // private Map<String, Object> _jsonToMap(String jsonString) { // try { // return objectReader.readValue(jsonString); // } catch (IOException e) { // throw new RuntimeException("Unable to parse JSON", e); // } // } // // private final ObjectWriter objectWriter = objectMapper.writerWithType(Map.class); // // private String _mapToJson(Map<String, ?> map) { // try { // return objectWriter.writeValueAsString(map); // } catch (IOException e) { // throw new RuntimeException("Unable to write JSON", e); // } // } // } // Path: reactive-lab-services/src/main/java/io/reactivex/lab/services/impls/SocialService.java import com.netflix.eureka2.client.EurekaClient; import io.reactivex.lab.services.common.SimpleJson; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import io.reactivex.netty.protocol.http.sse.ServerSentEvent; import rx.Observable; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; package io.reactivex.lab.services.impls; public class SocialService extends AbstractMiddleTierService { public SocialService(EurekaClient client) { super("reactive-lab-social-service", client); } @Override protected Observable<Void> handleRequest(HttpServerRequest<?> request, HttpServerResponse<ServerSentEvent> response) { return Observable.from(request.getQueryParameters().get("userId")).map(userId -> { Map<String, Object> user = new HashMap<>(); user.put("userId", userId); user.put("friends", Arrays.asList(randomUser(), randomUser(), randomUser(), randomUser())); return user;
}).flatMap(list -> response.writeStringAndFlush("data: " + SimpleJson.mapToJson(list) + "\n"))
Netflix/ReactiveLab
reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/clients/PersonalizedCatalogCommand.java
// Path: reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/clients/PersonalizedCatalogCommand.java // public static class Catalog { // // private final Map<String, Object> data; // // private Catalog(Map<String, Object> data) { // this.data = data; // } // // @SuppressWarnings("unchecked") // public Observable<Video> videos() { // try { // return Observable.from((List<Integer>) data.get("videos")).map(Video::new); // } catch (Exception e) { // return Observable.error(e); // } // } // // public static Catalog fromJson(String json) { // return new Catalog(SimpleJson.jsonToMap(json)); // } // // } // // Path: reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/common/SimpleJson.java // public class SimpleJson { // // private static final SimpleJson INSTANCE = new SimpleJson(); // // private SimpleJson() { // // } // // public static Map<String, Object> jsonToMap(String jsonString) { // return INSTANCE._jsonToMap(jsonString); // } // // public static String mapToJson(Map<String, ? extends Object> map) { // return INSTANCE._mapToJson(map); // } // // private final ObjectMapper objectMapper = new ObjectMapper(); // private final ObjectReader objectReader = objectMapper.reader(Map.class); // // private Map<String, Object> _jsonToMap(String jsonString) { // try { // return objectReader.readValue(jsonString); // } catch (IOException e) { // throw new RuntimeException("Unable to parse JSON", e); // } // } // // private final ObjectWriter objectWriter = objectMapper.writerWithType(Map.class); // // private String _mapToJson(Map<String, ? extends Object> map) { // try { // return objectWriter.writeValueAsString(map); // } catch (IOException e) { // throw new RuntimeException("Unable to write JSON", e); // } // } // }
import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixObservableCommand; import io.netty.buffer.ByteBuf; import io.reactivex.lab.gateway.clients.PersonalizedCatalogCommand.Catalog; import io.reactivex.lab.gateway.clients.UserCommand.User; import io.reactivex.lab.gateway.common.SimpleJson; import io.reactivex.lab.gateway.loadbalancer.DiscoveryAndLoadBalancer; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import io.reactivex.netty.protocol.http.sse.ServerSentEvent; import netflix.ocelli.LoadBalancer; import netflix.ocelli.rxnetty.HttpClientHolder; import rx.Observable; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map;
userData.put("list_title", "Really quirky and over detailed list title!"); userData.put("other_data", "goes_here"); userData.put("videos", Arrays.asList(12345, 23456, 34567, 45678, 56789, 67890)); return new Catalog(userData); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } }); } public static class Catalog { private final Map<String, Object> data; private Catalog(Map<String, Object> data) { this.data = data; } @SuppressWarnings("unchecked") public Observable<Video> videos() { try { return Observable.from((List<Integer>) data.get("videos")).map(Video::new); } catch (Exception e) { return Observable.error(e); } } public static Catalog fromJson(String json) {
// Path: reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/clients/PersonalizedCatalogCommand.java // public static class Catalog { // // private final Map<String, Object> data; // // private Catalog(Map<String, Object> data) { // this.data = data; // } // // @SuppressWarnings("unchecked") // public Observable<Video> videos() { // try { // return Observable.from((List<Integer>) data.get("videos")).map(Video::new); // } catch (Exception e) { // return Observable.error(e); // } // } // // public static Catalog fromJson(String json) { // return new Catalog(SimpleJson.jsonToMap(json)); // } // // } // // Path: reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/common/SimpleJson.java // public class SimpleJson { // // private static final SimpleJson INSTANCE = new SimpleJson(); // // private SimpleJson() { // // } // // public static Map<String, Object> jsonToMap(String jsonString) { // return INSTANCE._jsonToMap(jsonString); // } // // public static String mapToJson(Map<String, ? extends Object> map) { // return INSTANCE._mapToJson(map); // } // // private final ObjectMapper objectMapper = new ObjectMapper(); // private final ObjectReader objectReader = objectMapper.reader(Map.class); // // private Map<String, Object> _jsonToMap(String jsonString) { // try { // return objectReader.readValue(jsonString); // } catch (IOException e) { // throw new RuntimeException("Unable to parse JSON", e); // } // } // // private final ObjectWriter objectWriter = objectMapper.writerWithType(Map.class); // // private String _mapToJson(Map<String, ? extends Object> map) { // try { // return objectWriter.writeValueAsString(map); // } catch (IOException e) { // throw new RuntimeException("Unable to write JSON", e); // } // } // } // Path: reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/clients/PersonalizedCatalogCommand.java import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixObservableCommand; import io.netty.buffer.ByteBuf; import io.reactivex.lab.gateway.clients.PersonalizedCatalogCommand.Catalog; import io.reactivex.lab.gateway.clients.UserCommand.User; import io.reactivex.lab.gateway.common.SimpleJson; import io.reactivex.lab.gateway.loadbalancer.DiscoveryAndLoadBalancer; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import io.reactivex.netty.protocol.http.sse.ServerSentEvent; import netflix.ocelli.LoadBalancer; import netflix.ocelli.rxnetty.HttpClientHolder; import rx.Observable; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; userData.put("list_title", "Really quirky and over detailed list title!"); userData.put("other_data", "goes_here"); userData.put("videos", Arrays.asList(12345, 23456, 34567, 45678, 56789, 67890)); return new Catalog(userData); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } }); } public static class Catalog { private final Map<String, Object> data; private Catalog(Map<String, Object> data) { this.data = data; } @SuppressWarnings("unchecked") public Observable<Video> videos() { try { return Observable.from((List<Integer>) data.get("videos")).map(Video::new); } catch (Exception e) { return Observable.error(e); } } public static Catalog fromJson(String json) {
return new Catalog(SimpleJson.jsonToMap(json));
Netflix/ReactiveLab
reactive-lab-services/src/main/java/io/reactivex/lab/services/impls/PersonalizedCatalogService.java
// Path: reactive-lab-services/src/main/java/io/reactivex/lab/services/common/SimpleJson.java // public class SimpleJson { // // private static final SimpleJson INSTANCE = new SimpleJson(); // // private SimpleJson() { // // } // // public static Map<String, Object> jsonToMap(String jsonString) { // return INSTANCE._jsonToMap(jsonString); // } // // public static String mapToJson(Map<String, ?> map) { // return INSTANCE._mapToJson(map); // } // // private final ObjectMapper objectMapper = new ObjectMapper(); // private final ObjectReader objectReader = objectMapper.reader(Map.class); // // private Map<String, Object> _jsonToMap(String jsonString) { // try { // return objectReader.readValue(jsonString); // } catch (IOException e) { // throw new RuntimeException("Unable to parse JSON", e); // } // } // // private final ObjectWriter objectWriter = objectMapper.writerWithType(Map.class); // // private String _mapToJson(Map<String, ?> map) { // try { // return objectWriter.writeValueAsString(map); // } catch (IOException e) { // throw new RuntimeException("Unable to write JSON", e); // } // } // }
import com.netflix.eureka2.client.EurekaClient; import io.reactivex.lab.services.common.SimpleJson; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import io.reactivex.netty.protocol.http.sse.ServerSentEvent; import rx.Observable; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit;
package io.reactivex.lab.services.impls; public class PersonalizedCatalogService extends AbstractMiddleTierService { public PersonalizedCatalogService(EurekaClient client) { super("reactive-lab-personalized-catalog-service", client); } @Override protected Observable<Void> handleRequest(HttpServerRequest<?> request, HttpServerResponse<ServerSentEvent> response) { return Observable.from(request.getQueryParameters().get("userId")).map(userId -> { Map<String, Object> userData = new HashMap<>(); userData.put("user_id", userId); userData.put("list_title", "Really quirky and over detailed list title!"); userData.put("other_data", "goes_here"); userData.put("videos", Arrays.asList(12345, 23456, 34567, 45678, 56789, 67890)); return userData;
// Path: reactive-lab-services/src/main/java/io/reactivex/lab/services/common/SimpleJson.java // public class SimpleJson { // // private static final SimpleJson INSTANCE = new SimpleJson(); // // private SimpleJson() { // // } // // public static Map<String, Object> jsonToMap(String jsonString) { // return INSTANCE._jsonToMap(jsonString); // } // // public static String mapToJson(Map<String, ?> map) { // return INSTANCE._mapToJson(map); // } // // private final ObjectMapper objectMapper = new ObjectMapper(); // private final ObjectReader objectReader = objectMapper.reader(Map.class); // // private Map<String, Object> _jsonToMap(String jsonString) { // try { // return objectReader.readValue(jsonString); // } catch (IOException e) { // throw new RuntimeException("Unable to parse JSON", e); // } // } // // private final ObjectWriter objectWriter = objectMapper.writerWithType(Map.class); // // private String _mapToJson(Map<String, ?> map) { // try { // return objectWriter.writeValueAsString(map); // } catch (IOException e) { // throw new RuntimeException("Unable to write JSON", e); // } // } // } // Path: reactive-lab-services/src/main/java/io/reactivex/lab/services/impls/PersonalizedCatalogService.java import com.netflix.eureka2.client.EurekaClient; import io.reactivex.lab.services.common.SimpleJson; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import io.reactivex.netty.protocol.http.sse.ServerSentEvent; import rx.Observable; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; package io.reactivex.lab.services.impls; public class PersonalizedCatalogService extends AbstractMiddleTierService { public PersonalizedCatalogService(EurekaClient client) { super("reactive-lab-personalized-catalog-service", client); } @Override protected Observable<Void> handleRequest(HttpServerRequest<?> request, HttpServerResponse<ServerSentEvent> response) { return Observable.from(request.getQueryParameters().get("userId")).map(userId -> { Map<String, Object> userData = new HashMap<>(); userData.put("user_id", userId); userData.put("list_title", "Really quirky and over detailed list title!"); userData.put("other_data", "goes_here"); userData.put("videos", Arrays.asList(12345, 23456, 34567, 45678, 56789, 67890)); return userData;
}).flatMap(list -> response.writeStringAndFlush("data: " + SimpleJson.mapToJson(list) + "\n"))
Netflix/ReactiveLab
reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/clients/RatingsCommand.java
// Path: reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/clients/PersonalizedCatalogCommand.java // public static class Video implements ID { // // private final int id; // // public Video(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // } // // Path: reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/clients/RatingsCommand.java // public static class Rating { // // private final Map<String, Object> data; // // private Rating(Map<String, Object> data) { // this.data = data; // } // // public double getEstimatedUserRating() { // return (double) data.get("estimated_user_rating"); // } // // public double getActualUserRating() { // return (double) data.get("actual_user_rating"); // } // // public double getAverageUserRating() { // return (double) data.get("average_user_rating"); // } // // public static Rating fromJson(String json) { // return new Rating(SimpleJson.jsonToMap(json)); // } // // } // // Path: reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/common/SimpleJson.java // public class SimpleJson { // // private static final SimpleJson INSTANCE = new SimpleJson(); // // private SimpleJson() { // // } // // public static Map<String, Object> jsonToMap(String jsonString) { // return INSTANCE._jsonToMap(jsonString); // } // // public static String mapToJson(Map<String, ? extends Object> map) { // return INSTANCE._mapToJson(map); // } // // private final ObjectMapper objectMapper = new ObjectMapper(); // private final ObjectReader objectReader = objectMapper.reader(Map.class); // // private Map<String, Object> _jsonToMap(String jsonString) { // try { // return objectReader.readValue(jsonString); // } catch (IOException e) { // throw new RuntimeException("Unable to parse JSON", e); // } // } // // private final ObjectWriter objectWriter = objectMapper.writerWithType(Map.class); // // private String _mapToJson(Map<String, ? extends Object> map) { // try { // return objectWriter.writeValueAsString(map); // } catch (IOException e) { // throw new RuntimeException("Unable to write JSON", e); // } // } // }
import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixObservableCommand; import io.netty.buffer.ByteBuf; import io.reactivex.lab.gateway.clients.PersonalizedCatalogCommand.Video; import io.reactivex.lab.gateway.clients.RatingsCommand.Rating; import io.reactivex.lab.gateway.common.SimpleJson; import io.reactivex.lab.gateway.loadbalancer.DiscoveryAndLoadBalancer; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import io.reactivex.netty.protocol.http.sse.ServerSentEvent; import netflix.ocelli.LoadBalancer; import netflix.ocelli.rxnetty.HttpClientHolder; import rx.Observable; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map;
protected Observable<Rating> resumeWithFallback() { Map<String, Object> video = new HashMap<>(); video.put("videoId", videos.get(0).getId()); video.put("estimated_user_rating", 3.5); video.put("actual_user_rating", 4); video.put("average_user_rating", 3.1); return Observable.just(new Rating(video)); } public static class Rating { private final Map<String, Object> data; private Rating(Map<String, Object> data) { this.data = data; } public double getEstimatedUserRating() { return (double) data.get("estimated_user_rating"); } public double getActualUserRating() { return (double) data.get("actual_user_rating"); } public double getAverageUserRating() { return (double) data.get("average_user_rating"); } public static Rating fromJson(String json) {
// Path: reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/clients/PersonalizedCatalogCommand.java // public static class Video implements ID { // // private final int id; // // public Video(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // } // // Path: reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/clients/RatingsCommand.java // public static class Rating { // // private final Map<String, Object> data; // // private Rating(Map<String, Object> data) { // this.data = data; // } // // public double getEstimatedUserRating() { // return (double) data.get("estimated_user_rating"); // } // // public double getActualUserRating() { // return (double) data.get("actual_user_rating"); // } // // public double getAverageUserRating() { // return (double) data.get("average_user_rating"); // } // // public static Rating fromJson(String json) { // return new Rating(SimpleJson.jsonToMap(json)); // } // // } // // Path: reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/common/SimpleJson.java // public class SimpleJson { // // private static final SimpleJson INSTANCE = new SimpleJson(); // // private SimpleJson() { // // } // // public static Map<String, Object> jsonToMap(String jsonString) { // return INSTANCE._jsonToMap(jsonString); // } // // public static String mapToJson(Map<String, ? extends Object> map) { // return INSTANCE._mapToJson(map); // } // // private final ObjectMapper objectMapper = new ObjectMapper(); // private final ObjectReader objectReader = objectMapper.reader(Map.class); // // private Map<String, Object> _jsonToMap(String jsonString) { // try { // return objectReader.readValue(jsonString); // } catch (IOException e) { // throw new RuntimeException("Unable to parse JSON", e); // } // } // // private final ObjectWriter objectWriter = objectMapper.writerWithType(Map.class); // // private String _mapToJson(Map<String, ? extends Object> map) { // try { // return objectWriter.writeValueAsString(map); // } catch (IOException e) { // throw new RuntimeException("Unable to write JSON", e); // } // } // } // Path: reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/clients/RatingsCommand.java import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixObservableCommand; import io.netty.buffer.ByteBuf; import io.reactivex.lab.gateway.clients.PersonalizedCatalogCommand.Video; import io.reactivex.lab.gateway.clients.RatingsCommand.Rating; import io.reactivex.lab.gateway.common.SimpleJson; import io.reactivex.lab.gateway.loadbalancer.DiscoveryAndLoadBalancer; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import io.reactivex.netty.protocol.http.sse.ServerSentEvent; import netflix.ocelli.LoadBalancer; import netflix.ocelli.rxnetty.HttpClientHolder; import rx.Observable; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; protected Observable<Rating> resumeWithFallback() { Map<String, Object> video = new HashMap<>(); video.put("videoId", videos.get(0).getId()); video.put("estimated_user_rating", 3.5); video.put("actual_user_rating", 4); video.put("average_user_rating", 3.1); return Observable.just(new Rating(video)); } public static class Rating { private final Map<String, Object> data; private Rating(Map<String, Object> data) { this.data = data; } public double getEstimatedUserRating() { return (double) data.get("estimated_user_rating"); } public double getActualUserRating() { return (double) data.get("actual_user_rating"); } public double getAverageUserRating() { return (double) data.get("average_user_rating"); } public static Rating fromJson(String json) {
return new Rating(SimpleJson.jsonToMap(json));
Netflix/ReactiveLab
reactive-lab-gateway/src/test/java/io/reactivex/lab/gateway/mock/BackendResponseTest.java
// Path: reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/routes/mock/BackendResponse.java // public class BackendResponse { // // private final static JsonFactory jsonFactory = new JsonFactory(); // // private final long responseKey; // private final int delay; // private final int numItems; // private final int itemSize; // private final String[] items; // // public BackendResponse(long responseKey, int delay, int numItems, int itemSize, String[] items) { // this.responseKey = responseKey; // this.delay = delay; // this.numItems = numItems; // this.itemSize = itemSize; // this.items = items; // } // // public static BackendResponse fromJson(InputStream inputStream) { // try { // JsonParser parser = jsonFactory.createJsonParser(inputStream); // return parseBackendResponse(parser); // } catch (Exception e) { // throw new RuntimeException("Failed to parse JSON", e); // } // } // // public static BackendResponse fromJson(String json) { // try { // JsonParser parser = jsonFactory.createJsonParser(json); // return parseBackendResponse(parser); // } catch (Exception e) { // throw new RuntimeException("Failed to parse JSON", e); // } // } // // public static Observable<BackendResponse> fromJsonToObservable(InputStream inputStream) { // return fromJsonToObservable(inputStream, Schedulers.computation()); // } // // public static Observable<BackendResponse> fromJsonToObservable(final InputStream inputStream, Scheduler scheduler) { // return Observable.create((Subscriber<? super BackendResponse> o) -> { // try { // o.onNext(fromJson(inputStream)); // o.onCompleted(); // } catch (Exception e) { // o.onError(e); // } // }).subscribeOn(scheduler); // } // // private static BackendResponse parseBackendResponse(JsonParser parser) throws IOException { // try { // // Sanity check: verify that we got "Json Object": // if (parser.nextToken() != JsonToken.START_OBJECT) { // throw new IOException("Expected data to start with an Object"); // } // long responseKey = 0; // int delay = 0; // int numItems = 0; // int itemSize = 0; // String[] items = null; // JsonToken current; // // while (parser.nextToken() != JsonToken.END_OBJECT) { // String fieldName = parser.getCurrentName(); // // advance // current = parser.nextToken(); // if (fieldName.equals("responseKey")) { // responseKey = parser.getLongValue(); // } else if (fieldName.equals("delay")) { // delay = parser.getIntValue(); // } else if (fieldName.equals("itemSize")) { // itemSize = parser.getIntValue(); // } else if (fieldName.equals("numItems")) { // numItems = parser.getIntValue(); // } else if (fieldName.equals("items")) { // // expect numItems to be populated before hitting this // if (numItems == 0) { // throw new IllegalStateException("Expected numItems > 0"); // } // items = new String[numItems]; // if (current == JsonToken.START_ARRAY) { // int j = 0; // // For each of the records in the array // while (parser.nextToken() != JsonToken.END_ARRAY) { // items[j++] = parser.getText(); // } // } else { // // System.out.println("Error: items should be an array: skipping."); // parser.skipChildren(); // } // // } // } // return new BackendResponse(responseKey, delay, numItems, itemSize, items); // } finally { // parser.close(); // } // } // // public long getResponseKey() { // return responseKey; // } // // public int getDelay() { // return delay; // } // // public int getNumItems() { // return numItems; // } // // public int getItemSize() { // return itemSize; // } // // public String[] getItems() { // return items; // } // // }
import static junit.framework.Assert.assertEquals; import io.reactivex.lab.gateway.routes.mock.BackendResponse; import org.junit.Test;
package io.reactivex.lab.gateway.mock; public class BackendResponseTest { @Test public void testJsonParse() throws Exception {
// Path: reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/routes/mock/BackendResponse.java // public class BackendResponse { // // private final static JsonFactory jsonFactory = new JsonFactory(); // // private final long responseKey; // private final int delay; // private final int numItems; // private final int itemSize; // private final String[] items; // // public BackendResponse(long responseKey, int delay, int numItems, int itemSize, String[] items) { // this.responseKey = responseKey; // this.delay = delay; // this.numItems = numItems; // this.itemSize = itemSize; // this.items = items; // } // // public static BackendResponse fromJson(InputStream inputStream) { // try { // JsonParser parser = jsonFactory.createJsonParser(inputStream); // return parseBackendResponse(parser); // } catch (Exception e) { // throw new RuntimeException("Failed to parse JSON", e); // } // } // // public static BackendResponse fromJson(String json) { // try { // JsonParser parser = jsonFactory.createJsonParser(json); // return parseBackendResponse(parser); // } catch (Exception e) { // throw new RuntimeException("Failed to parse JSON", e); // } // } // // public static Observable<BackendResponse> fromJsonToObservable(InputStream inputStream) { // return fromJsonToObservable(inputStream, Schedulers.computation()); // } // // public static Observable<BackendResponse> fromJsonToObservable(final InputStream inputStream, Scheduler scheduler) { // return Observable.create((Subscriber<? super BackendResponse> o) -> { // try { // o.onNext(fromJson(inputStream)); // o.onCompleted(); // } catch (Exception e) { // o.onError(e); // } // }).subscribeOn(scheduler); // } // // private static BackendResponse parseBackendResponse(JsonParser parser) throws IOException { // try { // // Sanity check: verify that we got "Json Object": // if (parser.nextToken() != JsonToken.START_OBJECT) { // throw new IOException("Expected data to start with an Object"); // } // long responseKey = 0; // int delay = 0; // int numItems = 0; // int itemSize = 0; // String[] items = null; // JsonToken current; // // while (parser.nextToken() != JsonToken.END_OBJECT) { // String fieldName = parser.getCurrentName(); // // advance // current = parser.nextToken(); // if (fieldName.equals("responseKey")) { // responseKey = parser.getLongValue(); // } else if (fieldName.equals("delay")) { // delay = parser.getIntValue(); // } else if (fieldName.equals("itemSize")) { // itemSize = parser.getIntValue(); // } else if (fieldName.equals("numItems")) { // numItems = parser.getIntValue(); // } else if (fieldName.equals("items")) { // // expect numItems to be populated before hitting this // if (numItems == 0) { // throw new IllegalStateException("Expected numItems > 0"); // } // items = new String[numItems]; // if (current == JsonToken.START_ARRAY) { // int j = 0; // // For each of the records in the array // while (parser.nextToken() != JsonToken.END_ARRAY) { // items[j++] = parser.getText(); // } // } else { // // System.out.println("Error: items should be an array: skipping."); // parser.skipChildren(); // } // // } // } // return new BackendResponse(responseKey, delay, numItems, itemSize, items); // } finally { // parser.close(); // } // } // // public long getResponseKey() { // return responseKey; // } // // public int getDelay() { // return delay; // } // // public int getNumItems() { // return numItems; // } // // public int getItemSize() { // return itemSize; // } // // public String[] getItems() { // return items; // } // // } // Path: reactive-lab-gateway/src/test/java/io/reactivex/lab/gateway/mock/BackendResponseTest.java import static junit.framework.Assert.assertEquals; import io.reactivex.lab.gateway.routes.mock.BackendResponse; import org.junit.Test; package io.reactivex.lab.gateway.mock; public class BackendResponseTest { @Test public void testJsonParse() throws Exception {
BackendResponse r = BackendResponse.fromJson("{ \"responseKey\": 9999, \"delay\": 50, \"itemSize\": 128, \"numItems\": 2, \"items\": [ \"Lorem\", \"Ipsum\" ]}");
Netflix/ReactiveLab
reactive-lab-services/src/main/java/io/reactivex/lab/services/impls/BookmarksService.java
// Path: reactive-lab-services/src/main/java/io/reactivex/lab/services/common/SimpleJson.java // public class SimpleJson { // // private static final SimpleJson INSTANCE = new SimpleJson(); // // private SimpleJson() { // // } // // public static Map<String, Object> jsonToMap(String jsonString) { // return INSTANCE._jsonToMap(jsonString); // } // // public static String mapToJson(Map<String, ?> map) { // return INSTANCE._mapToJson(map); // } // // private final ObjectMapper objectMapper = new ObjectMapper(); // private final ObjectReader objectReader = objectMapper.reader(Map.class); // // private Map<String, Object> _jsonToMap(String jsonString) { // try { // return objectReader.readValue(jsonString); // } catch (IOException e) { // throw new RuntimeException("Unable to parse JSON", e); // } // } // // private final ObjectWriter objectWriter = objectMapper.writerWithType(Map.class); // // private String _mapToJson(Map<String, ?> map) { // try { // return objectWriter.writeValueAsString(map); // } catch (IOException e) { // throw new RuntimeException("Unable to write JSON", e); // } // } // }
import com.netflix.eureka2.client.EurekaClient; import io.reactivex.lab.services.common.Random; import io.reactivex.lab.services.common.SimpleJson; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import io.reactivex.netty.protocol.http.sse.ServerSentEvent; import rx.Observable; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit;
package io.reactivex.lab.services.impls; public class BookmarksService extends AbstractMiddleTierService { public BookmarksService(EurekaClient client) { super("reactive-lab-bookmark-service", client); } @Override protected Observable<Void> handleRequest(HttpServerRequest<?> request, HttpServerResponse<ServerSentEvent> response) { List<String> videoIds = request.getQueryParameters().get("videoId"); int latency = 1; if (Random.randomIntFrom0to100() > 80) { latency = 10; } return Observable.from(videoIds).map(videoId -> { Map<String, Object> video = new HashMap<>(); video.put("videoId", videoId); video.put("position", (int) (Math.random() * 5000)); return video;
// Path: reactive-lab-services/src/main/java/io/reactivex/lab/services/common/SimpleJson.java // public class SimpleJson { // // private static final SimpleJson INSTANCE = new SimpleJson(); // // private SimpleJson() { // // } // // public static Map<String, Object> jsonToMap(String jsonString) { // return INSTANCE._jsonToMap(jsonString); // } // // public static String mapToJson(Map<String, ?> map) { // return INSTANCE._mapToJson(map); // } // // private final ObjectMapper objectMapper = new ObjectMapper(); // private final ObjectReader objectReader = objectMapper.reader(Map.class); // // private Map<String, Object> _jsonToMap(String jsonString) { // try { // return objectReader.readValue(jsonString); // } catch (IOException e) { // throw new RuntimeException("Unable to parse JSON", e); // } // } // // private final ObjectWriter objectWriter = objectMapper.writerWithType(Map.class); // // private String _mapToJson(Map<String, ?> map) { // try { // return objectWriter.writeValueAsString(map); // } catch (IOException e) { // throw new RuntimeException("Unable to write JSON", e); // } // } // } // Path: reactive-lab-services/src/main/java/io/reactivex/lab/services/impls/BookmarksService.java import com.netflix.eureka2.client.EurekaClient; import io.reactivex.lab.services.common.Random; import io.reactivex.lab.services.common.SimpleJson; import io.reactivex.netty.protocol.http.server.HttpServerRequest; import io.reactivex.netty.protocol.http.server.HttpServerResponse; import io.reactivex.netty.protocol.http.sse.ServerSentEvent; import rx.Observable; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; package io.reactivex.lab.services.impls; public class BookmarksService extends AbstractMiddleTierService { public BookmarksService(EurekaClient client) { super("reactive-lab-bookmark-service", client); } @Override protected Observable<Void> handleRequest(HttpServerRequest<?> request, HttpServerResponse<ServerSentEvent> response) { List<String> videoIds = request.getQueryParameters().get("videoId"); int latency = 1; if (Random.randomIntFrom0to100() > 80) { latency = 10; } return Observable.from(videoIds).map(videoId -> { Map<String, Object> video = new HashMap<>(); video.put("videoId", videoId); video.put("position", (int) (Math.random() * 5000)); return video;
}).flatMap(video -> response.writeStringAndFlush("data: " + SimpleJson.mapToJson(video) + "\n"))
Netflix/ReactiveLab
reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/clients/BookmarksCommand.java
// Path: reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/clients/BookmarksCommand.java // public static class Bookmark { // // private final Map<String, Object> data; // // Bookmark(Map<String, Object> data) { // this.data = data; // } // // public static Bookmark fromJson(String json) { // return new Bookmark(SimpleJson.jsonToMap(json)); // } // // public int getPosition() { // return (int) data.get("position"); // } // // public int getVideoId() { // return Integer.parseInt(String.valueOf(data.get("videoId"))); // } // // } // // Path: reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/clients/PersonalizedCatalogCommand.java // public static class Video implements ID { // // private final int id; // // public Video(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // } // // Path: reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/common/SimpleJson.java // public class SimpleJson { // // private static final SimpleJson INSTANCE = new SimpleJson(); // // private SimpleJson() { // // } // // public static Map<String, Object> jsonToMap(String jsonString) { // return INSTANCE._jsonToMap(jsonString); // } // // public static String mapToJson(Map<String, ? extends Object> map) { // return INSTANCE._mapToJson(map); // } // // private final ObjectMapper objectMapper = new ObjectMapper(); // private final ObjectReader objectReader = objectMapper.reader(Map.class); // // private Map<String, Object> _jsonToMap(String jsonString) { // try { // return objectReader.readValue(jsonString); // } catch (IOException e) { // throw new RuntimeException("Unable to parse JSON", e); // } // } // // private final ObjectWriter objectWriter = objectMapper.writerWithType(Map.class); // // private String _mapToJson(Map<String, ? extends Object> map) { // try { // return objectWriter.writeValueAsString(map); // } catch (IOException e) { // throw new RuntimeException("Unable to write JSON", e); // } // } // }
import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixObservableCommand; import io.netty.buffer.ByteBuf; import io.reactivex.lab.gateway.clients.BookmarksCommand.Bookmark; import io.reactivex.lab.gateway.clients.PersonalizedCatalogCommand.Video; import io.reactivex.lab.gateway.common.SimpleJson; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import io.reactivex.netty.protocol.http.sse.ServerSentEvent; import netflix.ocelli.LoadBalancer; import netflix.ocelli.rxnetty.HttpClientHolder; import rx.Observable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
.<Bookmark>flatMap(client -> client.submit(request) .flatMap(r -> r.getContent().map((ServerSentEvent sse) -> Bookmark.fromJson(sse.contentAsString())))) .retry(1); } protected Observable<Bookmark> resumeWithFallback() { List<Bookmark> bs = new ArrayList<>(); for (Video v : videos) { Map<String, Object> data = new HashMap<>(); data.put("position", 0); data.put("videoId", v.getId()); bs.add(new Bookmark(data)); } return Observable.from(bs); } @Override protected String getCacheKey() { return cacheKey; } public static class Bookmark { private final Map<String, Object> data; Bookmark(Map<String, Object> data) { this.data = data; } public static Bookmark fromJson(String json) {
// Path: reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/clients/BookmarksCommand.java // public static class Bookmark { // // private final Map<String, Object> data; // // Bookmark(Map<String, Object> data) { // this.data = data; // } // // public static Bookmark fromJson(String json) { // return new Bookmark(SimpleJson.jsonToMap(json)); // } // // public int getPosition() { // return (int) data.get("position"); // } // // public int getVideoId() { // return Integer.parseInt(String.valueOf(data.get("videoId"))); // } // // } // // Path: reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/clients/PersonalizedCatalogCommand.java // public static class Video implements ID { // // private final int id; // // public Video(int id) { // this.id = id; // } // // public int getId() { // return id; // } // // } // // Path: reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/common/SimpleJson.java // public class SimpleJson { // // private static final SimpleJson INSTANCE = new SimpleJson(); // // private SimpleJson() { // // } // // public static Map<String, Object> jsonToMap(String jsonString) { // return INSTANCE._jsonToMap(jsonString); // } // // public static String mapToJson(Map<String, ? extends Object> map) { // return INSTANCE._mapToJson(map); // } // // private final ObjectMapper objectMapper = new ObjectMapper(); // private final ObjectReader objectReader = objectMapper.reader(Map.class); // // private Map<String, Object> _jsonToMap(String jsonString) { // try { // return objectReader.readValue(jsonString); // } catch (IOException e) { // throw new RuntimeException("Unable to parse JSON", e); // } // } // // private final ObjectWriter objectWriter = objectMapper.writerWithType(Map.class); // // private String _mapToJson(Map<String, ? extends Object> map) { // try { // return objectWriter.writeValueAsString(map); // } catch (IOException e) { // throw new RuntimeException("Unable to write JSON", e); // } // } // } // Path: reactive-lab-gateway/src/main/java/io/reactivex/lab/gateway/clients/BookmarksCommand.java import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixObservableCommand; import io.netty.buffer.ByteBuf; import io.reactivex.lab.gateway.clients.BookmarksCommand.Bookmark; import io.reactivex.lab.gateway.clients.PersonalizedCatalogCommand.Video; import io.reactivex.lab.gateway.common.SimpleJson; import io.reactivex.netty.protocol.http.client.HttpClientRequest; import io.reactivex.netty.protocol.http.sse.ServerSentEvent; import netflix.ocelli.LoadBalancer; import netflix.ocelli.rxnetty.HttpClientHolder; import rx.Observable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; .<Bookmark>flatMap(client -> client.submit(request) .flatMap(r -> r.getContent().map((ServerSentEvent sse) -> Bookmark.fromJson(sse.contentAsString())))) .retry(1); } protected Observable<Bookmark> resumeWithFallback() { List<Bookmark> bs = new ArrayList<>(); for (Video v : videos) { Map<String, Object> data = new HashMap<>(); data.put("position", 0); data.put("videoId", v.getId()); bs.add(new Bookmark(data)); } return Observable.from(bs); } @Override protected String getCacheKey() { return cacheKey; } public static class Bookmark { private final Map<String, Object> data; Bookmark(Map<String, Object> data) { this.data = data; } public static Bookmark fromJson(String json) {
return new Bookmark(SimpleJson.jsonToMap(json));
vangj/jbayes
src/test/java/com/github/vangj/jbayes/inf/exact/graph/pptc/EvidenceTest.java
// Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/Node.java // public class Node extends Variable { // // private final List<Double> probs; // private List<String> valueList; // private Potential potential; // private Map<String, Object> metadata; // // public Node() { // probs = new ArrayList<>(); // } // // public Node(Variable v) { // probs = new ArrayList<>(); // metadata = new HashMap<>(); // this.id = v.id; // this.name = v.name; // this.values = v.values; // this.valueList = this.values.stream() // .collect(Collectors.toList()); // } // // private Node(NodeBuilder builder) { // id = builder.id; // metadata = new HashMap<>(); // name = builder.name; // values = builder.values; // probs = builder.probs; // this.valueList = this.values.stream() // .collect(Collectors.toList()); // } // // public static NodeBuilder builder() { // return new NodeBuilder(); // } // // /** // * Adds any metadata. // * // * @param k Key. // * @param v Value. // */ // public void addMetadata(String k, Object v) { // metadata.put(k, v); // } // // /** // * Gets the metadata associated with the specified key. // * // * @param k Key. // * @return Value. // */ // public Object getMetadata(String k) { // return metadata.get(k); // } // // public Potential getPotential() { // return potential; // } // // public void setPotential(Potential potential) { // this.potential = potential; // } // // public Node addProb(Double prob) { // probs.add(prob); // return this; // } // // public int weight() { // return values.size(); // } // // public List<Double> probs() { // return probs; // } // // public List<String> getValueList() { // return valueList; // } // // public static final class NodeBuilder { // // private String id; // private String name; // private Set<String> values; // private List<Double> probs; // // private NodeBuilder() { // values = new LinkedHashSet<>(); // probs = new ArrayList<>(); // } // // public NodeBuilder from(Variable v) { // this.id = v.id; // this.name = v.name; // this.values = v.values; // return this; // } // // public NodeBuilder id(String val) { // id = val; // return this; // } // // public NodeBuilder name(String val) { // name = val; // return this; // } // // public NodeBuilder value(String val) { // values.add(val); // return this; // } // // public NodeBuilder values(Set<String> val) { // values = val; // return this; // } // // public NodeBuilder probs(List<Double> probs) { // this.probs = probs; // return this; // } // // public NodeBuilder prob(Double prob) { // this.probs.add(prob); // return this; // } // // public Node build() { // return new Node(this); // } // } // }
import static org.junit.Assert.assertEquals; import com.github.vangj.jbayes.inf.exact.graph.Node; import org.junit.Test;
package com.github.vangj.jbayes.inf.exact.graph.pptc; public class EvidenceTest extends HuangExample { @Test public void testVirtual() {
// Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/Node.java // public class Node extends Variable { // // private final List<Double> probs; // private List<String> valueList; // private Potential potential; // private Map<String, Object> metadata; // // public Node() { // probs = new ArrayList<>(); // } // // public Node(Variable v) { // probs = new ArrayList<>(); // metadata = new HashMap<>(); // this.id = v.id; // this.name = v.name; // this.values = v.values; // this.valueList = this.values.stream() // .collect(Collectors.toList()); // } // // private Node(NodeBuilder builder) { // id = builder.id; // metadata = new HashMap<>(); // name = builder.name; // values = builder.values; // probs = builder.probs; // this.valueList = this.values.stream() // .collect(Collectors.toList()); // } // // public static NodeBuilder builder() { // return new NodeBuilder(); // } // // /** // * Adds any metadata. // * // * @param k Key. // * @param v Value. // */ // public void addMetadata(String k, Object v) { // metadata.put(k, v); // } // // /** // * Gets the metadata associated with the specified key. // * // * @param k Key. // * @return Value. // */ // public Object getMetadata(String k) { // return metadata.get(k); // } // // public Potential getPotential() { // return potential; // } // // public void setPotential(Potential potential) { // this.potential = potential; // } // // public Node addProb(Double prob) { // probs.add(prob); // return this; // } // // public int weight() { // return values.size(); // } // // public List<Double> probs() { // return probs; // } // // public List<String> getValueList() { // return valueList; // } // // public static final class NodeBuilder { // // private String id; // private String name; // private Set<String> values; // private List<Double> probs; // // private NodeBuilder() { // values = new LinkedHashSet<>(); // probs = new ArrayList<>(); // } // // public NodeBuilder from(Variable v) { // this.id = v.id; // this.name = v.name; // this.values = v.values; // return this; // } // // public NodeBuilder id(String val) { // id = val; // return this; // } // // public NodeBuilder name(String val) { // name = val; // return this; // } // // public NodeBuilder value(String val) { // values.add(val); // return this; // } // // public NodeBuilder values(Set<String> val) { // values = val; // return this; // } // // public NodeBuilder probs(List<Double> probs) { // this.probs = probs; // return this; // } // // public NodeBuilder prob(Double prob) { // this.probs.add(prob); // return this; // } // // public Node build() { // return new Node(this); // } // } // } // Path: src/test/java/com/github/vangj/jbayes/inf/exact/graph/pptc/EvidenceTest.java import static org.junit.Assert.assertEquals; import com.github.vangj.jbayes.inf.exact.graph.Node; import org.junit.Test; package com.github.vangj.jbayes.inf.exact.graph.pptc; public class EvidenceTest extends HuangExample { @Test public void testVirtual() {
Node node = getNode("a");
vangj/jbayes
src/main/java/com/github/vangj/jbayes/inf/prob/Graph.java
// Path: src/main/java/com/github/vangj/jbayes/inf/prob/util/CptUtil.java // public class CptUtil { // // private CptUtil() { // // } // // /** // * Converts the CPT into matrix form. // * // * @param cpt CPT. // * @return 2D representation of CPT. // */ // public static double[][] getMatrix(Cpt cpt) { // ArrayAccumulatorListener listener = new ArrayAccumulatorListener(); // (new CptPoDfsTraversal(cpt, listener)).start(); // return listener.get(); // } // // /** // * Builds a CPT for the specified node using the specified conditional probabilities passed in. // * // * @param node Node. // * @param probs Conditional proabilities. // * @return Cpt. // */ // public static Cpt build(Node node, double[][] probs) { // Cpt cpt = build(node); // // CptPoDfsTraversal.CptPoDfsTraversalListener listener = // new CptPoDfsTraversal.CptPoDfsTraversalListener() { // int row = 0; // // @Override // public void visited(Cpt cpt) { // if (cpt.numOfValues() > 0) { // if (row >= probs.length) { // //return, not enough cpts were specified // return; // } // // if (cpt.numOfValues() != probs[row].length) { // //throw a fit if the cardinalities do not match // throw new IllegalArgumentException( // String.format( // "cardinality mismatch, cpt = %d and probs = %d", // cpt.numOfValues(), // probs[row].length // )); // } // // for (int col = 0; col < probs[row].length; col++) { // cpt.getValues().set(col, probs[row][col]); // } // // row++; // } // } // }; // (new CptPoDfsTraversal(cpt, listener)).start(); // // return cpt; // } // // /** // * Builds a CPT for a node. Random conditional probabilities are assigned. // * // * @param node Node. // * @return Cpt. // */ // public static Cpt build(Node node) { // // if (!node.hasParents()) { // return Cpt.newBuilder() // .values(randomValues(node.numValues())) // .build(); // } // // Cpt root = new Cpt(); // build(node, root, 0); // return root; // } // // private static void build(Node node, Cpt cpt, int paIndex) { // if (paIndex >= node.numParents()) { // cpt.setValues(randomValues(node.numValues())); // return; // } // // Node parent = node.getParent(paIndex); // int numValues = parent.numValues(); // for (int i = 0; i < numValues; i++) { // Cpt child = Cpt.newBuilder() // .index(i) // .build(); // cpt.addChild(child); // } // // for (int i = 0; i < numValues; i++) { // Cpt child = cpt.get(i); // build(node, child, paIndex + 1); // } // } // // /** // * Generates a List of Doubles. // * // * @param total Total number of Doubles to generate. // * @return List of Doubles. // */ // private static List<Double> randomValues(int total) { // List<Double> values = new ArrayList<>(); // double sum = 0.0d; // for (int i = 0; i < total; i++) { // double d = RandomUtil.nextDouble(); // values.add(d); // sum += d; // } // for (int i = 0; i < total; i++) { // double p = values.get(i) / sum; // values.set(i, p); // } // return values; // } // // private static class ArrayAccumulatorListener implements // CptPoDfsTraversal.CptPoDfsTraversalListener { // // private final List<List<Double>> list = new ArrayList<>(); // // @Override // public void visited(Cpt cpt) { // if (cpt.numOfValues() > 0) { // list.add(cpt.getValues()); // } // } // // public double[][] get() { // final int rows = list.size(); // final int cols = list.get(0).size(); // // double[][] cpts = new double[rows][cols]; // for (int r = 0; r < rows; r++) { // for (int c = 0; c < cols; c++) { // cpts[r][c] = list.get(r).get(c); // } // } // return cpts; // } // } // }
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.github.vangj.jbayes.inf.prob.util.CptUtil; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
} return _nodes.get(name); } public void observe(String name, String value) { Node node = getNode(name); if (null == node) { return; } node.observe(value); } public void unobserve(String name) { Node node = getNode(name); if (null == node) { return; } node.unobserve(); } public void addNode(Node node) { nodes.add(node); } /** * Reinitializes the nodes' CPTs. */ public void reinit() { for (Node node : nodes) {
// Path: src/main/java/com/github/vangj/jbayes/inf/prob/util/CptUtil.java // public class CptUtil { // // private CptUtil() { // // } // // /** // * Converts the CPT into matrix form. // * // * @param cpt CPT. // * @return 2D representation of CPT. // */ // public static double[][] getMatrix(Cpt cpt) { // ArrayAccumulatorListener listener = new ArrayAccumulatorListener(); // (new CptPoDfsTraversal(cpt, listener)).start(); // return listener.get(); // } // // /** // * Builds a CPT for the specified node using the specified conditional probabilities passed in. // * // * @param node Node. // * @param probs Conditional proabilities. // * @return Cpt. // */ // public static Cpt build(Node node, double[][] probs) { // Cpt cpt = build(node); // // CptPoDfsTraversal.CptPoDfsTraversalListener listener = // new CptPoDfsTraversal.CptPoDfsTraversalListener() { // int row = 0; // // @Override // public void visited(Cpt cpt) { // if (cpt.numOfValues() > 0) { // if (row >= probs.length) { // //return, not enough cpts were specified // return; // } // // if (cpt.numOfValues() != probs[row].length) { // //throw a fit if the cardinalities do not match // throw new IllegalArgumentException( // String.format( // "cardinality mismatch, cpt = %d and probs = %d", // cpt.numOfValues(), // probs[row].length // )); // } // // for (int col = 0; col < probs[row].length; col++) { // cpt.getValues().set(col, probs[row][col]); // } // // row++; // } // } // }; // (new CptPoDfsTraversal(cpt, listener)).start(); // // return cpt; // } // // /** // * Builds a CPT for a node. Random conditional probabilities are assigned. // * // * @param node Node. // * @return Cpt. // */ // public static Cpt build(Node node) { // // if (!node.hasParents()) { // return Cpt.newBuilder() // .values(randomValues(node.numValues())) // .build(); // } // // Cpt root = new Cpt(); // build(node, root, 0); // return root; // } // // private static void build(Node node, Cpt cpt, int paIndex) { // if (paIndex >= node.numParents()) { // cpt.setValues(randomValues(node.numValues())); // return; // } // // Node parent = node.getParent(paIndex); // int numValues = parent.numValues(); // for (int i = 0; i < numValues; i++) { // Cpt child = Cpt.newBuilder() // .index(i) // .build(); // cpt.addChild(child); // } // // for (int i = 0; i < numValues; i++) { // Cpt child = cpt.get(i); // build(node, child, paIndex + 1); // } // } // // /** // * Generates a List of Doubles. // * // * @param total Total number of Doubles to generate. // * @return List of Doubles. // */ // private static List<Double> randomValues(int total) { // List<Double> values = new ArrayList<>(); // double sum = 0.0d; // for (int i = 0; i < total; i++) { // double d = RandomUtil.nextDouble(); // values.add(d); // sum += d; // } // for (int i = 0; i < total; i++) { // double p = values.get(i) / sum; // values.set(i, p); // } // return values; // } // // private static class ArrayAccumulatorListener implements // CptPoDfsTraversal.CptPoDfsTraversalListener { // // private final List<List<Double>> list = new ArrayList<>(); // // @Override // public void visited(Cpt cpt) { // if (cpt.numOfValues() > 0) { // list.add(cpt.getValues()); // } // } // // public double[][] get() { // final int rows = list.size(); // final int cols = list.get(0).size(); // // double[][] cpts = new double[rows][cols]; // for (int r = 0; r < rows; r++) { // for (int c = 0; c < cols; c++) { // cpts[r][c] = list.get(r).get(c); // } // } // return cpts; // } // } // } // Path: src/main/java/com/github/vangj/jbayes/inf/prob/Graph.java import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.github.vangj.jbayes.inf.prob.util.CptUtil; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; } return _nodes.get(name); } public void observe(String name, String value) { Node node = getNode(name); if (null == node) { return; } node.observe(value); } public void unobserve(String name) { Node node = getNode(name); if (null == node) { return; } node.unobserve(); } public void addNode(Node node) { nodes.add(node); } /** * Reinitializes the nodes' CPTs. */ public void reinit() { for (Node node : nodes) {
Cpt cpt = CptUtil.build(node);
vangj/jbayes
src/main/java/com/github/vangj/jbayes/inf/exact/graph/util/NodeUtil.java
// Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/Node.java // public class Node extends Variable { // // private final List<Double> probs; // private List<String> valueList; // private Potential potential; // private Map<String, Object> metadata; // // public Node() { // probs = new ArrayList<>(); // } // // public Node(Variable v) { // probs = new ArrayList<>(); // metadata = new HashMap<>(); // this.id = v.id; // this.name = v.name; // this.values = v.values; // this.valueList = this.values.stream() // .collect(Collectors.toList()); // } // // private Node(NodeBuilder builder) { // id = builder.id; // metadata = new HashMap<>(); // name = builder.name; // values = builder.values; // probs = builder.probs; // this.valueList = this.values.stream() // .collect(Collectors.toList()); // } // // public static NodeBuilder builder() { // return new NodeBuilder(); // } // // /** // * Adds any metadata. // * // * @param k Key. // * @param v Value. // */ // public void addMetadata(String k, Object v) { // metadata.put(k, v); // } // // /** // * Gets the metadata associated with the specified key. // * // * @param k Key. // * @return Value. // */ // public Object getMetadata(String k) { // return metadata.get(k); // } // // public Potential getPotential() { // return potential; // } // // public void setPotential(Potential potential) { // this.potential = potential; // } // // public Node addProb(Double prob) { // probs.add(prob); // return this; // } // // public int weight() { // return values.size(); // } // // public List<Double> probs() { // return probs; // } // // public List<String> getValueList() { // return valueList; // } // // public static final class NodeBuilder { // // private String id; // private String name; // private Set<String> values; // private List<Double> probs; // // private NodeBuilder() { // values = new LinkedHashSet<>(); // probs = new ArrayList<>(); // } // // public NodeBuilder from(Variable v) { // this.id = v.id; // this.name = v.name; // this.values = v.values; // return this; // } // // public NodeBuilder id(String val) { // id = val; // return this; // } // // public NodeBuilder name(String val) { // name = val; // return this; // } // // public NodeBuilder value(String val) { // values.add(val); // return this; // } // // public NodeBuilder values(Set<String> val) { // values = val; // return this; // } // // public NodeBuilder probs(List<Double> probs) { // this.probs = probs; // return this; // } // // public NodeBuilder prob(Double prob) { // this.probs.add(prob); // return this; // } // // public Node build() { // return new Node(this); // } // } // }
import com.github.vangj.jbayes.inf.exact.graph.Node; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors;
package com.github.vangj.jbayes.inf.exact.graph.util; /** * Node util. */ public class NodeUtil { private NodeUtil() { } /** * Gets the string id composed of the specified nodes. * * @param nodes List of nodes. * @return Id. */
// Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/Node.java // public class Node extends Variable { // // private final List<Double> probs; // private List<String> valueList; // private Potential potential; // private Map<String, Object> metadata; // // public Node() { // probs = new ArrayList<>(); // } // // public Node(Variable v) { // probs = new ArrayList<>(); // metadata = new HashMap<>(); // this.id = v.id; // this.name = v.name; // this.values = v.values; // this.valueList = this.values.stream() // .collect(Collectors.toList()); // } // // private Node(NodeBuilder builder) { // id = builder.id; // metadata = new HashMap<>(); // name = builder.name; // values = builder.values; // probs = builder.probs; // this.valueList = this.values.stream() // .collect(Collectors.toList()); // } // // public static NodeBuilder builder() { // return new NodeBuilder(); // } // // /** // * Adds any metadata. // * // * @param k Key. // * @param v Value. // */ // public void addMetadata(String k, Object v) { // metadata.put(k, v); // } // // /** // * Gets the metadata associated with the specified key. // * // * @param k Key. // * @return Value. // */ // public Object getMetadata(String k) { // return metadata.get(k); // } // // public Potential getPotential() { // return potential; // } // // public void setPotential(Potential potential) { // this.potential = potential; // } // // public Node addProb(Double prob) { // probs.add(prob); // return this; // } // // public int weight() { // return values.size(); // } // // public List<Double> probs() { // return probs; // } // // public List<String> getValueList() { // return valueList; // } // // public static final class NodeBuilder { // // private String id; // private String name; // private Set<String> values; // private List<Double> probs; // // private NodeBuilder() { // values = new LinkedHashSet<>(); // probs = new ArrayList<>(); // } // // public NodeBuilder from(Variable v) { // this.id = v.id; // this.name = v.name; // this.values = v.values; // return this; // } // // public NodeBuilder id(String val) { // id = val; // return this; // } // // public NodeBuilder name(String val) { // name = val; // return this; // } // // public NodeBuilder value(String val) { // values.add(val); // return this; // } // // public NodeBuilder values(Set<String> val) { // values = val; // return this; // } // // public NodeBuilder probs(List<Double> probs) { // this.probs = probs; // return this; // } // // public NodeBuilder prob(Double prob) { // this.probs.add(prob); // return this; // } // // public Node build() { // return new Node(this); // } // } // } // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/util/NodeUtil.java import com.github.vangj.jbayes.inf.exact.graph.Node; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; package com.github.vangj.jbayes.inf.exact.graph.util; /** * Node util. */ public class NodeUtil { private NodeUtil() { } /** * Gets the string id composed of the specified nodes. * * @param nodes List of nodes. * @return Id. */
public static String id(List<Node> nodes) {
vangj/jbayes
src/main/java/com/github/vangj/jbayes/inf/exact/graph/Pdag.java
// Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/traversal/PdagShortestPath.java // public class PdagShortestPath extends GraphShortestPath { // // private final Pdag pdag; // // protected PdagShortestPath(Pdag pdag, Node start, Node stop, ShortestPathListener listener) { // super(pdag, start, stop, listener); // this.pdag = pdag; // } // // public static boolean exists(Pdag graph, Node start, Node stop, ShortestPathListener listener) { // return (new PdagShortestPath(graph, start, stop, listener)).search(); // } // // private boolean search() { // if (null != listener) { // listener.pre(graph, start, stop); // } // // if (start.equals(stop)) { // if (null != listener) { // listener.post(graph, start, stop); // } // return false; // } // // boolean result = search(start); // // if (null != listener) { // listener.post(graph, start, stop); // } // // return result; // } // // private boolean search(Node node) { // if (null != listener) { // listener.visited(node); // } // // Set<Node> outNodes = outNodes(node); // if (outNodes.contains(stop)) { // return true; // } else { // seen.add(node); // for (Node outNode : outNodes) { // if (!seen.contains(outNode)) { // if (search(outNode)) { // return true; // } // } // } // } // // return false; // } // // private Set<Node> outNodes(Node node) { // Set<Node> outNodes = new HashSet<>(); // outNodes.addAll(pdag.neighbors(node)); // outNodes.removeAll(pdag.parents(node)); // return outNodes; // } // }
import com.github.vangj.jbayes.inf.exact.graph.traversal.PdagShortestPath; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
package com.github.vangj.jbayes.inf.exact.graph; /** * A partially directed acyclic graph (PDAG). "A PDAG is a graph where some edges are directed and * some are undirected and one cannot trace a cycle by following the direction of directed edges and * any direction for undirected edges." * <ul> * <li>Quote above taken directly from http://jmlr.csail.mit.edu/papers/volume8/kalisch07a/kalisch07a.pdf</li> * </ul> */ public class Pdag extends Graph { protected Map<String, List<Node>> parents; protected Map<String, List<Node>> children; public Pdag() { parents = new HashMap<>(); children = new HashMap<>(); } @Override protected Graph instance() { return new Pdag(); } @Override public Graph addEdge(Edge edge) { if (Edge.Type.UNDIRECTED == edge.type) { super.addEdge(edge); } else {
// Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/traversal/PdagShortestPath.java // public class PdagShortestPath extends GraphShortestPath { // // private final Pdag pdag; // // protected PdagShortestPath(Pdag pdag, Node start, Node stop, ShortestPathListener listener) { // super(pdag, start, stop, listener); // this.pdag = pdag; // } // // public static boolean exists(Pdag graph, Node start, Node stop, ShortestPathListener listener) { // return (new PdagShortestPath(graph, start, stop, listener)).search(); // } // // private boolean search() { // if (null != listener) { // listener.pre(graph, start, stop); // } // // if (start.equals(stop)) { // if (null != listener) { // listener.post(graph, start, stop); // } // return false; // } // // boolean result = search(start); // // if (null != listener) { // listener.post(graph, start, stop); // } // // return result; // } // // private boolean search(Node node) { // if (null != listener) { // listener.visited(node); // } // // Set<Node> outNodes = outNodes(node); // if (outNodes.contains(stop)) { // return true; // } else { // seen.add(node); // for (Node outNode : outNodes) { // if (!seen.contains(outNode)) { // if (search(outNode)) { // return true; // } // } // } // } // // return false; // } // // private Set<Node> outNodes(Node node) { // Set<Node> outNodes = new HashSet<>(); // outNodes.addAll(pdag.neighbors(node)); // outNodes.removeAll(pdag.parents(node)); // return outNodes; // } // } // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/Pdag.java import com.github.vangj.jbayes.inf.exact.graph.traversal.PdagShortestPath; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; package com.github.vangj.jbayes.inf.exact.graph; /** * A partially directed acyclic graph (PDAG). "A PDAG is a graph where some edges are directed and * some are undirected and one cannot trace a cycle by following the direction of directed edges and * any direction for undirected edges." * <ul> * <li>Quote above taken directly from http://jmlr.csail.mit.edu/papers/volume8/kalisch07a/kalisch07a.pdf</li> * </ul> */ public class Pdag extends Graph { protected Map<String, List<Node>> parents; protected Map<String, List<Node>> children; public Pdag() { parents = new HashMap<>(); children = new HashMap<>(); } @Override protected Graph instance() { return new Pdag(); } @Override public Graph addEdge(Edge edge) { if (Edge.Type.UNDIRECTED == edge.type) { super.addEdge(edge); } else {
if (PdagShortestPath.exists(this, edge.right, edge.left, null)) {
vangj/jbayes
src/main/java/com/github/vangj/jbayes/inf/prob/util/CsvUtil.java
// Path: src/main/java/com/github/vangj/jbayes/inf/prob/Graph.java // @JsonInclude(content = Include.NON_NULL) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Graph { // // @JsonIgnore // private final List<String[]> _samples = new ArrayList<>(); // private final List<Node> nodes; // private boolean saveSamples = false; // @JsonIgnore // private Map<String, Node> _nodes = new HashMap<>(); // // public Graph() { // nodes = new ArrayList<>(); // } // // public boolean isSaveSamples() { // return saveSamples; // } // // public void setSaveSamples(boolean saveSamples) { // this.saveSamples = saveSamples; // } // // public List<Node> getNodes() { // return nodes; // } // // @JsonIgnore // public String[] getNodeNames() { // final int size = nodes.size(); // String[] names = new String[size]; // for (int i = 0; i < size; i++) { // names[i] = nodes.get(i).getName(); // } // return names; // } // // @JsonIgnore // public List<String[]> getSamples() { // return _samples; // } // // public Node getNode(String name) { // synchronized (_nodes) { // if (null == _nodes || 0 == _nodes.size()) { // _nodes = new HashMap<>(); // nodes.forEach(n -> _nodes.put(n.getName(), n)); // } // } // // return _nodes.get(name); // } // // public void observe(String name, String value) { // Node node = getNode(name); // if (null == node) { // return; // } // node.observe(value); // } // // public void unobserve(String name) { // Node node = getNode(name); // if (null == node) { // return; // } // node.unobserve(); // } // // public void addNode(Node node) { // nodes.add(node); // } // // /** // * Reinitializes the nodes' CPTs. // */ // public void reinit() { // for (Node node : nodes) { // Cpt cpt = CptUtil.build(node); // node.setCpt(cpt); // } // } // // public void clearSamples() { // _samples.clear(); // } // // /** // * Performs the sampling. // * // * @param samples Total samples to generate. // * @return Likelihood-weighted sum. // */ // public double sample(int samples) { // clearSamples(); // // nodes.forEach(Node::resetSampledLw); // // double lwSum = 0.0d; // final int numNodes = nodes.size(); // // for (int count = 0; count < samples; count++) { // for (Node node : nodes) { // if (!node.isObserved()) { // node.setValue(-1); // } // node.setWasSampled(false); // } // // double fa = 1.0d; // for (Node node : nodes) { // fa *= node.sampleLw(); // } // // lwSum += fa; // // for (Node node : nodes) { // node.saveSampleLw(fa); // } // // if (saveSamples) { // String[] sampledValues = new String[numNodes]; // for (int i = 0; i < numNodes; i++) { // sampledValues[i] = nodes.get(i).getSampledValue(); // } // _samples.add(sampledValues); // } // } // // return lwSum; // } // }
import au.com.bytecode.opencsv.CSVWriter; import com.github.vangj.jbayes.inf.prob.Graph; import java.io.IOException; import java.io.Writer;
package com.github.vangj.jbayes.inf.prob.util; /** * CSV util. */ public class CsvUtil { private CsvUtil() { }
// Path: src/main/java/com/github/vangj/jbayes/inf/prob/Graph.java // @JsonInclude(content = Include.NON_NULL) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Graph { // // @JsonIgnore // private final List<String[]> _samples = new ArrayList<>(); // private final List<Node> nodes; // private boolean saveSamples = false; // @JsonIgnore // private Map<String, Node> _nodes = new HashMap<>(); // // public Graph() { // nodes = new ArrayList<>(); // } // // public boolean isSaveSamples() { // return saveSamples; // } // // public void setSaveSamples(boolean saveSamples) { // this.saveSamples = saveSamples; // } // // public List<Node> getNodes() { // return nodes; // } // // @JsonIgnore // public String[] getNodeNames() { // final int size = nodes.size(); // String[] names = new String[size]; // for (int i = 0; i < size; i++) { // names[i] = nodes.get(i).getName(); // } // return names; // } // // @JsonIgnore // public List<String[]> getSamples() { // return _samples; // } // // public Node getNode(String name) { // synchronized (_nodes) { // if (null == _nodes || 0 == _nodes.size()) { // _nodes = new HashMap<>(); // nodes.forEach(n -> _nodes.put(n.getName(), n)); // } // } // // return _nodes.get(name); // } // // public void observe(String name, String value) { // Node node = getNode(name); // if (null == node) { // return; // } // node.observe(value); // } // // public void unobserve(String name) { // Node node = getNode(name); // if (null == node) { // return; // } // node.unobserve(); // } // // public void addNode(Node node) { // nodes.add(node); // } // // /** // * Reinitializes the nodes' CPTs. // */ // public void reinit() { // for (Node node : nodes) { // Cpt cpt = CptUtil.build(node); // node.setCpt(cpt); // } // } // // public void clearSamples() { // _samples.clear(); // } // // /** // * Performs the sampling. // * // * @param samples Total samples to generate. // * @return Likelihood-weighted sum. // */ // public double sample(int samples) { // clearSamples(); // // nodes.forEach(Node::resetSampledLw); // // double lwSum = 0.0d; // final int numNodes = nodes.size(); // // for (int count = 0; count < samples; count++) { // for (Node node : nodes) { // if (!node.isObserved()) { // node.setValue(-1); // } // node.setWasSampled(false); // } // // double fa = 1.0d; // for (Node node : nodes) { // fa *= node.sampleLw(); // } // // lwSum += fa; // // for (Node node : nodes) { // node.saveSampleLw(fa); // } // // if (saveSamples) { // String[] sampledValues = new String[numNodes]; // for (int i = 0; i < numNodes; i++) { // sampledValues[i] = nodes.get(i).getSampledValue(); // } // _samples.add(sampledValues); // } // } // // return lwSum; // } // } // Path: src/main/java/com/github/vangj/jbayes/inf/prob/util/CsvUtil.java import au.com.bytecode.opencsv.CSVWriter; import com.github.vangj.jbayes.inf.prob.Graph; import java.io.IOException; import java.io.Writer; package com.github.vangj.jbayes.inf.prob.util; /** * CSV util. */ public class CsvUtil { private CsvUtil() { }
public static void saveSamples(Graph graph, Writer writer) throws IOException {
vangj/jbayes
src/main/java/com/github/vangj/jbayes/inf/prob/Node.java
// Path: src/main/java/com/github/vangj/jbayes/inf/prob/util/CptUtil.java // public class CptUtil { // // private CptUtil() { // // } // // /** // * Converts the CPT into matrix form. // * // * @param cpt CPT. // * @return 2D representation of CPT. // */ // public static double[][] getMatrix(Cpt cpt) { // ArrayAccumulatorListener listener = new ArrayAccumulatorListener(); // (new CptPoDfsTraversal(cpt, listener)).start(); // return listener.get(); // } // // /** // * Builds a CPT for the specified node using the specified conditional probabilities passed in. // * // * @param node Node. // * @param probs Conditional proabilities. // * @return Cpt. // */ // public static Cpt build(Node node, double[][] probs) { // Cpt cpt = build(node); // // CptPoDfsTraversal.CptPoDfsTraversalListener listener = // new CptPoDfsTraversal.CptPoDfsTraversalListener() { // int row = 0; // // @Override // public void visited(Cpt cpt) { // if (cpt.numOfValues() > 0) { // if (row >= probs.length) { // //return, not enough cpts were specified // return; // } // // if (cpt.numOfValues() != probs[row].length) { // //throw a fit if the cardinalities do not match // throw new IllegalArgumentException( // String.format( // "cardinality mismatch, cpt = %d and probs = %d", // cpt.numOfValues(), // probs[row].length // )); // } // // for (int col = 0; col < probs[row].length; col++) { // cpt.getValues().set(col, probs[row][col]); // } // // row++; // } // } // }; // (new CptPoDfsTraversal(cpt, listener)).start(); // // return cpt; // } // // /** // * Builds a CPT for a node. Random conditional probabilities are assigned. // * // * @param node Node. // * @return Cpt. // */ // public static Cpt build(Node node) { // // if (!node.hasParents()) { // return Cpt.newBuilder() // .values(randomValues(node.numValues())) // .build(); // } // // Cpt root = new Cpt(); // build(node, root, 0); // return root; // } // // private static void build(Node node, Cpt cpt, int paIndex) { // if (paIndex >= node.numParents()) { // cpt.setValues(randomValues(node.numValues())); // return; // } // // Node parent = node.getParent(paIndex); // int numValues = parent.numValues(); // for (int i = 0; i < numValues; i++) { // Cpt child = Cpt.newBuilder() // .index(i) // .build(); // cpt.addChild(child); // } // // for (int i = 0; i < numValues; i++) { // Cpt child = cpt.get(i); // build(node, child, paIndex + 1); // } // } // // /** // * Generates a List of Doubles. // * // * @param total Total number of Doubles to generate. // * @return List of Doubles. // */ // private static List<Double> randomValues(int total) { // List<Double> values = new ArrayList<>(); // double sum = 0.0d; // for (int i = 0; i < total; i++) { // double d = RandomUtil.nextDouble(); // values.add(d); // sum += d; // } // for (int i = 0; i < total; i++) { // double p = values.get(i) / sum; // values.set(i, p); // } // return values; // } // // private static class ArrayAccumulatorListener implements // CptPoDfsTraversal.CptPoDfsTraversalListener { // // private final List<List<Double>> list = new ArrayList<>(); // // @Override // public void visited(Cpt cpt) { // if (cpt.numOfValues() > 0) { // list.add(cpt.getValues()); // } // } // // public double[][] get() { // final int rows = list.size(); // final int cols = list.get(0).size(); // // double[][] cpts = new double[rows][cols]; // for (int r = 0; r < rows; r++) { // for (int c = 0; c < cols; c++) { // cpts[r][c] = list.get(r).get(c); // } // } // return cpts; // } // } // } // // Path: src/main/java/com/github/vangj/jbayes/inf/prob/util/RandomUtil.java // public class RandomUtil { // // private static final Random R = new Random(37L); // // private RandomUtil() { // // } // // public static double nextDouble() { // return R.nextDouble(); // } // }
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.github.vangj.jbayes.inf.prob.util.CptUtil; import com.github.vangj.jbayes.inf.prob.util.RandomUtil; import java.util.ArrayList; import java.util.List;
public Node() { parents = new ArrayList<>(); sampledLw = new ArrayList<>(); } private Node(Builder b) { this.name = b.name; this.values = b.values; this.parents = b.parents; } /** * Gets a new Builder instance. * * @return Builder. */ public static Builder newBuilder() { return new Builder(); } public Cpt getCpt() { return cpt; } public void setCpt(Cpt cpt) { this.cpt = cpt; } public void setCpt(double[][] probs) {
// Path: src/main/java/com/github/vangj/jbayes/inf/prob/util/CptUtil.java // public class CptUtil { // // private CptUtil() { // // } // // /** // * Converts the CPT into matrix form. // * // * @param cpt CPT. // * @return 2D representation of CPT. // */ // public static double[][] getMatrix(Cpt cpt) { // ArrayAccumulatorListener listener = new ArrayAccumulatorListener(); // (new CptPoDfsTraversal(cpt, listener)).start(); // return listener.get(); // } // // /** // * Builds a CPT for the specified node using the specified conditional probabilities passed in. // * // * @param node Node. // * @param probs Conditional proabilities. // * @return Cpt. // */ // public static Cpt build(Node node, double[][] probs) { // Cpt cpt = build(node); // // CptPoDfsTraversal.CptPoDfsTraversalListener listener = // new CptPoDfsTraversal.CptPoDfsTraversalListener() { // int row = 0; // // @Override // public void visited(Cpt cpt) { // if (cpt.numOfValues() > 0) { // if (row >= probs.length) { // //return, not enough cpts were specified // return; // } // // if (cpt.numOfValues() != probs[row].length) { // //throw a fit if the cardinalities do not match // throw new IllegalArgumentException( // String.format( // "cardinality mismatch, cpt = %d and probs = %d", // cpt.numOfValues(), // probs[row].length // )); // } // // for (int col = 0; col < probs[row].length; col++) { // cpt.getValues().set(col, probs[row][col]); // } // // row++; // } // } // }; // (new CptPoDfsTraversal(cpt, listener)).start(); // // return cpt; // } // // /** // * Builds a CPT for a node. Random conditional probabilities are assigned. // * // * @param node Node. // * @return Cpt. // */ // public static Cpt build(Node node) { // // if (!node.hasParents()) { // return Cpt.newBuilder() // .values(randomValues(node.numValues())) // .build(); // } // // Cpt root = new Cpt(); // build(node, root, 0); // return root; // } // // private static void build(Node node, Cpt cpt, int paIndex) { // if (paIndex >= node.numParents()) { // cpt.setValues(randomValues(node.numValues())); // return; // } // // Node parent = node.getParent(paIndex); // int numValues = parent.numValues(); // for (int i = 0; i < numValues; i++) { // Cpt child = Cpt.newBuilder() // .index(i) // .build(); // cpt.addChild(child); // } // // for (int i = 0; i < numValues; i++) { // Cpt child = cpt.get(i); // build(node, child, paIndex + 1); // } // } // // /** // * Generates a List of Doubles. // * // * @param total Total number of Doubles to generate. // * @return List of Doubles. // */ // private static List<Double> randomValues(int total) { // List<Double> values = new ArrayList<>(); // double sum = 0.0d; // for (int i = 0; i < total; i++) { // double d = RandomUtil.nextDouble(); // values.add(d); // sum += d; // } // for (int i = 0; i < total; i++) { // double p = values.get(i) / sum; // values.set(i, p); // } // return values; // } // // private static class ArrayAccumulatorListener implements // CptPoDfsTraversal.CptPoDfsTraversalListener { // // private final List<List<Double>> list = new ArrayList<>(); // // @Override // public void visited(Cpt cpt) { // if (cpt.numOfValues() > 0) { // list.add(cpt.getValues()); // } // } // // public double[][] get() { // final int rows = list.size(); // final int cols = list.get(0).size(); // // double[][] cpts = new double[rows][cols]; // for (int r = 0; r < rows; r++) { // for (int c = 0; c < cols; c++) { // cpts[r][c] = list.get(r).get(c); // } // } // return cpts; // } // } // } // // Path: src/main/java/com/github/vangj/jbayes/inf/prob/util/RandomUtil.java // public class RandomUtil { // // private static final Random R = new Random(37L); // // private RandomUtil() { // // } // // public static double nextDouble() { // return R.nextDouble(); // } // } // Path: src/main/java/com/github/vangj/jbayes/inf/prob/Node.java import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.github.vangj.jbayes.inf.prob.util.CptUtil; import com.github.vangj.jbayes.inf.prob.util.RandomUtil; import java.util.ArrayList; import java.util.List; public Node() { parents = new ArrayList<>(); sampledLw = new ArrayList<>(); } private Node(Builder b) { this.name = b.name; this.values = b.values; this.parents = b.parents; } /** * Gets a new Builder instance. * * @return Builder. */ public static Builder newBuilder() { return new Builder(); } public Cpt getCpt() { return cpt; } public void setCpt(Cpt cpt) { this.cpt = cpt; } public void setCpt(double[][] probs) {
cpt = CptUtil.build(this, probs);
vangj/jbayes
src/main/java/com/github/vangj/jbayes/inf/exact/graph/pptc/Evidence.java
// Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/Node.java // public class Node extends Variable { // // private final List<Double> probs; // private List<String> valueList; // private Potential potential; // private Map<String, Object> metadata; // // public Node() { // probs = new ArrayList<>(); // } // // public Node(Variable v) { // probs = new ArrayList<>(); // metadata = new HashMap<>(); // this.id = v.id; // this.name = v.name; // this.values = v.values; // this.valueList = this.values.stream() // .collect(Collectors.toList()); // } // // private Node(NodeBuilder builder) { // id = builder.id; // metadata = new HashMap<>(); // name = builder.name; // values = builder.values; // probs = builder.probs; // this.valueList = this.values.stream() // .collect(Collectors.toList()); // } // // public static NodeBuilder builder() { // return new NodeBuilder(); // } // // /** // * Adds any metadata. // * // * @param k Key. // * @param v Value. // */ // public void addMetadata(String k, Object v) { // metadata.put(k, v); // } // // /** // * Gets the metadata associated with the specified key. // * // * @param k Key. // * @return Value. // */ // public Object getMetadata(String k) { // return metadata.get(k); // } // // public Potential getPotential() { // return potential; // } // // public void setPotential(Potential potential) { // this.potential = potential; // } // // public Node addProb(Double prob) { // probs.add(prob); // return this; // } // // public int weight() { // return values.size(); // } // // public List<Double> probs() { // return probs; // } // // public List<String> getValueList() { // return valueList; // } // // public static final class NodeBuilder { // // private String id; // private String name; // private Set<String> values; // private List<Double> probs; // // private NodeBuilder() { // values = new LinkedHashSet<>(); // probs = new ArrayList<>(); // } // // public NodeBuilder from(Variable v) { // this.id = v.id; // this.name = v.name; // this.values = v.values; // return this; // } // // public NodeBuilder id(String val) { // id = val; // return this; // } // // public NodeBuilder name(String val) { // name = val; // return this; // } // // public NodeBuilder value(String val) { // values.add(val); // return this; // } // // public NodeBuilder values(Set<String> val) { // values = val; // return this; // } // // public NodeBuilder probs(List<Double> probs) { // this.probs = probs; // return this; // } // // public NodeBuilder prob(Double prob) { // this.probs.add(prob); // return this; // } // // public Node build() { // return new Node(this); // } // } // } // // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/lpd/Potential.java // public class Potential { // // private final List<PotentialEntry> entries; // // public Potential() { // entries = new ArrayList<>(); // } // // /** // * Finds matching potential entries to the specified one passed in. // * // * @param potentialEntry Potential entry. // * @return List of ootential entries. // */ // public List<PotentialEntry> match(PotentialEntry potentialEntry) { // List<PotentialEntry> entries = new ArrayList<>(); // for (PotentialEntry entry : this.entries) { // if (entry.match(potentialEntry)) { // entries.add(entry); // } // } // return entries; // } // // public List<PotentialEntry> entries() { // return entries; // } // // public Potential addEntry(PotentialEntry entry) { // entries.add(entry); // return this; // } // // @Override // public String toString() { // return entries.stream() // .map(PotentialEntry::toString) // .collect(Collectors.joining(System.lineSeparator())); // } // }
import com.github.vangj.jbayes.inf.exact.graph.Node; import com.github.vangj.jbayes.inf.exact.graph.lpd.Potential; import java.util.LinkedHashMap; import java.util.Map;
package com.github.vangj.jbayes.inf.exact.graph.pptc; /** * Evidence. */ public class Evidence { private final Node node; private final Map<String, Double> values; private final Type type; private Evidence(Builder builder) { node = builder.node; values = builder.values; type = builder.type; } /** * Converts a map of values to potentials to a map of values to likelihoods. * * @param map Map. * @return Map. */
// Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/Node.java // public class Node extends Variable { // // private final List<Double> probs; // private List<String> valueList; // private Potential potential; // private Map<String, Object> metadata; // // public Node() { // probs = new ArrayList<>(); // } // // public Node(Variable v) { // probs = new ArrayList<>(); // metadata = new HashMap<>(); // this.id = v.id; // this.name = v.name; // this.values = v.values; // this.valueList = this.values.stream() // .collect(Collectors.toList()); // } // // private Node(NodeBuilder builder) { // id = builder.id; // metadata = new HashMap<>(); // name = builder.name; // values = builder.values; // probs = builder.probs; // this.valueList = this.values.stream() // .collect(Collectors.toList()); // } // // public static NodeBuilder builder() { // return new NodeBuilder(); // } // // /** // * Adds any metadata. // * // * @param k Key. // * @param v Value. // */ // public void addMetadata(String k, Object v) { // metadata.put(k, v); // } // // /** // * Gets the metadata associated with the specified key. // * // * @param k Key. // * @return Value. // */ // public Object getMetadata(String k) { // return metadata.get(k); // } // // public Potential getPotential() { // return potential; // } // // public void setPotential(Potential potential) { // this.potential = potential; // } // // public Node addProb(Double prob) { // probs.add(prob); // return this; // } // // public int weight() { // return values.size(); // } // // public List<Double> probs() { // return probs; // } // // public List<String> getValueList() { // return valueList; // } // // public static final class NodeBuilder { // // private String id; // private String name; // private Set<String> values; // private List<Double> probs; // // private NodeBuilder() { // values = new LinkedHashSet<>(); // probs = new ArrayList<>(); // } // // public NodeBuilder from(Variable v) { // this.id = v.id; // this.name = v.name; // this.values = v.values; // return this; // } // // public NodeBuilder id(String val) { // id = val; // return this; // } // // public NodeBuilder name(String val) { // name = val; // return this; // } // // public NodeBuilder value(String val) { // values.add(val); // return this; // } // // public NodeBuilder values(Set<String> val) { // values = val; // return this; // } // // public NodeBuilder probs(List<Double> probs) { // this.probs = probs; // return this; // } // // public NodeBuilder prob(Double prob) { // this.probs.add(prob); // return this; // } // // public Node build() { // return new Node(this); // } // } // } // // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/lpd/Potential.java // public class Potential { // // private final List<PotentialEntry> entries; // // public Potential() { // entries = new ArrayList<>(); // } // // /** // * Finds matching potential entries to the specified one passed in. // * // * @param potentialEntry Potential entry. // * @return List of ootential entries. // */ // public List<PotentialEntry> match(PotentialEntry potentialEntry) { // List<PotentialEntry> entries = new ArrayList<>(); // for (PotentialEntry entry : this.entries) { // if (entry.match(potentialEntry)) { // entries.add(entry); // } // } // return entries; // } // // public List<PotentialEntry> entries() { // return entries; // } // // public Potential addEntry(PotentialEntry entry) { // entries.add(entry); // return this; // } // // @Override // public String toString() { // return entries.stream() // .map(PotentialEntry::toString) // .collect(Collectors.joining(System.lineSeparator())); // } // } // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/pptc/Evidence.java import com.github.vangj.jbayes.inf.exact.graph.Node; import com.github.vangj.jbayes.inf.exact.graph.lpd.Potential; import java.util.LinkedHashMap; import java.util.Map; package com.github.vangj.jbayes.inf.exact.graph.pptc; /** * Evidence. */ public class Evidence { private final Node node; private final Map<String, Double> values; private final Type type; private Evidence(Builder builder) { node = builder.node; values = builder.values; type = builder.type; } /** * Converts a map of values to potentials to a map of values to likelihoods. * * @param map Map. * @return Map. */
private static Map<String, Double> convert(Map<String, Potential> map) {
vangj/jbayes
src/main/java/com/github/vangj/jbayes/inf/exact/graph/traversal/PdagShortestPath.java
// Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/Node.java // public class Node extends Variable { // // private final List<Double> probs; // private List<String> valueList; // private Potential potential; // private Map<String, Object> metadata; // // public Node() { // probs = new ArrayList<>(); // } // // public Node(Variable v) { // probs = new ArrayList<>(); // metadata = new HashMap<>(); // this.id = v.id; // this.name = v.name; // this.values = v.values; // this.valueList = this.values.stream() // .collect(Collectors.toList()); // } // // private Node(NodeBuilder builder) { // id = builder.id; // metadata = new HashMap<>(); // name = builder.name; // values = builder.values; // probs = builder.probs; // this.valueList = this.values.stream() // .collect(Collectors.toList()); // } // // public static NodeBuilder builder() { // return new NodeBuilder(); // } // // /** // * Adds any metadata. // * // * @param k Key. // * @param v Value. // */ // public void addMetadata(String k, Object v) { // metadata.put(k, v); // } // // /** // * Gets the metadata associated with the specified key. // * // * @param k Key. // * @return Value. // */ // public Object getMetadata(String k) { // return metadata.get(k); // } // // public Potential getPotential() { // return potential; // } // // public void setPotential(Potential potential) { // this.potential = potential; // } // // public Node addProb(Double prob) { // probs.add(prob); // return this; // } // // public int weight() { // return values.size(); // } // // public List<Double> probs() { // return probs; // } // // public List<String> getValueList() { // return valueList; // } // // public static final class NodeBuilder { // // private String id; // private String name; // private Set<String> values; // private List<Double> probs; // // private NodeBuilder() { // values = new LinkedHashSet<>(); // probs = new ArrayList<>(); // } // // public NodeBuilder from(Variable v) { // this.id = v.id; // this.name = v.name; // this.values = v.values; // return this; // } // // public NodeBuilder id(String val) { // id = val; // return this; // } // // public NodeBuilder name(String val) { // name = val; // return this; // } // // public NodeBuilder value(String val) { // values.add(val); // return this; // } // // public NodeBuilder values(Set<String> val) { // values = val; // return this; // } // // public NodeBuilder probs(List<Double> probs) { // this.probs = probs; // return this; // } // // public NodeBuilder prob(Double prob) { // this.probs.add(prob); // return this; // } // // public Node build() { // return new Node(this); // } // } // } // // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/Pdag.java // public class Pdag extends Graph { // // protected Map<String, List<Node>> parents; // protected Map<String, List<Node>> children; // // public Pdag() { // parents = new HashMap<>(); // children = new HashMap<>(); // } // // @Override // protected Graph instance() { // return new Pdag(); // } // // @Override // public Graph addEdge(Edge edge) { // if (Edge.Type.UNDIRECTED == edge.type) { // super.addEdge(edge); // } else { // if (PdagShortestPath.exists(this, edge.right, edge.left, null)) { // //if right -> -- -> -- left path exists // //then adding left -> right will form cycle // //do not add it! // return this; // } // // super.addEdge(edge); // // Node n1 = edge.left; // Node n2 = edge.right; // // List<Node> parents = parents(n2); // if (!parents.contains(n1)) { // parents.add(n1); // } // // List<Node> children = children(n1); // if (!children.contains(n2)) { // children.add(n2); // } // } // // return this; // } // // public List<Node> parents(Node node) { // List<Node> parents = this.parents.get(node.id); // if (null == parents) { // parents = new ArrayList<>(); // this.parents.put(node.id, parents); // } // return parents; // } // // public List<Node> children(Node node) { // List<Node> children = this.children.get(node.id); // if (null == children) { // children = new ArrayList<>(); // this.children.put(node.id, children); // } // return children; // } // }
import com.github.vangj.jbayes.inf.exact.graph.Node; import com.github.vangj.jbayes.inf.exact.graph.Pdag; import java.util.HashSet; import java.util.Set;
package com.github.vangj.jbayes.inf.exact.graph.traversal; public class PdagShortestPath extends GraphShortestPath { private final Pdag pdag;
// Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/Node.java // public class Node extends Variable { // // private final List<Double> probs; // private List<String> valueList; // private Potential potential; // private Map<String, Object> metadata; // // public Node() { // probs = new ArrayList<>(); // } // // public Node(Variable v) { // probs = new ArrayList<>(); // metadata = new HashMap<>(); // this.id = v.id; // this.name = v.name; // this.values = v.values; // this.valueList = this.values.stream() // .collect(Collectors.toList()); // } // // private Node(NodeBuilder builder) { // id = builder.id; // metadata = new HashMap<>(); // name = builder.name; // values = builder.values; // probs = builder.probs; // this.valueList = this.values.stream() // .collect(Collectors.toList()); // } // // public static NodeBuilder builder() { // return new NodeBuilder(); // } // // /** // * Adds any metadata. // * // * @param k Key. // * @param v Value. // */ // public void addMetadata(String k, Object v) { // metadata.put(k, v); // } // // /** // * Gets the metadata associated with the specified key. // * // * @param k Key. // * @return Value. // */ // public Object getMetadata(String k) { // return metadata.get(k); // } // // public Potential getPotential() { // return potential; // } // // public void setPotential(Potential potential) { // this.potential = potential; // } // // public Node addProb(Double prob) { // probs.add(prob); // return this; // } // // public int weight() { // return values.size(); // } // // public List<Double> probs() { // return probs; // } // // public List<String> getValueList() { // return valueList; // } // // public static final class NodeBuilder { // // private String id; // private String name; // private Set<String> values; // private List<Double> probs; // // private NodeBuilder() { // values = new LinkedHashSet<>(); // probs = new ArrayList<>(); // } // // public NodeBuilder from(Variable v) { // this.id = v.id; // this.name = v.name; // this.values = v.values; // return this; // } // // public NodeBuilder id(String val) { // id = val; // return this; // } // // public NodeBuilder name(String val) { // name = val; // return this; // } // // public NodeBuilder value(String val) { // values.add(val); // return this; // } // // public NodeBuilder values(Set<String> val) { // values = val; // return this; // } // // public NodeBuilder probs(List<Double> probs) { // this.probs = probs; // return this; // } // // public NodeBuilder prob(Double prob) { // this.probs.add(prob); // return this; // } // // public Node build() { // return new Node(this); // } // } // } // // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/Pdag.java // public class Pdag extends Graph { // // protected Map<String, List<Node>> parents; // protected Map<String, List<Node>> children; // // public Pdag() { // parents = new HashMap<>(); // children = new HashMap<>(); // } // // @Override // protected Graph instance() { // return new Pdag(); // } // // @Override // public Graph addEdge(Edge edge) { // if (Edge.Type.UNDIRECTED == edge.type) { // super.addEdge(edge); // } else { // if (PdagShortestPath.exists(this, edge.right, edge.left, null)) { // //if right -> -- -> -- left path exists // //then adding left -> right will form cycle // //do not add it! // return this; // } // // super.addEdge(edge); // // Node n1 = edge.left; // Node n2 = edge.right; // // List<Node> parents = parents(n2); // if (!parents.contains(n1)) { // parents.add(n1); // } // // List<Node> children = children(n1); // if (!children.contains(n2)) { // children.add(n2); // } // } // // return this; // } // // public List<Node> parents(Node node) { // List<Node> parents = this.parents.get(node.id); // if (null == parents) { // parents = new ArrayList<>(); // this.parents.put(node.id, parents); // } // return parents; // } // // public List<Node> children(Node node) { // List<Node> children = this.children.get(node.id); // if (null == children) { // children = new ArrayList<>(); // this.children.put(node.id, children); // } // return children; // } // } // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/traversal/PdagShortestPath.java import com.github.vangj.jbayes.inf.exact.graph.Node; import com.github.vangj.jbayes.inf.exact.graph.Pdag; import java.util.HashSet; import java.util.Set; package com.github.vangj.jbayes.inf.exact.graph.traversal; public class PdagShortestPath extends GraphShortestPath { private final Pdag pdag;
protected PdagShortestPath(Pdag pdag, Node start, Node stop, ShortestPathListener listener) {
vangj/jbayes
src/main/java/com/github/vangj/jbayes/inf/exact/graph/lpd/PotentialEntry.java
// Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/util/PotentialUtil.java // public static String asString(Map<String, String> entries) { // return entries.entrySet().stream() // .map(entry -> (new StringBuilder()) // .append(entry.getKey()) // .append('=') // .append(entry.getValue()) // .toString()) // .collect(Collectors.joining(",", "[", "]")); // } // // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/util/PotentialUtil.java // public static Map<String, String> sortByKeys(Map<String, String> map) { // Map<String, String> out = new TreeMap<>(map); // return out; // }
import static com.github.vangj.jbayes.inf.exact.graph.util.PotentialUtil.asString; import static com.github.vangj.jbayes.inf.exact.graph.util.PotentialUtil.sortByKeys; import java.util.LinkedHashMap; import java.util.Map;
public PotentialEntry setValue(Double value) { this.value = value; return this; } /** * Checks if the specified potential entry matches. This potential entry must contain, at the very * least, all the same key-value pairs as the specified potential entry passed in. * * @param that Potential entry. * @return Boolean. */ public boolean match(PotentialEntry that) { for (Map.Entry<String, String> entry : that.entries.entrySet()) { String k = entry.getKey(); String v = entry.getValue(); if (!this.entries.containsKey(k)) { return false; } else { if (!this.entries.get(k).equalsIgnoreCase(v)) { return false; } } } return true; } @Override public int hashCode() {
// Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/util/PotentialUtil.java // public static String asString(Map<String, String> entries) { // return entries.entrySet().stream() // .map(entry -> (new StringBuilder()) // .append(entry.getKey()) // .append('=') // .append(entry.getValue()) // .toString()) // .collect(Collectors.joining(",", "[", "]")); // } // // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/util/PotentialUtil.java // public static Map<String, String> sortByKeys(Map<String, String> map) { // Map<String, String> out = new TreeMap<>(map); // return out; // } // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/lpd/PotentialEntry.java import static com.github.vangj.jbayes.inf.exact.graph.util.PotentialUtil.asString; import static com.github.vangj.jbayes.inf.exact.graph.util.PotentialUtil.sortByKeys; import java.util.LinkedHashMap; import java.util.Map; public PotentialEntry setValue(Double value) { this.value = value; return this; } /** * Checks if the specified potential entry matches. This potential entry must contain, at the very * least, all the same key-value pairs as the specified potential entry passed in. * * @param that Potential entry. * @return Boolean. */ public boolean match(PotentialEntry that) { for (Map.Entry<String, String> entry : that.entries.entrySet()) { String k = entry.getKey(); String v = entry.getValue(); if (!this.entries.containsKey(k)) { return false; } else { if (!this.entries.get(k).equalsIgnoreCase(v)) { return false; } } } return true; } @Override public int hashCode() {
return asString(sortByKeys(entries)).hashCode();
vangj/jbayes
src/main/java/com/github/vangj/jbayes/inf/exact/graph/lpd/PotentialEntry.java
// Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/util/PotentialUtil.java // public static String asString(Map<String, String> entries) { // return entries.entrySet().stream() // .map(entry -> (new StringBuilder()) // .append(entry.getKey()) // .append('=') // .append(entry.getValue()) // .toString()) // .collect(Collectors.joining(",", "[", "]")); // } // // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/util/PotentialUtil.java // public static Map<String, String> sortByKeys(Map<String, String> map) { // Map<String, String> out = new TreeMap<>(map); // return out; // }
import static com.github.vangj.jbayes.inf.exact.graph.util.PotentialUtil.asString; import static com.github.vangj.jbayes.inf.exact.graph.util.PotentialUtil.sortByKeys; import java.util.LinkedHashMap; import java.util.Map;
public PotentialEntry setValue(Double value) { this.value = value; return this; } /** * Checks if the specified potential entry matches. This potential entry must contain, at the very * least, all the same key-value pairs as the specified potential entry passed in. * * @param that Potential entry. * @return Boolean. */ public boolean match(PotentialEntry that) { for (Map.Entry<String, String> entry : that.entries.entrySet()) { String k = entry.getKey(); String v = entry.getValue(); if (!this.entries.containsKey(k)) { return false; } else { if (!this.entries.get(k).equalsIgnoreCase(v)) { return false; } } } return true; } @Override public int hashCode() {
// Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/util/PotentialUtil.java // public static String asString(Map<String, String> entries) { // return entries.entrySet().stream() // .map(entry -> (new StringBuilder()) // .append(entry.getKey()) // .append('=') // .append(entry.getValue()) // .toString()) // .collect(Collectors.joining(",", "[", "]")); // } // // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/util/PotentialUtil.java // public static Map<String, String> sortByKeys(Map<String, String> map) { // Map<String, String> out = new TreeMap<>(map); // return out; // } // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/lpd/PotentialEntry.java import static com.github.vangj.jbayes.inf.exact.graph.util.PotentialUtil.asString; import static com.github.vangj.jbayes.inf.exact.graph.util.PotentialUtil.sortByKeys; import java.util.LinkedHashMap; import java.util.Map; public PotentialEntry setValue(Double value) { this.value = value; return this; } /** * Checks if the specified potential entry matches. This potential entry must contain, at the very * least, all the same key-value pairs as the specified potential entry passed in. * * @param that Potential entry. * @return Boolean. */ public boolean match(PotentialEntry that) { for (Map.Entry<String, String> entry : that.entries.entrySet()) { String k = entry.getKey(); String v = entry.getValue(); if (!this.entries.containsKey(k)) { return false; } else { if (!this.entries.get(k).equalsIgnoreCase(v)) { return false; } } } return true; } @Override public int hashCode() {
return asString(sortByKeys(entries)).hashCode();
vangj/jbayes
src/main/java/com/github/vangj/jbayes/inf/exact/graph/Dag.java
// Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/util/PotentialUtil.java // public static Potential getPotential(Node node, List<Node> parents) { // Potential potential = getPotential(merge(node, parents)); // // final int total = Math.min(node.probs().size(), potential.entries().size()); // for (int i = 0; i < total; i++) { // Double prob = node.probs().get(i); // potential.entries().get(i).setValue(prob); // } // // return potential; // } // // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/lpd/Potential.java // public class Potential { // // private final List<PotentialEntry> entries; // // public Potential() { // entries = new ArrayList<>(); // } // // /** // * Finds matching potential entries to the specified one passed in. // * // * @param potentialEntry Potential entry. // * @return List of ootential entries. // */ // public List<PotentialEntry> match(PotentialEntry potentialEntry) { // List<PotentialEntry> entries = new ArrayList<>(); // for (PotentialEntry entry : this.entries) { // if (entry.match(potentialEntry)) { // entries.add(entry); // } // } // return entries; // } // // public List<PotentialEntry> entries() { // return entries; // } // // public Potential addEntry(PotentialEntry entry) { // entries.add(entry); // return this; // } // // @Override // public String toString() { // return entries.stream() // .map(PotentialEntry::toString) // .collect(Collectors.joining(System.lineSeparator())); // } // } // // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/traversal/DagShortestPath.java // public class DagShortestPath extends GraphShortestPath { // // private final Dag dag; // // private DagShortestPath(Dag graph, Node start, Node stop, ShortestPathListener listener) { // super(graph, start, stop, listener); // this.dag = graph; // } // // public static boolean exists(Dag graph, Node start, Node stop, ShortestPathListener listener) { // return (new DagShortestPath(graph, start, stop, listener)).search(); // } // // private boolean search() { // if (null != listener) { // listener.pre(graph, start, stop); // } // // if (start.equals(stop)) { // if (null != listener) { // listener.post(graph, start, stop); // } // return false; // } // // boolean result = search(start); // // if (null != listener) { // listener.post(graph, start, stop); // } // // return result; // } // // private boolean search(Node node) { // if (null != listener) { // listener.visited(node); // } // // List<Node> children = dag.children(node); // if (null == children || children.size() == 0) { // return false; // } // // if (children.contains(stop)) { // return true; // } else { // seen.add(node); // for (Node child : children) { // if (!seen.contains(child)) { // if (search(child)) { // return true; // } // } // } // } // // return false; // } // }
import static com.github.vangj.jbayes.inf.exact.graph.util.PotentialUtil.getPotential; import com.github.vangj.jbayes.inf.exact.graph.lpd.Potential; import com.github.vangj.jbayes.inf.exact.graph.traversal.DagShortestPath; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set;
package com.github.vangj.jbayes.inf.exact.graph; /** * A directed acylic graph (DAG). */ public class Dag extends Graph { protected Map<String, List<Node>> parents; protected Map<String, List<Node>> children; public Dag() { parents = new HashMap<>(); children = new HashMap<>(); } /** * Initializes the potential for each node. * * @return Dag. */ public Dag initializePotentials() { nodes().forEach(node -> {
// Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/util/PotentialUtil.java // public static Potential getPotential(Node node, List<Node> parents) { // Potential potential = getPotential(merge(node, parents)); // // final int total = Math.min(node.probs().size(), potential.entries().size()); // for (int i = 0; i < total; i++) { // Double prob = node.probs().get(i); // potential.entries().get(i).setValue(prob); // } // // return potential; // } // // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/lpd/Potential.java // public class Potential { // // private final List<PotentialEntry> entries; // // public Potential() { // entries = new ArrayList<>(); // } // // /** // * Finds matching potential entries to the specified one passed in. // * // * @param potentialEntry Potential entry. // * @return List of ootential entries. // */ // public List<PotentialEntry> match(PotentialEntry potentialEntry) { // List<PotentialEntry> entries = new ArrayList<>(); // for (PotentialEntry entry : this.entries) { // if (entry.match(potentialEntry)) { // entries.add(entry); // } // } // return entries; // } // // public List<PotentialEntry> entries() { // return entries; // } // // public Potential addEntry(PotentialEntry entry) { // entries.add(entry); // return this; // } // // @Override // public String toString() { // return entries.stream() // .map(PotentialEntry::toString) // .collect(Collectors.joining(System.lineSeparator())); // } // } // // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/traversal/DagShortestPath.java // public class DagShortestPath extends GraphShortestPath { // // private final Dag dag; // // private DagShortestPath(Dag graph, Node start, Node stop, ShortestPathListener listener) { // super(graph, start, stop, listener); // this.dag = graph; // } // // public static boolean exists(Dag graph, Node start, Node stop, ShortestPathListener listener) { // return (new DagShortestPath(graph, start, stop, listener)).search(); // } // // private boolean search() { // if (null != listener) { // listener.pre(graph, start, stop); // } // // if (start.equals(stop)) { // if (null != listener) { // listener.post(graph, start, stop); // } // return false; // } // // boolean result = search(start); // // if (null != listener) { // listener.post(graph, start, stop); // } // // return result; // } // // private boolean search(Node node) { // if (null != listener) { // listener.visited(node); // } // // List<Node> children = dag.children(node); // if (null == children || children.size() == 0) { // return false; // } // // if (children.contains(stop)) { // return true; // } else { // seen.add(node); // for (Node child : children) { // if (!seen.contains(child)) { // if (search(child)) { // return true; // } // } // } // } // // return false; // } // } // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/Dag.java import static com.github.vangj.jbayes.inf.exact.graph.util.PotentialUtil.getPotential; import com.github.vangj.jbayes.inf.exact.graph.lpd.Potential; import com.github.vangj.jbayes.inf.exact.graph.traversal.DagShortestPath; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; package com.github.vangj.jbayes.inf.exact.graph; /** * A directed acylic graph (DAG). */ public class Dag extends Graph { protected Map<String, List<Node>> parents; protected Map<String, List<Node>> children; public Dag() { parents = new HashMap<>(); children = new HashMap<>(); } /** * Initializes the potential for each node. * * @return Dag. */ public Dag initializePotentials() { nodes().forEach(node -> {
Potential potential = getPotential(node, parents(node));
vangj/jbayes
src/main/java/com/github/vangj/jbayes/inf/exact/graph/Dag.java
// Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/util/PotentialUtil.java // public static Potential getPotential(Node node, List<Node> parents) { // Potential potential = getPotential(merge(node, parents)); // // final int total = Math.min(node.probs().size(), potential.entries().size()); // for (int i = 0; i < total; i++) { // Double prob = node.probs().get(i); // potential.entries().get(i).setValue(prob); // } // // return potential; // } // // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/lpd/Potential.java // public class Potential { // // private final List<PotentialEntry> entries; // // public Potential() { // entries = new ArrayList<>(); // } // // /** // * Finds matching potential entries to the specified one passed in. // * // * @param potentialEntry Potential entry. // * @return List of ootential entries. // */ // public List<PotentialEntry> match(PotentialEntry potentialEntry) { // List<PotentialEntry> entries = new ArrayList<>(); // for (PotentialEntry entry : this.entries) { // if (entry.match(potentialEntry)) { // entries.add(entry); // } // } // return entries; // } // // public List<PotentialEntry> entries() { // return entries; // } // // public Potential addEntry(PotentialEntry entry) { // entries.add(entry); // return this; // } // // @Override // public String toString() { // return entries.stream() // .map(PotentialEntry::toString) // .collect(Collectors.joining(System.lineSeparator())); // } // } // // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/traversal/DagShortestPath.java // public class DagShortestPath extends GraphShortestPath { // // private final Dag dag; // // private DagShortestPath(Dag graph, Node start, Node stop, ShortestPathListener listener) { // super(graph, start, stop, listener); // this.dag = graph; // } // // public static boolean exists(Dag graph, Node start, Node stop, ShortestPathListener listener) { // return (new DagShortestPath(graph, start, stop, listener)).search(); // } // // private boolean search() { // if (null != listener) { // listener.pre(graph, start, stop); // } // // if (start.equals(stop)) { // if (null != listener) { // listener.post(graph, start, stop); // } // return false; // } // // boolean result = search(start); // // if (null != listener) { // listener.post(graph, start, stop); // } // // return result; // } // // private boolean search(Node node) { // if (null != listener) { // listener.visited(node); // } // // List<Node> children = dag.children(node); // if (null == children || children.size() == 0) { // return false; // } // // if (children.contains(stop)) { // return true; // } else { // seen.add(node); // for (Node child : children) { // if (!seen.contains(child)) { // if (search(child)) { // return true; // } // } // } // } // // return false; // } // }
import static com.github.vangj.jbayes.inf.exact.graph.util.PotentialUtil.getPotential; import com.github.vangj.jbayes.inf.exact.graph.lpd.Potential; import com.github.vangj.jbayes.inf.exact.graph.traversal.DagShortestPath; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set;
package com.github.vangj.jbayes.inf.exact.graph; /** * A directed acylic graph (DAG). */ public class Dag extends Graph { protected Map<String, List<Node>> parents; protected Map<String, List<Node>> children; public Dag() { parents = new HashMap<>(); children = new HashMap<>(); } /** * Initializes the potential for each node. * * @return Dag. */ public Dag initializePotentials() { nodes().forEach(node -> {
// Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/util/PotentialUtil.java // public static Potential getPotential(Node node, List<Node> parents) { // Potential potential = getPotential(merge(node, parents)); // // final int total = Math.min(node.probs().size(), potential.entries().size()); // for (int i = 0; i < total; i++) { // Double prob = node.probs().get(i); // potential.entries().get(i).setValue(prob); // } // // return potential; // } // // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/lpd/Potential.java // public class Potential { // // private final List<PotentialEntry> entries; // // public Potential() { // entries = new ArrayList<>(); // } // // /** // * Finds matching potential entries to the specified one passed in. // * // * @param potentialEntry Potential entry. // * @return List of ootential entries. // */ // public List<PotentialEntry> match(PotentialEntry potentialEntry) { // List<PotentialEntry> entries = new ArrayList<>(); // for (PotentialEntry entry : this.entries) { // if (entry.match(potentialEntry)) { // entries.add(entry); // } // } // return entries; // } // // public List<PotentialEntry> entries() { // return entries; // } // // public Potential addEntry(PotentialEntry entry) { // entries.add(entry); // return this; // } // // @Override // public String toString() { // return entries.stream() // .map(PotentialEntry::toString) // .collect(Collectors.joining(System.lineSeparator())); // } // } // // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/traversal/DagShortestPath.java // public class DagShortestPath extends GraphShortestPath { // // private final Dag dag; // // private DagShortestPath(Dag graph, Node start, Node stop, ShortestPathListener listener) { // super(graph, start, stop, listener); // this.dag = graph; // } // // public static boolean exists(Dag graph, Node start, Node stop, ShortestPathListener listener) { // return (new DagShortestPath(graph, start, stop, listener)).search(); // } // // private boolean search() { // if (null != listener) { // listener.pre(graph, start, stop); // } // // if (start.equals(stop)) { // if (null != listener) { // listener.post(graph, start, stop); // } // return false; // } // // boolean result = search(start); // // if (null != listener) { // listener.post(graph, start, stop); // } // // return result; // } // // private boolean search(Node node) { // if (null != listener) { // listener.visited(node); // } // // List<Node> children = dag.children(node); // if (null == children || children.size() == 0) { // return false; // } // // if (children.contains(stop)) { // return true; // } else { // seen.add(node); // for (Node child : children) { // if (!seen.contains(child)) { // if (search(child)) { // return true; // } // } // } // } // // return false; // } // } // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/Dag.java import static com.github.vangj.jbayes.inf.exact.graph.util.PotentialUtil.getPotential; import com.github.vangj.jbayes.inf.exact.graph.lpd.Potential; import com.github.vangj.jbayes.inf.exact.graph.traversal.DagShortestPath; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; package com.github.vangj.jbayes.inf.exact.graph; /** * A directed acylic graph (DAG). */ public class Dag extends Graph { protected Map<String, List<Node>> parents; protected Map<String, List<Node>> children; public Dag() { parents = new HashMap<>(); children = new HashMap<>(); } /** * Initializes the potential for each node. * * @return Dag. */ public Dag initializePotentials() { nodes().forEach(node -> {
Potential potential = getPotential(node, parents(node));
vangj/jbayes
src/main/java/com/github/vangj/jbayes/inf/exact/graph/Dag.java
// Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/util/PotentialUtil.java // public static Potential getPotential(Node node, List<Node> parents) { // Potential potential = getPotential(merge(node, parents)); // // final int total = Math.min(node.probs().size(), potential.entries().size()); // for (int i = 0; i < total; i++) { // Double prob = node.probs().get(i); // potential.entries().get(i).setValue(prob); // } // // return potential; // } // // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/lpd/Potential.java // public class Potential { // // private final List<PotentialEntry> entries; // // public Potential() { // entries = new ArrayList<>(); // } // // /** // * Finds matching potential entries to the specified one passed in. // * // * @param potentialEntry Potential entry. // * @return List of ootential entries. // */ // public List<PotentialEntry> match(PotentialEntry potentialEntry) { // List<PotentialEntry> entries = new ArrayList<>(); // for (PotentialEntry entry : this.entries) { // if (entry.match(potentialEntry)) { // entries.add(entry); // } // } // return entries; // } // // public List<PotentialEntry> entries() { // return entries; // } // // public Potential addEntry(PotentialEntry entry) { // entries.add(entry); // return this; // } // // @Override // public String toString() { // return entries.stream() // .map(PotentialEntry::toString) // .collect(Collectors.joining(System.lineSeparator())); // } // } // // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/traversal/DagShortestPath.java // public class DagShortestPath extends GraphShortestPath { // // private final Dag dag; // // private DagShortestPath(Dag graph, Node start, Node stop, ShortestPathListener listener) { // super(graph, start, stop, listener); // this.dag = graph; // } // // public static boolean exists(Dag graph, Node start, Node stop, ShortestPathListener listener) { // return (new DagShortestPath(graph, start, stop, listener)).search(); // } // // private boolean search() { // if (null != listener) { // listener.pre(graph, start, stop); // } // // if (start.equals(stop)) { // if (null != listener) { // listener.post(graph, start, stop); // } // return false; // } // // boolean result = search(start); // // if (null != listener) { // listener.post(graph, start, stop); // } // // return result; // } // // private boolean search(Node node) { // if (null != listener) { // listener.visited(node); // } // // List<Node> children = dag.children(node); // if (null == children || children.size() == 0) { // return false; // } // // if (children.contains(stop)) { // return true; // } else { // seen.add(node); // for (Node child : children) { // if (!seen.contains(child)) { // if (search(child)) { // return true; // } // } // } // } // // return false; // } // }
import static com.github.vangj.jbayes.inf.exact.graph.util.PotentialUtil.getPotential; import com.github.vangj.jbayes.inf.exact.graph.lpd.Potential; import com.github.vangj.jbayes.inf.exact.graph.traversal.DagShortestPath; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set;
package com.github.vangj.jbayes.inf.exact.graph; /** * A directed acylic graph (DAG). */ public class Dag extends Graph { protected Map<String, List<Node>> parents; protected Map<String, List<Node>> children; public Dag() { parents = new HashMap<>(); children = new HashMap<>(); } /** * Initializes the potential for each node. * * @return Dag. */ public Dag initializePotentials() { nodes().forEach(node -> { Potential potential = getPotential(node, parents(node)); node.setPotential(potential); }); return this; } @Override protected Graph instance() { return new Dag(); } @Override public Graph addEdge(Edge edge) { edge.type = Edge.Type.DIRECTED;
// Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/util/PotentialUtil.java // public static Potential getPotential(Node node, List<Node> parents) { // Potential potential = getPotential(merge(node, parents)); // // final int total = Math.min(node.probs().size(), potential.entries().size()); // for (int i = 0; i < total; i++) { // Double prob = node.probs().get(i); // potential.entries().get(i).setValue(prob); // } // // return potential; // } // // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/lpd/Potential.java // public class Potential { // // private final List<PotentialEntry> entries; // // public Potential() { // entries = new ArrayList<>(); // } // // /** // * Finds matching potential entries to the specified one passed in. // * // * @param potentialEntry Potential entry. // * @return List of ootential entries. // */ // public List<PotentialEntry> match(PotentialEntry potentialEntry) { // List<PotentialEntry> entries = new ArrayList<>(); // for (PotentialEntry entry : this.entries) { // if (entry.match(potentialEntry)) { // entries.add(entry); // } // } // return entries; // } // // public List<PotentialEntry> entries() { // return entries; // } // // public Potential addEntry(PotentialEntry entry) { // entries.add(entry); // return this; // } // // @Override // public String toString() { // return entries.stream() // .map(PotentialEntry::toString) // .collect(Collectors.joining(System.lineSeparator())); // } // } // // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/traversal/DagShortestPath.java // public class DagShortestPath extends GraphShortestPath { // // private final Dag dag; // // private DagShortestPath(Dag graph, Node start, Node stop, ShortestPathListener listener) { // super(graph, start, stop, listener); // this.dag = graph; // } // // public static boolean exists(Dag graph, Node start, Node stop, ShortestPathListener listener) { // return (new DagShortestPath(graph, start, stop, listener)).search(); // } // // private boolean search() { // if (null != listener) { // listener.pre(graph, start, stop); // } // // if (start.equals(stop)) { // if (null != listener) { // listener.post(graph, start, stop); // } // return false; // } // // boolean result = search(start); // // if (null != listener) { // listener.post(graph, start, stop); // } // // return result; // } // // private boolean search(Node node) { // if (null != listener) { // listener.visited(node); // } // // List<Node> children = dag.children(node); // if (null == children || children.size() == 0) { // return false; // } // // if (children.contains(stop)) { // return true; // } else { // seen.add(node); // for (Node child : children) { // if (!seen.contains(child)) { // if (search(child)) { // return true; // } // } // } // } // // return false; // } // } // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/Dag.java import static com.github.vangj.jbayes.inf.exact.graph.util.PotentialUtil.getPotential; import com.github.vangj.jbayes.inf.exact.graph.lpd.Potential; import com.github.vangj.jbayes.inf.exact.graph.traversal.DagShortestPath; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; package com.github.vangj.jbayes.inf.exact.graph; /** * A directed acylic graph (DAG). */ public class Dag extends Graph { protected Map<String, List<Node>> parents; protected Map<String, List<Node>> children; public Dag() { parents = new HashMap<>(); children = new HashMap<>(); } /** * Initializes the potential for each node. * * @return Dag. */ public Dag initializePotentials() { nodes().forEach(node -> { Potential potential = getPotential(node, parents(node)); node.setPotential(potential); }); return this; } @Override protected Graph instance() { return new Dag(); } @Override public Graph addEdge(Edge edge) { edge.type = Edge.Type.DIRECTED;
if (DagShortestPath.exists(this, edge.right, edge.left, null)) {
vangj/jbayes
src/test/java/com/github/vangj/jbayes/inf/exact/sampling/TableTest.java
// Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/Node.java // public class Node extends Variable { // // private final List<Double> probs; // private List<String> valueList; // private Potential potential; // private Map<String, Object> metadata; // // public Node() { // probs = new ArrayList<>(); // } // // public Node(Variable v) { // probs = new ArrayList<>(); // metadata = new HashMap<>(); // this.id = v.id; // this.name = v.name; // this.values = v.values; // this.valueList = this.values.stream() // .collect(Collectors.toList()); // } // // private Node(NodeBuilder builder) { // id = builder.id; // metadata = new HashMap<>(); // name = builder.name; // values = builder.values; // probs = builder.probs; // this.valueList = this.values.stream() // .collect(Collectors.toList()); // } // // public static NodeBuilder builder() { // return new NodeBuilder(); // } // // /** // * Adds any metadata. // * // * @param k Key. // * @param v Value. // */ // public void addMetadata(String k, Object v) { // metadata.put(k, v); // } // // /** // * Gets the metadata associated with the specified key. // * // * @param k Key. // * @return Value. // */ // public Object getMetadata(String k) { // return metadata.get(k); // } // // public Potential getPotential() { // return potential; // } // // public void setPotential(Potential potential) { // this.potential = potential; // } // // public Node addProb(Double prob) { // probs.add(prob); // return this; // } // // public int weight() { // return values.size(); // } // // public List<Double> probs() { // return probs; // } // // public List<String> getValueList() { // return valueList; // } // // public static final class NodeBuilder { // // private String id; // private String name; // private Set<String> values; // private List<Double> probs; // // private NodeBuilder() { // values = new LinkedHashSet<>(); // probs = new ArrayList<>(); // } // // public NodeBuilder from(Variable v) { // this.id = v.id; // this.name = v.name; // this.values = v.values; // return this; // } // // public NodeBuilder id(String val) { // id = val; // return this; // } // // public NodeBuilder name(String val) { // name = val; // return this; // } // // public NodeBuilder value(String val) { // values.add(val); // return this; // } // // public NodeBuilder values(Set<String> val) { // values = val; // return this; // } // // public NodeBuilder probs(List<Double> probs) { // this.probs = probs; // return this; // } // // public NodeBuilder prob(Double prob) { // this.probs.add(prob); // return this; // } // // public Node build() { // return new Node(this); // } // } // }
import com.github.vangj.jbayes.inf.exact.graph.Node; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Assert; import org.junit.Test;
package com.github.vangj.jbayes.inf.exact.sampling; public class TableTest { @Test public void testNoParents() {
// Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/Node.java // public class Node extends Variable { // // private final List<Double> probs; // private List<String> valueList; // private Potential potential; // private Map<String, Object> metadata; // // public Node() { // probs = new ArrayList<>(); // } // // public Node(Variable v) { // probs = new ArrayList<>(); // metadata = new HashMap<>(); // this.id = v.id; // this.name = v.name; // this.values = v.values; // this.valueList = this.values.stream() // .collect(Collectors.toList()); // } // // private Node(NodeBuilder builder) { // id = builder.id; // metadata = new HashMap<>(); // name = builder.name; // values = builder.values; // probs = builder.probs; // this.valueList = this.values.stream() // .collect(Collectors.toList()); // } // // public static NodeBuilder builder() { // return new NodeBuilder(); // } // // /** // * Adds any metadata. // * // * @param k Key. // * @param v Value. // */ // public void addMetadata(String k, Object v) { // metadata.put(k, v); // } // // /** // * Gets the metadata associated with the specified key. // * // * @param k Key. // * @return Value. // */ // public Object getMetadata(String k) { // return metadata.get(k); // } // // public Potential getPotential() { // return potential; // } // // public void setPotential(Potential potential) { // this.potential = potential; // } // // public Node addProb(Double prob) { // probs.add(prob); // return this; // } // // public int weight() { // return values.size(); // } // // public List<Double> probs() { // return probs; // } // // public List<String> getValueList() { // return valueList; // } // // public static final class NodeBuilder { // // private String id; // private String name; // private Set<String> values; // private List<Double> probs; // // private NodeBuilder() { // values = new LinkedHashSet<>(); // probs = new ArrayList<>(); // } // // public NodeBuilder from(Variable v) { // this.id = v.id; // this.name = v.name; // this.values = v.values; // return this; // } // // public NodeBuilder id(String val) { // id = val; // return this; // } // // public NodeBuilder name(String val) { // name = val; // return this; // } // // public NodeBuilder value(String val) { // values.add(val); // return this; // } // // public NodeBuilder values(Set<String> val) { // values = val; // return this; // } // // public NodeBuilder probs(List<Double> probs) { // this.probs = probs; // return this; // } // // public NodeBuilder prob(Double prob) { // this.probs.add(prob); // return this; // } // // public Node build() { // return new Node(this); // } // } // } // Path: src/test/java/com/github/vangj/jbayes/inf/exact/sampling/TableTest.java import com.github.vangj.jbayes.inf.exact.graph.Node; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Assert; import org.junit.Test; package com.github.vangj.jbayes.inf.exact.sampling; public class TableTest { @Test public void testNoParents() {
Node a = Node.builder()
vangj/jbayes
src/main/java/com/github/vangj/jbayes/inf/exact/graph/Node.java
// Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/lpd/Potential.java // public class Potential { // // private final List<PotentialEntry> entries; // // public Potential() { // entries = new ArrayList<>(); // } // // /** // * Finds matching potential entries to the specified one passed in. // * // * @param potentialEntry Potential entry. // * @return List of ootential entries. // */ // public List<PotentialEntry> match(PotentialEntry potentialEntry) { // List<PotentialEntry> entries = new ArrayList<>(); // for (PotentialEntry entry : this.entries) { // if (entry.match(potentialEntry)) { // entries.add(entry); // } // } // return entries; // } // // public List<PotentialEntry> entries() { // return entries; // } // // public Potential addEntry(PotentialEntry entry) { // entries.add(entry); // return this; // } // // @Override // public String toString() { // return entries.stream() // .map(PotentialEntry::toString) // .collect(Collectors.joining(System.lineSeparator())); // } // }
import com.github.vangj.jbayes.inf.exact.graph.lpd.Potential; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors;
package com.github.vangj.jbayes.inf.exact.graph; /** * A node in a graph. */ public class Node extends Variable { private final List<Double> probs; private List<String> valueList;
// Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/lpd/Potential.java // public class Potential { // // private final List<PotentialEntry> entries; // // public Potential() { // entries = new ArrayList<>(); // } // // /** // * Finds matching potential entries to the specified one passed in. // * // * @param potentialEntry Potential entry. // * @return List of ootential entries. // */ // public List<PotentialEntry> match(PotentialEntry potentialEntry) { // List<PotentialEntry> entries = new ArrayList<>(); // for (PotentialEntry entry : this.entries) { // if (entry.match(potentialEntry)) { // entries.add(entry); // } // } // return entries; // } // // public List<PotentialEntry> entries() { // return entries; // } // // public Potential addEntry(PotentialEntry entry) { // entries.add(entry); // return this; // } // // @Override // public String toString() { // return entries.stream() // .map(PotentialEntry::toString) // .collect(Collectors.joining(System.lineSeparator())); // } // } // Path: src/main/java/com/github/vangj/jbayes/inf/exact/graph/Node.java import com.github.vangj.jbayes.inf.exact.graph.lpd.Potential; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; package com.github.vangj.jbayes.inf.exact.graph; /** * A node in a graph. */ public class Node extends Variable { private final List<Double> probs; private List<String> valueList;
private Potential potential;
iacobcl/MARA
src/objs/stats/RateStats.java
// Path: src/objs/CodeDistr.java // public class CodeDistr // { // // private String code; // private int total; // private double perc; // private int totalrel; // private double percrel; // // public CodeDistr() // { // code = new String(); // total = 0; // perc = 0; // totalrel = 0; // percrel = 0; // } // // public CodeDistr(String c, int t, double p, int totalr, double perrel) // { // code = c; // total = t; // perc = p; // totalrel = totalr; // percrel = perrel; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public int getTotal() { // return total; // } // // // public void setTotal(int total) { // this.total = total; // } // // // public double getPerc() { // return perc; // } // // // public void setPerc(double perc) { // this.perc = perc; // } // // public int getTotalrel() { // return totalrel; // } // // public void setTotalrel(int totalrel) { // this.totalrel = totalrel; // } // // public double getPercrel() { // return percrel; // } // // public void setPercrel(double percrel) { // this.percrel = percrel; // } // // // }
import java.util.ArrayList; import objs.CodeDistr;
/* # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. */ package objs.stats; public class RateStats { private int stars;
// Path: src/objs/CodeDistr.java // public class CodeDistr // { // // private String code; // private int total; // private double perc; // private int totalrel; // private double percrel; // // public CodeDistr() // { // code = new String(); // total = 0; // perc = 0; // totalrel = 0; // percrel = 0; // } // // public CodeDistr(String c, int t, double p, int totalr, double perrel) // { // code = c; // total = t; // perc = p; // totalrel = totalr; // percrel = perrel; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public int getTotal() { // return total; // } // // // public void setTotal(int total) { // this.total = total; // } // // // public double getPerc() { // return perc; // } // // // public void setPerc(double perc) { // this.perc = perc; // } // // public int getTotalrel() { // return totalrel; // } // // public void setTotalrel(int totalrel) { // this.totalrel = totalrel; // } // // public double getPercrel() { // return percrel; // } // // public void setPercrel(double percrel) { // this.percrel = percrel; // } // // // } // Path: src/objs/stats/RateStats.java import java.util.ArrayList; import objs.CodeDistr; /* # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. */ package objs.stats; public class RateStats { private int stars;
private ArrayList<CodeDistr> dist;
iacobcl/MARA
src/objs/stats/reports/ReportAvgDistrStats.java
// Path: src/objs/CodeDistr.java // public class CodeDistr // { // // private String code; // private int total; // private double perc; // private int totalrel; // private double percrel; // // public CodeDistr() // { // code = new String(); // total = 0; // perc = 0; // totalrel = 0; // percrel = 0; // } // // public CodeDistr(String c, int t, double p, int totalr, double perrel) // { // code = c; // total = t; // perc = p; // totalrel = totalr; // percrel = perrel; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public int getTotal() { // return total; // } // // // public void setTotal(int total) { // this.total = total; // } // // // public double getPerc() { // return perc; // } // // // public void setPerc(double perc) { // this.perc = perc; // } // // public int getTotalrel() { // return totalrel; // } // // public void setTotalrel(int totalrel) { // this.totalrel = totalrel; // } // // public double getPercrel() { // return percrel; // } // // public void setPercrel(double percrel) { // this.percrel = percrel; // } // // // } // // Path: src/objs/stats/AvgDistrPriceStats.java // public class AvgDistrPriceStats // { // // private double min; // private double max; // private double avg; // // public AvgDistrPriceStats() // { // min = 0; // max = 0; // avg = 0; // } // // // public AvgDistrPriceStats(double min, double max, double avg) // { // this.min = min; // this.max = max; // this.avg = avg; // } // // // public double getMin() { // return min; // } // // // public void setMin(double min) { // this.min = min; // } // // // public double getMax() { // return max; // } // // // public void setMax(double max) { // this.max = max; // } // // // public double getAvg() { // return avg; // } // // // public void setAvg(double avg) { // this.avg = avg; // } // // // // } // // Path: src/objs/stats/RefCodeStats.java // public class RefCodeStats // { // private String classCode; // private ArrayList<CodeDistr> dist; // // // public RefCodeStats() // { // classCode = new String(); // dist = new ArrayList<CodeDistr>(); // // } // // // // public RefCodeStats(String classCode, ArrayList<CodeDistr> dist) { // super(); // this.classCode = classCode; // this.dist = dist; // } // // // // public String getClassCode() { // return classCode; // } // public void setClassCode(String classCode) { // this.classCode = classCode; // } // public ArrayList<CodeDistr> getDist() { // return dist; // } // public void setDist(ArrayList<CodeDistr> dist) { // this.dist = dist; // } // // // // }
import java.io.BufferedWriter; import java.io.FileWriter; import java.util.ArrayList; import objs.CodeDistr; import objs.stats.AvgDistrPriceStats; import objs.stats.RefCodeStats;
/* # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. */ package objs.stats.reports; public class ReportAvgDistrStats {
// Path: src/objs/CodeDistr.java // public class CodeDistr // { // // private String code; // private int total; // private double perc; // private int totalrel; // private double percrel; // // public CodeDistr() // { // code = new String(); // total = 0; // perc = 0; // totalrel = 0; // percrel = 0; // } // // public CodeDistr(String c, int t, double p, int totalr, double perrel) // { // code = c; // total = t; // perc = p; // totalrel = totalr; // percrel = perrel; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public int getTotal() { // return total; // } // // // public void setTotal(int total) { // this.total = total; // } // // // public double getPerc() { // return perc; // } // // // public void setPerc(double perc) { // this.perc = perc; // } // // public int getTotalrel() { // return totalrel; // } // // public void setTotalrel(int totalrel) { // this.totalrel = totalrel; // } // // public double getPercrel() { // return percrel; // } // // public void setPercrel(double percrel) { // this.percrel = percrel; // } // // // } // // Path: src/objs/stats/AvgDistrPriceStats.java // public class AvgDistrPriceStats // { // // private double min; // private double max; // private double avg; // // public AvgDistrPriceStats() // { // min = 0; // max = 0; // avg = 0; // } // // // public AvgDistrPriceStats(double min, double max, double avg) // { // this.min = min; // this.max = max; // this.avg = avg; // } // // // public double getMin() { // return min; // } // // // public void setMin(double min) { // this.min = min; // } // // // public double getMax() { // return max; // } // // // public void setMax(double max) { // this.max = max; // } // // // public double getAvg() { // return avg; // } // // // public void setAvg(double avg) { // this.avg = avg; // } // // // // } // // Path: src/objs/stats/RefCodeStats.java // public class RefCodeStats // { // private String classCode; // private ArrayList<CodeDistr> dist; // // // public RefCodeStats() // { // classCode = new String(); // dist = new ArrayList<CodeDistr>(); // // } // // // // public RefCodeStats(String classCode, ArrayList<CodeDistr> dist) { // super(); // this.classCode = classCode; // this.dist = dist; // } // // // // public String getClassCode() { // return classCode; // } // public void setClassCode(String classCode) { // this.classCode = classCode; // } // public ArrayList<CodeDistr> getDist() { // return dist; // } // public void setDist(ArrayList<CodeDistr> dist) { // this.dist = dist; // } // // // // } // Path: src/objs/stats/reports/ReportAvgDistrStats.java import java.io.BufferedWriter; import java.io.FileWriter; import java.util.ArrayList; import objs.CodeDistr; import objs.stats.AvgDistrPriceStats; import objs.stats.RefCodeStats; /* # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. */ package objs.stats.reports; public class ReportAvgDistrStats {
public static ArrayList<AvgDistrPriceStats> report;
iacobcl/MARA
src/objs/stats/reports/ReportClassCodeStats.java
// Path: src/objs/CodeDistr.java // public class CodeDistr // { // // private String code; // private int total; // private double perc; // private int totalrel; // private double percrel; // // public CodeDistr() // { // code = new String(); // total = 0; // perc = 0; // totalrel = 0; // percrel = 0; // } // // public CodeDistr(String c, int t, double p, int totalr, double perrel) // { // code = c; // total = t; // perc = p; // totalrel = totalr; // percrel = perrel; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public int getTotal() { // return total; // } // // // public void setTotal(int total) { // this.total = total; // } // // // public double getPerc() { // return perc; // } // // // public void setPerc(double perc) { // this.perc = perc; // } // // public int getTotalrel() { // return totalrel; // } // // public void setTotalrel(int totalrel) { // this.totalrel = totalrel; // } // // public double getPercrel() { // return percrel; // } // // public void setPercrel(double percrel) { // this.percrel = percrel; // } // // // } // // Path: src/objs/stats/RefCodeStats.java // public class RefCodeStats // { // private String classCode; // private ArrayList<CodeDistr> dist; // // // public RefCodeStats() // { // classCode = new String(); // dist = new ArrayList<CodeDistr>(); // // } // // // // public RefCodeStats(String classCode, ArrayList<CodeDistr> dist) { // super(); // this.classCode = classCode; // this.dist = dist; // } // // // // public String getClassCode() { // return classCode; // } // public void setClassCode(String classCode) { // this.classCode = classCode; // } // public ArrayList<CodeDistr> getDist() { // return dist; // } // public void setDist(ArrayList<CodeDistr> dist) { // this.dist = dist; // } // // // // }
import java.io.BufferedWriter; import java.io.FileWriter; import java.util.ArrayList; import objs.CodeDistr; import objs.stats.RefCodeStats;
/* # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. */ package objs.stats.reports; public class ReportClassCodeStats {
// Path: src/objs/CodeDistr.java // public class CodeDistr // { // // private String code; // private int total; // private double perc; // private int totalrel; // private double percrel; // // public CodeDistr() // { // code = new String(); // total = 0; // perc = 0; // totalrel = 0; // percrel = 0; // } // // public CodeDistr(String c, int t, double p, int totalr, double perrel) // { // code = c; // total = t; // perc = p; // totalrel = totalr; // percrel = perrel; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public int getTotal() { // return total; // } // // // public void setTotal(int total) { // this.total = total; // } // // // public double getPerc() { // return perc; // } // // // public void setPerc(double perc) { // this.perc = perc; // } // // public int getTotalrel() { // return totalrel; // } // // public void setTotalrel(int totalrel) { // this.totalrel = totalrel; // } // // public double getPercrel() { // return percrel; // } // // public void setPercrel(double percrel) { // this.percrel = percrel; // } // // // } // // Path: src/objs/stats/RefCodeStats.java // public class RefCodeStats // { // private String classCode; // private ArrayList<CodeDistr> dist; // // // public RefCodeStats() // { // classCode = new String(); // dist = new ArrayList<CodeDistr>(); // // } // // // // public RefCodeStats(String classCode, ArrayList<CodeDistr> dist) { // super(); // this.classCode = classCode; // this.dist = dist; // } // // // // public String getClassCode() { // return classCode; // } // public void setClassCode(String classCode) { // this.classCode = classCode; // } // public ArrayList<CodeDistr> getDist() { // return dist; // } // public void setDist(ArrayList<CodeDistr> dist) { // this.dist = dist; // } // // // // } // Path: src/objs/stats/reports/ReportClassCodeStats.java import java.io.BufferedWriter; import java.io.FileWriter; import java.util.ArrayList; import objs.CodeDistr; import objs.stats.RefCodeStats; /* # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. */ package objs.stats.reports; public class ReportClassCodeStats {
public static ArrayList<RefCodeStats> report;
iacobcl/MARA
src/objs/stats/reports/ReportClassCodeStats.java
// Path: src/objs/CodeDistr.java // public class CodeDistr // { // // private String code; // private int total; // private double perc; // private int totalrel; // private double percrel; // // public CodeDistr() // { // code = new String(); // total = 0; // perc = 0; // totalrel = 0; // percrel = 0; // } // // public CodeDistr(String c, int t, double p, int totalr, double perrel) // { // code = c; // total = t; // perc = p; // totalrel = totalr; // percrel = perrel; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public int getTotal() { // return total; // } // // // public void setTotal(int total) { // this.total = total; // } // // // public double getPerc() { // return perc; // } // // // public void setPerc(double perc) { // this.perc = perc; // } // // public int getTotalrel() { // return totalrel; // } // // public void setTotalrel(int totalrel) { // this.totalrel = totalrel; // } // // public double getPercrel() { // return percrel; // } // // public void setPercrel(double percrel) { // this.percrel = percrel; // } // // // } // // Path: src/objs/stats/RefCodeStats.java // public class RefCodeStats // { // private String classCode; // private ArrayList<CodeDistr> dist; // // // public RefCodeStats() // { // classCode = new String(); // dist = new ArrayList<CodeDistr>(); // // } // // // // public RefCodeStats(String classCode, ArrayList<CodeDistr> dist) { // super(); // this.classCode = classCode; // this.dist = dist; // } // // // // public String getClassCode() { // return classCode; // } // public void setClassCode(String classCode) { // this.classCode = classCode; // } // public ArrayList<CodeDistr> getDist() { // return dist; // } // public void setDist(ArrayList<CodeDistr> dist) { // this.dist = dist; // } // // // // }
import java.io.BufferedWriter; import java.io.FileWriter; import java.util.ArrayList; import objs.CodeDistr; import objs.stats.RefCodeStats;
/* # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. */ package objs.stats.reports; public class ReportClassCodeStats { public static ArrayList<RefCodeStats> report; public ReportClassCodeStats() { report = new ArrayList<RefCodeStats>(); } public ArrayList<RefCodeStats> getReport() { return report; } public void setReport(ArrayList<RefCodeStats> report) { this.report = report; } public static void print() { try { FileWriter fstream = new FileWriter("reports/class_codes_stats/reportclasscodesstats.txt"); BufferedWriter out = new BufferedWriter(fstream); for (int i = 0; i < report.size(); i++) { out.write("Class code:" + report.get(i).getClassCode()); out.newLine();
// Path: src/objs/CodeDistr.java // public class CodeDistr // { // // private String code; // private int total; // private double perc; // private int totalrel; // private double percrel; // // public CodeDistr() // { // code = new String(); // total = 0; // perc = 0; // totalrel = 0; // percrel = 0; // } // // public CodeDistr(String c, int t, double p, int totalr, double perrel) // { // code = c; // total = t; // perc = p; // totalrel = totalr; // percrel = perrel; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public int getTotal() { // return total; // } // // // public void setTotal(int total) { // this.total = total; // } // // // public double getPerc() { // return perc; // } // // // public void setPerc(double perc) { // this.perc = perc; // } // // public int getTotalrel() { // return totalrel; // } // // public void setTotalrel(int totalrel) { // this.totalrel = totalrel; // } // // public double getPercrel() { // return percrel; // } // // public void setPercrel(double percrel) { // this.percrel = percrel; // } // // // } // // Path: src/objs/stats/RefCodeStats.java // public class RefCodeStats // { // private String classCode; // private ArrayList<CodeDistr> dist; // // // public RefCodeStats() // { // classCode = new String(); // dist = new ArrayList<CodeDistr>(); // // } // // // // public RefCodeStats(String classCode, ArrayList<CodeDistr> dist) { // super(); // this.classCode = classCode; // this.dist = dist; // } // // // // public String getClassCode() { // return classCode; // } // public void setClassCode(String classCode) { // this.classCode = classCode; // } // public ArrayList<CodeDistr> getDist() { // return dist; // } // public void setDist(ArrayList<CodeDistr> dist) { // this.dist = dist; // } // // // // } // Path: src/objs/stats/reports/ReportClassCodeStats.java import java.io.BufferedWriter; import java.io.FileWriter; import java.util.ArrayList; import objs.CodeDistr; import objs.stats.RefCodeStats; /* # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. */ package objs.stats.reports; public class ReportClassCodeStats { public static ArrayList<RefCodeStats> report; public ReportClassCodeStats() { report = new ArrayList<RefCodeStats>(); } public ArrayList<RefCodeStats> getReport() { return report; } public void setReport(ArrayList<RefCodeStats> report) { this.report = report; } public static void print() { try { FileWriter fstream = new FileWriter("reports/class_codes_stats/reportclasscodesstats.txt"); BufferedWriter out = new BufferedWriter(fstream); for (int i = 0; i < report.size(); i++) { out.write("Class code:" + report.get(i).getClassCode()); out.newLine();
ArrayList<CodeDistr> codes = report.get(i).getDist();
iacobcl/MARA
src/objs/stats/UpdateStats.java
// Path: src/objs/CodeDistr.java // public class CodeDistr // { // // private String code; // private int total; // private double perc; // private int totalrel; // private double percrel; // // public CodeDistr() // { // code = new String(); // total = 0; // perc = 0; // totalrel = 0; // percrel = 0; // } // // public CodeDistr(String c, int t, double p, int totalr, double perrel) // { // code = c; // total = t; // perc = p; // totalrel = totalr; // percrel = perrel; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public int getTotal() { // return total; // } // // // public void setTotal(int total) { // this.total = total; // } // // // public double getPerc() { // return perc; // } // // // public void setPerc(double perc) { // this.perc = perc; // } // // public int getTotalrel() { // return totalrel; // } // // public void setTotalrel(int totalrel) { // this.totalrel = totalrel; // } // // public double getPercrel() { // return percrel; // } // // public void setPercrel(double percrel) { // this.percrel = percrel; // } // // // }
import java.util.ArrayList; import objs.CodeDistr;
/* # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. */ package objs.stats; public class UpdateStats { private float min; private float max;
// Path: src/objs/CodeDistr.java // public class CodeDistr // { // // private String code; // private int total; // private double perc; // private int totalrel; // private double percrel; // // public CodeDistr() // { // code = new String(); // total = 0; // perc = 0; // totalrel = 0; // percrel = 0; // } // // public CodeDistr(String c, int t, double p, int totalr, double perrel) // { // code = c; // total = t; // perc = p; // totalrel = totalr; // percrel = perrel; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public int getTotal() { // return total; // } // // // public void setTotal(int total) { // this.total = total; // } // // // public double getPerc() { // return perc; // } // // // public void setPerc(double perc) { // this.perc = perc; // } // // public int getTotalrel() { // return totalrel; // } // // public void setTotalrel(int totalrel) { // this.totalrel = totalrel; // } // // public double getPercrel() { // return percrel; // } // // public void setPercrel(double percrel) { // this.percrel = percrel; // } // // // } // Path: src/objs/stats/UpdateStats.java import java.util.ArrayList; import objs.CodeDistr; /* # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. */ package objs.stats; public class UpdateStats { private float min; private float max;
private ArrayList<CodeDistr> dist;
iacobcl/MARA
src/objs/stats/reports/ReportRateStats.java
// Path: src/objs/CodeDistr.java // public class CodeDistr // { // // private String code; // private int total; // private double perc; // private int totalrel; // private double percrel; // // public CodeDistr() // { // code = new String(); // total = 0; // perc = 0; // totalrel = 0; // percrel = 0; // } // // public CodeDistr(String c, int t, double p, int totalr, double perrel) // { // code = c; // total = t; // perc = p; // totalrel = totalr; // percrel = perrel; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public int getTotal() { // return total; // } // // // public void setTotal(int total) { // this.total = total; // } // // // public double getPerc() { // return perc; // } // // // public void setPerc(double perc) { // this.perc = perc; // } // // public int getTotalrel() { // return totalrel; // } // // public void setTotalrel(int totalrel) { // this.totalrel = totalrel; // } // // public double getPercrel() { // return percrel; // } // // public void setPercrel(double percrel) { // this.percrel = percrel; // } // // // } // // Path: src/objs/stats/PosNegCatStats.java // public class PosNegCatStats // { // private String cat; // private CodeDistr pos; // private CodeDistr neg; // // // public PosNegCatStats() // { // cat = new String(); // pos = new CodeDistr(); // neg = new CodeDistr(); // } // // // public PosNegCatStats(String cat, CodeDistr pos, CodeDistr neg) { // super(); // this.cat = cat; // this.pos = pos; // this.neg = neg; // } // // // public String getCat() { // return cat; // } // // // public void setCat(String cat) { // this.cat = cat; // } // // // public CodeDistr getPos() { // return pos; // } // // // public void setPos(CodeDistr pos) { // this.pos = pos; // } // // // public CodeDistr getNeg() { // return neg; // } // // // public void setNeg(CodeDistr neg) { // this.neg = neg; // } // // // // // } // // Path: src/objs/stats/RateStats.java // public class RateStats // { // private int stars; // private ArrayList<CodeDistr> dist; // // public RateStats() // { // stars = 0; // dist = new ArrayList<CodeDistr>(); // } // // // public int getStars() { // return stars; // } // public void setStars(int stars) { // this.stars = stars; // } // public ArrayList<CodeDistr> getDist() { // return dist; // } // public void setDist(ArrayList<CodeDistr> dist) { // this.dist = dist; // } // // // // }
import java.io.BufferedWriter; import java.io.FileWriter; import java.util.ArrayList; import objs.CodeDistr; import objs.stats.PosNegCatStats; import objs.stats.RateStats;
/* # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. */ package objs.stats.reports; public class ReportRateStats {
// Path: src/objs/CodeDistr.java // public class CodeDistr // { // // private String code; // private int total; // private double perc; // private int totalrel; // private double percrel; // // public CodeDistr() // { // code = new String(); // total = 0; // perc = 0; // totalrel = 0; // percrel = 0; // } // // public CodeDistr(String c, int t, double p, int totalr, double perrel) // { // code = c; // total = t; // perc = p; // totalrel = totalr; // percrel = perrel; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public int getTotal() { // return total; // } // // // public void setTotal(int total) { // this.total = total; // } // // // public double getPerc() { // return perc; // } // // // public void setPerc(double perc) { // this.perc = perc; // } // // public int getTotalrel() { // return totalrel; // } // // public void setTotalrel(int totalrel) { // this.totalrel = totalrel; // } // // public double getPercrel() { // return percrel; // } // // public void setPercrel(double percrel) { // this.percrel = percrel; // } // // // } // // Path: src/objs/stats/PosNegCatStats.java // public class PosNegCatStats // { // private String cat; // private CodeDistr pos; // private CodeDistr neg; // // // public PosNegCatStats() // { // cat = new String(); // pos = new CodeDistr(); // neg = new CodeDistr(); // } // // // public PosNegCatStats(String cat, CodeDistr pos, CodeDistr neg) { // super(); // this.cat = cat; // this.pos = pos; // this.neg = neg; // } // // // public String getCat() { // return cat; // } // // // public void setCat(String cat) { // this.cat = cat; // } // // // public CodeDistr getPos() { // return pos; // } // // // public void setPos(CodeDistr pos) { // this.pos = pos; // } // // // public CodeDistr getNeg() { // return neg; // } // // // public void setNeg(CodeDistr neg) { // this.neg = neg; // } // // // // // } // // Path: src/objs/stats/RateStats.java // public class RateStats // { // private int stars; // private ArrayList<CodeDistr> dist; // // public RateStats() // { // stars = 0; // dist = new ArrayList<CodeDistr>(); // } // // // public int getStars() { // return stars; // } // public void setStars(int stars) { // this.stars = stars; // } // public ArrayList<CodeDistr> getDist() { // return dist; // } // public void setDist(ArrayList<CodeDistr> dist) { // this.dist = dist; // } // // // // } // Path: src/objs/stats/reports/ReportRateStats.java import java.io.BufferedWriter; import java.io.FileWriter; import java.util.ArrayList; import objs.CodeDistr; import objs.stats.PosNegCatStats; import objs.stats.RateStats; /* # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. */ package objs.stats.reports; public class ReportRateStats {
public static ArrayList<RateStats> report;
iacobcl/MARA
src/objs/stats/reports/ReportRateStats.java
// Path: src/objs/CodeDistr.java // public class CodeDistr // { // // private String code; // private int total; // private double perc; // private int totalrel; // private double percrel; // // public CodeDistr() // { // code = new String(); // total = 0; // perc = 0; // totalrel = 0; // percrel = 0; // } // // public CodeDistr(String c, int t, double p, int totalr, double perrel) // { // code = c; // total = t; // perc = p; // totalrel = totalr; // percrel = perrel; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public int getTotal() { // return total; // } // // // public void setTotal(int total) { // this.total = total; // } // // // public double getPerc() { // return perc; // } // // // public void setPerc(double perc) { // this.perc = perc; // } // // public int getTotalrel() { // return totalrel; // } // // public void setTotalrel(int totalrel) { // this.totalrel = totalrel; // } // // public double getPercrel() { // return percrel; // } // // public void setPercrel(double percrel) { // this.percrel = percrel; // } // // // } // // Path: src/objs/stats/PosNegCatStats.java // public class PosNegCatStats // { // private String cat; // private CodeDistr pos; // private CodeDistr neg; // // // public PosNegCatStats() // { // cat = new String(); // pos = new CodeDistr(); // neg = new CodeDistr(); // } // // // public PosNegCatStats(String cat, CodeDistr pos, CodeDistr neg) { // super(); // this.cat = cat; // this.pos = pos; // this.neg = neg; // } // // // public String getCat() { // return cat; // } // // // public void setCat(String cat) { // this.cat = cat; // } // // // public CodeDistr getPos() { // return pos; // } // // // public void setPos(CodeDistr pos) { // this.pos = pos; // } // // // public CodeDistr getNeg() { // return neg; // } // // // public void setNeg(CodeDistr neg) { // this.neg = neg; // } // // // // // } // // Path: src/objs/stats/RateStats.java // public class RateStats // { // private int stars; // private ArrayList<CodeDistr> dist; // // public RateStats() // { // stars = 0; // dist = new ArrayList<CodeDistr>(); // } // // // public int getStars() { // return stars; // } // public void setStars(int stars) { // this.stars = stars; // } // public ArrayList<CodeDistr> getDist() { // return dist; // } // public void setDist(ArrayList<CodeDistr> dist) { // this.dist = dist; // } // // // // }
import java.io.BufferedWriter; import java.io.FileWriter; import java.util.ArrayList; import objs.CodeDistr; import objs.stats.PosNegCatStats; import objs.stats.RateStats;
/* # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. */ package objs.stats.reports; public class ReportRateStats { public static ArrayList<RateStats> report; public ReportRateStats() { report = new ArrayList<RateStats>(); } public ArrayList<RateStats> getReport() { return report; } public void setReport(ArrayList<RateStats> report) { this.report = report; } public static void print() { try { FileWriter fstream = new FileWriter("reports/rate_range_stats/reportratestats.txt"); BufferedWriter out = new BufferedWriter(fstream); for (int i = 0; i < report.size(); i++) { out.write("Class code:" + report.get(i).getStars()); out.newLine();
// Path: src/objs/CodeDistr.java // public class CodeDistr // { // // private String code; // private int total; // private double perc; // private int totalrel; // private double percrel; // // public CodeDistr() // { // code = new String(); // total = 0; // perc = 0; // totalrel = 0; // percrel = 0; // } // // public CodeDistr(String c, int t, double p, int totalr, double perrel) // { // code = c; // total = t; // perc = p; // totalrel = totalr; // percrel = perrel; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public int getTotal() { // return total; // } // // // public void setTotal(int total) { // this.total = total; // } // // // public double getPerc() { // return perc; // } // // // public void setPerc(double perc) { // this.perc = perc; // } // // public int getTotalrel() { // return totalrel; // } // // public void setTotalrel(int totalrel) { // this.totalrel = totalrel; // } // // public double getPercrel() { // return percrel; // } // // public void setPercrel(double percrel) { // this.percrel = percrel; // } // // // } // // Path: src/objs/stats/PosNegCatStats.java // public class PosNegCatStats // { // private String cat; // private CodeDistr pos; // private CodeDistr neg; // // // public PosNegCatStats() // { // cat = new String(); // pos = new CodeDistr(); // neg = new CodeDistr(); // } // // // public PosNegCatStats(String cat, CodeDistr pos, CodeDistr neg) { // super(); // this.cat = cat; // this.pos = pos; // this.neg = neg; // } // // // public String getCat() { // return cat; // } // // // public void setCat(String cat) { // this.cat = cat; // } // // // public CodeDistr getPos() { // return pos; // } // // // public void setPos(CodeDistr pos) { // this.pos = pos; // } // // // public CodeDistr getNeg() { // return neg; // } // // // public void setNeg(CodeDistr neg) { // this.neg = neg; // } // // // // // } // // Path: src/objs/stats/RateStats.java // public class RateStats // { // private int stars; // private ArrayList<CodeDistr> dist; // // public RateStats() // { // stars = 0; // dist = new ArrayList<CodeDistr>(); // } // // // public int getStars() { // return stars; // } // public void setStars(int stars) { // this.stars = stars; // } // public ArrayList<CodeDistr> getDist() { // return dist; // } // public void setDist(ArrayList<CodeDistr> dist) { // this.dist = dist; // } // // // // } // Path: src/objs/stats/reports/ReportRateStats.java import java.io.BufferedWriter; import java.io.FileWriter; import java.util.ArrayList; import objs.CodeDistr; import objs.stats.PosNegCatStats; import objs.stats.RateStats; /* # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. */ package objs.stats.reports; public class ReportRateStats { public static ArrayList<RateStats> report; public ReportRateStats() { report = new ArrayList<RateStats>(); } public ArrayList<RateStats> getReport() { return report; } public void setReport(ArrayList<RateStats> report) { this.report = report; } public static void print() { try { FileWriter fstream = new FileWriter("reports/rate_range_stats/reportratestats.txt"); BufferedWriter out = new BufferedWriter(fstream); for (int i = 0; i < report.size(); i++) { out.write("Class code:" + report.get(i).getStars()); out.newLine();
ArrayList<CodeDistr> codes = report.get(i).getDist();
iacobcl/MARA
src/objs/stats/reports/ReportNoRatesDistrStats.java
// Path: src/objs/CodeDistr.java // public class CodeDistr // { // // private String code; // private int total; // private double perc; // private int totalrel; // private double percrel; // // public CodeDistr() // { // code = new String(); // total = 0; // perc = 0; // totalrel = 0; // percrel = 0; // } // // public CodeDistr(String c, int t, double p, int totalr, double perrel) // { // code = c; // total = t; // perc = p; // totalrel = totalr; // percrel = perrel; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public int getTotal() { // return total; // } // // // public void setTotal(int total) { // this.total = total; // } // // // public double getPerc() { // return perc; // } // // // public void setPerc(double perc) { // this.perc = perc; // } // // public int getTotalrel() { // return totalrel; // } // // public void setTotalrel(int totalrel) { // this.totalrel = totalrel; // } // // public double getPercrel() { // return percrel; // } // // public void setPercrel(double percrel) { // this.percrel = percrel; // } // // // } // // Path: src/objs/stats/NoRatesDistrStats.java // public class NoRatesDistrStats // { // private int min; // private int max; // private ArrayList<CodeDistr> dist; // // public NoRatesDistrStats() // { // min = 0; // max = 0; // dist = new ArrayList<CodeDistr>(); // } // // public int getMin() { // return min; // } // // public void setMin(int min) { // this.min = min; // } // // public int getMax() { // return max; // } // // public void setMax(int max) { // this.max = max; // } // // public ArrayList<CodeDistr> getDist() { // return dist; // } // // public void setDist(ArrayList<CodeDistr> dist) { // this.dist = dist; // } // // // // // } // // Path: src/objs/stats/PriceWorthStats.java // public class PriceWorthStats // { // private double min; // private double max; // private CodeDistr worth; // private CodeDistr nworth; // // public PriceWorthStats() // { // min = 0; // max = 0; // worth = new CodeDistr(); // nworth = new CodeDistr(); // } // // // // public PriceWorthStats(double min, double max, CodeDistr worth, // CodeDistr nworth) { // super(); // this.min = min; // this.max = max; // this.worth = worth; // this.nworth = nworth; // } // // // // public double getMin() { // return min; // } // public void setMin(double min) { // this.min = min; // } // public double getMax() { // return max; // } // public void setMax(double max) { // this.max = max; // } // public CodeDistr getWorth() { // return worth; // } // public void setWorth(CodeDistr worth) { // this.worth = worth; // } // public CodeDistr getNworth() { // return nworth; // } // public void setNworth(CodeDistr nworth) { // this.nworth = nworth; // } // // // // // }
import java.io.BufferedWriter; import java.io.FileWriter; import java.util.ArrayList; import objs.CodeDistr; import objs.stats.NoRatesDistrStats; import objs.stats.PriceWorthStats;
/* # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. */ package objs.stats.reports; public class ReportNoRatesDistrStats {
// Path: src/objs/CodeDistr.java // public class CodeDistr // { // // private String code; // private int total; // private double perc; // private int totalrel; // private double percrel; // // public CodeDistr() // { // code = new String(); // total = 0; // perc = 0; // totalrel = 0; // percrel = 0; // } // // public CodeDistr(String c, int t, double p, int totalr, double perrel) // { // code = c; // total = t; // perc = p; // totalrel = totalr; // percrel = perrel; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public int getTotal() { // return total; // } // // // public void setTotal(int total) { // this.total = total; // } // // // public double getPerc() { // return perc; // } // // // public void setPerc(double perc) { // this.perc = perc; // } // // public int getTotalrel() { // return totalrel; // } // // public void setTotalrel(int totalrel) { // this.totalrel = totalrel; // } // // public double getPercrel() { // return percrel; // } // // public void setPercrel(double percrel) { // this.percrel = percrel; // } // // // } // // Path: src/objs/stats/NoRatesDistrStats.java // public class NoRatesDistrStats // { // private int min; // private int max; // private ArrayList<CodeDistr> dist; // // public NoRatesDistrStats() // { // min = 0; // max = 0; // dist = new ArrayList<CodeDistr>(); // } // // public int getMin() { // return min; // } // // public void setMin(int min) { // this.min = min; // } // // public int getMax() { // return max; // } // // public void setMax(int max) { // this.max = max; // } // // public ArrayList<CodeDistr> getDist() { // return dist; // } // // public void setDist(ArrayList<CodeDistr> dist) { // this.dist = dist; // } // // // // // } // // Path: src/objs/stats/PriceWorthStats.java // public class PriceWorthStats // { // private double min; // private double max; // private CodeDistr worth; // private CodeDistr nworth; // // public PriceWorthStats() // { // min = 0; // max = 0; // worth = new CodeDistr(); // nworth = new CodeDistr(); // } // // // // public PriceWorthStats(double min, double max, CodeDistr worth, // CodeDistr nworth) { // super(); // this.min = min; // this.max = max; // this.worth = worth; // this.nworth = nworth; // } // // // // public double getMin() { // return min; // } // public void setMin(double min) { // this.min = min; // } // public double getMax() { // return max; // } // public void setMax(double max) { // this.max = max; // } // public CodeDistr getWorth() { // return worth; // } // public void setWorth(CodeDistr worth) { // this.worth = worth; // } // public CodeDistr getNworth() { // return nworth; // } // public void setNworth(CodeDistr nworth) { // this.nworth = nworth; // } // // // // // } // Path: src/objs/stats/reports/ReportNoRatesDistrStats.java import java.io.BufferedWriter; import java.io.FileWriter; import java.util.ArrayList; import objs.CodeDistr; import objs.stats.NoRatesDistrStats; import objs.stats.PriceWorthStats; /* # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. */ package objs.stats.reports; public class ReportNoRatesDistrStats {
public ArrayList<NoRatesDistrStats> report;
iacobcl/MARA
src/objs/stats/NoRatesDistrStats.java
// Path: src/objs/CodeDistr.java // public class CodeDistr // { // // private String code; // private int total; // private double perc; // private int totalrel; // private double percrel; // // public CodeDistr() // { // code = new String(); // total = 0; // perc = 0; // totalrel = 0; // percrel = 0; // } // // public CodeDistr(String c, int t, double p, int totalr, double perrel) // { // code = c; // total = t; // perc = p; // totalrel = totalr; // percrel = perrel; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public int getTotal() { // return total; // } // // // public void setTotal(int total) { // this.total = total; // } // // // public double getPerc() { // return perc; // } // // // public void setPerc(double perc) { // this.perc = perc; // } // // public int getTotalrel() { // return totalrel; // } // // public void setTotalrel(int totalrel) { // this.totalrel = totalrel; // } // // public double getPercrel() { // return percrel; // } // // public void setPercrel(double percrel) { // this.percrel = percrel; // } // // // }
import java.util.ArrayList; import objs.CodeDistr;
/* # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. */ package objs.stats; public class NoRatesDistrStats { private int min; private int max;
// Path: src/objs/CodeDistr.java // public class CodeDistr // { // // private String code; // private int total; // private double perc; // private int totalrel; // private double percrel; // // public CodeDistr() // { // code = new String(); // total = 0; // perc = 0; // totalrel = 0; // percrel = 0; // } // // public CodeDistr(String c, int t, double p, int totalr, double perrel) // { // code = c; // total = t; // perc = p; // totalrel = totalr; // percrel = perrel; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public int getTotal() { // return total; // } // // // public void setTotal(int total) { // this.total = total; // } // // // public double getPerc() { // return perc; // } // // // public void setPerc(double perc) { // this.perc = perc; // } // // public int getTotalrel() { // return totalrel; // } // // public void setTotalrel(int totalrel) { // this.totalrel = totalrel; // } // // public double getPercrel() { // return percrel; // } // // public void setPercrel(double percrel) { // this.percrel = percrel; // } // // // } // Path: src/objs/stats/NoRatesDistrStats.java import java.util.ArrayList; import objs.CodeDistr; /* # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. */ package objs.stats; public class NoRatesDistrStats { private int min; private int max;
private ArrayList<CodeDistr> dist;
iacobcl/MARA
src/objs/stats/PriceWorthStats.java
// Path: src/objs/CodeDistr.java // public class CodeDistr // { // // private String code; // private int total; // private double perc; // private int totalrel; // private double percrel; // // public CodeDistr() // { // code = new String(); // total = 0; // perc = 0; // totalrel = 0; // percrel = 0; // } // // public CodeDistr(String c, int t, double p, int totalr, double perrel) // { // code = c; // total = t; // perc = p; // totalrel = totalr; // percrel = perrel; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public int getTotal() { // return total; // } // // // public void setTotal(int total) { // this.total = total; // } // // // public double getPerc() { // return perc; // } // // // public void setPerc(double perc) { // this.perc = perc; // } // // public int getTotalrel() { // return totalrel; // } // // public void setTotalrel(int totalrel) { // this.totalrel = totalrel; // } // // public double getPercrel() { // return percrel; // } // // public void setPercrel(double percrel) { // this.percrel = percrel; // } // // // }
import objs.CodeDistr;
/* # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. */ package objs.stats; public class PriceWorthStats { private double min; private double max;
// Path: src/objs/CodeDistr.java // public class CodeDistr // { // // private String code; // private int total; // private double perc; // private int totalrel; // private double percrel; // // public CodeDistr() // { // code = new String(); // total = 0; // perc = 0; // totalrel = 0; // percrel = 0; // } // // public CodeDistr(String c, int t, double p, int totalr, double perrel) // { // code = c; // total = t; // perc = p; // totalrel = totalr; // percrel = perrel; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public int getTotal() { // return total; // } // // // public void setTotal(int total) { // this.total = total; // } // // // public double getPerc() { // return perc; // } // // // public void setPerc(double perc) { // this.perc = perc; // } // // public int getTotalrel() { // return totalrel; // } // // public void setTotalrel(int totalrel) { // this.totalrel = totalrel; // } // // public double getPercrel() { // return percrel; // } // // public void setPercrel(double percrel) { // this.percrel = percrel; // } // // // } // Path: src/objs/stats/PriceWorthStats.java import objs.CodeDistr; /* # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. */ package objs.stats; public class PriceWorthStats { private double min; private double max;
private CodeDistr worth;
iacobcl/MARA
src/objs/stats/reports/ReportUpdateStats.java
// Path: src/objs/stats/DeviceStats.java // public class DeviceStats // { // private String device; // private ArrayList<CodeDistr> dist; // // public String getDevice() // { // return device; // } // // public void setDevice(String device) // { // this.device = device; // } // // public ArrayList<CodeDistr> getDist() // { // return dist; // } // // public void setDist(ArrayList<CodeDistr> dist) // { // this.dist = dist; // } // // public DeviceStats(String device, ArrayList<CodeDistr> dist) // { // this.device = device; // this.dist = dist; // } // // public DeviceStats() // { // device = new String(); // dist = new ArrayList<CodeDistr>(); // } // // // // // } // // Path: src/objs/stats/UpdateStats.java // public class UpdateStats // { // // private float min; // private float max; // private ArrayList<CodeDistr> dist; // // public UpdateStats() // { // min = 0; // max = 0; // dist = new ArrayList<CodeDistr>(); // } // // public float getMin() { // return min; // } // public void setMin(float min) { // this.min = min; // } // public float getMax() { // return max; // } // public void setMax(float max) { // this.max = max; // } // public ArrayList<CodeDistr> getDist() { // return dist; // } // public void setDist(ArrayList<CodeDistr> dist) { // this.dist = dist; // } // // // }
import objs.stats.UpdateStats; import java.util.ArrayList; import objs.stats.DeviceStats;
/* # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. */ package objs.stats.reports; public class ReportUpdateStats {
// Path: src/objs/stats/DeviceStats.java // public class DeviceStats // { // private String device; // private ArrayList<CodeDistr> dist; // // public String getDevice() // { // return device; // } // // public void setDevice(String device) // { // this.device = device; // } // // public ArrayList<CodeDistr> getDist() // { // return dist; // } // // public void setDist(ArrayList<CodeDistr> dist) // { // this.dist = dist; // } // // public DeviceStats(String device, ArrayList<CodeDistr> dist) // { // this.device = device; // this.dist = dist; // } // // public DeviceStats() // { // device = new String(); // dist = new ArrayList<CodeDistr>(); // } // // // // // } // // Path: src/objs/stats/UpdateStats.java // public class UpdateStats // { // // private float min; // private float max; // private ArrayList<CodeDistr> dist; // // public UpdateStats() // { // min = 0; // max = 0; // dist = new ArrayList<CodeDistr>(); // } // // public float getMin() { // return min; // } // public void setMin(float min) { // this.min = min; // } // public float getMax() { // return max; // } // public void setMax(float max) { // this.max = max; // } // public ArrayList<CodeDistr> getDist() { // return dist; // } // public void setDist(ArrayList<CodeDistr> dist) { // this.dist = dist; // } // // // } // Path: src/objs/stats/reports/ReportUpdateStats.java import objs.stats.UpdateStats; import java.util.ArrayList; import objs.stats.DeviceStats; /* # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. */ package objs.stats.reports; public class ReportUpdateStats {
public ArrayList<UpdateStats> report;
iacobcl/MARA
src/objs/stats/reports/ReportPriceRangeWorthStats.java
// Path: src/objs/stats/PriceWorthStats.java // public class PriceWorthStats // { // private double min; // private double max; // private CodeDistr worth; // private CodeDistr nworth; // // public PriceWorthStats() // { // min = 0; // max = 0; // worth = new CodeDistr(); // nworth = new CodeDistr(); // } // // // // public PriceWorthStats(double min, double max, CodeDistr worth, // CodeDistr nworth) { // super(); // this.min = min; // this.max = max; // this.worth = worth; // this.nworth = nworth; // } // // // // public double getMin() { // return min; // } // public void setMin(double min) { // this.min = min; // } // public double getMax() { // return max; // } // public void setMax(double max) { // this.max = max; // } // public CodeDistr getWorth() { // return worth; // } // public void setWorth(CodeDistr worth) { // this.worth = worth; // } // public CodeDistr getNworth() { // return nworth; // } // public void setNworth(CodeDistr nworth) { // this.nworth = nworth; // } // // // // // }
import objs.stats.PriceWorthStats; import java.io.BufferedWriter; import java.io.FileWriter; import java.util.ArrayList;
/* # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. */ package objs.stats.reports; public class ReportPriceRangeWorthStats {
// Path: src/objs/stats/PriceWorthStats.java // public class PriceWorthStats // { // private double min; // private double max; // private CodeDistr worth; // private CodeDistr nworth; // // public PriceWorthStats() // { // min = 0; // max = 0; // worth = new CodeDistr(); // nworth = new CodeDistr(); // } // // // // public PriceWorthStats(double min, double max, CodeDistr worth, // CodeDistr nworth) { // super(); // this.min = min; // this.max = max; // this.worth = worth; // this.nworth = nworth; // } // // // // public double getMin() { // return min; // } // public void setMin(double min) { // this.min = min; // } // public double getMax() { // return max; // } // public void setMax(double max) { // this.max = max; // } // public CodeDistr getWorth() { // return worth; // } // public void setWorth(CodeDistr worth) { // this.worth = worth; // } // public CodeDistr getNworth() { // return nworth; // } // public void setNworth(CodeDistr nworth) { // this.nworth = nworth; // } // // // // // } // Path: src/objs/stats/reports/ReportPriceRangeWorthStats.java import objs.stats.PriceWorthStats; import java.io.BufferedWriter; import java.io.FileWriter; import java.util.ArrayList; /* # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. */ package objs.stats.reports; public class ReportPriceRangeWorthStats {
public ArrayList<PriceWorthStats> report;
iacobcl/MARA
src/objs/stats/reports/ReportPosNegCatStats.java
// Path: src/objs/CodeDistr.java // public class CodeDistr // { // // private String code; // private int total; // private double perc; // private int totalrel; // private double percrel; // // public CodeDistr() // { // code = new String(); // total = 0; // perc = 0; // totalrel = 0; // percrel = 0; // } // // public CodeDistr(String c, int t, double p, int totalr, double perrel) // { // code = c; // total = t; // perc = p; // totalrel = totalr; // percrel = perrel; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public int getTotal() { // return total; // } // // // public void setTotal(int total) { // this.total = total; // } // // // public double getPerc() { // return perc; // } // // // public void setPerc(double perc) { // this.perc = perc; // } // // public int getTotalrel() { // return totalrel; // } // // public void setTotalrel(int totalrel) { // this.totalrel = totalrel; // } // // public double getPercrel() { // return percrel; // } // // public void setPercrel(double percrel) { // this.percrel = percrel; // } // // // } // // Path: src/objs/stats/DeviceStats.java // public class DeviceStats // { // private String device; // private ArrayList<CodeDistr> dist; // // public String getDevice() // { // return device; // } // // public void setDevice(String device) // { // this.device = device; // } // // public ArrayList<CodeDistr> getDist() // { // return dist; // } // // public void setDist(ArrayList<CodeDistr> dist) // { // this.dist = dist; // } // // public DeviceStats(String device, ArrayList<CodeDistr> dist) // { // this.device = device; // this.dist = dist; // } // // public DeviceStats() // { // device = new String(); // dist = new ArrayList<CodeDistr>(); // } // // // // // } // // Path: src/objs/stats/PosNegCatStats.java // public class PosNegCatStats // { // private String cat; // private CodeDistr pos; // private CodeDistr neg; // // // public PosNegCatStats() // { // cat = new String(); // pos = new CodeDistr(); // neg = new CodeDistr(); // } // // // public PosNegCatStats(String cat, CodeDistr pos, CodeDistr neg) { // super(); // this.cat = cat; // this.pos = pos; // this.neg = neg; // } // // // public String getCat() { // return cat; // } // // // public void setCat(String cat) { // this.cat = cat; // } // // // public CodeDistr getPos() { // return pos; // } // // // public void setPos(CodeDistr pos) { // this.pos = pos; // } // // // public CodeDistr getNeg() { // return neg; // } // // // public void setNeg(CodeDistr neg) { // this.neg = neg; // } // // // // // }
import java.io.BufferedWriter; import java.io.FileWriter; import java.util.ArrayList; import objs.CodeDistr; import objs.stats.DeviceStats; import objs.stats.PosNegCatStats;
/* # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. */ package objs.stats.reports; public class ReportPosNegCatStats {
// Path: src/objs/CodeDistr.java // public class CodeDistr // { // // private String code; // private int total; // private double perc; // private int totalrel; // private double percrel; // // public CodeDistr() // { // code = new String(); // total = 0; // perc = 0; // totalrel = 0; // percrel = 0; // } // // public CodeDistr(String c, int t, double p, int totalr, double perrel) // { // code = c; // total = t; // perc = p; // totalrel = totalr; // percrel = perrel; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public int getTotal() { // return total; // } // // // public void setTotal(int total) { // this.total = total; // } // // // public double getPerc() { // return perc; // } // // // public void setPerc(double perc) { // this.perc = perc; // } // // public int getTotalrel() { // return totalrel; // } // // public void setTotalrel(int totalrel) { // this.totalrel = totalrel; // } // // public double getPercrel() { // return percrel; // } // // public void setPercrel(double percrel) { // this.percrel = percrel; // } // // // } // // Path: src/objs/stats/DeviceStats.java // public class DeviceStats // { // private String device; // private ArrayList<CodeDistr> dist; // // public String getDevice() // { // return device; // } // // public void setDevice(String device) // { // this.device = device; // } // // public ArrayList<CodeDistr> getDist() // { // return dist; // } // // public void setDist(ArrayList<CodeDistr> dist) // { // this.dist = dist; // } // // public DeviceStats(String device, ArrayList<CodeDistr> dist) // { // this.device = device; // this.dist = dist; // } // // public DeviceStats() // { // device = new String(); // dist = new ArrayList<CodeDistr>(); // } // // // // // } // // Path: src/objs/stats/PosNegCatStats.java // public class PosNegCatStats // { // private String cat; // private CodeDistr pos; // private CodeDistr neg; // // // public PosNegCatStats() // { // cat = new String(); // pos = new CodeDistr(); // neg = new CodeDistr(); // } // // // public PosNegCatStats(String cat, CodeDistr pos, CodeDistr neg) { // super(); // this.cat = cat; // this.pos = pos; // this.neg = neg; // } // // // public String getCat() { // return cat; // } // // // public void setCat(String cat) { // this.cat = cat; // } // // // public CodeDistr getPos() { // return pos; // } // // // public void setPos(CodeDistr pos) { // this.pos = pos; // } // // // public CodeDistr getNeg() { // return neg; // } // // // public void setNeg(CodeDistr neg) { // this.neg = neg; // } // // // // // } // Path: src/objs/stats/reports/ReportPosNegCatStats.java import java.io.BufferedWriter; import java.io.FileWriter; import java.util.ArrayList; import objs.CodeDistr; import objs.stats.DeviceStats; import objs.stats.PosNegCatStats; /* # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. */ package objs.stats.reports; public class ReportPosNegCatStats {
public ArrayList<PosNegCatStats> report = new ArrayList<PosNegCatStats>();
iacobcl/MARA
src/objs/stats/PriceStats.java
// Path: src/objs/CodeDistr.java // public class CodeDistr // { // // private String code; // private int total; // private double perc; // private int totalrel; // private double percrel; // // public CodeDistr() // { // code = new String(); // total = 0; // perc = 0; // totalrel = 0; // percrel = 0; // } // // public CodeDistr(String c, int t, double p, int totalr, double perrel) // { // code = c; // total = t; // perc = p; // totalrel = totalr; // percrel = perrel; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public int getTotal() { // return total; // } // // // public void setTotal(int total) { // this.total = total; // } // // // public double getPerc() { // return perc; // } // // // public void setPerc(double perc) { // this.perc = perc; // } // // public int getTotalrel() { // return totalrel; // } // // public void setTotalrel(int totalrel) { // this.totalrel = totalrel; // } // // public double getPercrel() { // return percrel; // } // // public void setPercrel(double percrel) { // this.percrel = percrel; // } // // // }
import java.util.ArrayList; import objs.CodeDistr;
/* # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. */ package objs.stats; public class PriceStats { private double min; private double max;
// Path: src/objs/CodeDistr.java // public class CodeDistr // { // // private String code; // private int total; // private double perc; // private int totalrel; // private double percrel; // // public CodeDistr() // { // code = new String(); // total = 0; // perc = 0; // totalrel = 0; // percrel = 0; // } // // public CodeDistr(String c, int t, double p, int totalr, double perrel) // { // code = c; // total = t; // perc = p; // totalrel = totalr; // percrel = perrel; // } // // // public String getCode() { // return code; // } // // // public void setCode(String code) { // this.code = code; // } // // // public int getTotal() { // return total; // } // // // public void setTotal(int total) { // this.total = total; // } // // // public double getPerc() { // return perc; // } // // // public void setPerc(double perc) { // this.perc = perc; // } // // public int getTotalrel() { // return totalrel; // } // // public void setTotalrel(int totalrel) { // this.totalrel = totalrel; // } // // public double getPercrel() { // return percrel; // } // // public void setPercrel(double percrel) { // this.percrel = percrel; // } // // // } // Path: src/objs/stats/PriceStats.java import java.util.ArrayList; import objs.CodeDistr; /* # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. */ package objs.stats; public class PriceStats { private double min; private double max;
private ArrayList<CodeDistr> dist;