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 |
|---|---|---|---|---|---|---|
Cantara/ConfigService | src/main/java/no/cantara/cs/admin/ApplicationConfigResource.java | // Path: src/main/java/no/cantara/cs/persistence/ApplicationConfigDao.java
// public interface ApplicationConfigDao {
//
// Application getApplication(String artifact);
//
// Application createApplication(Application newApplication);
//
// ApplicationConfig createApplicationConfig(String applicationId, ApplicationConfig newConfig);
//
// List<ApplicationConfig> findAllApplicationConfigsByArtifactId(String artifactId);
//
// ApplicationConfig findTheLatestApplicationConfigByArtifactId(String artifactId);
//
// List<ApplicationConfig> findAllApplicationConfigsByApplicationId(String applicationId);
//
// ApplicationConfig findTheLatestApplicationConfigByApplicationId(String applicationId);
//
// ApplicationConfig getApplicationConfig(String configId);
//
// ApplicationConfig deleteApplicationConfig(String configId);
//
// ApplicationConfig updateApplicationConfig(String configId, ApplicationConfig updatedConfig);
//
// String getArtifactId(ApplicationConfig config);
//
// List< ApplicationConfig> getAllConfigs();
//
// List<Application> getApplications();
//
// Application deleteApplication(String applicationId);
//
// boolean canDeleteApplicationConfig(String configId);
//
// boolean canDeleteApplication(String applicationId);
// }
| import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import no.cantara.cs.dto.Application;
import no.cantara.cs.dto.ApplicationConfig;
import no.cantara.cs.persistence.ApplicationConfigDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.util.List;
import java.util.Map; | package no.cantara.cs.admin;
/**
* CRUD, http endpoint for ApplicationConfig
*
* @author <a href="mailto:erik-dev@fjas.no">Erik Drolshammer</a>
*/
@Path(ApplicationResource.APPLICATION_PATH)
public class ApplicationConfigResource {
public static final String CONFIG_PATH_WITH_APPID = "/{applicationId}/config";
public static final String CONFIG_PATH = "/config";
private static final Logger log = LoggerFactory.getLogger(ApplicationConfigResource.class);
private static final ObjectMapper mapper = new ObjectMapper(); | // Path: src/main/java/no/cantara/cs/persistence/ApplicationConfigDao.java
// public interface ApplicationConfigDao {
//
// Application getApplication(String artifact);
//
// Application createApplication(Application newApplication);
//
// ApplicationConfig createApplicationConfig(String applicationId, ApplicationConfig newConfig);
//
// List<ApplicationConfig> findAllApplicationConfigsByArtifactId(String artifactId);
//
// ApplicationConfig findTheLatestApplicationConfigByArtifactId(String artifactId);
//
// List<ApplicationConfig> findAllApplicationConfigsByApplicationId(String applicationId);
//
// ApplicationConfig findTheLatestApplicationConfigByApplicationId(String applicationId);
//
// ApplicationConfig getApplicationConfig(String configId);
//
// ApplicationConfig deleteApplicationConfig(String configId);
//
// ApplicationConfig updateApplicationConfig(String configId, ApplicationConfig updatedConfig);
//
// String getArtifactId(ApplicationConfig config);
//
// List< ApplicationConfig> getAllConfigs();
//
// List<Application> getApplications();
//
// Application deleteApplication(String applicationId);
//
// boolean canDeleteApplicationConfig(String configId);
//
// boolean canDeleteApplication(String applicationId);
// }
// Path: src/main/java/no/cantara/cs/admin/ApplicationConfigResource.java
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import no.cantara.cs.dto.Application;
import no.cantara.cs.dto.ApplicationConfig;
import no.cantara.cs.persistence.ApplicationConfigDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.util.List;
import java.util.Map;
package no.cantara.cs.admin;
/**
* CRUD, http endpoint for ApplicationConfig
*
* @author <a href="mailto:erik-dev@fjas.no">Erik Drolshammer</a>
*/
@Path(ApplicationResource.APPLICATION_PATH)
public class ApplicationConfigResource {
public static final String CONFIG_PATH_WITH_APPID = "/{applicationId}/config";
public static final String CONFIG_PATH = "/config";
private static final Logger log = LoggerFactory.getLogger(ApplicationConfigResource.class);
private static final ObjectMapper mapper = new ObjectMapper(); | private final ApplicationConfigDao applicationConfigDao; |
Cantara/ConfigService | src/test/java/no/cantara/cs/admin/ClientAdminResourceStatusTest.java | // Path: src/test/java/no/cantara/cs/testsupport/ApplicationConfigBuilder.java
// public class ApplicationConfigBuilder {
//
// public static ApplicationConfig createConfigDto(String name, Application application) {
// MavenMetadata metadata = new MavenMetadata("net.whydah.identity", application.artifactId, "2.0.1.Final");
// String url = new NexusUrlBuilder("http://mvnrepo.cantara.no", "releases").build(metadata);
// DownloadItem downloadItem = new DownloadItem(url, null, null, metadata);
// EventExtractionConfig extractionConfig = new EventExtractionConfig("jau");
// EventExtractionTag tag = new EventExtractionTag("testtag", "\\bheihei\\b", "logs/blabla.logg");
// extractionConfig.addEventExtractionTag(tag);
//
// ApplicationConfig config = new ApplicationConfig(name);
// config.addDownloadItem(downloadItem);
// config.addEventExtractionConfig(extractionConfig);
// config.setStartServiceScript("java -DIAM_MODE=DEV -jar " + downloadItem.filename());
//
// LinkedHashMap<String, String> propertiesMap = new LinkedHashMap<>();
// propertiesMap.put("a", "1");
// propertiesMap.put("b", "2");
// config.addPropertiesStore(new NamedPropertiesStore(propertiesMap, "named_properties_store.properties"));
//
// return config;
// }
// }
//
// Path: src/test/java/no/cantara/cs/testsupport/BaseSystemTest.java
// @Test(groups = "system-test")
// public abstract class BaseSystemTest {
// private TestServer testServer;
// private ConfigServiceClient configServiceClient;
//
// @BeforeClass
// @Parameters({ "persistenceType" })
// public void startServer(@Optional("mapdb") String persistenceType) throws Exception {
// if (persistenceType.equals("postgres")) {
// testServer = new TestServerPostgres(getClass());
// } else {
// testServer = new TestServerMapDb(getClass());
// }
// testServer.cleanAllData();
// testServer.start();
// configServiceClient = testServer.getConfigServiceClient();
// }
//
// @AfterClass
// public void stop() {
// if (testServer != null) {
// testServer.stop();
// }
// configServiceClient.cleanApplicationState();
// }
//
// public TestServer getTestServer() {
// return testServer;
// }
//
// public ConfigServiceClient getConfigServiceClient() {
// return configServiceClient;
// }
//
// public ConfigServiceAdminClient getConfigServiceAdminClient() {
// return testServer.getAdminClient();
// }
// }
| import no.cantara.cs.client.ConfigServiceAdminClient;
import no.cantara.cs.dto.*;
import no.cantara.cs.testsupport.ApplicationConfigBuilder;
import no.cantara.cs.testsupport.BaseSystemTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.HashMap;
import static org.testng.Assert.*; | package no.cantara.cs.admin;
/**
* @author Asbjørn Willersrud
*/
public class ClientAdminResourceStatusTest extends BaseSystemTest {
private Application application;
private ClientConfig clientConfig;
@BeforeClass
public void setup() throws Exception {
ConfigServiceAdminClient configServiceAdminClient = getConfigServiceAdminClient();
application = configServiceAdminClient.registerApplication("ClientStatusTest-ArtifactId"); | // Path: src/test/java/no/cantara/cs/testsupport/ApplicationConfigBuilder.java
// public class ApplicationConfigBuilder {
//
// public static ApplicationConfig createConfigDto(String name, Application application) {
// MavenMetadata metadata = new MavenMetadata("net.whydah.identity", application.artifactId, "2.0.1.Final");
// String url = new NexusUrlBuilder("http://mvnrepo.cantara.no", "releases").build(metadata);
// DownloadItem downloadItem = new DownloadItem(url, null, null, metadata);
// EventExtractionConfig extractionConfig = new EventExtractionConfig("jau");
// EventExtractionTag tag = new EventExtractionTag("testtag", "\\bheihei\\b", "logs/blabla.logg");
// extractionConfig.addEventExtractionTag(tag);
//
// ApplicationConfig config = new ApplicationConfig(name);
// config.addDownloadItem(downloadItem);
// config.addEventExtractionConfig(extractionConfig);
// config.setStartServiceScript("java -DIAM_MODE=DEV -jar " + downloadItem.filename());
//
// LinkedHashMap<String, String> propertiesMap = new LinkedHashMap<>();
// propertiesMap.put("a", "1");
// propertiesMap.put("b", "2");
// config.addPropertiesStore(new NamedPropertiesStore(propertiesMap, "named_properties_store.properties"));
//
// return config;
// }
// }
//
// Path: src/test/java/no/cantara/cs/testsupport/BaseSystemTest.java
// @Test(groups = "system-test")
// public abstract class BaseSystemTest {
// private TestServer testServer;
// private ConfigServiceClient configServiceClient;
//
// @BeforeClass
// @Parameters({ "persistenceType" })
// public void startServer(@Optional("mapdb") String persistenceType) throws Exception {
// if (persistenceType.equals("postgres")) {
// testServer = new TestServerPostgres(getClass());
// } else {
// testServer = new TestServerMapDb(getClass());
// }
// testServer.cleanAllData();
// testServer.start();
// configServiceClient = testServer.getConfigServiceClient();
// }
//
// @AfterClass
// public void stop() {
// if (testServer != null) {
// testServer.stop();
// }
// configServiceClient.cleanApplicationState();
// }
//
// public TestServer getTestServer() {
// return testServer;
// }
//
// public ConfigServiceClient getConfigServiceClient() {
// return configServiceClient;
// }
//
// public ConfigServiceAdminClient getConfigServiceAdminClient() {
// return testServer.getAdminClient();
// }
// }
// Path: src/test/java/no/cantara/cs/admin/ClientAdminResourceStatusTest.java
import no.cantara.cs.client.ConfigServiceAdminClient;
import no.cantara.cs.dto.*;
import no.cantara.cs.testsupport.ApplicationConfigBuilder;
import no.cantara.cs.testsupport.BaseSystemTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.HashMap;
import static org.testng.Assert.*;
package no.cantara.cs.admin;
/**
* @author Asbjørn Willersrud
*/
public class ClientAdminResourceStatusTest extends BaseSystemTest {
private Application application;
private ClientConfig clientConfig;
@BeforeClass
public void setup() throws Exception {
ConfigServiceAdminClient configServiceAdminClient = getConfigServiceAdminClient();
application = configServiceAdminClient.registerApplication("ClientStatusTest-ArtifactId"); | configServiceAdminClient.createApplicationConfig(application, ApplicationConfigBuilder.createConfigDto("arbitrary-config", application)); |
Cantara/ConfigService | src/main/java/no/cantara/cs/cloudwatch/CloudWatchLogger.java | // Path: src/main/java/no/cantara/cs/config/ConstrettoConfig.java
// public class ConstrettoConfig {
// private static final ConstrettoConfiguration configuration = new ConstrettoBuilder()
// .createPropertiesStore()
// .addResource(Resource.create("classpath:application.properties"))
// .addResource(Resource.create("file:./config_override/application_override.properties"))
// .done()
// .getConfiguration();
//
// private ConstrettoConfig() {}
//
// public static String getString(String key) {
// return configuration.evaluateToString(key);
// }
//
// public static Integer getInt(String key) {
// return configuration.evaluateToInt(key);
// }
//
// public static Integer getInt(String key, int defaultValue) {
// return configuration.evaluateTo(key, defaultValue);
// }
//
// public static boolean getBoolean(String key) {
// return configuration.evaluateToBoolean(key);
// }
// }
| import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.logs.AWSLogsAsyncClient;
import com.amazonaws.services.logs.model.*;
import no.cantara.cs.config.ConstrettoConfig;
import no.cantara.cs.dto.event.EventFile;
import no.cantara.cs.dto.event.EventGroup;
import no.cantara.cs.dto.event.EventTag;
import no.cantara.cs.dto.event.ExtractedEventsStore;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue; | package no.cantara.cs.cloudwatch;
/**
* Forwards log events from ConfigService clients to Amazon CloudWatch.
* <p>
* Assumes that the CloudWatch log groups exist, but dynamically creates log streams within the groups (one log stream
* per client ID / tag combination).
* <p>
* Uses the following configuration properties:
* <ul>
* <li>cloudwatch.logging.enabled - Whether CloudWatch logging is enabled.</li>
* <li>cloudwatch.region - The AWS region to use, e.g., "eu-west-1".</li>
* <li>cloudwatch.logging.maxBatchSize - The max number of log events to bundle per AWS call. Default value: {@link #DEFAULT_MAX_BATCH_SIZE}. Must not exceed 10,000.</li>
* <li>cloudwatch.logging.internalQueueSize - The max number of log requests to buffer internally. Default value: {@link #DEFAULT_INTERNAL_QUEUE_SIZE}.</li>
* </ul>
*
* @author Sindre Mehus
*/
@Service
public class CloudWatchLogger {
private static final Logger log = LoggerFactory.getLogger(CloudWatchLogger.class);
private static final int DEFAULT_MAX_BATCH_SIZE = 512;
private static final int DEFAULT_INTERNAL_QUEUE_SIZE = 1024;
private int maxBatchSize;
private LinkedBlockingQueue<LogRequest> logRequestQueue;
private AWSLogsAsyncClient awsClient;
public CloudWatchLogger() { | // Path: src/main/java/no/cantara/cs/config/ConstrettoConfig.java
// public class ConstrettoConfig {
// private static final ConstrettoConfiguration configuration = new ConstrettoBuilder()
// .createPropertiesStore()
// .addResource(Resource.create("classpath:application.properties"))
// .addResource(Resource.create("file:./config_override/application_override.properties"))
// .done()
// .getConfiguration();
//
// private ConstrettoConfig() {}
//
// public static String getString(String key) {
// return configuration.evaluateToString(key);
// }
//
// public static Integer getInt(String key) {
// return configuration.evaluateToInt(key);
// }
//
// public static Integer getInt(String key, int defaultValue) {
// return configuration.evaluateTo(key, defaultValue);
// }
//
// public static boolean getBoolean(String key) {
// return configuration.evaluateToBoolean(key);
// }
// }
// Path: src/main/java/no/cantara/cs/cloudwatch/CloudWatchLogger.java
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.logs.AWSLogsAsyncClient;
import com.amazonaws.services.logs.model.*;
import no.cantara.cs.config.ConstrettoConfig;
import no.cantara.cs.dto.event.EventFile;
import no.cantara.cs.dto.event.EventGroup;
import no.cantara.cs.dto.event.EventTag;
import no.cantara.cs.dto.event.ExtractedEventsStore;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
package no.cantara.cs.cloudwatch;
/**
* Forwards log events from ConfigService clients to Amazon CloudWatch.
* <p>
* Assumes that the CloudWatch log groups exist, but dynamically creates log streams within the groups (one log stream
* per client ID / tag combination).
* <p>
* Uses the following configuration properties:
* <ul>
* <li>cloudwatch.logging.enabled - Whether CloudWatch logging is enabled.</li>
* <li>cloudwatch.region - The AWS region to use, e.g., "eu-west-1".</li>
* <li>cloudwatch.logging.maxBatchSize - The max number of log events to bundle per AWS call. Default value: {@link #DEFAULT_MAX_BATCH_SIZE}. Must not exceed 10,000.</li>
* <li>cloudwatch.logging.internalQueueSize - The max number of log requests to buffer internally. Default value: {@link #DEFAULT_INTERNAL_QUEUE_SIZE}.</li>
* </ul>
*
* @author Sindre Mehus
*/
@Service
public class CloudWatchLogger {
private static final Logger log = LoggerFactory.getLogger(CloudWatchLogger.class);
private static final int DEFAULT_MAX_BATCH_SIZE = 512;
private static final int DEFAULT_INTERNAL_QUEUE_SIZE = 1024;
private int maxBatchSize;
private LinkedBlockingQueue<LogRequest> logRequestQueue;
private AWSLogsAsyncClient awsClient;
public CloudWatchLogger() { | if (ConstrettoConfig.getBoolean("cloudwatch.logging.enabled")) { |
Cantara/ConfigService | src/test/java/no/cantara/cs/client/RegisterClientTest.java | // Path: src/test/java/no/cantara/cs/testsupport/ApplicationConfigBuilder.java
// public class ApplicationConfigBuilder {
//
// public static ApplicationConfig createConfigDto(String name, Application application) {
// MavenMetadata metadata = new MavenMetadata("net.whydah.identity", application.artifactId, "2.0.1.Final");
// String url = new NexusUrlBuilder("http://mvnrepo.cantara.no", "releases").build(metadata);
// DownloadItem downloadItem = new DownloadItem(url, null, null, metadata);
// EventExtractionConfig extractionConfig = new EventExtractionConfig("jau");
// EventExtractionTag tag = new EventExtractionTag("testtag", "\\bheihei\\b", "logs/blabla.logg");
// extractionConfig.addEventExtractionTag(tag);
//
// ApplicationConfig config = new ApplicationConfig(name);
// config.addDownloadItem(downloadItem);
// config.addEventExtractionConfig(extractionConfig);
// config.setStartServiceScript("java -DIAM_MODE=DEV -jar " + downloadItem.filename());
//
// LinkedHashMap<String, String> propertiesMap = new LinkedHashMap<>();
// propertiesMap.put("a", "1");
// propertiesMap.put("b", "2");
// config.addPropertiesStore(new NamedPropertiesStore(propertiesMap, "named_properties_store.properties"));
//
// return config;
// }
// }
//
// Path: src/test/java/no/cantara/cs/testsupport/BaseSystemTest.java
// @Test(groups = "system-test")
// public abstract class BaseSystemTest {
// private TestServer testServer;
// private ConfigServiceClient configServiceClient;
//
// @BeforeClass
// @Parameters({ "persistenceType" })
// public void startServer(@Optional("mapdb") String persistenceType) throws Exception {
// if (persistenceType.equals("postgres")) {
// testServer = new TestServerPostgres(getClass());
// } else {
// testServer = new TestServerMapDb(getClass());
// }
// testServer.cleanAllData();
// testServer.start();
// configServiceClient = testServer.getConfigServiceClient();
// }
//
// @AfterClass
// public void stop() {
// if (testServer != null) {
// testServer.stop();
// }
// configServiceClient.cleanApplicationState();
// }
//
// public TestServer getTestServer() {
// return testServer;
// }
//
// public ConfigServiceClient getConfigServiceClient() {
// return configServiceClient;
// }
//
// public ConfigServiceAdminClient getConfigServiceAdminClient() {
// return testServer.getAdminClient();
// }
// }
//
// Path: src/test/java/no/cantara/cs/testsupport/TestServer.java
// public interface TestServer {
// String USERNAME = "read";
// String PASSWORD = "baretillesing";
// String ADMIN_USERNAME = "admin";
// String ADMIN_PASSWORD = "configservice";
//
// void cleanAllData() throws Exception;
//
// void start() throws InterruptedException;
//
// void stop();
//
// ConfigServiceClient getConfigServiceClient();
//
// ConfigServiceAdminClient getAdminClient();
// }
| import com.jayway.restassured.http.ContentType;
import no.cantara.cs.dto.Application;
import no.cantara.cs.dto.ApplicationConfig;
import no.cantara.cs.dto.ClientConfig;
import no.cantara.cs.dto.ClientRegistrationRequest;
import no.cantara.cs.testsupport.ApplicationConfigBuilder;
import no.cantara.cs.testsupport.BaseSystemTest;
import no.cantara.cs.testsupport.TestServer;
import org.apache.http.HttpStatus;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.net.HttpURLConnection;
import java.util.Properties;
import static com.jayway.restassured.RestAssured.given;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.fail; | package no.cantara.cs.client;
public class RegisterClientTest extends BaseSystemTest {
private ConfigServiceClient configServiceClient;
private Application application;
private ClientConfig clientConfig;
private ConfigServiceAdminClient configServiceAdminClient;
private ApplicationConfig defaultConfig;
@BeforeClass
public void startServer() throws Exception {
configServiceClient = getConfigServiceClient();
configServiceAdminClient = getConfigServiceAdminClient();
application = configServiceAdminClient.registerApplication("RegisterClientTest"); | // Path: src/test/java/no/cantara/cs/testsupport/ApplicationConfigBuilder.java
// public class ApplicationConfigBuilder {
//
// public static ApplicationConfig createConfigDto(String name, Application application) {
// MavenMetadata metadata = new MavenMetadata("net.whydah.identity", application.artifactId, "2.0.1.Final");
// String url = new NexusUrlBuilder("http://mvnrepo.cantara.no", "releases").build(metadata);
// DownloadItem downloadItem = new DownloadItem(url, null, null, metadata);
// EventExtractionConfig extractionConfig = new EventExtractionConfig("jau");
// EventExtractionTag tag = new EventExtractionTag("testtag", "\\bheihei\\b", "logs/blabla.logg");
// extractionConfig.addEventExtractionTag(tag);
//
// ApplicationConfig config = new ApplicationConfig(name);
// config.addDownloadItem(downloadItem);
// config.addEventExtractionConfig(extractionConfig);
// config.setStartServiceScript("java -DIAM_MODE=DEV -jar " + downloadItem.filename());
//
// LinkedHashMap<String, String> propertiesMap = new LinkedHashMap<>();
// propertiesMap.put("a", "1");
// propertiesMap.put("b", "2");
// config.addPropertiesStore(new NamedPropertiesStore(propertiesMap, "named_properties_store.properties"));
//
// return config;
// }
// }
//
// Path: src/test/java/no/cantara/cs/testsupport/BaseSystemTest.java
// @Test(groups = "system-test")
// public abstract class BaseSystemTest {
// private TestServer testServer;
// private ConfigServiceClient configServiceClient;
//
// @BeforeClass
// @Parameters({ "persistenceType" })
// public void startServer(@Optional("mapdb") String persistenceType) throws Exception {
// if (persistenceType.equals("postgres")) {
// testServer = new TestServerPostgres(getClass());
// } else {
// testServer = new TestServerMapDb(getClass());
// }
// testServer.cleanAllData();
// testServer.start();
// configServiceClient = testServer.getConfigServiceClient();
// }
//
// @AfterClass
// public void stop() {
// if (testServer != null) {
// testServer.stop();
// }
// configServiceClient.cleanApplicationState();
// }
//
// public TestServer getTestServer() {
// return testServer;
// }
//
// public ConfigServiceClient getConfigServiceClient() {
// return configServiceClient;
// }
//
// public ConfigServiceAdminClient getConfigServiceAdminClient() {
// return testServer.getAdminClient();
// }
// }
//
// Path: src/test/java/no/cantara/cs/testsupport/TestServer.java
// public interface TestServer {
// String USERNAME = "read";
// String PASSWORD = "baretillesing";
// String ADMIN_USERNAME = "admin";
// String ADMIN_PASSWORD = "configservice";
//
// void cleanAllData() throws Exception;
//
// void start() throws InterruptedException;
//
// void stop();
//
// ConfigServiceClient getConfigServiceClient();
//
// ConfigServiceAdminClient getAdminClient();
// }
// Path: src/test/java/no/cantara/cs/client/RegisterClientTest.java
import com.jayway.restassured.http.ContentType;
import no.cantara.cs.dto.Application;
import no.cantara.cs.dto.ApplicationConfig;
import no.cantara.cs.dto.ClientConfig;
import no.cantara.cs.dto.ClientRegistrationRequest;
import no.cantara.cs.testsupport.ApplicationConfigBuilder;
import no.cantara.cs.testsupport.BaseSystemTest;
import no.cantara.cs.testsupport.TestServer;
import org.apache.http.HttpStatus;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.net.HttpURLConnection;
import java.util.Properties;
import static com.jayway.restassured.RestAssured.given;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.fail;
package no.cantara.cs.client;
public class RegisterClientTest extends BaseSystemTest {
private ConfigServiceClient configServiceClient;
private Application application;
private ClientConfig clientConfig;
private ConfigServiceAdminClient configServiceAdminClient;
private ApplicationConfig defaultConfig;
@BeforeClass
public void startServer() throws Exception {
configServiceClient = getConfigServiceClient();
configServiceAdminClient = getConfigServiceAdminClient();
application = configServiceAdminClient.registerApplication("RegisterClientTest"); | defaultConfig = configServiceAdminClient.createApplicationConfig(application, ApplicationConfigBuilder.createConfigDto("default-config", application)); |
Cantara/ConfigService | src/test/java/no/cantara/cs/client/RegisterClientTest.java | // Path: src/test/java/no/cantara/cs/testsupport/ApplicationConfigBuilder.java
// public class ApplicationConfigBuilder {
//
// public static ApplicationConfig createConfigDto(String name, Application application) {
// MavenMetadata metadata = new MavenMetadata("net.whydah.identity", application.artifactId, "2.0.1.Final");
// String url = new NexusUrlBuilder("http://mvnrepo.cantara.no", "releases").build(metadata);
// DownloadItem downloadItem = new DownloadItem(url, null, null, metadata);
// EventExtractionConfig extractionConfig = new EventExtractionConfig("jau");
// EventExtractionTag tag = new EventExtractionTag("testtag", "\\bheihei\\b", "logs/blabla.logg");
// extractionConfig.addEventExtractionTag(tag);
//
// ApplicationConfig config = new ApplicationConfig(name);
// config.addDownloadItem(downloadItem);
// config.addEventExtractionConfig(extractionConfig);
// config.setStartServiceScript("java -DIAM_MODE=DEV -jar " + downloadItem.filename());
//
// LinkedHashMap<String, String> propertiesMap = new LinkedHashMap<>();
// propertiesMap.put("a", "1");
// propertiesMap.put("b", "2");
// config.addPropertiesStore(new NamedPropertiesStore(propertiesMap, "named_properties_store.properties"));
//
// return config;
// }
// }
//
// Path: src/test/java/no/cantara/cs/testsupport/BaseSystemTest.java
// @Test(groups = "system-test")
// public abstract class BaseSystemTest {
// private TestServer testServer;
// private ConfigServiceClient configServiceClient;
//
// @BeforeClass
// @Parameters({ "persistenceType" })
// public void startServer(@Optional("mapdb") String persistenceType) throws Exception {
// if (persistenceType.equals("postgres")) {
// testServer = new TestServerPostgres(getClass());
// } else {
// testServer = new TestServerMapDb(getClass());
// }
// testServer.cleanAllData();
// testServer.start();
// configServiceClient = testServer.getConfigServiceClient();
// }
//
// @AfterClass
// public void stop() {
// if (testServer != null) {
// testServer.stop();
// }
// configServiceClient.cleanApplicationState();
// }
//
// public TestServer getTestServer() {
// return testServer;
// }
//
// public ConfigServiceClient getConfigServiceClient() {
// return configServiceClient;
// }
//
// public ConfigServiceAdminClient getConfigServiceAdminClient() {
// return testServer.getAdminClient();
// }
// }
//
// Path: src/test/java/no/cantara/cs/testsupport/TestServer.java
// public interface TestServer {
// String USERNAME = "read";
// String PASSWORD = "baretillesing";
// String ADMIN_USERNAME = "admin";
// String ADMIN_PASSWORD = "configservice";
//
// void cleanAllData() throws Exception;
//
// void start() throws InterruptedException;
//
// void stop();
//
// ConfigServiceClient getConfigServiceClient();
//
// ConfigServiceAdminClient getAdminClient();
// }
| import com.jayway.restassured.http.ContentType;
import no.cantara.cs.dto.Application;
import no.cantara.cs.dto.ApplicationConfig;
import no.cantara.cs.dto.ClientConfig;
import no.cantara.cs.dto.ClientRegistrationRequest;
import no.cantara.cs.testsupport.ApplicationConfigBuilder;
import no.cantara.cs.testsupport.BaseSystemTest;
import no.cantara.cs.testsupport.TestServer;
import org.apache.http.HttpStatus;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.net.HttpURLConnection;
import java.util.Properties;
import static com.jayway.restassured.RestAssured.given;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.fail; | }
}
@Test
public void testRegisterClientWithoutConfigShouldReturnNotFound() throws Exception {
Application applicationWithoutConfig = configServiceAdminClient.registerApplication("NewArtifactId");
ClientRegistrationRequest request = new ClientRegistrationRequest(applicationWithoutConfig.artifactId);
try {
configServiceClient.registerClient(request);
fail("Expected registerClient to fail without config");
} catch (HttpException e) {
assertEquals(e.getStatusCode(), HttpURLConnection.HTTP_NOT_FOUND);
}
}
@Test(dependsOnMethods = "testRegisterClient")
public void testRegisterClientWithExistingClientId() throws Exception {
ClientRegistrationRequest request = new ClientRegistrationRequest(application.artifactId);
request.clientId = clientConfig.clientId;
ClientConfig newClientConfig = configServiceClient.registerClient(request);
assertNotNull(newClientConfig);
assertEquals(newClientConfig.config.getId(), clientConfig.config.getId());
assertEquals(newClientConfig.clientId, request.clientId);
}
@Test
public void testBrokenJsonShouldReturnBadRequest() throws Exception {
given() | // Path: src/test/java/no/cantara/cs/testsupport/ApplicationConfigBuilder.java
// public class ApplicationConfigBuilder {
//
// public static ApplicationConfig createConfigDto(String name, Application application) {
// MavenMetadata metadata = new MavenMetadata("net.whydah.identity", application.artifactId, "2.0.1.Final");
// String url = new NexusUrlBuilder("http://mvnrepo.cantara.no", "releases").build(metadata);
// DownloadItem downloadItem = new DownloadItem(url, null, null, metadata);
// EventExtractionConfig extractionConfig = new EventExtractionConfig("jau");
// EventExtractionTag tag = new EventExtractionTag("testtag", "\\bheihei\\b", "logs/blabla.logg");
// extractionConfig.addEventExtractionTag(tag);
//
// ApplicationConfig config = new ApplicationConfig(name);
// config.addDownloadItem(downloadItem);
// config.addEventExtractionConfig(extractionConfig);
// config.setStartServiceScript("java -DIAM_MODE=DEV -jar " + downloadItem.filename());
//
// LinkedHashMap<String, String> propertiesMap = new LinkedHashMap<>();
// propertiesMap.put("a", "1");
// propertiesMap.put("b", "2");
// config.addPropertiesStore(new NamedPropertiesStore(propertiesMap, "named_properties_store.properties"));
//
// return config;
// }
// }
//
// Path: src/test/java/no/cantara/cs/testsupport/BaseSystemTest.java
// @Test(groups = "system-test")
// public abstract class BaseSystemTest {
// private TestServer testServer;
// private ConfigServiceClient configServiceClient;
//
// @BeforeClass
// @Parameters({ "persistenceType" })
// public void startServer(@Optional("mapdb") String persistenceType) throws Exception {
// if (persistenceType.equals("postgres")) {
// testServer = new TestServerPostgres(getClass());
// } else {
// testServer = new TestServerMapDb(getClass());
// }
// testServer.cleanAllData();
// testServer.start();
// configServiceClient = testServer.getConfigServiceClient();
// }
//
// @AfterClass
// public void stop() {
// if (testServer != null) {
// testServer.stop();
// }
// configServiceClient.cleanApplicationState();
// }
//
// public TestServer getTestServer() {
// return testServer;
// }
//
// public ConfigServiceClient getConfigServiceClient() {
// return configServiceClient;
// }
//
// public ConfigServiceAdminClient getConfigServiceAdminClient() {
// return testServer.getAdminClient();
// }
// }
//
// Path: src/test/java/no/cantara/cs/testsupport/TestServer.java
// public interface TestServer {
// String USERNAME = "read";
// String PASSWORD = "baretillesing";
// String ADMIN_USERNAME = "admin";
// String ADMIN_PASSWORD = "configservice";
//
// void cleanAllData() throws Exception;
//
// void start() throws InterruptedException;
//
// void stop();
//
// ConfigServiceClient getConfigServiceClient();
//
// ConfigServiceAdminClient getAdminClient();
// }
// Path: src/test/java/no/cantara/cs/client/RegisterClientTest.java
import com.jayway.restassured.http.ContentType;
import no.cantara.cs.dto.Application;
import no.cantara.cs.dto.ApplicationConfig;
import no.cantara.cs.dto.ClientConfig;
import no.cantara.cs.dto.ClientRegistrationRequest;
import no.cantara.cs.testsupport.ApplicationConfigBuilder;
import no.cantara.cs.testsupport.BaseSystemTest;
import no.cantara.cs.testsupport.TestServer;
import org.apache.http.HttpStatus;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.net.HttpURLConnection;
import java.util.Properties;
import static com.jayway.restassured.RestAssured.given;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.fail;
}
}
@Test
public void testRegisterClientWithoutConfigShouldReturnNotFound() throws Exception {
Application applicationWithoutConfig = configServiceAdminClient.registerApplication("NewArtifactId");
ClientRegistrationRequest request = new ClientRegistrationRequest(applicationWithoutConfig.artifactId);
try {
configServiceClient.registerClient(request);
fail("Expected registerClient to fail without config");
} catch (HttpException e) {
assertEquals(e.getStatusCode(), HttpURLConnection.HTTP_NOT_FOUND);
}
}
@Test(dependsOnMethods = "testRegisterClient")
public void testRegisterClientWithExistingClientId() throws Exception {
ClientRegistrationRequest request = new ClientRegistrationRequest(application.artifactId);
request.clientId = clientConfig.clientId;
ClientConfig newClientConfig = configServiceClient.registerClient(request);
assertNotNull(newClientConfig);
assertEquals(newClientConfig.config.getId(), clientConfig.config.getId());
assertEquals(newClientConfig.clientId, request.clientId);
}
@Test
public void testBrokenJsonShouldReturnBadRequest() throws Exception {
given() | .auth().basic(TestServer.USERNAME, TestServer.PASSWORD) |
Cantara/ConfigService | src/test/java/no/cantara/cs/client/ChangeConfigForSpecificClientTest.java | // Path: src/test/java/no/cantara/cs/testsupport/ApplicationConfigBuilder.java
// public class ApplicationConfigBuilder {
//
// public static ApplicationConfig createConfigDto(String name, Application application) {
// MavenMetadata metadata = new MavenMetadata("net.whydah.identity", application.artifactId, "2.0.1.Final");
// String url = new NexusUrlBuilder("http://mvnrepo.cantara.no", "releases").build(metadata);
// DownloadItem downloadItem = new DownloadItem(url, null, null, metadata);
// EventExtractionConfig extractionConfig = new EventExtractionConfig("jau");
// EventExtractionTag tag = new EventExtractionTag("testtag", "\\bheihei\\b", "logs/blabla.logg");
// extractionConfig.addEventExtractionTag(tag);
//
// ApplicationConfig config = new ApplicationConfig(name);
// config.addDownloadItem(downloadItem);
// config.addEventExtractionConfig(extractionConfig);
// config.setStartServiceScript("java -DIAM_MODE=DEV -jar " + downloadItem.filename());
//
// LinkedHashMap<String, String> propertiesMap = new LinkedHashMap<>();
// propertiesMap.put("a", "1");
// propertiesMap.put("b", "2");
// config.addPropertiesStore(new NamedPropertiesStore(propertiesMap, "named_properties_store.properties"));
//
// return config;
// }
// }
//
// Path: src/test/java/no/cantara/cs/testsupport/BaseSystemTest.java
// @Test(groups = "system-test")
// public abstract class BaseSystemTest {
// private TestServer testServer;
// private ConfigServiceClient configServiceClient;
//
// @BeforeClass
// @Parameters({ "persistenceType" })
// public void startServer(@Optional("mapdb") String persistenceType) throws Exception {
// if (persistenceType.equals("postgres")) {
// testServer = new TestServerPostgres(getClass());
// } else {
// testServer = new TestServerMapDb(getClass());
// }
// testServer.cleanAllData();
// testServer.start();
// configServiceClient = testServer.getConfigServiceClient();
// }
//
// @AfterClass
// public void stop() {
// if (testServer != null) {
// testServer.stop();
// }
// configServiceClient.cleanApplicationState();
// }
//
// public TestServer getTestServer() {
// return testServer;
// }
//
// public ConfigServiceClient getConfigServiceClient() {
// return configServiceClient;
// }
//
// public ConfigServiceAdminClient getConfigServiceAdminClient() {
// return testServer.getAdminClient();
// }
// }
| import no.cantara.cs.dto.Application;
import no.cantara.cs.dto.ApplicationConfig;
import no.cantara.cs.dto.CheckForUpdateRequest;
import no.cantara.cs.dto.Client;
import no.cantara.cs.dto.ClientConfig;
import no.cantara.cs.dto.ClientRegistrationRequest;
import no.cantara.cs.testsupport.ApplicationConfigBuilder;
import no.cantara.cs.testsupport.BaseSystemTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.IOException;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotEquals;
import static org.testng.Assert.assertNotNull; | package no.cantara.cs.client;
public class ChangeConfigForSpecificClientTest extends BaseSystemTest {
private ConfigServiceClient configServiceClient;
private Application application;
private ConfigServiceAdminClient configServiceAdminClient;
private ClientConfig currentClientConfig;
@BeforeClass
public void setup() throws Exception {
configServiceClient = getConfigServiceClient();
configServiceAdminClient = getConfigServiceAdminClient();
application = configServiceAdminClient.registerApplication(getClass().getSimpleName()); | // Path: src/test/java/no/cantara/cs/testsupport/ApplicationConfigBuilder.java
// public class ApplicationConfigBuilder {
//
// public static ApplicationConfig createConfigDto(String name, Application application) {
// MavenMetadata metadata = new MavenMetadata("net.whydah.identity", application.artifactId, "2.0.1.Final");
// String url = new NexusUrlBuilder("http://mvnrepo.cantara.no", "releases").build(metadata);
// DownloadItem downloadItem = new DownloadItem(url, null, null, metadata);
// EventExtractionConfig extractionConfig = new EventExtractionConfig("jau");
// EventExtractionTag tag = new EventExtractionTag("testtag", "\\bheihei\\b", "logs/blabla.logg");
// extractionConfig.addEventExtractionTag(tag);
//
// ApplicationConfig config = new ApplicationConfig(name);
// config.addDownloadItem(downloadItem);
// config.addEventExtractionConfig(extractionConfig);
// config.setStartServiceScript("java -DIAM_MODE=DEV -jar " + downloadItem.filename());
//
// LinkedHashMap<String, String> propertiesMap = new LinkedHashMap<>();
// propertiesMap.put("a", "1");
// propertiesMap.put("b", "2");
// config.addPropertiesStore(new NamedPropertiesStore(propertiesMap, "named_properties_store.properties"));
//
// return config;
// }
// }
//
// Path: src/test/java/no/cantara/cs/testsupport/BaseSystemTest.java
// @Test(groups = "system-test")
// public abstract class BaseSystemTest {
// private TestServer testServer;
// private ConfigServiceClient configServiceClient;
//
// @BeforeClass
// @Parameters({ "persistenceType" })
// public void startServer(@Optional("mapdb") String persistenceType) throws Exception {
// if (persistenceType.equals("postgres")) {
// testServer = new TestServerPostgres(getClass());
// } else {
// testServer = new TestServerMapDb(getClass());
// }
// testServer.cleanAllData();
// testServer.start();
// configServiceClient = testServer.getConfigServiceClient();
// }
//
// @AfterClass
// public void stop() {
// if (testServer != null) {
// testServer.stop();
// }
// configServiceClient.cleanApplicationState();
// }
//
// public TestServer getTestServer() {
// return testServer;
// }
//
// public ConfigServiceClient getConfigServiceClient() {
// return configServiceClient;
// }
//
// public ConfigServiceAdminClient getConfigServiceAdminClient() {
// return testServer.getAdminClient();
// }
// }
// Path: src/test/java/no/cantara/cs/client/ChangeConfigForSpecificClientTest.java
import no.cantara.cs.dto.Application;
import no.cantara.cs.dto.ApplicationConfig;
import no.cantara.cs.dto.CheckForUpdateRequest;
import no.cantara.cs.dto.Client;
import no.cantara.cs.dto.ClientConfig;
import no.cantara.cs.dto.ClientRegistrationRequest;
import no.cantara.cs.testsupport.ApplicationConfigBuilder;
import no.cantara.cs.testsupport.BaseSystemTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.IOException;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotEquals;
import static org.testng.Assert.assertNotNull;
package no.cantara.cs.client;
public class ChangeConfigForSpecificClientTest extends BaseSystemTest {
private ConfigServiceClient configServiceClient;
private Application application;
private ConfigServiceAdminClient configServiceAdminClient;
private ClientConfig currentClientConfig;
@BeforeClass
public void setup() throws Exception {
configServiceClient = getConfigServiceClient();
configServiceAdminClient = getConfigServiceAdminClient();
application = configServiceAdminClient.registerApplication(getClass().getSimpleName()); | configServiceAdminClient.createApplicationConfig(application, ApplicationConfigBuilder.createConfigDto("default-config", application)); |
Cantara/ConfigService | src/test/java/no/cantara/cs/client/RegisterClientWithPreconfiguredConfigTest.java | // Path: src/test/java/no/cantara/cs/testsupport/ApplicationConfigBuilder.java
// public class ApplicationConfigBuilder {
//
// public static ApplicationConfig createConfigDto(String name, Application application) {
// MavenMetadata metadata = new MavenMetadata("net.whydah.identity", application.artifactId, "2.0.1.Final");
// String url = new NexusUrlBuilder("http://mvnrepo.cantara.no", "releases").build(metadata);
// DownloadItem downloadItem = new DownloadItem(url, null, null, metadata);
// EventExtractionConfig extractionConfig = new EventExtractionConfig("jau");
// EventExtractionTag tag = new EventExtractionTag("testtag", "\\bheihei\\b", "logs/blabla.logg");
// extractionConfig.addEventExtractionTag(tag);
//
// ApplicationConfig config = new ApplicationConfig(name);
// config.addDownloadItem(downloadItem);
// config.addEventExtractionConfig(extractionConfig);
// config.setStartServiceScript("java -DIAM_MODE=DEV -jar " + downloadItem.filename());
//
// LinkedHashMap<String, String> propertiesMap = new LinkedHashMap<>();
// propertiesMap.put("a", "1");
// propertiesMap.put("b", "2");
// config.addPropertiesStore(new NamedPropertiesStore(propertiesMap, "named_properties_store.properties"));
//
// return config;
// }
// }
//
// Path: src/test/java/no/cantara/cs/testsupport/BaseSystemTest.java
// @Test(groups = "system-test")
// public abstract class BaseSystemTest {
// private TestServer testServer;
// private ConfigServiceClient configServiceClient;
//
// @BeforeClass
// @Parameters({ "persistenceType" })
// public void startServer(@Optional("mapdb") String persistenceType) throws Exception {
// if (persistenceType.equals("postgres")) {
// testServer = new TestServerPostgres(getClass());
// } else {
// testServer = new TestServerMapDb(getClass());
// }
// testServer.cleanAllData();
// testServer.start();
// configServiceClient = testServer.getConfigServiceClient();
// }
//
// @AfterClass
// public void stop() {
// if (testServer != null) {
// testServer.stop();
// }
// configServiceClient.cleanApplicationState();
// }
//
// public TestServer getTestServer() {
// return testServer;
// }
//
// public ConfigServiceClient getConfigServiceClient() {
// return configServiceClient;
// }
//
// public ConfigServiceAdminClient getConfigServiceAdminClient() {
// return testServer.getAdminClient();
// }
// }
| import no.cantara.cs.dto.Application;
import no.cantara.cs.dto.ApplicationConfig;
import no.cantara.cs.dto.ApplicationStatus;
import no.cantara.cs.dto.Client;
import no.cantara.cs.dto.ClientConfig;
import no.cantara.cs.dto.ClientRegistrationRequest;
import no.cantara.cs.testsupport.ApplicationConfigBuilder;
import no.cantara.cs.testsupport.BaseSystemTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue; | package no.cantara.cs.client;
public class RegisterClientWithPreconfiguredConfigTest extends BaseSystemTest {
private ConfigServiceClient configServiceClient;
private ConfigServiceAdminClient configServiceAdminClient;
private ClientConfig preconfiguredClientConfig;
private String artifactId;
private Application application;
@BeforeClass
public void startServer() throws Exception {
configServiceClient = getConfigServiceClient();
configServiceAdminClient = getConfigServiceAdminClient();
artifactId = getClass().getSimpleName();
configServiceAdminClient.registerApplication(artifactId);
}
@Test
public void findApplicationIdByArtifactId() throws IOException {
List<Application> allApplications = configServiceAdminClient.getAllApplications();
Optional<Application> optionalApplication = allApplications.stream().filter(a -> a.artifactId.equals(artifactId)).findAny();
assertTrue(optionalApplication.isPresent());
application = optionalApplication.get();
}
@Test(dependsOnMethods = "findApplicationIdByArtifactId")
public void testRegisterClientWithPreconfiguredConfig() throws Exception { | // Path: src/test/java/no/cantara/cs/testsupport/ApplicationConfigBuilder.java
// public class ApplicationConfigBuilder {
//
// public static ApplicationConfig createConfigDto(String name, Application application) {
// MavenMetadata metadata = new MavenMetadata("net.whydah.identity", application.artifactId, "2.0.1.Final");
// String url = new NexusUrlBuilder("http://mvnrepo.cantara.no", "releases").build(metadata);
// DownloadItem downloadItem = new DownloadItem(url, null, null, metadata);
// EventExtractionConfig extractionConfig = new EventExtractionConfig("jau");
// EventExtractionTag tag = new EventExtractionTag("testtag", "\\bheihei\\b", "logs/blabla.logg");
// extractionConfig.addEventExtractionTag(tag);
//
// ApplicationConfig config = new ApplicationConfig(name);
// config.addDownloadItem(downloadItem);
// config.addEventExtractionConfig(extractionConfig);
// config.setStartServiceScript("java -DIAM_MODE=DEV -jar " + downloadItem.filename());
//
// LinkedHashMap<String, String> propertiesMap = new LinkedHashMap<>();
// propertiesMap.put("a", "1");
// propertiesMap.put("b", "2");
// config.addPropertiesStore(new NamedPropertiesStore(propertiesMap, "named_properties_store.properties"));
//
// return config;
// }
// }
//
// Path: src/test/java/no/cantara/cs/testsupport/BaseSystemTest.java
// @Test(groups = "system-test")
// public abstract class BaseSystemTest {
// private TestServer testServer;
// private ConfigServiceClient configServiceClient;
//
// @BeforeClass
// @Parameters({ "persistenceType" })
// public void startServer(@Optional("mapdb") String persistenceType) throws Exception {
// if (persistenceType.equals("postgres")) {
// testServer = new TestServerPostgres(getClass());
// } else {
// testServer = new TestServerMapDb(getClass());
// }
// testServer.cleanAllData();
// testServer.start();
// configServiceClient = testServer.getConfigServiceClient();
// }
//
// @AfterClass
// public void stop() {
// if (testServer != null) {
// testServer.stop();
// }
// configServiceClient.cleanApplicationState();
// }
//
// public TestServer getTestServer() {
// return testServer;
// }
//
// public ConfigServiceClient getConfigServiceClient() {
// return configServiceClient;
// }
//
// public ConfigServiceAdminClient getConfigServiceAdminClient() {
// return testServer.getAdminClient();
// }
// }
// Path: src/test/java/no/cantara/cs/client/RegisterClientWithPreconfiguredConfigTest.java
import no.cantara.cs.dto.Application;
import no.cantara.cs.dto.ApplicationConfig;
import no.cantara.cs.dto.ApplicationStatus;
import no.cantara.cs.dto.Client;
import no.cantara.cs.dto.ClientConfig;
import no.cantara.cs.dto.ClientRegistrationRequest;
import no.cantara.cs.testsupport.ApplicationConfigBuilder;
import no.cantara.cs.testsupport.BaseSystemTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
package no.cantara.cs.client;
public class RegisterClientWithPreconfiguredConfigTest extends BaseSystemTest {
private ConfigServiceClient configServiceClient;
private ConfigServiceAdminClient configServiceAdminClient;
private ClientConfig preconfiguredClientConfig;
private String artifactId;
private Application application;
@BeforeClass
public void startServer() throws Exception {
configServiceClient = getConfigServiceClient();
configServiceAdminClient = getConfigServiceAdminClient();
artifactId = getClass().getSimpleName();
configServiceAdminClient.registerApplication(artifactId);
}
@Test
public void findApplicationIdByArtifactId() throws IOException {
List<Application> allApplications = configServiceAdminClient.getAllApplications();
Optional<Application> optionalApplication = allApplications.stream().filter(a -> a.artifactId.equals(artifactId)).findAny();
assertTrue(optionalApplication.isPresent());
application = optionalApplication.get();
}
@Test(dependsOnMethods = "findApplicationIdByArtifactId")
public void testRegisterClientWithPreconfiguredConfig() throws Exception { | ApplicationConfig config = configServiceAdminClient.createApplicationConfig(application, ApplicationConfigBuilder.createConfigDto("pre-registered-config", application)); |
Cantara/ConfigService | src/test/java/no/cantara/cs/admin/ClientAdminResourceEnvTest.java | // Path: src/test/java/no/cantara/cs/testsupport/ApplicationConfigBuilder.java
// public class ApplicationConfigBuilder {
//
// public static ApplicationConfig createConfigDto(String name, Application application) {
// MavenMetadata metadata = new MavenMetadata("net.whydah.identity", application.artifactId, "2.0.1.Final");
// String url = new NexusUrlBuilder("http://mvnrepo.cantara.no", "releases").build(metadata);
// DownloadItem downloadItem = new DownloadItem(url, null, null, metadata);
// EventExtractionConfig extractionConfig = new EventExtractionConfig("jau");
// EventExtractionTag tag = new EventExtractionTag("testtag", "\\bheihei\\b", "logs/blabla.logg");
// extractionConfig.addEventExtractionTag(tag);
//
// ApplicationConfig config = new ApplicationConfig(name);
// config.addDownloadItem(downloadItem);
// config.addEventExtractionConfig(extractionConfig);
// config.setStartServiceScript("java -DIAM_MODE=DEV -jar " + downloadItem.filename());
//
// LinkedHashMap<String, String> propertiesMap = new LinkedHashMap<>();
// propertiesMap.put("a", "1");
// propertiesMap.put("b", "2");
// config.addPropertiesStore(new NamedPropertiesStore(propertiesMap, "named_properties_store.properties"));
//
// return config;
// }
// }
//
// Path: src/test/java/no/cantara/cs/testsupport/BaseSystemTest.java
// @Test(groups = "system-test")
// public abstract class BaseSystemTest {
// private TestServer testServer;
// private ConfigServiceClient configServiceClient;
//
// @BeforeClass
// @Parameters({ "persistenceType" })
// public void startServer(@Optional("mapdb") String persistenceType) throws Exception {
// if (persistenceType.equals("postgres")) {
// testServer = new TestServerPostgres(getClass());
// } else {
// testServer = new TestServerMapDb(getClass());
// }
// testServer.cleanAllData();
// testServer.start();
// configServiceClient = testServer.getConfigServiceClient();
// }
//
// @AfterClass
// public void stop() {
// if (testServer != null) {
// testServer.stop();
// }
// configServiceClient.cleanApplicationState();
// }
//
// public TestServer getTestServer() {
// return testServer;
// }
//
// public ConfigServiceClient getConfigServiceClient() {
// return configServiceClient;
// }
//
// public ConfigServiceAdminClient getConfigServiceAdminClient() {
// return testServer.getAdminClient();
// }
// }
| import no.cantara.cs.client.ConfigServiceAdminClient;
import no.cantara.cs.dto.*;
import no.cantara.cs.testsupport.ApplicationConfigBuilder;
import no.cantara.cs.testsupport.BaseSystemTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.HashMap;
import static org.testng.Assert.*; | package no.cantara.cs.admin;
/**
* @author Asbjørn Willersrud
*/
public class ClientAdminResourceEnvTest extends BaseSystemTest {
private Application application;
private ClientConfig clientConfig;
@BeforeClass
public void setup() throws Exception {
ConfigServiceAdminClient configServiceAdminClient = getTestServer().getAdminClient();
application = configServiceAdminClient.registerApplication("ClientStatusTest-ArtifactId"); | // Path: src/test/java/no/cantara/cs/testsupport/ApplicationConfigBuilder.java
// public class ApplicationConfigBuilder {
//
// public static ApplicationConfig createConfigDto(String name, Application application) {
// MavenMetadata metadata = new MavenMetadata("net.whydah.identity", application.artifactId, "2.0.1.Final");
// String url = new NexusUrlBuilder("http://mvnrepo.cantara.no", "releases").build(metadata);
// DownloadItem downloadItem = new DownloadItem(url, null, null, metadata);
// EventExtractionConfig extractionConfig = new EventExtractionConfig("jau");
// EventExtractionTag tag = new EventExtractionTag("testtag", "\\bheihei\\b", "logs/blabla.logg");
// extractionConfig.addEventExtractionTag(tag);
//
// ApplicationConfig config = new ApplicationConfig(name);
// config.addDownloadItem(downloadItem);
// config.addEventExtractionConfig(extractionConfig);
// config.setStartServiceScript("java -DIAM_MODE=DEV -jar " + downloadItem.filename());
//
// LinkedHashMap<String, String> propertiesMap = new LinkedHashMap<>();
// propertiesMap.put("a", "1");
// propertiesMap.put("b", "2");
// config.addPropertiesStore(new NamedPropertiesStore(propertiesMap, "named_properties_store.properties"));
//
// return config;
// }
// }
//
// Path: src/test/java/no/cantara/cs/testsupport/BaseSystemTest.java
// @Test(groups = "system-test")
// public abstract class BaseSystemTest {
// private TestServer testServer;
// private ConfigServiceClient configServiceClient;
//
// @BeforeClass
// @Parameters({ "persistenceType" })
// public void startServer(@Optional("mapdb") String persistenceType) throws Exception {
// if (persistenceType.equals("postgres")) {
// testServer = new TestServerPostgres(getClass());
// } else {
// testServer = new TestServerMapDb(getClass());
// }
// testServer.cleanAllData();
// testServer.start();
// configServiceClient = testServer.getConfigServiceClient();
// }
//
// @AfterClass
// public void stop() {
// if (testServer != null) {
// testServer.stop();
// }
// configServiceClient.cleanApplicationState();
// }
//
// public TestServer getTestServer() {
// return testServer;
// }
//
// public ConfigServiceClient getConfigServiceClient() {
// return configServiceClient;
// }
//
// public ConfigServiceAdminClient getConfigServiceAdminClient() {
// return testServer.getAdminClient();
// }
// }
// Path: src/test/java/no/cantara/cs/admin/ClientAdminResourceEnvTest.java
import no.cantara.cs.client.ConfigServiceAdminClient;
import no.cantara.cs.dto.*;
import no.cantara.cs.testsupport.ApplicationConfigBuilder;
import no.cantara.cs.testsupport.BaseSystemTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.HashMap;
import static org.testng.Assert.*;
package no.cantara.cs.admin;
/**
* @author Asbjørn Willersrud
*/
public class ClientAdminResourceEnvTest extends BaseSystemTest {
private Application application;
private ClientConfig clientConfig;
@BeforeClass
public void setup() throws Exception {
ConfigServiceAdminClient configServiceAdminClient = getTestServer().getAdminClient();
application = configServiceAdminClient.registerApplication("ClientStatusTest-ArtifactId"); | configServiceAdminClient.createApplicationConfig(application, ApplicationConfigBuilder.createConfigDto("arbitrary-config", application)); |
Cantara/ConfigService | src/test/java/no/cantara/cs/client/CheckForUpdateTest.java | // Path: src/test/java/no/cantara/cs/testsupport/BaseSystemTest.java
// @Test(groups = "system-test")
// public abstract class BaseSystemTest {
// private TestServer testServer;
// private ConfigServiceClient configServiceClient;
//
// @BeforeClass
// @Parameters({ "persistenceType" })
// public void startServer(@Optional("mapdb") String persistenceType) throws Exception {
// if (persistenceType.equals("postgres")) {
// testServer = new TestServerPostgres(getClass());
// } else {
// testServer = new TestServerMapDb(getClass());
// }
// testServer.cleanAllData();
// testServer.start();
// configServiceClient = testServer.getConfigServiceClient();
// }
//
// @AfterClass
// public void stop() {
// if (testServer != null) {
// testServer.stop();
// }
// configServiceClient.cleanApplicationState();
// }
//
// public TestServer getTestServer() {
// return testServer;
// }
//
// public ConfigServiceClient getConfigServiceClient() {
// return configServiceClient;
// }
//
// public ConfigServiceAdminClient getConfigServiceAdminClient() {
// return testServer.getAdminClient();
// }
// }
//
// Path: src/test/java/no/cantara/cs/testsupport/TestServer.java
// public interface TestServer {
// String USERNAME = "read";
// String PASSWORD = "baretillesing";
// String ADMIN_USERNAME = "admin";
// String ADMIN_PASSWORD = "configservice";
//
// void cleanAllData() throws Exception;
//
// void start() throws InterruptedException;
//
// void stop();
//
// ConfigServiceClient getConfigServiceClient();
//
// ConfigServiceAdminClient getAdminClient();
// }
| import com.jayway.restassured.http.ContentType;
import no.cantara.cs.dto.CheckForUpdateRequest;
import no.cantara.cs.testsupport.BaseSystemTest;
import no.cantara.cs.testsupport.TestServer;
import org.apache.http.HttpStatus;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.IOException;
import static com.jayway.restassured.RestAssured.given;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail; | package no.cantara.cs.client;
public class CheckForUpdateTest extends BaseSystemTest {
private ConfigServiceClient configServiceClient;
@BeforeClass
public void startServer() throws Exception {
configServiceClient = getConfigServiceClient();
}
@Test
public void testCheckForUpdateBrokenJson() {
given() | // Path: src/test/java/no/cantara/cs/testsupport/BaseSystemTest.java
// @Test(groups = "system-test")
// public abstract class BaseSystemTest {
// private TestServer testServer;
// private ConfigServiceClient configServiceClient;
//
// @BeforeClass
// @Parameters({ "persistenceType" })
// public void startServer(@Optional("mapdb") String persistenceType) throws Exception {
// if (persistenceType.equals("postgres")) {
// testServer = new TestServerPostgres(getClass());
// } else {
// testServer = new TestServerMapDb(getClass());
// }
// testServer.cleanAllData();
// testServer.start();
// configServiceClient = testServer.getConfigServiceClient();
// }
//
// @AfterClass
// public void stop() {
// if (testServer != null) {
// testServer.stop();
// }
// configServiceClient.cleanApplicationState();
// }
//
// public TestServer getTestServer() {
// return testServer;
// }
//
// public ConfigServiceClient getConfigServiceClient() {
// return configServiceClient;
// }
//
// public ConfigServiceAdminClient getConfigServiceAdminClient() {
// return testServer.getAdminClient();
// }
// }
//
// Path: src/test/java/no/cantara/cs/testsupport/TestServer.java
// public interface TestServer {
// String USERNAME = "read";
// String PASSWORD = "baretillesing";
// String ADMIN_USERNAME = "admin";
// String ADMIN_PASSWORD = "configservice";
//
// void cleanAllData() throws Exception;
//
// void start() throws InterruptedException;
//
// void stop();
//
// ConfigServiceClient getConfigServiceClient();
//
// ConfigServiceAdminClient getAdminClient();
// }
// Path: src/test/java/no/cantara/cs/client/CheckForUpdateTest.java
import com.jayway.restassured.http.ContentType;
import no.cantara.cs.dto.CheckForUpdateRequest;
import no.cantara.cs.testsupport.BaseSystemTest;
import no.cantara.cs.testsupport.TestServer;
import org.apache.http.HttpStatus;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.IOException;
import static com.jayway.restassured.RestAssured.given;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;
package no.cantara.cs.client;
public class CheckForUpdateTest extends BaseSystemTest {
private ConfigServiceClient configServiceClient;
@BeforeClass
public void startServer() throws Exception {
configServiceClient = getConfigServiceClient();
}
@Test
public void testCheckForUpdateBrokenJson() {
given() | .auth().basic(TestServer.USERNAME, TestServer.PASSWORD) |
Cantara/ConfigService | src/main/java/no/cantara/cs/cloudwatch/CloudWatchMetricsPublisher.java | // Path: src/main/java/no/cantara/cs/config/ConstrettoConfig.java
// public class ConstrettoConfig {
// private static final ConstrettoConfiguration configuration = new ConstrettoBuilder()
// .createPropertiesStore()
// .addResource(Resource.create("classpath:application.properties"))
// .addResource(Resource.create("file:./config_override/application_override.properties"))
// .done()
// .getConfiguration();
//
// private ConstrettoConfig() {}
//
// public static String getString(String key) {
// return configuration.evaluateToString(key);
// }
//
// public static Integer getInt(String key) {
// return configuration.evaluateToInt(key);
// }
//
// public static Integer getInt(String key, int defaultValue) {
// return configuration.evaluateTo(key, defaultValue);
// }
//
// public static boolean getBoolean(String key) {
// return configuration.evaluateToBoolean(key);
// }
// }
| import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.cloudwatch.AmazonCloudWatch;
import com.amazonaws.services.cloudwatch.AmazonCloudWatchClient;
import com.amazonaws.services.cloudwatch.model.Dimension;
import com.amazonaws.services.cloudwatch.model.MetricDatum;
import com.amazonaws.services.cloudwatch.model.PutMetricDataRequest;
import com.amazonaws.services.cloudwatch.model.StandardUnit;
import no.cantara.cs.config.ConstrettoConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors; | package no.cantara.cs.cloudwatch;
/**
* Publishes custom metrics to Amazon CloudWatch.
* <p>
* Currently the only metric published is the number of heartbeats received per client.
* <p>
* Uses the following configuration properties:
* <ul>
* <li>cloudwatch.metrics.enabled - Whether Amazon CloudWatch metrics publishing is enabled.</li>
* <li>cloudwatch.region - The AWS region to use, e.g., "eu-west-1".</li>
* <li>cloudwatch.metrics.namespace - The namespace to use for custom CloudWatch metrics.</li>
* <li>cloudwatch.metrics.intervalSeconds - How often to publish metrics.</li>
* </ul>
*
* @author Sindre Mehus
*/
@Service
public class CloudWatchMetricsPublisher {
private static final Logger log = LoggerFactory.getLogger(CloudWatchMetricsPublisher.class);
private final ConcurrentMap<String, Integer> heartbeats = new ConcurrentSkipListMap<>();
private AmazonCloudWatch awsClient;
private String namespace;
public CloudWatchMetricsPublisher() { | // Path: src/main/java/no/cantara/cs/config/ConstrettoConfig.java
// public class ConstrettoConfig {
// private static final ConstrettoConfiguration configuration = new ConstrettoBuilder()
// .createPropertiesStore()
// .addResource(Resource.create("classpath:application.properties"))
// .addResource(Resource.create("file:./config_override/application_override.properties"))
// .done()
// .getConfiguration();
//
// private ConstrettoConfig() {}
//
// public static String getString(String key) {
// return configuration.evaluateToString(key);
// }
//
// public static Integer getInt(String key) {
// return configuration.evaluateToInt(key);
// }
//
// public static Integer getInt(String key, int defaultValue) {
// return configuration.evaluateTo(key, defaultValue);
// }
//
// public static boolean getBoolean(String key) {
// return configuration.evaluateToBoolean(key);
// }
// }
// Path: src/main/java/no/cantara/cs/cloudwatch/CloudWatchMetricsPublisher.java
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.cloudwatch.AmazonCloudWatch;
import com.amazonaws.services.cloudwatch.AmazonCloudWatchClient;
import com.amazonaws.services.cloudwatch.model.Dimension;
import com.amazonaws.services.cloudwatch.model.MetricDatum;
import com.amazonaws.services.cloudwatch.model.PutMetricDataRequest;
import com.amazonaws.services.cloudwatch.model.StandardUnit;
import no.cantara.cs.config.ConstrettoConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
package no.cantara.cs.cloudwatch;
/**
* Publishes custom metrics to Amazon CloudWatch.
* <p>
* Currently the only metric published is the number of heartbeats received per client.
* <p>
* Uses the following configuration properties:
* <ul>
* <li>cloudwatch.metrics.enabled - Whether Amazon CloudWatch metrics publishing is enabled.</li>
* <li>cloudwatch.region - The AWS region to use, e.g., "eu-west-1".</li>
* <li>cloudwatch.metrics.namespace - The namespace to use for custom CloudWatch metrics.</li>
* <li>cloudwatch.metrics.intervalSeconds - How often to publish metrics.</li>
* </ul>
*
* @author Sindre Mehus
*/
@Service
public class CloudWatchMetricsPublisher {
private static final Logger log = LoggerFactory.getLogger(CloudWatchMetricsPublisher.class);
private final ConcurrentMap<String, Integer> heartbeats = new ConcurrentSkipListMap<>();
private AmazonCloudWatch awsClient;
private String namespace;
public CloudWatchMetricsPublisher() { | if (ConstrettoConfig.getBoolean("cloudwatch.metrics.enabled")) { |
kong-jing/PreRect | app/src/main/java/xyz/kongjing/prerect/view/FaceView.java | // Path: app/src/main/java/xyz/kongjing/prerect/model/FaceInfo.java
// public class FaceInfo {
// public RectF rect;
// public int id;
// public int living;
// public int score;
//
// public RectF getRect() {
// return rect;
// }
//
// public void setRect(RectF rect) {
// this.rect = rect;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public int getLiving() {
// return living;
// }
//
// public void setLiving(int living) {
// this.living = living;
// }
//
// public int getScore() {
// return score;
// }
//
// public void setScore(int score) {
// this.score = score;
// }
// }
| import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import xyz.kongjing.prerect.model.FaceInfo; | package xyz.kongjing.prerect.view;
/**
* Created by Jing on 16/8/5.
*/
public class FaceView extends View {
Context mContext;
private Paint mLinePaint;
Paint textPaint; | // Path: app/src/main/java/xyz/kongjing/prerect/model/FaceInfo.java
// public class FaceInfo {
// public RectF rect;
// public int id;
// public int living;
// public int score;
//
// public RectF getRect() {
// return rect;
// }
//
// public void setRect(RectF rect) {
// this.rect = rect;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public int getLiving() {
// return living;
// }
//
// public void setLiving(int living) {
// this.living = living;
// }
//
// public int getScore() {
// return score;
// }
//
// public void setScore(int score) {
// this.score = score;
// }
// }
// Path: app/src/main/java/xyz/kongjing/prerect/view/FaceView.java
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import xyz.kongjing.prerect.model.FaceInfo;
package xyz.kongjing.prerect.view;
/**
* Created by Jing on 16/8/5.
*/
public class FaceView extends View {
Context mContext;
private Paint mLinePaint;
Paint textPaint; | private FaceInfo[] mFaces; |
kong-jing/PreRect | app/src/main/java/xyz/kongjing/prerect/camera/CameraConfigurationManager.java | // Path: app/src/main/java/xyz/kongjing/prerect/callback/OnCaptureCallback.java
// public interface OnCaptureCallback {
//
// public void onCapture(byte[] jpgdata);
// }
| import android.util.Log;
import xyz.kongjing.prerect.callback.OnCaptureCallback;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
import android.content.Context;
import android.graphics.ImageFormat;
import android.graphics.Point;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.hardware.Camera.Size;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.view.Display;
import android.view.Surface;
import android.view.WindowManager; | parameters.set("zoom", String.valueOf(tenDesiredZoom / 10.0));
}
if (takingPictureZoomMaxString != null) {
parameters.set("taking-picture-zoom", tenDesiredZoom);
}
}
/**
* 设置照片尺寸为最接近指定尺寸
*
* @param list
* @return
*/
private void setPicutreSize(List<Size> list, int width, int height) {
int approach = Integer.MAX_VALUE;
for (Size size : list) {
int temp = Math.abs(size.width - width + size.height - height);
if (approach > temp) {
approach = temp;
pictureSize = size;
}
}
}
// 拍照
private ToneGenerator tone;
| // Path: app/src/main/java/xyz/kongjing/prerect/callback/OnCaptureCallback.java
// public interface OnCaptureCallback {
//
// public void onCapture(byte[] jpgdata);
// }
// Path: app/src/main/java/xyz/kongjing/prerect/camera/CameraConfigurationManager.java
import android.util.Log;
import xyz.kongjing.prerect.callback.OnCaptureCallback;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
import android.content.Context;
import android.graphics.ImageFormat;
import android.graphics.Point;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.hardware.Camera.Size;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.view.Display;
import android.view.Surface;
import android.view.WindowManager;
parameters.set("zoom", String.valueOf(tenDesiredZoom / 10.0));
}
if (takingPictureZoomMaxString != null) {
parameters.set("taking-picture-zoom", tenDesiredZoom);
}
}
/**
* 设置照片尺寸为最接近指定尺寸
*
* @param list
* @return
*/
private void setPicutreSize(List<Size> list, int width, int height) {
int approach = Integer.MAX_VALUE;
for (Size size : list) {
int temp = Math.abs(size.width - width + size.height - height);
if (approach > temp) {
approach = temp;
pictureSize = size;
}
}
}
// 拍照
private ToneGenerator tone;
| public void tackPicture(Camera camera, final OnCaptureCallback callback) |
aehrc/snorocket | snorocket-examples/src/main/java/au/csiro/snorocket/core/benchmark/OWLBenchmark.java | // Path: snorocket-owlapi/src/main/java/au/csiro/snorocket/owlapi/SnorocketReasonerFactory.java
// public class SnorocketReasonerFactory implements OWLReasonerFactory {
//
// public String getReasonerName() {
// return SnorocketReasonerFactory.class.getPackage().getImplementationTitle();
// }
//
// public OWLReasoner createNonBufferingReasoner(OWLOntology ontology) {
// return new SnorocketOWLReasoner(ontology, null, false);
// }
//
// public OWLReasoner createReasoner(OWLOntology ontology) {
// return new SnorocketOWLReasoner(ontology, null, true);
// }
//
// public OWLReasoner createNonBufferingReasoner(OWLOntology ontology,
// OWLReasonerConfiguration config)
// throws IllegalConfigurationException {
// return new SnorocketOWLReasoner(ontology, config, false);
// }
//
// public OWLReasoner createReasoner(OWLOntology ontology,
// OWLReasonerConfiguration config)
// throws IllegalConfigurationException {
// return new SnorocketOWLReasoner(ontology, config, true);
// }
//
// }
| import java.io.File;
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyManager;
import org.semanticweb.owlapi.reasoner.InferenceType;
import org.semanticweb.owlapi.reasoner.OWLReasoner;
import org.semanticweb.owlapi.reasoner.OWLReasonerFactory;
import au.csiro.ontology.util.Statistics;
import au.csiro.snorocket.owlapi.SnorocketReasonerFactory;
| /**
* Copyright CSIRO Australian e-Health Research Centre (http://aehrc.com).
* All rights reserved. Use is subject to license terms and conditions.
*/
package au.csiro.snorocket.core.benchmark;
/**
* @author Alejandro Metke
*
*/
public class OWLBenchmark {
/**
*
*/
public OWLBenchmark() {
}
/**
* @param args
*/
public static void main(String[] args) {
long start = System.currentTimeMillis();
OWLOntologyManager man = OWLManager.createOWLOntologyManager();
// loading the root ontology
OWLOntology root = null;
try {
root = man.loadOntologyFromOntologyDocument(new File(
"C:\\dev\\ontologies\\owl\\snomed_20130131_stated.owl"));
} catch (OWLOntologyCreationException e) {
e.printStackTrace();
return;
}
System.out.println("owl-api loading: "+(System.currentTimeMillis()-start));
// Create a Snorocket reasoner and classify
| // Path: snorocket-owlapi/src/main/java/au/csiro/snorocket/owlapi/SnorocketReasonerFactory.java
// public class SnorocketReasonerFactory implements OWLReasonerFactory {
//
// public String getReasonerName() {
// return SnorocketReasonerFactory.class.getPackage().getImplementationTitle();
// }
//
// public OWLReasoner createNonBufferingReasoner(OWLOntology ontology) {
// return new SnorocketOWLReasoner(ontology, null, false);
// }
//
// public OWLReasoner createReasoner(OWLOntology ontology) {
// return new SnorocketOWLReasoner(ontology, null, true);
// }
//
// public OWLReasoner createNonBufferingReasoner(OWLOntology ontology,
// OWLReasonerConfiguration config)
// throws IllegalConfigurationException {
// return new SnorocketOWLReasoner(ontology, config, false);
// }
//
// public OWLReasoner createReasoner(OWLOntology ontology,
// OWLReasonerConfiguration config)
// throws IllegalConfigurationException {
// return new SnorocketOWLReasoner(ontology, config, true);
// }
//
// }
// Path: snorocket-examples/src/main/java/au/csiro/snorocket/core/benchmark/OWLBenchmark.java
import java.io.File;
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyManager;
import org.semanticweb.owlapi.reasoner.InferenceType;
import org.semanticweb.owlapi.reasoner.OWLReasoner;
import org.semanticweb.owlapi.reasoner.OWLReasonerFactory;
import au.csiro.ontology.util.Statistics;
import au.csiro.snorocket.owlapi.SnorocketReasonerFactory;
/**
* Copyright CSIRO Australian e-Health Research Centre (http://aehrc.com).
* All rights reserved. Use is subject to license terms and conditions.
*/
package au.csiro.snorocket.core.benchmark;
/**
* @author Alejandro Metke
*
*/
public class OWLBenchmark {
/**
*
*/
public OWLBenchmark() {
}
/**
* @param args
*/
public static void main(String[] args) {
long start = System.currentTimeMillis();
OWLOntologyManager man = OWLManager.createOWLOntologyManager();
// loading the root ontology
OWLOntology root = null;
try {
root = man.loadOntologyFromOntologyDocument(new File(
"C:\\dev\\ontologies\\owl\\snomed_20130131_stated.owl"));
} catch (OWLOntologyCreationException e) {
e.printStackTrace();
return;
}
System.out.println("owl-api loading: "+(System.currentTimeMillis()-start));
// Create a Snorocket reasoner and classify
| OWLReasonerFactory reasonerFactory = new SnorocketReasonerFactory();
|
aehrc/snorocket | snorocket-core/src/test/java/au/csiro/snorocket/core/TestNormalisedOntology.java | // Path: snorocket-core/src/main/java/au/csiro/snorocket/core/axioms/Inclusion.java
// abstract public class Inclusion implements Serializable {
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// /**
// * Runs the first phase in the normalisation process (see Pushing the EL
// * Envelope).
// *
// * @param factory
// * @return
// */
// abstract public Inclusion[] normalise1(IFactory factory);
//
// /**
// * Runs the second phase in the normalisation process (see Pushing the EL
// * Envelope).
// *
// * @param factory
// * @return
// */
// abstract public Inclusion[] normalise2(IFactory factory);
//
// @Override
// abstract public int hashCode();
//
// @Override
// abstract public boolean equals(Object o);
//
// @Override
// abstract public String toString();
//
// abstract public NormalFormGCI getNormalForm();
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import au.csiro.ontology.Node;
import au.csiro.ontology.model.Axiom;
import au.csiro.ontology.model.Concept;
import au.csiro.ontology.model.ConceptInclusion;
import au.csiro.ontology.model.Conjunction;
import au.csiro.ontology.model.Datatype;
import au.csiro.ontology.model.Existential;
import au.csiro.ontology.model.IntegerLiteral;
import au.csiro.ontology.model.NamedConcept;
import au.csiro.ontology.model.NamedFeature;
import au.csiro.ontology.model.NamedRole;
import au.csiro.ontology.model.Operator;
import au.csiro.ontology.model.Role;
import au.csiro.ontology.model.RoleInclusion;
import au.csiro.snorocket.core.axioms.Inclusion;
| ConceptInclusion a3 = new ConceptInclusion(new Conjunction(
new Concept[] {
panadol,
new Datatype(mgPerTablet, Operator.EQUALS, new IntegerLiteral(250)) }), panadol_250mg);
ConceptInclusion a4 = new ConceptInclusion(panadol_500mg,
new Conjunction(new Concept[] {
panadol,
new Datatype(mgPerTablet, Operator.EQUALS, new IntegerLiteral(500)) }));
ConceptInclusion a5 = new ConceptInclusion(new Conjunction(
new Concept[] {
panadol,
new Datatype(mgPerTablet, Operator.EQUALS, new IntegerLiteral(500)) }), panadol_500mg);
ConceptInclusion a6 = new ConceptInclusion(panadol_pack_250mg,
new Conjunction(new Concept[] {
panadol,
new Datatype(mgPerTablet, Operator.EQUALS, new IntegerLiteral(250)),
new Existential(container, bottle) }));
Set<Axiom> axioms = new HashSet<Axiom>();
axioms.add(a1);
axioms.add(a2);
axioms.add(a3);
axioms.add(a4);
axioms.add(a5);
axioms.add(a6);
NormalisedOntology no = new NormalisedOntology(factory);
| // Path: snorocket-core/src/main/java/au/csiro/snorocket/core/axioms/Inclusion.java
// abstract public class Inclusion implements Serializable {
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// /**
// * Runs the first phase in the normalisation process (see Pushing the EL
// * Envelope).
// *
// * @param factory
// * @return
// */
// abstract public Inclusion[] normalise1(IFactory factory);
//
// /**
// * Runs the second phase in the normalisation process (see Pushing the EL
// * Envelope).
// *
// * @param factory
// * @return
// */
// abstract public Inclusion[] normalise2(IFactory factory);
//
// @Override
// abstract public int hashCode();
//
// @Override
// abstract public boolean equals(Object o);
//
// @Override
// abstract public String toString();
//
// abstract public NormalFormGCI getNormalForm();
//
// }
// Path: snorocket-core/src/test/java/au/csiro/snorocket/core/TestNormalisedOntology.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import au.csiro.ontology.Node;
import au.csiro.ontology.model.Axiom;
import au.csiro.ontology.model.Concept;
import au.csiro.ontology.model.ConceptInclusion;
import au.csiro.ontology.model.Conjunction;
import au.csiro.ontology.model.Datatype;
import au.csiro.ontology.model.Existential;
import au.csiro.ontology.model.IntegerLiteral;
import au.csiro.ontology.model.NamedConcept;
import au.csiro.ontology.model.NamedFeature;
import au.csiro.ontology.model.NamedRole;
import au.csiro.ontology.model.Operator;
import au.csiro.ontology.model.Role;
import au.csiro.ontology.model.RoleInclusion;
import au.csiro.snorocket.core.axioms.Inclusion;
ConceptInclusion a3 = new ConceptInclusion(new Conjunction(
new Concept[] {
panadol,
new Datatype(mgPerTablet, Operator.EQUALS, new IntegerLiteral(250)) }), panadol_250mg);
ConceptInclusion a4 = new ConceptInclusion(panadol_500mg,
new Conjunction(new Concept[] {
panadol,
new Datatype(mgPerTablet, Operator.EQUALS, new IntegerLiteral(500)) }));
ConceptInclusion a5 = new ConceptInclusion(new Conjunction(
new Concept[] {
panadol,
new Datatype(mgPerTablet, Operator.EQUALS, new IntegerLiteral(500)) }), panadol_500mg);
ConceptInclusion a6 = new ConceptInclusion(panadol_pack_250mg,
new Conjunction(new Concept[] {
panadol,
new Datatype(mgPerTablet, Operator.EQUALS, new IntegerLiteral(250)),
new Existential(container, bottle) }));
Set<Axiom> axioms = new HashSet<Axiom>();
axioms.add(a1);
axioms.add(a2);
axioms.add(a3);
axioms.add(a4);
axioms.add(a5);
axioms.add(a6);
NormalisedOntology no = new NormalisedOntology(factory);
| Set<Inclusion> norms = no.normalise(axioms);
|
aehrc/snorocket | snorocket-core/src/main/java/au/csiro/snorocket/core/util/IConceptSet.java | // Path: snorocket-core/src/main/java/au/csiro/snorocket/core/ConceptSetFactory.java
// public interface ConceptSetFactory {
// /**
// * With no size specified, may assume a sparse ConceptSet implementation is
// * suitable.
// *
// * @return
// */
// IConceptSet createConceptSet();
//
// /**
// * For a large size, should assume a dense ConceptSet implementation is
// * required.
// *
// * @return
// */
// IConceptSet createConceptSet(int size);
//
// /**
// * Use size of initial to guide selection of concrete implementation.
// *
// * @return
// */
// IConceptSet createConceptSet(IConceptSet initial);
// }
| import au.csiro.snorocket.core.ConceptSetFactory;
import java.io.Serializable;
| /**
* Copyright (c) 2009 International Health Terminology Standards Development
* Organisation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Copyright CSIRO Australian e-Health Research Centre (http://aehrc.com).
* All rights reserved. Use is subject to license terms and conditions.
*/
package au.csiro.snorocket.core.util;
public interface IConceptSet extends Serializable {
final static IConceptSet EMPTY_SET = new EmptyConceptSet();
| // Path: snorocket-core/src/main/java/au/csiro/snorocket/core/ConceptSetFactory.java
// public interface ConceptSetFactory {
// /**
// * With no size specified, may assume a sparse ConceptSet implementation is
// * suitable.
// *
// * @return
// */
// IConceptSet createConceptSet();
//
// /**
// * For a large size, should assume a dense ConceptSet implementation is
// * required.
// *
// * @return
// */
// IConceptSet createConceptSet(int size);
//
// /**
// * Use size of initial to guide selection of concrete implementation.
// *
// * @return
// */
// IConceptSet createConceptSet(IConceptSet initial);
// }
// Path: snorocket-core/src/main/java/au/csiro/snorocket/core/util/IConceptSet.java
import au.csiro.snorocket.core.ConceptSetFactory;
import java.io.Serializable;
/**
* Copyright (c) 2009 International Health Terminology Standards Development
* Organisation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Copyright CSIRO Australian e-Health Research Centre (http://aehrc.com).
* All rights reserved. Use is subject to license terms and conditions.
*/
package au.csiro.snorocket.core.util;
public interface IConceptSet extends Serializable {
final static IConceptSet EMPTY_SET = new EmptyConceptSet();
| public static ConceptSetFactory FACTORY = new ConceptSetFactory() {
|
aehrc/snorocket | snorocket-core/src/test/java/au/csiro/snorocket/core/TestIConceptSet.java | // Path: snorocket-core/src/main/java/au/csiro/snorocket/core/util/IConceptSet.java
// public interface IConceptSet extends Serializable {
// final static IConceptSet EMPTY_SET = new EmptyConceptSet();
//
// public static ConceptSetFactory FACTORY = new ConceptSetFactory() {
//
// public IConceptSet createConceptSet() {
// return new SparseConceptHashSet();
// }
//
// public IConceptSet createConceptSet(final int size) {
// return new SparseConceptHashSet(size);
// }
//
// public IConceptSet createConceptSet(final IConceptSet initial) {
// final IConceptSet result;
// if (null == initial) {
// result = createConceptSet();
// } else {
// result = createConceptSet(initial.size());
// result.addAll(initial);
// }
// return result;
// }
// };
//
// public void add(int concept);
//
// public void addAll(IConceptSet set);
//
// public boolean contains(int concept);
//
// public boolean containsAll(IConceptSet concepts);
//
// public void remove(int concept);
//
// public void removeAll(IConceptSet set);
//
// public boolean isEmpty();
//
// public int hashCode();
//
// public boolean equals(Object o);
//
// public String toString();
//
// public IntIterator iterator();
//
// public void clear();
//
// public int size();
//
// public void grow(int newSize);
//
// public int[] toArray();
// }
| import static org.junit.Assert.assertTrue;
import org.junit.Test;
import au.csiro.snorocket.core.util.IConceptSet;
import static org.junit.Assert.assertFalse;
| /**
* Copyright (c) 2009 International Health Terminology Standards Development
* Organisation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Copyright CSIRO Australian e-Health Research Centre (http://aehrc.com).
* All rights reserved. Use is subject to license terms and conditions.
*/
package au.csiro.snorocket.core;
public abstract class TestIConceptSet {
private static final int RANGE = 500000;
| // Path: snorocket-core/src/main/java/au/csiro/snorocket/core/util/IConceptSet.java
// public interface IConceptSet extends Serializable {
// final static IConceptSet EMPTY_SET = new EmptyConceptSet();
//
// public static ConceptSetFactory FACTORY = new ConceptSetFactory() {
//
// public IConceptSet createConceptSet() {
// return new SparseConceptHashSet();
// }
//
// public IConceptSet createConceptSet(final int size) {
// return new SparseConceptHashSet(size);
// }
//
// public IConceptSet createConceptSet(final IConceptSet initial) {
// final IConceptSet result;
// if (null == initial) {
// result = createConceptSet();
// } else {
// result = createConceptSet(initial.size());
// result.addAll(initial);
// }
// return result;
// }
// };
//
// public void add(int concept);
//
// public void addAll(IConceptSet set);
//
// public boolean contains(int concept);
//
// public boolean containsAll(IConceptSet concepts);
//
// public void remove(int concept);
//
// public void removeAll(IConceptSet set);
//
// public boolean isEmpty();
//
// public int hashCode();
//
// public boolean equals(Object o);
//
// public String toString();
//
// public IntIterator iterator();
//
// public void clear();
//
// public int size();
//
// public void grow(int newSize);
//
// public int[] toArray();
// }
// Path: snorocket-core/src/test/java/au/csiro/snorocket/core/TestIConceptSet.java
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import au.csiro.snorocket.core.util.IConceptSet;
import static org.junit.Assert.assertFalse;
/**
* Copyright (c) 2009 International Health Terminology Standards Development
* Organisation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Copyright CSIRO Australian e-Health Research Centre (http://aehrc.com).
* All rights reserved. Use is subject to license terms and conditions.
*/
package au.csiro.snorocket.core;
public abstract class TestIConceptSet {
private static final int RANGE = 500000;
| abstract IConceptSet createSet(final int capacity);
|
aehrc/snorocket | snorocket-core/src/main/java/au/csiro/snorocket/core/axioms/NF3.java | // Path: snorocket-core/src/main/java/au/csiro/snorocket/core/IFactory.java
// public interface IFactory extends Serializable {
//
// /**
// * Internal id used for the top concept.
// */
// public static final int TOP_CONCEPT = 0;
//
// /**
// * Internal id used for the bottom concept.
// */
// public static final int BOTTOM_CONCEPT = 1;
//
// /**
// * Indicates if a concept, either named or virtual, exists.
// *
// * @param key
// * @return
// */
// boolean conceptExists(final Object key);
//
// /**
// * Indicates if a role, either named or virtual, exists.
// *
// * @param key
// * @return
// */
// boolean roleExists(final Object key);
//
// /**
// * Indicates if a feature exists.
// *
// * @param key
// * @return
// */
// boolean featureExists(final String key);
//
// /**
// * Returns the internal id of a concept.
// *
// * @param key
// * @return
// */
// int getConcept(final Object key);
//
// /**
// * Returns the internal id of a role.
// *
// * @param key
// * @return
// */
// int getRole(final Object key);
//
// /**
// * Returns the internal id of a feature.
// *
// * @param key
// * @return
// */
// int getFeature(final String key);
//
// /**
// * Returns the total number of concepts.
// *
// * @return
// */
// int getTotalConcepts();
//
// /**
// * Returns the total number of roles.
// *
// * @return
// */
// int getTotalRoles();
//
// /**
// * Returns the total number of features.
// *
// * @return
// */
// int getTotalFeatures();
//
// /**
// * Returns the external id of a concept given its internal id.
// *
// * @param id
// * @return
// */
// Object lookupConceptId(final int id);
//
// /**
// * Returns the external id of a role given its internal id.
// *
// * @param id
// * @return
// */
// Object lookupRoleId(final int id);
//
// /**
// * Returns a feature given its id.
// *
// * @param id
// * @return
// */
// String lookupFeatureId(final int id);
//
// /**
// * Indicates if a concept, identified by its internal id, is virtual or
// * named.
// *
// * @param id
// * @return
// */
// boolean isVirtualConcept(int id);
//
// /**
// * Indicates if a role, identified by its internal id, is virtual or named.
// *
// * @param id
// * @return
// */
// boolean isVirtualRole(int id);
//
// /**
// * Flags a concept as virtual.
// *
// * @param id
// * @param isVirtual
// */
// public void setVirtualConcept(int id, boolean isVirtual);
//
// }
| import au.csiro.snorocket.core.IFactory;
| /**
* Copyright (c) 2009 International Health Terminology Standards Development
* Organisation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Copyright CSIRO Australian e-Health Research Centre (http://aehrc.com).
* All rights reserved. Use is subject to license terms and conditions.
*/
package au.csiro.snorocket.core.axioms;
/**
* Normal form 3: ∃r.A ⊓ B <br>
* role r with value A subsumes B
*
* @author law223
*
*/
public final class NF3 extends NormalFormGCI implements IConjunctionQueueEntry {
/**
* Serialisation version.
*/
private static final long serialVersionUID = 1L;
final public int lhsR;
final public int lhsA;
final public int rhsB;
/**
* r.A [ B
*
* @param ontology
* @param a
* @param r
* @param b
*/
private NF3(int r, int a, int b) {
lhsR = r;
lhsA = a;
rhsB = b;
}
public IConjunctionQueueEntry getQueueEntry() {
return this;
}
public String toString() {
return lhsR + "." + lhsA + " [ " + rhsB;
}
public static NF3 getInstance(int r, int A, int B) {
return new NF3(r, A, B);
}
@Override
public int[] getConceptsInAxiom() {
return new int[] { lhsA, rhsB };
}
public int getB() {
return rhsB;
}
public int getBi() {
| // Path: snorocket-core/src/main/java/au/csiro/snorocket/core/IFactory.java
// public interface IFactory extends Serializable {
//
// /**
// * Internal id used for the top concept.
// */
// public static final int TOP_CONCEPT = 0;
//
// /**
// * Internal id used for the bottom concept.
// */
// public static final int BOTTOM_CONCEPT = 1;
//
// /**
// * Indicates if a concept, either named or virtual, exists.
// *
// * @param key
// * @return
// */
// boolean conceptExists(final Object key);
//
// /**
// * Indicates if a role, either named or virtual, exists.
// *
// * @param key
// * @return
// */
// boolean roleExists(final Object key);
//
// /**
// * Indicates if a feature exists.
// *
// * @param key
// * @return
// */
// boolean featureExists(final String key);
//
// /**
// * Returns the internal id of a concept.
// *
// * @param key
// * @return
// */
// int getConcept(final Object key);
//
// /**
// * Returns the internal id of a role.
// *
// * @param key
// * @return
// */
// int getRole(final Object key);
//
// /**
// * Returns the internal id of a feature.
// *
// * @param key
// * @return
// */
// int getFeature(final String key);
//
// /**
// * Returns the total number of concepts.
// *
// * @return
// */
// int getTotalConcepts();
//
// /**
// * Returns the total number of roles.
// *
// * @return
// */
// int getTotalRoles();
//
// /**
// * Returns the total number of features.
// *
// * @return
// */
// int getTotalFeatures();
//
// /**
// * Returns the external id of a concept given its internal id.
// *
// * @param id
// * @return
// */
// Object lookupConceptId(final int id);
//
// /**
// * Returns the external id of a role given its internal id.
// *
// * @param id
// * @return
// */
// Object lookupRoleId(final int id);
//
// /**
// * Returns a feature given its id.
// *
// * @param id
// * @return
// */
// String lookupFeatureId(final int id);
//
// /**
// * Indicates if a concept, identified by its internal id, is virtual or
// * named.
// *
// * @param id
// * @return
// */
// boolean isVirtualConcept(int id);
//
// /**
// * Indicates if a role, identified by its internal id, is virtual or named.
// *
// * @param id
// * @return
// */
// boolean isVirtualRole(int id);
//
// /**
// * Flags a concept as virtual.
// *
// * @param id
// * @param isVirtual
// */
// public void setVirtualConcept(int id, boolean isVirtual);
//
// }
// Path: snorocket-core/src/main/java/au/csiro/snorocket/core/axioms/NF3.java
import au.csiro.snorocket.core.IFactory;
/**
* Copyright (c) 2009 International Health Terminology Standards Development
* Organisation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Copyright CSIRO Australian e-Health Research Centre (http://aehrc.com).
* All rights reserved. Use is subject to license terms and conditions.
*/
package au.csiro.snorocket.core.axioms;
/**
* Normal form 3: ∃r.A ⊓ B <br>
* role r with value A subsumes B
*
* @author law223
*
*/
public final class NF3 extends NormalFormGCI implements IConjunctionQueueEntry {
/**
* Serialisation version.
*/
private static final long serialVersionUID = 1L;
final public int lhsR;
final public int lhsA;
final public int rhsB;
/**
* r.A [ B
*
* @param ontology
* @param a
* @param r
* @param b
*/
private NF3(int r, int a, int b) {
lhsR = r;
lhsA = a;
rhsB = b;
}
public IConjunctionQueueEntry getQueueEntry() {
return this;
}
public String toString() {
return lhsR + "." + lhsA + " [ " + rhsB;
}
public static NF3 getInstance(int r, int A, int B) {
return new NF3(r, A, B);
}
@Override
public int[] getConceptsInAxiom() {
return new int[] { lhsA, rhsB };
}
public int getB() {
return rhsB;
}
public int getBi() {
| return IFactory.TOP_CONCEPT;
|
aehrc/snorocket | snorocket-core/src/main/java/au/csiro/snorocket/core/IQueue.java | // Path: snorocket-core/src/main/java/au/csiro/snorocket/core/util/MonotonicCollection.java
// public class MonotonicCollection<T> implements IMonotonicCollection<T> {
//
// /**
// * Serialisation version.
// */
// private static final long serialVersionUID = 1L;
//
// // Logger
// private final static Logger log = LoggerFactory.getLogger(
// MonotonicCollection.class);
//
// public T[] data;
// private int count = 0;
//
// @SuppressWarnings("unchecked")
// public MonotonicCollection(final int size) {
// data = (T[]) new Object[size];
// }
//
// public void add(T element) {
// checkSize();
// data[count++] = element;
// }
//
// @SuppressWarnings("unchecked")
// private void checkSize() {
// if (count == data.length) {
// final int newSize = count < 134217728 ? count << 1
// : count + 10000000;
// if (log.isTraceEnabled() && count > 1024)
// log.trace(hashCode() + "\t"
// + getClass().getSimpleName() + " resize to: "
// + (newSize));
// // For SNOMED 20061230, only a couple of these grow to 2048 entries
// T[] newData = (T[]) new Object[newSize];
// System.arraycopy(data, 0, newData, 0, data.length);
// data = newData;
// }
// }
//
// public Iterator<T> iterator() {
// return new Iterator<T>() {
//
// int next = 0;
//
// public boolean hasNext() {
// return next < count;
// }
//
// public T next() {
// return hasNext() ? data[next++] : null;
// }
//
// public void remove() {
// throw new UnsupportedOperationException();
// }
//
// };
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("[");
// for (final Iterator<T> itr = iterator(); itr.hasNext();) {
// final T o = itr.next();
// sb.append(o);
// if (itr.hasNext()) {
// sb.append(", ");
// }
// }
// sb.append("]");
// return sb.toString();
// }
//
// public void addAll(MonotonicCollection<T> collection) {
// for (T element : collection) {
// add(element);
// }
// }
//
// protected T getData(int idx) {
// return data[idx];
// }
//
// public int size() {
// return count;
// }
//
// public void clear() {
// count = 0;
// }
//
// }
| import au.csiro.snorocket.core.util.MonotonicCollection;
| /**
* Copyright (c) 2009 International Health Terminology Standards Development
* Organisation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Copyright CSIRO Australian e-Health Research Centre (http://aehrc.com).
* All rights reserved. Use is subject to license terms and conditions.
*/
package au.csiro.snorocket.core;
public interface IQueue<QueueEntry> {
void add(QueueEntry o);
QueueEntry remove();
int size();
boolean isEmpty();
| // Path: snorocket-core/src/main/java/au/csiro/snorocket/core/util/MonotonicCollection.java
// public class MonotonicCollection<T> implements IMonotonicCollection<T> {
//
// /**
// * Serialisation version.
// */
// private static final long serialVersionUID = 1L;
//
// // Logger
// private final static Logger log = LoggerFactory.getLogger(
// MonotonicCollection.class);
//
// public T[] data;
// private int count = 0;
//
// @SuppressWarnings("unchecked")
// public MonotonicCollection(final int size) {
// data = (T[]) new Object[size];
// }
//
// public void add(T element) {
// checkSize();
// data[count++] = element;
// }
//
// @SuppressWarnings("unchecked")
// private void checkSize() {
// if (count == data.length) {
// final int newSize = count < 134217728 ? count << 1
// : count + 10000000;
// if (log.isTraceEnabled() && count > 1024)
// log.trace(hashCode() + "\t"
// + getClass().getSimpleName() + " resize to: "
// + (newSize));
// // For SNOMED 20061230, only a couple of these grow to 2048 entries
// T[] newData = (T[]) new Object[newSize];
// System.arraycopy(data, 0, newData, 0, data.length);
// data = newData;
// }
// }
//
// public Iterator<T> iterator() {
// return new Iterator<T>() {
//
// int next = 0;
//
// public boolean hasNext() {
// return next < count;
// }
//
// public T next() {
// return hasNext() ? data[next++] : null;
// }
//
// public void remove() {
// throw new UnsupportedOperationException();
// }
//
// };
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("[");
// for (final Iterator<T> itr = iterator(); itr.hasNext();) {
// final T o = itr.next();
// sb.append(o);
// if (itr.hasNext()) {
// sb.append(", ");
// }
// }
// sb.append("]");
// return sb.toString();
// }
//
// public void addAll(MonotonicCollection<T> collection) {
// for (T element : collection) {
// add(element);
// }
// }
//
// protected T getData(int idx) {
// return data[idx];
// }
//
// public int size() {
// return count;
// }
//
// public void clear() {
// count = 0;
// }
//
// }
// Path: snorocket-core/src/main/java/au/csiro/snorocket/core/IQueue.java
import au.csiro.snorocket.core.util.MonotonicCollection;
/**
* Copyright (c) 2009 International Health Terminology Standards Development
* Organisation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Copyright CSIRO Australian e-Health Research Centre (http://aehrc.com).
* All rights reserved. Use is subject to license terms and conditions.
*/
package au.csiro.snorocket.core;
public interface IQueue<QueueEntry> {
void add(QueueEntry o);
QueueEntry remove();
int size();
boolean isEmpty();
| void addAll(MonotonicCollection<? extends QueueEntry> queue);
|
aehrc/snorocket | snorocket-core/src/main/java/au/csiro/snorocket/core/ParseException.java | // Path: snorocket-core/src/main/java/au/csiro/snorocket/core/util/LineReader.java
// public class LineReader {
// private int lineNumber = 0;
// private BufferedReader reader;
//
// public LineReader(Reader reader) {
// this(new BufferedReader(reader));
// }
//
// public LineReader(BufferedReader bufferedReader) {
// reader = bufferedReader;
// }
//
// public String readLine() throws IOException {
// final String line = reader.readLine();
// lineNumber++;
// return line;
// }
//
// public int getLineNumber() {
// return lineNumber;
// }
// }
| import au.csiro.snorocket.core.util.LineReader;
| /**
* Copyright (c) 2009 International Health Terminology Standards Development
* Organisation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Copyright CSIRO Australian e-Health Research Centre (http://aehrc.com).
* All rights reserved. Use is subject to license terms and conditions.
*/
package au.csiro.snorocket.core;
public class ParseException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
| // Path: snorocket-core/src/main/java/au/csiro/snorocket/core/util/LineReader.java
// public class LineReader {
// private int lineNumber = 0;
// private BufferedReader reader;
//
// public LineReader(Reader reader) {
// this(new BufferedReader(reader));
// }
//
// public LineReader(BufferedReader bufferedReader) {
// reader = bufferedReader;
// }
//
// public String readLine() throws IOException {
// final String line = reader.readLine();
// lineNumber++;
// return line;
// }
//
// public int getLineNumber() {
// return lineNumber;
// }
// }
// Path: snorocket-core/src/main/java/au/csiro/snorocket/core/ParseException.java
import au.csiro.snorocket.core.util.LineReader;
/**
* Copyright (c) 2009 International Health Terminology Standards Development
* Organisation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Copyright CSIRO Australian e-Health Research Centre (http://aehrc.com).
* All rights reserved. Use is subject to license terms and conditions.
*/
package au.csiro.snorocket.core;
public class ParseException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
| public ParseException(final String message, LineReader reader) {
|
aehrc/snorocket | snorocket-core/src/main/java/au/csiro/snorocket/core/axioms/NF8.java | // Path: snorocket-core/src/main/java/au/csiro/snorocket/core/model/Datatype.java
// public class Datatype extends AbstractConcept {
//
// /**
// * Serialisation version.
// */
// private static final long serialVersionUID = 1L;
//
// private int feature;
// private Operator operator;
// private AbstractLiteral literal;
//
// /**
// *
// */
// public Datatype(int feature, Operator operator, AbstractLiteral literal) {
// this.feature = feature;
// this.operator = operator;
// this.literal = literal;
// }
//
// public int getFeature() {
// return feature;
// }
//
// public Operator getOperator() {
// return operator;
// }
//
// public AbstractLiteral getLiteral() {
// return literal;
// }
//
// @Override
// public String toString() {
// return feature + ".(" + operator + "," + literal + ")";
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + feature;
// result = prime * result + ((literal == null) ? 0 : literal.hashCode());
// result = prime * result
// + ((operator == null) ? 0 : operator.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// Datatype other = (Datatype) obj;
// if (feature != other.feature)
// return false;
// if (literal == null) {
// if (other.literal != null)
// return false;
// } else if (!literal.equals(other.literal))
// return false;
// if (operator != other.operator)
// return false;
// return true;
// }
//
// @Override
// int compareToWhenHashCodesEqual(AbstractConcept other) {
// assert hashCode() == other.hashCode();
// assert other instanceof Datatype;
//
// final Datatype otherDatatype = (Datatype) other;
//
// final int featureCompare = feature - otherDatatype.feature;
//
// if (featureCompare == 0) {
// final int operatorCompare = operator.compareTo(
// otherDatatype.operator);
// if (operatorCompare == 0) {
// return literal.toString().compareTo(otherDatatype.literal.toString());
// } else {
// return operatorCompare;
// }
// } else {
// return featureCompare;
// }
// }
//
// }
| import au.csiro.snorocket.core.model.Datatype;
| /**
* Copyright CSIRO Australian e-Health Research Centre (http://aehrc.com).
* All rights reserved. Use is subject to license terms and conditions.
*/
package au.csiro.snorocket.core.axioms;
/**
* Normal form 8. Feature f with operator op and value v subsumes B.
*
* @author Alejandro Metke
*
*/
public final class NF8 extends NormalFormGCI {
/**
* Serialisation version.
*/
private static final long serialVersionUID = 1L;
| // Path: snorocket-core/src/main/java/au/csiro/snorocket/core/model/Datatype.java
// public class Datatype extends AbstractConcept {
//
// /**
// * Serialisation version.
// */
// private static final long serialVersionUID = 1L;
//
// private int feature;
// private Operator operator;
// private AbstractLiteral literal;
//
// /**
// *
// */
// public Datatype(int feature, Operator operator, AbstractLiteral literal) {
// this.feature = feature;
// this.operator = operator;
// this.literal = literal;
// }
//
// public int getFeature() {
// return feature;
// }
//
// public Operator getOperator() {
// return operator;
// }
//
// public AbstractLiteral getLiteral() {
// return literal;
// }
//
// @Override
// public String toString() {
// return feature + ".(" + operator + "," + literal + ")";
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + feature;
// result = prime * result + ((literal == null) ? 0 : literal.hashCode());
// result = prime * result
// + ((operator == null) ? 0 : operator.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// Datatype other = (Datatype) obj;
// if (feature != other.feature)
// return false;
// if (literal == null) {
// if (other.literal != null)
// return false;
// } else if (!literal.equals(other.literal))
// return false;
// if (operator != other.operator)
// return false;
// return true;
// }
//
// @Override
// int compareToWhenHashCodesEqual(AbstractConcept other) {
// assert hashCode() == other.hashCode();
// assert other instanceof Datatype;
//
// final Datatype otherDatatype = (Datatype) other;
//
// final int featureCompare = feature - otherDatatype.feature;
//
// if (featureCompare == 0) {
// final int operatorCompare = operator.compareTo(
// otherDatatype.operator);
// if (operatorCompare == 0) {
// return literal.toString().compareTo(otherDatatype.literal.toString());
// } else {
// return operatorCompare;
// }
// } else {
// return featureCompare;
// }
// }
//
// }
// Path: snorocket-core/src/main/java/au/csiro/snorocket/core/axioms/NF8.java
import au.csiro.snorocket.core.model.Datatype;
/**
* Copyright CSIRO Australian e-Health Research Centre (http://aehrc.com).
* All rights reserved. Use is subject to license terms and conditions.
*/
package au.csiro.snorocket.core.axioms;
/**
* Normal form 8. Feature f with operator op and value v subsumes B.
*
* @author Alejandro Metke
*
*/
public final class NF8 extends NormalFormGCI {
/**
* Serialisation version.
*/
private static final long serialVersionUID = 1L;
| final public Datatype lhsD;
|
aehrc/snorocket | snorocket-core/src/test/java/au/csiro/snorocket/core/TestSnorocketReasoner.java | // Path: snorocket-core/src/main/java/au/csiro/snorocket/core/util/Utils.java
// public class Utils {
//
// public static void printTaxonomy(Node top, Node bottom, Map<String, String> idNameMap) {
// if(top.equals(bottom)) return;
// System.out.println(nodeToString(top, idNameMap));
// for(Node child : top.getChildren()) {
// printTaxonomyLevel(child, bottom, 1, idNameMap);
// }
// }
//
// private static void printTaxonomyLevel(Node root,
// Node bottom, int level, Map<String, String> idNameMap) {
// if(root.equals(bottom)) return;
// System.out.println(spaces(level)+nodeToString(root, idNameMap));
// for(Node child : root.getChildren()) {
// printTaxonomyLevel(child, bottom, level+1, idNameMap);
// }
// }
//
// private static String nodeToString(Node node, Map<String, String> idNameMap) {
// StringBuilder sb = new StringBuilder();
// sb.append("{");
// for(String concept : node.getEquivalentConcepts()) {
// sb.append(" ");
// String desc = idNameMap.get(concept);
// if(desc == null) desc = "NA";
// sb.append(desc);
// }
// sb.append(" }");
// return sb.toString();
// }
//
// public static void printTaxonomy(Node top, Node bottom) {
// for(Node child : top.getChildren()) {
// printTaxonomyLevel(child, bottom, 0);
// }
// }
//
// private static void printTaxonomyLevel(Node root, Node bottom, int level) {
// if(root.equals(bottom)) return;
// System.out.println(spaces(level)+root.toString());
// for(Node child : root.getChildren()) {
// printTaxonomyLevel(child, bottom, level+1);
// }
// }
//
// private static String spaces(int num) {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < num; i++) {
// sb.append(" ");
// }
// return sb.toString();
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import junit.framework.Assert;
import org.junit.Test;
import au.csiro.ontology.Factory;
import au.csiro.ontology.Node;
import au.csiro.ontology.Ontology;
import au.csiro.ontology.model.Axiom;
import au.csiro.ontology.model.Concept;
import au.csiro.ontology.model.ConceptInclusion;
import au.csiro.ontology.model.Conjunction;
import au.csiro.ontology.model.Existential;
import au.csiro.ontology.model.NamedConcept;
import au.csiro.ontology.model.NamedRole;
import au.csiro.ontology.model.Role;
import au.csiro.ontology.model.RoleInclusion;
import au.csiro.snorocket.core.util.Utils;
| new Existential(am, burn),
};
Concept[] rhs = {
finding,
new Existential(rg, new Conjunction(g1)),
new Existential(rg, new Conjunction(g2)),
};
Concept[] rhs2 = {
finding,
new Existential(rg, new Existential(am, fracture)),
};
Axiom[] inclusions = {
new ConceptInclusion(multi, new Conjunction(rhs)),
new ConceptInclusion(arm, limb),
new ConceptInclusion(fracfind, new Conjunction(rhs2)),
new ConceptInclusion(new Conjunction(rhs2), fracfind),
};
Set<Axiom> axioms = new HashSet<Axiom>();
for (Axiom a : inclusions) {
axioms.add(a);
}
// Classify
SnorocketReasoner sr = new SnorocketReasoner();
sr.loadAxioms(axioms);
sr.classify();
Ontology ont = sr.getClassifiedOntology();
| // Path: snorocket-core/src/main/java/au/csiro/snorocket/core/util/Utils.java
// public class Utils {
//
// public static void printTaxonomy(Node top, Node bottom, Map<String, String> idNameMap) {
// if(top.equals(bottom)) return;
// System.out.println(nodeToString(top, idNameMap));
// for(Node child : top.getChildren()) {
// printTaxonomyLevel(child, bottom, 1, idNameMap);
// }
// }
//
// private static void printTaxonomyLevel(Node root,
// Node bottom, int level, Map<String, String> idNameMap) {
// if(root.equals(bottom)) return;
// System.out.println(spaces(level)+nodeToString(root, idNameMap));
// for(Node child : root.getChildren()) {
// printTaxonomyLevel(child, bottom, level+1, idNameMap);
// }
// }
//
// private static String nodeToString(Node node, Map<String, String> idNameMap) {
// StringBuilder sb = new StringBuilder();
// sb.append("{");
// for(String concept : node.getEquivalentConcepts()) {
// sb.append(" ");
// String desc = idNameMap.get(concept);
// if(desc == null) desc = "NA";
// sb.append(desc);
// }
// sb.append(" }");
// return sb.toString();
// }
//
// public static void printTaxonomy(Node top, Node bottom) {
// for(Node child : top.getChildren()) {
// printTaxonomyLevel(child, bottom, 0);
// }
// }
//
// private static void printTaxonomyLevel(Node root, Node bottom, int level) {
// if(root.equals(bottom)) return;
// System.out.println(spaces(level)+root.toString());
// for(Node child : root.getChildren()) {
// printTaxonomyLevel(child, bottom, level+1);
// }
// }
//
// private static String spaces(int num) {
// StringBuilder sb = new StringBuilder();
// for(int i = 0; i < num; i++) {
// sb.append(" ");
// }
// return sb.toString();
// }
//
// }
// Path: snorocket-core/src/test/java/au/csiro/snorocket/core/TestSnorocketReasoner.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import junit.framework.Assert;
import org.junit.Test;
import au.csiro.ontology.Factory;
import au.csiro.ontology.Node;
import au.csiro.ontology.Ontology;
import au.csiro.ontology.model.Axiom;
import au.csiro.ontology.model.Concept;
import au.csiro.ontology.model.ConceptInclusion;
import au.csiro.ontology.model.Conjunction;
import au.csiro.ontology.model.Existential;
import au.csiro.ontology.model.NamedConcept;
import au.csiro.ontology.model.NamedRole;
import au.csiro.ontology.model.Role;
import au.csiro.ontology.model.RoleInclusion;
import au.csiro.snorocket.core.util.Utils;
new Existential(am, burn),
};
Concept[] rhs = {
finding,
new Existential(rg, new Conjunction(g1)),
new Existential(rg, new Conjunction(g2)),
};
Concept[] rhs2 = {
finding,
new Existential(rg, new Existential(am, fracture)),
};
Axiom[] inclusions = {
new ConceptInclusion(multi, new Conjunction(rhs)),
new ConceptInclusion(arm, limb),
new ConceptInclusion(fracfind, new Conjunction(rhs2)),
new ConceptInclusion(new Conjunction(rhs2), fracfind),
};
Set<Axiom> axioms = new HashSet<Axiom>();
for (Axiom a : inclusions) {
axioms.add(a);
}
// Classify
SnorocketReasoner sr = new SnorocketReasoner();
sr.loadAxioms(axioms);
sr.classify();
Ontology ont = sr.getClassifiedOntology();
| Utils.printTaxonomy(ont.getTopNode(), ont.getBottomNode());
|
aehrc/snorocket | snorocket-core/src/main/java/au/csiro/snorocket/core/axioms/RI.java | // Path: snorocket-core/src/main/java/au/csiro/snorocket/core/IFactory.java
// public interface IFactory extends Serializable {
//
// /**
// * Internal id used for the top concept.
// */
// public static final int TOP_CONCEPT = 0;
//
// /**
// * Internal id used for the bottom concept.
// */
// public static final int BOTTOM_CONCEPT = 1;
//
// /**
// * Indicates if a concept, either named or virtual, exists.
// *
// * @param key
// * @return
// */
// boolean conceptExists(final Object key);
//
// /**
// * Indicates if a role, either named or virtual, exists.
// *
// * @param key
// * @return
// */
// boolean roleExists(final Object key);
//
// /**
// * Indicates if a feature exists.
// *
// * @param key
// * @return
// */
// boolean featureExists(final String key);
//
// /**
// * Returns the internal id of a concept.
// *
// * @param key
// * @return
// */
// int getConcept(final Object key);
//
// /**
// * Returns the internal id of a role.
// *
// * @param key
// * @return
// */
// int getRole(final Object key);
//
// /**
// * Returns the internal id of a feature.
// *
// * @param key
// * @return
// */
// int getFeature(final String key);
//
// /**
// * Returns the total number of concepts.
// *
// * @return
// */
// int getTotalConcepts();
//
// /**
// * Returns the total number of roles.
// *
// * @return
// */
// int getTotalRoles();
//
// /**
// * Returns the total number of features.
// *
// * @return
// */
// int getTotalFeatures();
//
// /**
// * Returns the external id of a concept given its internal id.
// *
// * @param id
// * @return
// */
// Object lookupConceptId(final int id);
//
// /**
// * Returns the external id of a role given its internal id.
// *
// * @param id
// * @return
// */
// Object lookupRoleId(final int id);
//
// /**
// * Returns a feature given its id.
// *
// * @param id
// * @return
// */
// String lookupFeatureId(final int id);
//
// /**
// * Indicates if a concept, identified by its internal id, is virtual or
// * named.
// *
// * @param id
// * @return
// */
// boolean isVirtualConcept(int id);
//
// /**
// * Indicates if a role, identified by its internal id, is virtual or named.
// *
// * @param id
// * @return
// */
// boolean isVirtualRole(int id);
//
// /**
// * Flags a concept as virtual.
// *
// * @param id
// * @param isVirtual
// */
// public void setVirtualConcept(int id, boolean isVirtual);
//
// }
| import au.csiro.snorocket.core.IFactory;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.Arrays;
| /**
* Copyright (c) 2009 International Health Terminology Standards Development
* Organisation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Copyright CSIRO Australian e-Health Research Centre (http://aehrc.com).
* All rights reserved. Use is subject to license terms and conditions.
*/
package au.csiro.snorocket.core.axioms;
/**
*
* @param lhs
* lhs.length == 0 -> reflexive; == 1 -> role subtyping; >= 2 -> role
* composition
*
* @param rhs
*/
public class RI extends Inclusion {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final int PRIME = 31;
final private int[] lhs;
final private int rhs;
final private int hashCode;
@SuppressFBWarnings("EI_EXPOSE_REP")
public RI(final int[] lhs, final int rhs) {
assert null != lhs;
assert -1 < rhs;
this.lhs = lhs;
this.rhs = rhs;
hashCode = PRIME * (PRIME + Arrays.hashCode(this.lhs)) + this.rhs;
}
public RI(int lhs, int rhs) {
this(new int[] { lhs }, rhs);
}
@SuppressFBWarnings("EI_EXPOSE_REP")
public int[] getLhs() {
return lhs;
}
public int getRhs() {
return rhs;
}
@Override
| // Path: snorocket-core/src/main/java/au/csiro/snorocket/core/IFactory.java
// public interface IFactory extends Serializable {
//
// /**
// * Internal id used for the top concept.
// */
// public static final int TOP_CONCEPT = 0;
//
// /**
// * Internal id used for the bottom concept.
// */
// public static final int BOTTOM_CONCEPT = 1;
//
// /**
// * Indicates if a concept, either named or virtual, exists.
// *
// * @param key
// * @return
// */
// boolean conceptExists(final Object key);
//
// /**
// * Indicates if a role, either named or virtual, exists.
// *
// * @param key
// * @return
// */
// boolean roleExists(final Object key);
//
// /**
// * Indicates if a feature exists.
// *
// * @param key
// * @return
// */
// boolean featureExists(final String key);
//
// /**
// * Returns the internal id of a concept.
// *
// * @param key
// * @return
// */
// int getConcept(final Object key);
//
// /**
// * Returns the internal id of a role.
// *
// * @param key
// * @return
// */
// int getRole(final Object key);
//
// /**
// * Returns the internal id of a feature.
// *
// * @param key
// * @return
// */
// int getFeature(final String key);
//
// /**
// * Returns the total number of concepts.
// *
// * @return
// */
// int getTotalConcepts();
//
// /**
// * Returns the total number of roles.
// *
// * @return
// */
// int getTotalRoles();
//
// /**
// * Returns the total number of features.
// *
// * @return
// */
// int getTotalFeatures();
//
// /**
// * Returns the external id of a concept given its internal id.
// *
// * @param id
// * @return
// */
// Object lookupConceptId(final int id);
//
// /**
// * Returns the external id of a role given its internal id.
// *
// * @param id
// * @return
// */
// Object lookupRoleId(final int id);
//
// /**
// * Returns a feature given its id.
// *
// * @param id
// * @return
// */
// String lookupFeatureId(final int id);
//
// /**
// * Indicates if a concept, identified by its internal id, is virtual or
// * named.
// *
// * @param id
// * @return
// */
// boolean isVirtualConcept(int id);
//
// /**
// * Indicates if a role, identified by its internal id, is virtual or named.
// *
// * @param id
// * @return
// */
// boolean isVirtualRole(int id);
//
// /**
// * Flags a concept as virtual.
// *
// * @param id
// * @param isVirtual
// */
// public void setVirtualConcept(int id, boolean isVirtual);
//
// }
// Path: snorocket-core/src/main/java/au/csiro/snorocket/core/axioms/RI.java
import au.csiro.snorocket.core.IFactory;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.Arrays;
/**
* Copyright (c) 2009 International Health Terminology Standards Development
* Organisation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Copyright CSIRO Australian e-Health Research Centre (http://aehrc.com).
* All rights reserved. Use is subject to license terms and conditions.
*/
package au.csiro.snorocket.core.axioms;
/**
*
* @param lhs
* lhs.length == 0 -> reflexive; == 1 -> role subtyping; >= 2 -> role
* composition
*
* @param rhs
*/
public class RI extends Inclusion {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final int PRIME = 31;
final private int[] lhs;
final private int rhs;
final private int hashCode;
@SuppressFBWarnings("EI_EXPOSE_REP")
public RI(final int[] lhs, final int rhs) {
assert null != lhs;
assert -1 < rhs;
this.lhs = lhs;
this.rhs = rhs;
hashCode = PRIME * (PRIME + Arrays.hashCode(this.lhs)) + this.rhs;
}
public RI(int lhs, int rhs) {
this(new int[] { lhs }, rhs);
}
@SuppressFBWarnings("EI_EXPOSE_REP")
public int[] getLhs() {
return lhs;
}
public int getRhs() {
return rhs;
}
@Override
| public Inclusion[] normalise1(final IFactory factory) {
|
aehrc/snorocket | snorocket-core/src/main/java/au/csiro/snorocket/core/axioms/NF7.java | // Path: snorocket-core/src/main/java/au/csiro/snorocket/core/model/Datatype.java
// public class Datatype extends AbstractConcept {
//
// /**
// * Serialisation version.
// */
// private static final long serialVersionUID = 1L;
//
// private int feature;
// private Operator operator;
// private AbstractLiteral literal;
//
// /**
// *
// */
// public Datatype(int feature, Operator operator, AbstractLiteral literal) {
// this.feature = feature;
// this.operator = operator;
// this.literal = literal;
// }
//
// public int getFeature() {
// return feature;
// }
//
// public Operator getOperator() {
// return operator;
// }
//
// public AbstractLiteral getLiteral() {
// return literal;
// }
//
// @Override
// public String toString() {
// return feature + ".(" + operator + "," + literal + ")";
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + feature;
// result = prime * result + ((literal == null) ? 0 : literal.hashCode());
// result = prime * result
// + ((operator == null) ? 0 : operator.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// Datatype other = (Datatype) obj;
// if (feature != other.feature)
// return false;
// if (literal == null) {
// if (other.literal != null)
// return false;
// } else if (!literal.equals(other.literal))
// return false;
// if (operator != other.operator)
// return false;
// return true;
// }
//
// @Override
// int compareToWhenHashCodesEqual(AbstractConcept other) {
// assert hashCode() == other.hashCode();
// assert other instanceof Datatype;
//
// final Datatype otherDatatype = (Datatype) other;
//
// final int featureCompare = feature - otherDatatype.feature;
//
// if (featureCompare == 0) {
// final int operatorCompare = operator.compareTo(
// otherDatatype.operator);
// if (operatorCompare == 0) {
// return literal.toString().compareTo(otherDatatype.literal.toString());
// } else {
// return operatorCompare;
// }
// } else {
// return featureCompare;
// }
// }
//
// }
| import au.csiro.snorocket.core.model.Datatype;
| /**
* Copyright CSIRO Australian e-Health Research Centre (http://aehrc.com).
* All rights reserved. Use is subject to license terms and conditions.
*/
package au.csiro.snorocket.core.axioms;
/**
* Normal form 7. A subsumes feature f with operator op and value v.
*
* @author Alejandro Metke
*
*/
public final class NF7 extends NormalFormGCI implements IFeatureQueueEntry {
/**
* Serialisation version.
*/
private static final long serialVersionUID = 1L;
final public int lhsA;
| // Path: snorocket-core/src/main/java/au/csiro/snorocket/core/model/Datatype.java
// public class Datatype extends AbstractConcept {
//
// /**
// * Serialisation version.
// */
// private static final long serialVersionUID = 1L;
//
// private int feature;
// private Operator operator;
// private AbstractLiteral literal;
//
// /**
// *
// */
// public Datatype(int feature, Operator operator, AbstractLiteral literal) {
// this.feature = feature;
// this.operator = operator;
// this.literal = literal;
// }
//
// public int getFeature() {
// return feature;
// }
//
// public Operator getOperator() {
// return operator;
// }
//
// public AbstractLiteral getLiteral() {
// return literal;
// }
//
// @Override
// public String toString() {
// return feature + ".(" + operator + "," + literal + ")";
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + feature;
// result = prime * result + ((literal == null) ? 0 : literal.hashCode());
// result = prime * result
// + ((operator == null) ? 0 : operator.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// Datatype other = (Datatype) obj;
// if (feature != other.feature)
// return false;
// if (literal == null) {
// if (other.literal != null)
// return false;
// } else if (!literal.equals(other.literal))
// return false;
// if (operator != other.operator)
// return false;
// return true;
// }
//
// @Override
// int compareToWhenHashCodesEqual(AbstractConcept other) {
// assert hashCode() == other.hashCode();
// assert other instanceof Datatype;
//
// final Datatype otherDatatype = (Datatype) other;
//
// final int featureCompare = feature - otherDatatype.feature;
//
// if (featureCompare == 0) {
// final int operatorCompare = operator.compareTo(
// otherDatatype.operator);
// if (operatorCompare == 0) {
// return literal.toString().compareTo(otherDatatype.literal.toString());
// } else {
// return operatorCompare;
// }
// } else {
// return featureCompare;
// }
// }
//
// }
// Path: snorocket-core/src/main/java/au/csiro/snorocket/core/axioms/NF7.java
import au.csiro.snorocket.core.model.Datatype;
/**
* Copyright CSIRO Australian e-Health Research Centre (http://aehrc.com).
* All rights reserved. Use is subject to license terms and conditions.
*/
package au.csiro.snorocket.core.axioms;
/**
* Normal form 7. A subsumes feature f with operator op and value v.
*
* @author Alejandro Metke
*
*/
public final class NF7 extends NormalFormGCI implements IFeatureQueueEntry {
/**
* Serialisation version.
*/
private static final long serialVersionUID = 1L;
final public int lhsA;
| final public Datatype rhsD;
|
aehrc/snorocket | snorocket-core/src/main/java/au/csiro/snorocket/core/axioms/Inclusion.java | // Path: snorocket-core/src/main/java/au/csiro/snorocket/core/IFactory.java
// public interface IFactory extends Serializable {
//
// /**
// * Internal id used for the top concept.
// */
// public static final int TOP_CONCEPT = 0;
//
// /**
// * Internal id used for the bottom concept.
// */
// public static final int BOTTOM_CONCEPT = 1;
//
// /**
// * Indicates if a concept, either named or virtual, exists.
// *
// * @param key
// * @return
// */
// boolean conceptExists(final Object key);
//
// /**
// * Indicates if a role, either named or virtual, exists.
// *
// * @param key
// * @return
// */
// boolean roleExists(final Object key);
//
// /**
// * Indicates if a feature exists.
// *
// * @param key
// * @return
// */
// boolean featureExists(final String key);
//
// /**
// * Returns the internal id of a concept.
// *
// * @param key
// * @return
// */
// int getConcept(final Object key);
//
// /**
// * Returns the internal id of a role.
// *
// * @param key
// * @return
// */
// int getRole(final Object key);
//
// /**
// * Returns the internal id of a feature.
// *
// * @param key
// * @return
// */
// int getFeature(final String key);
//
// /**
// * Returns the total number of concepts.
// *
// * @return
// */
// int getTotalConcepts();
//
// /**
// * Returns the total number of roles.
// *
// * @return
// */
// int getTotalRoles();
//
// /**
// * Returns the total number of features.
// *
// * @return
// */
// int getTotalFeatures();
//
// /**
// * Returns the external id of a concept given its internal id.
// *
// * @param id
// * @return
// */
// Object lookupConceptId(final int id);
//
// /**
// * Returns the external id of a role given its internal id.
// *
// * @param id
// * @return
// */
// Object lookupRoleId(final int id);
//
// /**
// * Returns a feature given its id.
// *
// * @param id
// * @return
// */
// String lookupFeatureId(final int id);
//
// /**
// * Indicates if a concept, identified by its internal id, is virtual or
// * named.
// *
// * @param id
// * @return
// */
// boolean isVirtualConcept(int id);
//
// /**
// * Indicates if a role, identified by its internal id, is virtual or named.
// *
// * @param id
// * @return
// */
// boolean isVirtualRole(int id);
//
// /**
// * Flags a concept as virtual.
// *
// * @param id
// * @param isVirtual
// */
// public void setVirtualConcept(int id, boolean isVirtual);
//
// }
| import au.csiro.snorocket.core.IFactory;
import java.io.Serializable;
| /**
* Copyright (c) 2009 International Health Terminology Standards Development
* Organisation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Copyright CSIRO Australian e-Health Research Centre (http://aehrc.com).
* All rights reserved. Use is subject to license terms and conditions.
*/
package au.csiro.snorocket.core.axioms;
/**
* This class represents an abstract axiom that is not (necessarily) normalised.
*
* @author Alejandro Metke
*
*/
abstract public class Inclusion implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Runs the first phase in the normalisation process (see Pushing the EL
* Envelope).
*
* @param factory
* @return
*/
| // Path: snorocket-core/src/main/java/au/csiro/snorocket/core/IFactory.java
// public interface IFactory extends Serializable {
//
// /**
// * Internal id used for the top concept.
// */
// public static final int TOP_CONCEPT = 0;
//
// /**
// * Internal id used for the bottom concept.
// */
// public static final int BOTTOM_CONCEPT = 1;
//
// /**
// * Indicates if a concept, either named or virtual, exists.
// *
// * @param key
// * @return
// */
// boolean conceptExists(final Object key);
//
// /**
// * Indicates if a role, either named or virtual, exists.
// *
// * @param key
// * @return
// */
// boolean roleExists(final Object key);
//
// /**
// * Indicates if a feature exists.
// *
// * @param key
// * @return
// */
// boolean featureExists(final String key);
//
// /**
// * Returns the internal id of a concept.
// *
// * @param key
// * @return
// */
// int getConcept(final Object key);
//
// /**
// * Returns the internal id of a role.
// *
// * @param key
// * @return
// */
// int getRole(final Object key);
//
// /**
// * Returns the internal id of a feature.
// *
// * @param key
// * @return
// */
// int getFeature(final String key);
//
// /**
// * Returns the total number of concepts.
// *
// * @return
// */
// int getTotalConcepts();
//
// /**
// * Returns the total number of roles.
// *
// * @return
// */
// int getTotalRoles();
//
// /**
// * Returns the total number of features.
// *
// * @return
// */
// int getTotalFeatures();
//
// /**
// * Returns the external id of a concept given its internal id.
// *
// * @param id
// * @return
// */
// Object lookupConceptId(final int id);
//
// /**
// * Returns the external id of a role given its internal id.
// *
// * @param id
// * @return
// */
// Object lookupRoleId(final int id);
//
// /**
// * Returns a feature given its id.
// *
// * @param id
// * @return
// */
// String lookupFeatureId(final int id);
//
// /**
// * Indicates if a concept, identified by its internal id, is virtual or
// * named.
// *
// * @param id
// * @return
// */
// boolean isVirtualConcept(int id);
//
// /**
// * Indicates if a role, identified by its internal id, is virtual or named.
// *
// * @param id
// * @return
// */
// boolean isVirtualRole(int id);
//
// /**
// * Flags a concept as virtual.
// *
// * @param id
// * @param isVirtual
// */
// public void setVirtualConcept(int id, boolean isVirtual);
//
// }
// Path: snorocket-core/src/main/java/au/csiro/snorocket/core/axioms/Inclusion.java
import au.csiro.snorocket.core.IFactory;
import java.io.Serializable;
/**
* Copyright (c) 2009 International Health Terminology Standards Development
* Organisation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Copyright CSIRO Australian e-Health Research Centre (http://aehrc.com).
* All rights reserved. Use is subject to license terms and conditions.
*/
package au.csiro.snorocket.core.axioms;
/**
* This class represents an abstract axiom that is not (necessarily) normalised.
*
* @author Alejandro Metke
*
*/
abstract public class Inclusion implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Runs the first phase in the normalisation process (see Pushing the EL
* Envelope).
*
* @param factory
* @return
*/
| abstract public Inclusion[] normalise1(IFactory factory);
|
aehrc/snorocket | snorocket-core/src/main/java/au/csiro/snorocket/core/axioms/NF1a.java | // Path: snorocket-core/src/main/java/au/csiro/snorocket/core/IFactory.java
// public interface IFactory extends Serializable {
//
// /**
// * Internal id used for the top concept.
// */
// public static final int TOP_CONCEPT = 0;
//
// /**
// * Internal id used for the bottom concept.
// */
// public static final int BOTTOM_CONCEPT = 1;
//
// /**
// * Indicates if a concept, either named or virtual, exists.
// *
// * @param key
// * @return
// */
// boolean conceptExists(final Object key);
//
// /**
// * Indicates if a role, either named or virtual, exists.
// *
// * @param key
// * @return
// */
// boolean roleExists(final Object key);
//
// /**
// * Indicates if a feature exists.
// *
// * @param key
// * @return
// */
// boolean featureExists(final String key);
//
// /**
// * Returns the internal id of a concept.
// *
// * @param key
// * @return
// */
// int getConcept(final Object key);
//
// /**
// * Returns the internal id of a role.
// *
// * @param key
// * @return
// */
// int getRole(final Object key);
//
// /**
// * Returns the internal id of a feature.
// *
// * @param key
// * @return
// */
// int getFeature(final String key);
//
// /**
// * Returns the total number of concepts.
// *
// * @return
// */
// int getTotalConcepts();
//
// /**
// * Returns the total number of roles.
// *
// * @return
// */
// int getTotalRoles();
//
// /**
// * Returns the total number of features.
// *
// * @return
// */
// int getTotalFeatures();
//
// /**
// * Returns the external id of a concept given its internal id.
// *
// * @param id
// * @return
// */
// Object lookupConceptId(final int id);
//
// /**
// * Returns the external id of a role given its internal id.
// *
// * @param id
// * @return
// */
// Object lookupRoleId(final int id);
//
// /**
// * Returns a feature given its id.
// *
// * @param id
// * @return
// */
// String lookupFeatureId(final int id);
//
// /**
// * Indicates if a concept, identified by its internal id, is virtual or
// * named.
// *
// * @param id
// * @return
// */
// boolean isVirtualConcept(int id);
//
// /**
// * Indicates if a role, identified by its internal id, is virtual or named.
// *
// * @param id
// * @return
// */
// boolean isVirtualRole(int id);
//
// /**
// * Flags a concept as virtual.
// *
// * @param id
// * @param isVirtual
// */
// public void setVirtualConcept(int id, boolean isVirtual);
//
// }
| import au.csiro.snorocket.core.IFactory;
| /**
* Copyright (c) 2009 International Health Terminology Standards Development
* Organisation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Copyright CSIRO Australian e-Health Research Centre (http://aehrc.com).
* All rights reserved. Use is subject to license terms and conditions.
*/
package au.csiro.snorocket.core.axioms;
/**
* Normal form 1: A<sub>1</sub> ⊑ B <br>
* A<sub>1</sub> subsumes B
*
* @author Michael Lawley
*
*/
public final class NF1a extends NormalFormGCI implements IConjunctionQueueEntry {
/**
* Serialisation version.
*/
private static final long serialVersionUID = 2L;
final private int lhsA;
final private int rhsB;
private NF1a(final int lhs, final int rhs) {
rhsB = rhs;
lhsA = lhs;
}
static public NF1a getInstance(final int lhs, final int rhs) {
return new NF1a(lhs, rhs);
}
public IConjunctionQueueEntry getQueueEntry() {
return this;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(lhsA);
// sb.append(" \u2291 ");
sb.append(" [ ");
sb.append(rhsB);
return sb.toString();
}
public int getB() {
return rhsB;
}
public int getBi() {
| // Path: snorocket-core/src/main/java/au/csiro/snorocket/core/IFactory.java
// public interface IFactory extends Serializable {
//
// /**
// * Internal id used for the top concept.
// */
// public static final int TOP_CONCEPT = 0;
//
// /**
// * Internal id used for the bottom concept.
// */
// public static final int BOTTOM_CONCEPT = 1;
//
// /**
// * Indicates if a concept, either named or virtual, exists.
// *
// * @param key
// * @return
// */
// boolean conceptExists(final Object key);
//
// /**
// * Indicates if a role, either named or virtual, exists.
// *
// * @param key
// * @return
// */
// boolean roleExists(final Object key);
//
// /**
// * Indicates if a feature exists.
// *
// * @param key
// * @return
// */
// boolean featureExists(final String key);
//
// /**
// * Returns the internal id of a concept.
// *
// * @param key
// * @return
// */
// int getConcept(final Object key);
//
// /**
// * Returns the internal id of a role.
// *
// * @param key
// * @return
// */
// int getRole(final Object key);
//
// /**
// * Returns the internal id of a feature.
// *
// * @param key
// * @return
// */
// int getFeature(final String key);
//
// /**
// * Returns the total number of concepts.
// *
// * @return
// */
// int getTotalConcepts();
//
// /**
// * Returns the total number of roles.
// *
// * @return
// */
// int getTotalRoles();
//
// /**
// * Returns the total number of features.
// *
// * @return
// */
// int getTotalFeatures();
//
// /**
// * Returns the external id of a concept given its internal id.
// *
// * @param id
// * @return
// */
// Object lookupConceptId(final int id);
//
// /**
// * Returns the external id of a role given its internal id.
// *
// * @param id
// * @return
// */
// Object lookupRoleId(final int id);
//
// /**
// * Returns a feature given its id.
// *
// * @param id
// * @return
// */
// String lookupFeatureId(final int id);
//
// /**
// * Indicates if a concept, identified by its internal id, is virtual or
// * named.
// *
// * @param id
// * @return
// */
// boolean isVirtualConcept(int id);
//
// /**
// * Indicates if a role, identified by its internal id, is virtual or named.
// *
// * @param id
// * @return
// */
// boolean isVirtualRole(int id);
//
// /**
// * Flags a concept as virtual.
// *
// * @param id
// * @param isVirtual
// */
// public void setVirtualConcept(int id, boolean isVirtual);
//
// }
// Path: snorocket-core/src/main/java/au/csiro/snorocket/core/axioms/NF1a.java
import au.csiro.snorocket.core.IFactory;
/**
* Copyright (c) 2009 International Health Terminology Standards Development
* Organisation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Copyright CSIRO Australian e-Health Research Centre (http://aehrc.com).
* All rights reserved. Use is subject to license terms and conditions.
*/
package au.csiro.snorocket.core.axioms;
/**
* Normal form 1: A<sub>1</sub> ⊑ B <br>
* A<sub>1</sub> subsumes B
*
* @author Michael Lawley
*
*/
public final class NF1a extends NormalFormGCI implements IConjunctionQueueEntry {
/**
* Serialisation version.
*/
private static final long serialVersionUID = 2L;
final private int lhsA;
final private int rhsB;
private NF1a(final int lhs, final int rhs) {
rhsB = rhs;
lhsA = lhs;
}
static public NF1a getInstance(final int lhs, final int rhs) {
return new NF1a(lhs, rhs);
}
public IConjunctionQueueEntry getQueueEntry() {
return this;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(lhsA);
// sb.append(" \u2291 ");
sb.append(" [ ");
sb.append(rhsB);
return sb.toString();
}
public int getB() {
return rhsB;
}
public int getBi() {
| return IFactory.TOP_CONCEPT;
|
aehrc/snorocket | snorocket-core/src/main/java/au/csiro/snorocket/core/QueueImpl.java | // Path: snorocket-core/src/main/java/au/csiro/snorocket/core/util/MonotonicCollection.java
// public class MonotonicCollection<T> implements IMonotonicCollection<T> {
//
// /**
// * Serialisation version.
// */
// private static final long serialVersionUID = 1L;
//
// // Logger
// private final static Logger log = LoggerFactory.getLogger(
// MonotonicCollection.class);
//
// public T[] data;
// private int count = 0;
//
// @SuppressWarnings("unchecked")
// public MonotonicCollection(final int size) {
// data = (T[]) new Object[size];
// }
//
// public void add(T element) {
// checkSize();
// data[count++] = element;
// }
//
// @SuppressWarnings("unchecked")
// private void checkSize() {
// if (count == data.length) {
// final int newSize = count < 134217728 ? count << 1
// : count + 10000000;
// if (log.isTraceEnabled() && count > 1024)
// log.trace(hashCode() + "\t"
// + getClass().getSimpleName() + " resize to: "
// + (newSize));
// // For SNOMED 20061230, only a couple of these grow to 2048 entries
// T[] newData = (T[]) new Object[newSize];
// System.arraycopy(data, 0, newData, 0, data.length);
// data = newData;
// }
// }
//
// public Iterator<T> iterator() {
// return new Iterator<T>() {
//
// int next = 0;
//
// public boolean hasNext() {
// return next < count;
// }
//
// public T next() {
// return hasNext() ? data[next++] : null;
// }
//
// public void remove() {
// throw new UnsupportedOperationException();
// }
//
// };
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("[");
// for (final Iterator<T> itr = iterator(); itr.hasNext();) {
// final T o = itr.next();
// sb.append(o);
// if (itr.hasNext()) {
// sb.append(", ");
// }
// }
// sb.append("]");
// return sb.toString();
// }
//
// public void addAll(MonotonicCollection<T> collection) {
// for (T element : collection) {
// add(element);
// }
// }
//
// protected T getData(int idx) {
// return data[idx];
// }
//
// public int size() {
// return count;
// }
//
// public void clear() {
// count = 0;
// }
//
// }
| import au.csiro.snorocket.core.util.MonotonicCollection;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.Serializable;
| /**
* Copyright (c) 2009 International Health Terminology Standards Development
* Organisation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Copyright CSIRO Australian e-Health Research Centre (http://aehrc.com).
* All rights reserved. Use is subject to license terms and conditions.
*/
package au.csiro.snorocket.core;
/**
* A LIFO queue. Used to be a LIFO set to avoid duplicate entries but,
* <ol>
* <li>this has huge space overheads, and</li>
* <li>empirical evidence indicates they don't happen and thus this is redundant
* effort</li>
* </ol>
*
* @author Michael Lawley
*
* @param <QueueEntry>
*/
public final class QueueImpl<QueueEntry> implements IQueue<QueueEntry>, Serializable {
/**
* Serialisation version.
*/
private static final long serialVersionUID = 1L;
private static final int DEFAULT_ALLOC_SIZE = 4;
private static final Object[] EMPTY = {};
/**
* Index of next free slot in items array.
*/
protected int counter = 0;
protected QueueEntry[] items;
static int number = 0;
/**
* See chapter 8 of http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf
* for why we need the typeToken parameter
*
* @param typeToken
*/
@SuppressFBWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
@SuppressWarnings("unchecked")
public QueueImpl(Class<QueueEntry> typeToken) {
items = (QueueEntry[]) EMPTY;
number++;
}
public void add(QueueEntry entry) {
checkSize(1);
items[counter++] = entry;
}
| // Path: snorocket-core/src/main/java/au/csiro/snorocket/core/util/MonotonicCollection.java
// public class MonotonicCollection<T> implements IMonotonicCollection<T> {
//
// /**
// * Serialisation version.
// */
// private static final long serialVersionUID = 1L;
//
// // Logger
// private final static Logger log = LoggerFactory.getLogger(
// MonotonicCollection.class);
//
// public T[] data;
// private int count = 0;
//
// @SuppressWarnings("unchecked")
// public MonotonicCollection(final int size) {
// data = (T[]) new Object[size];
// }
//
// public void add(T element) {
// checkSize();
// data[count++] = element;
// }
//
// @SuppressWarnings("unchecked")
// private void checkSize() {
// if (count == data.length) {
// final int newSize = count < 134217728 ? count << 1
// : count + 10000000;
// if (log.isTraceEnabled() && count > 1024)
// log.trace(hashCode() + "\t"
// + getClass().getSimpleName() + " resize to: "
// + (newSize));
// // For SNOMED 20061230, only a couple of these grow to 2048 entries
// T[] newData = (T[]) new Object[newSize];
// System.arraycopy(data, 0, newData, 0, data.length);
// data = newData;
// }
// }
//
// public Iterator<T> iterator() {
// return new Iterator<T>() {
//
// int next = 0;
//
// public boolean hasNext() {
// return next < count;
// }
//
// public T next() {
// return hasNext() ? data[next++] : null;
// }
//
// public void remove() {
// throw new UnsupportedOperationException();
// }
//
// };
// }
//
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("[");
// for (final Iterator<T> itr = iterator(); itr.hasNext();) {
// final T o = itr.next();
// sb.append(o);
// if (itr.hasNext()) {
// sb.append(", ");
// }
// }
// sb.append("]");
// return sb.toString();
// }
//
// public void addAll(MonotonicCollection<T> collection) {
// for (T element : collection) {
// add(element);
// }
// }
//
// protected T getData(int idx) {
// return data[idx];
// }
//
// public int size() {
// return count;
// }
//
// public void clear() {
// count = 0;
// }
//
// }
// Path: snorocket-core/src/main/java/au/csiro/snorocket/core/QueueImpl.java
import au.csiro.snorocket.core.util.MonotonicCollection;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.Serializable;
/**
* Copyright (c) 2009 International Health Terminology Standards Development
* Organisation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Copyright CSIRO Australian e-Health Research Centre (http://aehrc.com).
* All rights reserved. Use is subject to license terms and conditions.
*/
package au.csiro.snorocket.core;
/**
* A LIFO queue. Used to be a LIFO set to avoid duplicate entries but,
* <ol>
* <li>this has huge space overheads, and</li>
* <li>empirical evidence indicates they don't happen and thus this is redundant
* effort</li>
* </ol>
*
* @author Michael Lawley
*
* @param <QueueEntry>
*/
public final class QueueImpl<QueueEntry> implements IQueue<QueueEntry>, Serializable {
/**
* Serialisation version.
*/
private static final long serialVersionUID = 1L;
private static final int DEFAULT_ALLOC_SIZE = 4;
private static final Object[] EMPTY = {};
/**
* Index of next free slot in items array.
*/
protected int counter = 0;
protected QueueEntry[] items;
static int number = 0;
/**
* See chapter 8 of http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf
* for why we need the typeToken parameter
*
* @param typeToken
*/
@SuppressFBWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
@SuppressWarnings("unchecked")
public QueueImpl(Class<QueueEntry> typeToken) {
items = (QueueEntry[]) EMPTY;
number++;
}
public void add(QueueEntry entry) {
checkSize(1);
items[counter++] = entry;
}
| public void addAll(MonotonicCollection<? extends QueueEntry> queue) {
|
HagertyRobotics/ftc_app_networked_simulator | PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/USBMotorControllerDevice.java | // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/MotorSimData.java
// @XmlRootElement(name="MotorSimData")
// @XmlAccessorType(XmlAccessType.NONE)
// public class MotorSimData extends SimData {
//
// float mMotorSpeed=0;
// boolean mMotorFloatMode=false;
//
// public MotorSimData() {
// super();
// construct();
// }
//
// @Override
// protected void construct() {
// //System.out.println("Building Legacy Motor SimData");
// }
//
// public float getMotorSpeed() {
// lock.readLock().lock();
// try {
// return mMotorSpeed;
// } finally {
// lock.readLock().unlock();
// }
// }
//
// public boolean getMotorFloatMode() {
// return mMotorFloatMode;
// }
//
// public void setMotorSpeed(byte speedByte) {
// lock.writeLock().lock();
// try {
// if (speedByte == (byte)0x80) {
// mMotorFloatMode = true;
// mMotorSpeed=0.0f;
// } else {
// mMotorSpeed = (float)speedByte/100.0f;
// }
// } finally {
// lock.writeLock().unlock();
// }
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/SimData.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class SimData {
// public final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
//
// protected StringProperty mName = null;
//
// public SimData() {
// mName = new SimpleStringProperty("");
// }
//
// // Do subclass level processing in this method
// protected abstract void construct();
//
//
// public String getName() {
// return mName.getValue();
// }
//
// @XmlElement
// public void setName(String name) {
// mName.set(name);
// }
// }
| import org.ftccommunity.simulator.data.MotorSimData;
import org.ftccommunity.simulator.data.SimData;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlRootElement;
import javafx.geometry.Insets;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text; | package org.ftccommunity.simulator.modules.devices;
@XmlRootElement(name="USBMotorControllerDevice")
@XmlAccessorType(XmlAccessType.NONE)
public class USBMotorControllerDevice extends Device {
// GUI stuff for the Debug windows
public Label mMotor1SpeedDebugLabel;
public Label mMotor2SpeedDebugLabel;
/**
* Default constructor.
*/
public USBMotorControllerDevice() {
super(DeviceType.USB_MOTOR); | // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/MotorSimData.java
// @XmlRootElement(name="MotorSimData")
// @XmlAccessorType(XmlAccessType.NONE)
// public class MotorSimData extends SimData {
//
// float mMotorSpeed=0;
// boolean mMotorFloatMode=false;
//
// public MotorSimData() {
// super();
// construct();
// }
//
// @Override
// protected void construct() {
// //System.out.println("Building Legacy Motor SimData");
// }
//
// public float getMotorSpeed() {
// lock.readLock().lock();
// try {
// return mMotorSpeed;
// } finally {
// lock.readLock().unlock();
// }
// }
//
// public boolean getMotorFloatMode() {
// return mMotorFloatMode;
// }
//
// public void setMotorSpeed(byte speedByte) {
// lock.writeLock().lock();
// try {
// if (speedByte == (byte)0x80) {
// mMotorFloatMode = true;
// mMotorSpeed=0.0f;
// } else {
// mMotorSpeed = (float)speedByte/100.0f;
// }
// } finally {
// lock.writeLock().unlock();
// }
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/SimData.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class SimData {
// public final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
//
// protected StringProperty mName = null;
//
// public SimData() {
// mName = new SimpleStringProperty("");
// }
//
// // Do subclass level processing in this method
// protected abstract void construct();
//
//
// public String getName() {
// return mName.getValue();
// }
//
// @XmlElement
// public void setName(String name) {
// mName.set(name);
// }
// }
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/USBMotorControllerDevice.java
import org.ftccommunity.simulator.data.MotorSimData;
import org.ftccommunity.simulator.data.SimData;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlRootElement;
import javafx.geometry.Insets;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
package org.ftccommunity.simulator.modules.devices;
@XmlRootElement(name="USBMotorControllerDevice")
@XmlAccessorType(XmlAccessType.NONE)
public class USBMotorControllerDevice extends Device {
// GUI stuff for the Debug windows
public Label mMotor1SpeedDebugLabel;
public Label mMotor2SpeedDebugLabel;
/**
* Default constructor.
*/
public USBMotorControllerDevice() {
super(DeviceType.USB_MOTOR); | mSimData = new SimData[2]; |
HagertyRobotics/ftc_app_networked_simulator | PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/USBMotorControllerDevice.java | // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/MotorSimData.java
// @XmlRootElement(name="MotorSimData")
// @XmlAccessorType(XmlAccessType.NONE)
// public class MotorSimData extends SimData {
//
// float mMotorSpeed=0;
// boolean mMotorFloatMode=false;
//
// public MotorSimData() {
// super();
// construct();
// }
//
// @Override
// protected void construct() {
// //System.out.println("Building Legacy Motor SimData");
// }
//
// public float getMotorSpeed() {
// lock.readLock().lock();
// try {
// return mMotorSpeed;
// } finally {
// lock.readLock().unlock();
// }
// }
//
// public boolean getMotorFloatMode() {
// return mMotorFloatMode;
// }
//
// public void setMotorSpeed(byte speedByte) {
// lock.writeLock().lock();
// try {
// if (speedByte == (byte)0x80) {
// mMotorFloatMode = true;
// mMotorSpeed=0.0f;
// } else {
// mMotorSpeed = (float)speedByte/100.0f;
// }
// } finally {
// lock.writeLock().unlock();
// }
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/SimData.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class SimData {
// public final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
//
// protected StringProperty mName = null;
//
// public SimData() {
// mName = new SimpleStringProperty("");
// }
//
// // Do subclass level processing in this method
// protected abstract void construct();
//
//
// public String getName() {
// return mName.getValue();
// }
//
// @XmlElement
// public void setName(String name) {
// mName.set(name);
// }
// }
| import org.ftccommunity.simulator.data.MotorSimData;
import org.ftccommunity.simulator.data.SimData;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlRootElement;
import javafx.geometry.Insets;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text; | package org.ftccommunity.simulator.modules.devices;
@XmlRootElement(name="USBMotorControllerDevice")
@XmlAccessorType(XmlAccessType.NONE)
public class USBMotorControllerDevice extends Device {
// GUI stuff for the Debug windows
public Label mMotor1SpeedDebugLabel;
public Label mMotor2SpeedDebugLabel;
/**
* Default constructor.
*/
public USBMotorControllerDevice() {
super(DeviceType.USB_MOTOR);
mSimData = new SimData[2]; | // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/MotorSimData.java
// @XmlRootElement(name="MotorSimData")
// @XmlAccessorType(XmlAccessType.NONE)
// public class MotorSimData extends SimData {
//
// float mMotorSpeed=0;
// boolean mMotorFloatMode=false;
//
// public MotorSimData() {
// super();
// construct();
// }
//
// @Override
// protected void construct() {
// //System.out.println("Building Legacy Motor SimData");
// }
//
// public float getMotorSpeed() {
// lock.readLock().lock();
// try {
// return mMotorSpeed;
// } finally {
// lock.readLock().unlock();
// }
// }
//
// public boolean getMotorFloatMode() {
// return mMotorFloatMode;
// }
//
// public void setMotorSpeed(byte speedByte) {
// lock.writeLock().lock();
// try {
// if (speedByte == (byte)0x80) {
// mMotorFloatMode = true;
// mMotorSpeed=0.0f;
// } else {
// mMotorSpeed = (float)speedByte/100.0f;
// }
// } finally {
// lock.writeLock().unlock();
// }
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/SimData.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class SimData {
// public final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
//
// protected StringProperty mName = null;
//
// public SimData() {
// mName = new SimpleStringProperty("");
// }
//
// // Do subclass level processing in this method
// protected abstract void construct();
//
//
// public String getName() {
// return mName.getValue();
// }
//
// @XmlElement
// public void setName(String name) {
// mName.set(name);
// }
// }
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/USBMotorControllerDevice.java
import org.ftccommunity.simulator.data.MotorSimData;
import org.ftccommunity.simulator.data.SimData;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlRootElement;
import javafx.geometry.Insets;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
package org.ftccommunity.simulator.modules.devices;
@XmlRootElement(name="USBMotorControllerDevice")
@XmlAccessorType(XmlAccessType.NONE)
public class USBMotorControllerDevice extends Device {
// GUI stuff for the Debug windows
public Label mMotor1SpeedDebugLabel;
public Label mMotor2SpeedDebugLabel;
/**
* Default constructor.
*/
public USBMotorControllerDevice() {
super(DeviceType.USB_MOTOR);
mSimData = new SimData[2]; | mSimData[0] = new MotorSimData(); // Add 1st motor |
HagertyRobotics/ftc_app_networked_simulator | PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/TetrixMotorControllerDevice.java | // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/MotorSimData.java
// @XmlRootElement(name="MotorSimData")
// @XmlAccessorType(XmlAccessType.NONE)
// public class MotorSimData extends SimData {
//
// float mMotorSpeed=0;
// boolean mMotorFloatMode=false;
//
// public MotorSimData() {
// super();
// construct();
// }
//
// @Override
// protected void construct() {
// //System.out.println("Building Legacy Motor SimData");
// }
//
// public float getMotorSpeed() {
// lock.readLock().lock();
// try {
// return mMotorSpeed;
// } finally {
// lock.readLock().unlock();
// }
// }
//
// public boolean getMotorFloatMode() {
// return mMotorFloatMode;
// }
//
// public void setMotorSpeed(byte speedByte) {
// lock.writeLock().lock();
// try {
// if (speedByte == (byte)0x80) {
// mMotorFloatMode = true;
// mMotorSpeed=0.0f;
// } else {
// mMotorSpeed = (float)speedByte/100.0f;
// }
// } finally {
// lock.writeLock().unlock();
// }
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/SimData.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class SimData {
// public final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
//
// protected StringProperty mName = null;
//
// public SimData() {
// mName = new SimpleStringProperty("");
// }
//
// // Do subclass level processing in this method
// protected abstract void construct();
//
//
// public String getName() {
// return mName.getValue();
// }
//
// @XmlElement
// public void setName(String name) {
// mName.set(name);
// }
// }
| import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlRootElement;
import org.ftccommunity.simulator.data.MotorSimData;
import org.ftccommunity.simulator.data.SimData;
import javafx.geometry.Insets;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text; | package org.ftccommunity.simulator.modules.devices;
@XmlRootElement(name="TetrixMotorControllerDevice")
@XmlAccessorType(XmlAccessType.NONE)
public class TetrixMotorControllerDevice extends Device {
// GUI stuff for the Debug windows
public Label mMotor1SpeedDebugLabel;
public Label mMotor2SpeedDebugLabel;
/**
* Default constructor.
*/
public TetrixMotorControllerDevice() {
super(DeviceType.TETRIX_MOTOR); | // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/MotorSimData.java
// @XmlRootElement(name="MotorSimData")
// @XmlAccessorType(XmlAccessType.NONE)
// public class MotorSimData extends SimData {
//
// float mMotorSpeed=0;
// boolean mMotorFloatMode=false;
//
// public MotorSimData() {
// super();
// construct();
// }
//
// @Override
// protected void construct() {
// //System.out.println("Building Legacy Motor SimData");
// }
//
// public float getMotorSpeed() {
// lock.readLock().lock();
// try {
// return mMotorSpeed;
// } finally {
// lock.readLock().unlock();
// }
// }
//
// public boolean getMotorFloatMode() {
// return mMotorFloatMode;
// }
//
// public void setMotorSpeed(byte speedByte) {
// lock.writeLock().lock();
// try {
// if (speedByte == (byte)0x80) {
// mMotorFloatMode = true;
// mMotorSpeed=0.0f;
// } else {
// mMotorSpeed = (float)speedByte/100.0f;
// }
// } finally {
// lock.writeLock().unlock();
// }
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/SimData.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class SimData {
// public final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
//
// protected StringProperty mName = null;
//
// public SimData() {
// mName = new SimpleStringProperty("");
// }
//
// // Do subclass level processing in this method
// protected abstract void construct();
//
//
// public String getName() {
// return mName.getValue();
// }
//
// @XmlElement
// public void setName(String name) {
// mName.set(name);
// }
// }
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/TetrixMotorControllerDevice.java
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlRootElement;
import org.ftccommunity.simulator.data.MotorSimData;
import org.ftccommunity.simulator.data.SimData;
import javafx.geometry.Insets;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
package org.ftccommunity.simulator.modules.devices;
@XmlRootElement(name="TetrixMotorControllerDevice")
@XmlAccessorType(XmlAccessType.NONE)
public class TetrixMotorControllerDevice extends Device {
// GUI stuff for the Debug windows
public Label mMotor1SpeedDebugLabel;
public Label mMotor2SpeedDebugLabel;
/**
* Default constructor.
*/
public TetrixMotorControllerDevice() {
super(DeviceType.TETRIX_MOTOR); | mSimData = new SimData[2]; |
HagertyRobotics/ftc_app_networked_simulator | PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/TetrixMotorControllerDevice.java | // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/MotorSimData.java
// @XmlRootElement(name="MotorSimData")
// @XmlAccessorType(XmlAccessType.NONE)
// public class MotorSimData extends SimData {
//
// float mMotorSpeed=0;
// boolean mMotorFloatMode=false;
//
// public MotorSimData() {
// super();
// construct();
// }
//
// @Override
// protected void construct() {
// //System.out.println("Building Legacy Motor SimData");
// }
//
// public float getMotorSpeed() {
// lock.readLock().lock();
// try {
// return mMotorSpeed;
// } finally {
// lock.readLock().unlock();
// }
// }
//
// public boolean getMotorFloatMode() {
// return mMotorFloatMode;
// }
//
// public void setMotorSpeed(byte speedByte) {
// lock.writeLock().lock();
// try {
// if (speedByte == (byte)0x80) {
// mMotorFloatMode = true;
// mMotorSpeed=0.0f;
// } else {
// mMotorSpeed = (float)speedByte/100.0f;
// }
// } finally {
// lock.writeLock().unlock();
// }
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/SimData.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class SimData {
// public final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
//
// protected StringProperty mName = null;
//
// public SimData() {
// mName = new SimpleStringProperty("");
// }
//
// // Do subclass level processing in this method
// protected abstract void construct();
//
//
// public String getName() {
// return mName.getValue();
// }
//
// @XmlElement
// public void setName(String name) {
// mName.set(name);
// }
// }
| import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlRootElement;
import org.ftccommunity.simulator.data.MotorSimData;
import org.ftccommunity.simulator.data.SimData;
import javafx.geometry.Insets;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text; | package org.ftccommunity.simulator.modules.devices;
@XmlRootElement(name="TetrixMotorControllerDevice")
@XmlAccessorType(XmlAccessType.NONE)
public class TetrixMotorControllerDevice extends Device {
// GUI stuff for the Debug windows
public Label mMotor1SpeedDebugLabel;
public Label mMotor2SpeedDebugLabel;
/**
* Default constructor.
*/
public TetrixMotorControllerDevice() {
super(DeviceType.TETRIX_MOTOR);
mSimData = new SimData[2]; | // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/MotorSimData.java
// @XmlRootElement(name="MotorSimData")
// @XmlAccessorType(XmlAccessType.NONE)
// public class MotorSimData extends SimData {
//
// float mMotorSpeed=0;
// boolean mMotorFloatMode=false;
//
// public MotorSimData() {
// super();
// construct();
// }
//
// @Override
// protected void construct() {
// //System.out.println("Building Legacy Motor SimData");
// }
//
// public float getMotorSpeed() {
// lock.readLock().lock();
// try {
// return mMotorSpeed;
// } finally {
// lock.readLock().unlock();
// }
// }
//
// public boolean getMotorFloatMode() {
// return mMotorFloatMode;
// }
//
// public void setMotorSpeed(byte speedByte) {
// lock.writeLock().lock();
// try {
// if (speedByte == (byte)0x80) {
// mMotorFloatMode = true;
// mMotorSpeed=0.0f;
// } else {
// mMotorSpeed = (float)speedByte/100.0f;
// }
// } finally {
// lock.writeLock().unlock();
// }
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/SimData.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class SimData {
// public final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
//
// protected StringProperty mName = null;
//
// public SimData() {
// mName = new SimpleStringProperty("");
// }
//
// // Do subclass level processing in this method
// protected abstract void construct();
//
//
// public String getName() {
// return mName.getValue();
// }
//
// @XmlElement
// public void setName(String name) {
// mName.set(name);
// }
// }
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/TetrixMotorControllerDevice.java
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlRootElement;
import org.ftccommunity.simulator.data.MotorSimData;
import org.ftccommunity.simulator.data.SimData;
import javafx.geometry.Insets;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
package org.ftccommunity.simulator.modules.devices;
@XmlRootElement(name="TetrixMotorControllerDevice")
@XmlAccessorType(XmlAccessType.NONE)
public class TetrixMotorControllerDevice extends Device {
// GUI stuff for the Debug windows
public Label mMotor1SpeedDebugLabel;
public Label mMotor2SpeedDebugLabel;
/**
* Default constructor.
*/
public TetrixMotorControllerDevice() {
super(DeviceType.TETRIX_MOTOR);
mSimData = new SimData[2]; | mSimData[0] = new MotorSimData(); // Add 1st motor |
HagertyRobotics/ftc_app_networked_simulator | PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/NullDevice.java | // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/NullSimData.java
// @XmlRootElement(name="NullSimData")
// @XmlAccessorType(XmlAccessType.NONE)
// public class NullSimData extends SimData {
//
// public NullSimData() {
// super();
// construct();
// }
//
// @Override
// protected void construct() {
// //System.out.println("Building Null SimData");
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/SimData.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class SimData {
// public final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
//
// protected StringProperty mName = null;
//
// public SimData() {
// mName = new SimpleStringProperty("");
// }
//
// // Do subclass level processing in this method
// protected abstract void construct();
//
//
// public String getName() {
// return mName.getValue();
// }
//
// @XmlElement
// public void setName(String name) {
// mName.set(name);
// }
// }
| import org.ftccommunity.simulator.data.NullSimData;
import org.ftccommunity.simulator.data.SimData;
import javax.xml.bind.annotation.XmlRootElement;
import javafx.scene.layout.VBox; | package org.ftccommunity.simulator.modules.devices;
@XmlRootElement(name="NullDevice")
//@XmlAccessorType(XmlAccessType.NONE)
public class NullDevice extends Device {
public NullDevice() {
super(DeviceType.NONE); | // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/NullSimData.java
// @XmlRootElement(name="NullSimData")
// @XmlAccessorType(XmlAccessType.NONE)
// public class NullSimData extends SimData {
//
// public NullSimData() {
// super();
// construct();
// }
//
// @Override
// protected void construct() {
// //System.out.println("Building Null SimData");
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/SimData.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class SimData {
// public final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
//
// protected StringProperty mName = null;
//
// public SimData() {
// mName = new SimpleStringProperty("");
// }
//
// // Do subclass level processing in this method
// protected abstract void construct();
//
//
// public String getName() {
// return mName.getValue();
// }
//
// @XmlElement
// public void setName(String name) {
// mName.set(name);
// }
// }
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/NullDevice.java
import org.ftccommunity.simulator.data.NullSimData;
import org.ftccommunity.simulator.data.SimData;
import javax.xml.bind.annotation.XmlRootElement;
import javafx.scene.layout.VBox;
package org.ftccommunity.simulator.modules.devices;
@XmlRootElement(name="NullDevice")
//@XmlAccessorType(XmlAccessType.NONE)
public class NullDevice extends Device {
public NullDevice() {
super(DeviceType.NONE); | mSimData = new SimData[1]; |
HagertyRobotics/ftc_app_networked_simulator | PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/NullDevice.java | // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/NullSimData.java
// @XmlRootElement(name="NullSimData")
// @XmlAccessorType(XmlAccessType.NONE)
// public class NullSimData extends SimData {
//
// public NullSimData() {
// super();
// construct();
// }
//
// @Override
// protected void construct() {
// //System.out.println("Building Null SimData");
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/SimData.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class SimData {
// public final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
//
// protected StringProperty mName = null;
//
// public SimData() {
// mName = new SimpleStringProperty("");
// }
//
// // Do subclass level processing in this method
// protected abstract void construct();
//
//
// public String getName() {
// return mName.getValue();
// }
//
// @XmlElement
// public void setName(String name) {
// mName.set(name);
// }
// }
| import org.ftccommunity.simulator.data.NullSimData;
import org.ftccommunity.simulator.data.SimData;
import javax.xml.bind.annotation.XmlRootElement;
import javafx.scene.layout.VBox; | package org.ftccommunity.simulator.modules.devices;
@XmlRootElement(name="NullDevice")
//@XmlAccessorType(XmlAccessType.NONE)
public class NullDevice extends Device {
public NullDevice() {
super(DeviceType.NONE);
mSimData = new SimData[1]; | // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/NullSimData.java
// @XmlRootElement(name="NullSimData")
// @XmlAccessorType(XmlAccessType.NONE)
// public class NullSimData extends SimData {
//
// public NullSimData() {
// super();
// construct();
// }
//
// @Override
// protected void construct() {
// //System.out.println("Building Null SimData");
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/SimData.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class SimData {
// public final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
//
// protected StringProperty mName = null;
//
// public SimData() {
// mName = new SimpleStringProperty("");
// }
//
// // Do subclass level processing in this method
// protected abstract void construct();
//
//
// public String getName() {
// return mName.getValue();
// }
//
// @XmlElement
// public void setName(String name) {
// mName.set(name);
// }
// }
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/NullDevice.java
import org.ftccommunity.simulator.data.NullSimData;
import org.ftccommunity.simulator.data.SimData;
import javax.xml.bind.annotation.XmlRootElement;
import javafx.scene.layout.VBox;
package org.ftccommunity.simulator.modules.devices;
@XmlRootElement(name="NullDevice")
//@XmlAccessorType(XmlAccessType.NONE)
public class NullDevice extends Device {
public NullDevice() {
super(DeviceType.NONE);
mSimData = new SimData[1]; | mSimData[0] = new NullSimData(); // Add 1st motor |
HagertyRobotics/ftc_app_networked_simulator | PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/Device.java | // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/SimData.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class SimData {
// public final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
//
// protected StringProperty mName = null;
//
// public SimData() {
// mName = new SimpleStringProperty("");
// }
//
// // Do subclass level processing in this method
// protected abstract void construct();
//
//
// public String getName() {
// return mName.getValue();
// }
//
// @XmlElement
// public void setName(String name) {
// mName.set(name);
// }
// }
| import org.ftccommunity.simulator.data.SimData;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlAccessType;
import javafx.scene.layout.VBox; | package org.ftccommunity.simulator.modules.devices;
@XmlAccessorType(XmlAccessType.NONE)
public abstract class Device {
protected DeviceType mType=null;
| // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/SimData.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class SimData {
// public final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
//
// protected StringProperty mName = null;
//
// public SimData() {
// mName = new SimpleStringProperty("");
// }
//
// // Do subclass level processing in this method
// protected abstract void construct();
//
//
// public String getName() {
// return mName.getValue();
// }
//
// @XmlElement
// public void setName(String name) {
// mName.set(name);
// }
// }
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/Device.java
import org.ftccommunity.simulator.data.SimData;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlAccessType;
import javafx.scene.layout.VBox;
package org.ftccommunity.simulator.modules.devices;
@XmlAccessorType(XmlAccessType.NONE)
public abstract class Device {
protected DeviceType mType=null;
| @XmlElementRef(name="SimData") |
HagertyRobotics/ftc_app_networked_simulator | PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/LegacyBrickSimulator.java | // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/Device.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class Device {
//
// protected DeviceType mType=null;
//
// @XmlElementRef(name="SimData")
// protected SimData[] mSimData;
//
// public Device() {
// }
//
// public Device(DeviceType type) {
// mType=type;
// }
//
// abstract public void processBuffer(byte[] currentStateBuffer, int portNum);
// abstract public void updateDebugGuiVbox();
// abstract public void setupDebugGuiVbox(VBox vbox);
//
// public DeviceType getType() {
// return mType;
// }
//
// public void setmSimData(SimData[] s) {
// mSimData = s;
// }
//
// public SimData[] getmSimData() {
// return mSimData;
// }
//
// public SimData[] getSimDataArray() {
// return mSimData;
// }
//
// public int getNumberOfPorts() {
// return mSimData.length;
// }
//
// public List<String> getPortNames() {
// List<String> names = new ArrayList<>();
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// names.add(mSimData[i].getName());
// }
// return names;
// }
//
// public void setDeviceNames(String[] names) {
// for (int i = 0; i < mSimData.length; i++) {
// mSimData[i].setName(names[i]);
// }
// }
//
// public SimData findSimDataByName(String name) {
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// if (mSimData[i].getName().equals(name)) {
// return mSimData[i];
// }
// }
// return null;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/DeviceType.java
// @XmlAccessorType(XmlAccessType.NONE)
// public enum DeviceType {
// NONE("None"),
// TETRIX_MOTOR("Tetrix Motor Controller"),
// TETRIX_SERVO("Tetrix Servo Controller"),
// LEGO_LIGHT("Lego Light Sensor"),
// LEGO_TOUCH("Lego Touch Sensor"),
// USB_MOTOR("USB Motor Controller"),
// USB_SERVO("USB Servo Controller");
//
// private final String mName;
// DeviceType(String name) {
// mName = name;
// }
//
// public String getName() {
// return mName;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/NullDevice.java
// @XmlRootElement(name="NullDevice")
// //@XmlAccessorType(XmlAccessType.NONE)
// public class NullDevice extends Device {
//
// public NullDevice() {
// super(DeviceType.NONE);
// mSimData = new SimData[1];
// mSimData[0] = new NullSimData(); // Add 1st motor
// }
//
// public void processBuffer(byte[] currentStateBuffer, int portNum) {
// }
//
// public void updateDebugGuiVbox() {
// }
//
// public void setupDebugGuiVbox(VBox vbox) {
// }
// }
| import org.ftccommunity.simulator.modules.devices.Device;
import org.ftccommunity.simulator.modules.devices.DeviceType;
import org.ftccommunity.simulator.modules.devices.NullDevice;
import javafx.geometry.Insets;
import javafx.scene.layout.*;
import javafx.scene.text.Text;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.IOException;
import java.net.DatagramPacket;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger; | package org.ftccommunity.simulator.modules;
/**
* Model class for a Motor Controller
*
* @author Hagerty High
*/
@XmlRootElement(name="Legacy")
public class LegacyBrickSimulator extends BrickSimulator {
private static final Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
protected final byte[] mCurrentStateBuffer = new byte[208];
protected final byte[] temp15 = new byte[15];
protected final byte[] temp12 = new byte[12];
/*
** Packet types
*/
protected static final byte PACKET_HEADER_0 = (byte)0x55;
protected static final byte PACKET_HEADER_1 = (byte)0xaa;
protected static final byte PACKET_WRITE_FLAG = (byte)0x00;
protected static final byte PACKET_READ_FLAG = (byte)0x80;
/**
* Default constructor.
*/
public LegacyBrickSimulator() {
mType = "Core Legacy Module";
mFXMLFileName = "view/EditDialog.fxml";
mNumberOfPorts = 6; | // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/Device.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class Device {
//
// protected DeviceType mType=null;
//
// @XmlElementRef(name="SimData")
// protected SimData[] mSimData;
//
// public Device() {
// }
//
// public Device(DeviceType type) {
// mType=type;
// }
//
// abstract public void processBuffer(byte[] currentStateBuffer, int portNum);
// abstract public void updateDebugGuiVbox();
// abstract public void setupDebugGuiVbox(VBox vbox);
//
// public DeviceType getType() {
// return mType;
// }
//
// public void setmSimData(SimData[] s) {
// mSimData = s;
// }
//
// public SimData[] getmSimData() {
// return mSimData;
// }
//
// public SimData[] getSimDataArray() {
// return mSimData;
// }
//
// public int getNumberOfPorts() {
// return mSimData.length;
// }
//
// public List<String> getPortNames() {
// List<String> names = new ArrayList<>();
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// names.add(mSimData[i].getName());
// }
// return names;
// }
//
// public void setDeviceNames(String[] names) {
// for (int i = 0; i < mSimData.length; i++) {
// mSimData[i].setName(names[i]);
// }
// }
//
// public SimData findSimDataByName(String name) {
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// if (mSimData[i].getName().equals(name)) {
// return mSimData[i];
// }
// }
// return null;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/DeviceType.java
// @XmlAccessorType(XmlAccessType.NONE)
// public enum DeviceType {
// NONE("None"),
// TETRIX_MOTOR("Tetrix Motor Controller"),
// TETRIX_SERVO("Tetrix Servo Controller"),
// LEGO_LIGHT("Lego Light Sensor"),
// LEGO_TOUCH("Lego Touch Sensor"),
// USB_MOTOR("USB Motor Controller"),
// USB_SERVO("USB Servo Controller");
//
// private final String mName;
// DeviceType(String name) {
// mName = name;
// }
//
// public String getName() {
// return mName;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/NullDevice.java
// @XmlRootElement(name="NullDevice")
// //@XmlAccessorType(XmlAccessType.NONE)
// public class NullDevice extends Device {
//
// public NullDevice() {
// super(DeviceType.NONE);
// mSimData = new SimData[1];
// mSimData[0] = new NullSimData(); // Add 1st motor
// }
//
// public void processBuffer(byte[] currentStateBuffer, int portNum) {
// }
//
// public void updateDebugGuiVbox() {
// }
//
// public void setupDebugGuiVbox(VBox vbox) {
// }
// }
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/LegacyBrickSimulator.java
import org.ftccommunity.simulator.modules.devices.Device;
import org.ftccommunity.simulator.modules.devices.DeviceType;
import org.ftccommunity.simulator.modules.devices.NullDevice;
import javafx.geometry.Insets;
import javafx.scene.layout.*;
import javafx.scene.text.Text;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.IOException;
import java.net.DatagramPacket;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
package org.ftccommunity.simulator.modules;
/**
* Model class for a Motor Controller
*
* @author Hagerty High
*/
@XmlRootElement(name="Legacy")
public class LegacyBrickSimulator extends BrickSimulator {
private static final Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
protected final byte[] mCurrentStateBuffer = new byte[208];
protected final byte[] temp15 = new byte[15];
protected final byte[] temp12 = new byte[12];
/*
** Packet types
*/
protected static final byte PACKET_HEADER_0 = (byte)0x55;
protected static final byte PACKET_HEADER_1 = (byte)0xaa;
protected static final byte PACKET_WRITE_FLAG = (byte)0x00;
protected static final byte PACKET_READ_FLAG = (byte)0x80;
/**
* Default constructor.
*/
public LegacyBrickSimulator() {
mType = "Core Legacy Module";
mFXMLFileName = "view/EditDialog.fxml";
mNumberOfPorts = 6; | mDevices = new Device[mNumberOfPorts]; |
HagertyRobotics/ftc_app_networked_simulator | PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/LegacyBrickSimulator.java | // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/Device.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class Device {
//
// protected DeviceType mType=null;
//
// @XmlElementRef(name="SimData")
// protected SimData[] mSimData;
//
// public Device() {
// }
//
// public Device(DeviceType type) {
// mType=type;
// }
//
// abstract public void processBuffer(byte[] currentStateBuffer, int portNum);
// abstract public void updateDebugGuiVbox();
// abstract public void setupDebugGuiVbox(VBox vbox);
//
// public DeviceType getType() {
// return mType;
// }
//
// public void setmSimData(SimData[] s) {
// mSimData = s;
// }
//
// public SimData[] getmSimData() {
// return mSimData;
// }
//
// public SimData[] getSimDataArray() {
// return mSimData;
// }
//
// public int getNumberOfPorts() {
// return mSimData.length;
// }
//
// public List<String> getPortNames() {
// List<String> names = new ArrayList<>();
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// names.add(mSimData[i].getName());
// }
// return names;
// }
//
// public void setDeviceNames(String[] names) {
// for (int i = 0; i < mSimData.length; i++) {
// mSimData[i].setName(names[i]);
// }
// }
//
// public SimData findSimDataByName(String name) {
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// if (mSimData[i].getName().equals(name)) {
// return mSimData[i];
// }
// }
// return null;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/DeviceType.java
// @XmlAccessorType(XmlAccessType.NONE)
// public enum DeviceType {
// NONE("None"),
// TETRIX_MOTOR("Tetrix Motor Controller"),
// TETRIX_SERVO("Tetrix Servo Controller"),
// LEGO_LIGHT("Lego Light Sensor"),
// LEGO_TOUCH("Lego Touch Sensor"),
// USB_MOTOR("USB Motor Controller"),
// USB_SERVO("USB Servo Controller");
//
// private final String mName;
// DeviceType(String name) {
// mName = name;
// }
//
// public String getName() {
// return mName;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/NullDevice.java
// @XmlRootElement(name="NullDevice")
// //@XmlAccessorType(XmlAccessType.NONE)
// public class NullDevice extends Device {
//
// public NullDevice() {
// super(DeviceType.NONE);
// mSimData = new SimData[1];
// mSimData[0] = new NullSimData(); // Add 1st motor
// }
//
// public void processBuffer(byte[] currentStateBuffer, int portNum) {
// }
//
// public void updateDebugGuiVbox() {
// }
//
// public void setupDebugGuiVbox(VBox vbox) {
// }
// }
| import org.ftccommunity.simulator.modules.devices.Device;
import org.ftccommunity.simulator.modules.devices.DeviceType;
import org.ftccommunity.simulator.modules.devices.NullDevice;
import javafx.geometry.Insets;
import javafx.scene.layout.*;
import javafx.scene.text.Text;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.IOException;
import java.net.DatagramPacket;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger; | package org.ftccommunity.simulator.modules;
/**
* Model class for a Motor Controller
*
* @author Hagerty High
*/
@XmlRootElement(name="Legacy")
public class LegacyBrickSimulator extends BrickSimulator {
private static final Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
protected final byte[] mCurrentStateBuffer = new byte[208];
protected final byte[] temp15 = new byte[15];
protected final byte[] temp12 = new byte[12];
/*
** Packet types
*/
protected static final byte PACKET_HEADER_0 = (byte)0x55;
protected static final byte PACKET_HEADER_1 = (byte)0xaa;
protected static final byte PACKET_WRITE_FLAG = (byte)0x00;
protected static final byte PACKET_READ_FLAG = (byte)0x80;
/**
* Default constructor.
*/
public LegacyBrickSimulator() {
mType = "Core Legacy Module";
mFXMLFileName = "view/EditDialog.fxml";
mNumberOfPorts = 6;
mDevices = new Device[mNumberOfPorts];
for (int i=0;i<mNumberOfPorts;i++) { | // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/Device.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class Device {
//
// protected DeviceType mType=null;
//
// @XmlElementRef(name="SimData")
// protected SimData[] mSimData;
//
// public Device() {
// }
//
// public Device(DeviceType type) {
// mType=type;
// }
//
// abstract public void processBuffer(byte[] currentStateBuffer, int portNum);
// abstract public void updateDebugGuiVbox();
// abstract public void setupDebugGuiVbox(VBox vbox);
//
// public DeviceType getType() {
// return mType;
// }
//
// public void setmSimData(SimData[] s) {
// mSimData = s;
// }
//
// public SimData[] getmSimData() {
// return mSimData;
// }
//
// public SimData[] getSimDataArray() {
// return mSimData;
// }
//
// public int getNumberOfPorts() {
// return mSimData.length;
// }
//
// public List<String> getPortNames() {
// List<String> names = new ArrayList<>();
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// names.add(mSimData[i].getName());
// }
// return names;
// }
//
// public void setDeviceNames(String[] names) {
// for (int i = 0; i < mSimData.length; i++) {
// mSimData[i].setName(names[i]);
// }
// }
//
// public SimData findSimDataByName(String name) {
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// if (mSimData[i].getName().equals(name)) {
// return mSimData[i];
// }
// }
// return null;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/DeviceType.java
// @XmlAccessorType(XmlAccessType.NONE)
// public enum DeviceType {
// NONE("None"),
// TETRIX_MOTOR("Tetrix Motor Controller"),
// TETRIX_SERVO("Tetrix Servo Controller"),
// LEGO_LIGHT("Lego Light Sensor"),
// LEGO_TOUCH("Lego Touch Sensor"),
// USB_MOTOR("USB Motor Controller"),
// USB_SERVO("USB Servo Controller");
//
// private final String mName;
// DeviceType(String name) {
// mName = name;
// }
//
// public String getName() {
// return mName;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/NullDevice.java
// @XmlRootElement(name="NullDevice")
// //@XmlAccessorType(XmlAccessType.NONE)
// public class NullDevice extends Device {
//
// public NullDevice() {
// super(DeviceType.NONE);
// mSimData = new SimData[1];
// mSimData[0] = new NullSimData(); // Add 1st motor
// }
//
// public void processBuffer(byte[] currentStateBuffer, int portNum) {
// }
//
// public void updateDebugGuiVbox() {
// }
//
// public void setupDebugGuiVbox(VBox vbox) {
// }
// }
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/LegacyBrickSimulator.java
import org.ftccommunity.simulator.modules.devices.Device;
import org.ftccommunity.simulator.modules.devices.DeviceType;
import org.ftccommunity.simulator.modules.devices.NullDevice;
import javafx.geometry.Insets;
import javafx.scene.layout.*;
import javafx.scene.text.Text;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.IOException;
import java.net.DatagramPacket;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
package org.ftccommunity.simulator.modules;
/**
* Model class for a Motor Controller
*
* @author Hagerty High
*/
@XmlRootElement(name="Legacy")
public class LegacyBrickSimulator extends BrickSimulator {
private static final Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
protected final byte[] mCurrentStateBuffer = new byte[208];
protected final byte[] temp15 = new byte[15];
protected final byte[] temp12 = new byte[12];
/*
** Packet types
*/
protected static final byte PACKET_HEADER_0 = (byte)0x55;
protected static final byte PACKET_HEADER_1 = (byte)0xaa;
protected static final byte PACKET_WRITE_FLAG = (byte)0x00;
protected static final byte PACKET_READ_FLAG = (byte)0x80;
/**
* Default constructor.
*/
public LegacyBrickSimulator() {
mType = "Core Legacy Module";
mFXMLFileName = "view/EditDialog.fxml";
mNumberOfPorts = 6;
mDevices = new Device[mNumberOfPorts];
for (int i=0;i<mNumberOfPorts;i++) { | mDevices[i] = new NullDevice(); |
HagertyRobotics/ftc_app_networked_simulator | PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/LegacyBrickSimulator.java | // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/Device.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class Device {
//
// protected DeviceType mType=null;
//
// @XmlElementRef(name="SimData")
// protected SimData[] mSimData;
//
// public Device() {
// }
//
// public Device(DeviceType type) {
// mType=type;
// }
//
// abstract public void processBuffer(byte[] currentStateBuffer, int portNum);
// abstract public void updateDebugGuiVbox();
// abstract public void setupDebugGuiVbox(VBox vbox);
//
// public DeviceType getType() {
// return mType;
// }
//
// public void setmSimData(SimData[] s) {
// mSimData = s;
// }
//
// public SimData[] getmSimData() {
// return mSimData;
// }
//
// public SimData[] getSimDataArray() {
// return mSimData;
// }
//
// public int getNumberOfPorts() {
// return mSimData.length;
// }
//
// public List<String> getPortNames() {
// List<String> names = new ArrayList<>();
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// names.add(mSimData[i].getName());
// }
// return names;
// }
//
// public void setDeviceNames(String[] names) {
// for (int i = 0; i < mSimData.length; i++) {
// mSimData[i].setName(names[i]);
// }
// }
//
// public SimData findSimDataByName(String name) {
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// if (mSimData[i].getName().equals(name)) {
// return mSimData[i];
// }
// }
// return null;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/DeviceType.java
// @XmlAccessorType(XmlAccessType.NONE)
// public enum DeviceType {
// NONE("None"),
// TETRIX_MOTOR("Tetrix Motor Controller"),
// TETRIX_SERVO("Tetrix Servo Controller"),
// LEGO_LIGHT("Lego Light Sensor"),
// LEGO_TOUCH("Lego Touch Sensor"),
// USB_MOTOR("USB Motor Controller"),
// USB_SERVO("USB Servo Controller");
//
// private final String mName;
// DeviceType(String name) {
// mName = name;
// }
//
// public String getName() {
// return mName;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/NullDevice.java
// @XmlRootElement(name="NullDevice")
// //@XmlAccessorType(XmlAccessType.NONE)
// public class NullDevice extends Device {
//
// public NullDevice() {
// super(DeviceType.NONE);
// mSimData = new SimData[1];
// mSimData[0] = new NullSimData(); // Add 1st motor
// }
//
// public void processBuffer(byte[] currentStateBuffer, int portNum) {
// }
//
// public void updateDebugGuiVbox() {
// }
//
// public void setupDebugGuiVbox(VBox vbox) {
// }
// }
| import org.ftccommunity.simulator.modules.devices.Device;
import org.ftccommunity.simulator.modules.devices.DeviceType;
import org.ftccommunity.simulator.modules.devices.NullDevice;
import javafx.geometry.Insets;
import javafx.scene.layout.*;
import javafx.scene.text.Text;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.IOException;
import java.net.DatagramPacket;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger; | }
}
pane.getChildren().add(grid);
}
/**
* Getters/Setters
*/
/**
* GUI Stuff
*/
public void setupDebugGuiVbox(VBox vbox) {
for (int i=0;i<mNumberOfPorts;i++) {
mDevices[i].setupDebugGuiVbox(vbox);
}
}
public void updateDebugGuiVbox() {
for (int i=0;i<mNumberOfPorts;i++) {
mDevices[i].updateDebugGuiVbox();
}
}
| // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/Device.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class Device {
//
// protected DeviceType mType=null;
//
// @XmlElementRef(name="SimData")
// protected SimData[] mSimData;
//
// public Device() {
// }
//
// public Device(DeviceType type) {
// mType=type;
// }
//
// abstract public void processBuffer(byte[] currentStateBuffer, int portNum);
// abstract public void updateDebugGuiVbox();
// abstract public void setupDebugGuiVbox(VBox vbox);
//
// public DeviceType getType() {
// return mType;
// }
//
// public void setmSimData(SimData[] s) {
// mSimData = s;
// }
//
// public SimData[] getmSimData() {
// return mSimData;
// }
//
// public SimData[] getSimDataArray() {
// return mSimData;
// }
//
// public int getNumberOfPorts() {
// return mSimData.length;
// }
//
// public List<String> getPortNames() {
// List<String> names = new ArrayList<>();
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// names.add(mSimData[i].getName());
// }
// return names;
// }
//
// public void setDeviceNames(String[] names) {
// for (int i = 0; i < mSimData.length; i++) {
// mSimData[i].setName(names[i]);
// }
// }
//
// public SimData findSimDataByName(String name) {
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// if (mSimData[i].getName().equals(name)) {
// return mSimData[i];
// }
// }
// return null;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/DeviceType.java
// @XmlAccessorType(XmlAccessType.NONE)
// public enum DeviceType {
// NONE("None"),
// TETRIX_MOTOR("Tetrix Motor Controller"),
// TETRIX_SERVO("Tetrix Servo Controller"),
// LEGO_LIGHT("Lego Light Sensor"),
// LEGO_TOUCH("Lego Touch Sensor"),
// USB_MOTOR("USB Motor Controller"),
// USB_SERVO("USB Servo Controller");
//
// private final String mName;
// DeviceType(String name) {
// mName = name;
// }
//
// public String getName() {
// return mName;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/NullDevice.java
// @XmlRootElement(name="NullDevice")
// //@XmlAccessorType(XmlAccessType.NONE)
// public class NullDevice extends Device {
//
// public NullDevice() {
// super(DeviceType.NONE);
// mSimData = new SimData[1];
// mSimData[0] = new NullSimData(); // Add 1st motor
// }
//
// public void processBuffer(byte[] currentStateBuffer, int portNum) {
// }
//
// public void updateDebugGuiVbox() {
// }
//
// public void setupDebugGuiVbox(VBox vbox) {
// }
// }
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/LegacyBrickSimulator.java
import org.ftccommunity.simulator.modules.devices.Device;
import org.ftccommunity.simulator.modules.devices.DeviceType;
import org.ftccommunity.simulator.modules.devices.NullDevice;
import javafx.geometry.Insets;
import javafx.scene.layout.*;
import javafx.scene.text.Text;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.IOException;
import java.net.DatagramPacket;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
}
}
pane.getChildren().add(grid);
}
/**
* Getters/Setters
*/
/**
* GUI Stuff
*/
public void setupDebugGuiVbox(VBox vbox) {
for (int i=0;i<mNumberOfPorts;i++) {
mDevices[i].setupDebugGuiVbox(vbox);
}
}
public void updateDebugGuiVbox() {
for (int i=0;i<mNumberOfPorts;i++) {
mDevices[i].updateDebugGuiVbox();
}
}
| public List<DeviceType> getDeviceTypeList() { |
HagertyRobotics/ftc_app_networked_simulator | PC/Java/RobotSimulator/src/org/ftccommunity/simulator/RobotSimulator.java | // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/BrickSimulator.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class BrickSimulator implements Runnable {
// private static final Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
// protected String mType;
// protected int mNumberOfPorts;
//
// protected final StringProperty mName;
// protected final StringProperty mSerial;
// protected IntegerProperty mPort;
// protected ServerSocket mServerSocket;
// protected Socket mClientSocket;
// protected DataOutputStream os = null;
// protected DataInputStream is = null;
// protected String mFXMLFileName;
//
// @XmlElementRef(name="Devices")
// protected Device[] mDevices;
//
// byte[] mReceiveData = new byte[1024];
// byte[] mSendData = new byte[1024];
//
// /** Default Constructor.
// *
// */
// public BrickSimulator() {
// mName = new SimpleStringProperty("");
// mPort = new SimpleIntegerProperty(0);
// mSerial = new SimpleStringProperty("");
// }
//
//
// @Override
// public void run() {
// byte[] packet;
// try {
// mServerSocket = new ServerSocket(mPort.intValue());
// mClientSocket = mServerSocket.accept();
//
// is = new DataInputStream(mClientSocket.getInputStream());
// os = new DataOutputStream(mClientSocket.getOutputStream());
//
// while (!Thread.currentThread().isInterrupted()) {
// packet = receivePacketFromPhone();
// handleIncomingPacket(packet, packet.length, false);
// }
// // Catch unhandled exceptions and cleanup
// } catch (IOException e) {
// e.printStackTrace();
// close();
// }
// }
//
// private byte[] receivePacketFromPhone() {
// // First byte in packet is the length
// int length;
// try {
// length = is.readByte() & 0xff;
//
// // Create a buffer to hold new packet
// byte[] mypacket = new byte[length];
// is.readFully(mypacket);
// return mypacket;
//
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// return null;
// }
//
// }
//
// public void close() {
// try {
// mServerSocket.close();
// } catch (Exception ex) {
// System.out.println("An error occurred while closing!");
// ex.printStackTrace();
// }
// }
//
// public abstract void setupDebugGuiVbox(VBox vbox);
//
// public abstract void updateDebugGuiVbox();
//
// public abstract void populateDetailsPane(Pane pane);
//
// public abstract void handleIncomingPacket(byte[] data, int length, boolean wait);
//
// public abstract List<DeviceType> getDeviceTypeList();
//
//
// //---------------------------------------------------------------
// //
// // Getters and Setters
// //
//
// public int getNumberOfPorts() {
// return mNumberOfPorts;
// }
//
// public String getType() {
// return mType;
// }
//
// public String getName() {
// return mName.get();
// }
//
// @XmlElement
// public void setName(String name) {
// mName.set(name);
// }
//
// public Integer getPort() {
// return mPort.get();
// }
//
// @XmlElement
// public void setPort(Integer port) {
// mPort.set(port);
// }
//
// public String getSerial() {
// return mSerial.get();
// }
//
// @XmlElement
// public void setSerial(String serial) {
// mSerial.set(serial);
// }
//
// public StringProperty nameProperty() {
// return mName;
// }
//
// public StringProperty serialProperty() {
// return mSerial;
// }
//
// public Device getPortDevice(int i) {
// // TODO add try catch for device length
// return mDevices[i];
// }
//
// public DeviceType getPortDeviceType(int i) {
// return mDevices[i].getType();
// }
//
// public void setPortDeviceType(int i, DeviceType type) {
// mDevices[i] = DeviceFactory.buildDevice(type);
// }
//
// public String getFXMLFileName() {
// return mFXMLFileName;
// }
//
// public Device[] getDevices() {
// return mDevices;
// }
//
// public void setDevices(Device[] dev) {
// mDevices = dev;
// }
//
// /**
// *
// */
// public SimData findSimDataByName(String name) {
// for (Device d: mDevices) {
// SimData s = d.findSimDataByName(name);
// if (s != null) {
// return s;
// }
// }
// return null;
// }
// }
| import org.ftccommunity.simulator.modules.BrickSimulator;
import java.net.InetAddress;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger; | package org.ftccommunity.simulator;
public class RobotSimulator {
private static final Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
private static BrickListGenerator gBrickListGenerator;
private static CoppeliaApiClient gCoppeliaApiClient;
private static volatile boolean gThreadsAreRunning = true;
private static LinkedList<Thread> threadLinkedList = new LinkedList<>();
private static int gPhonePort;
private static InetAddress gPhoneIPAddress;
private static boolean simulatorStarted = false;
private static boolean visualizerStarted = false;
static public void startSimulator(org.ftccommunity.gui.MainApp mainApp) {
simulatorStarted = true;
// Start the module info server
System.out.println("Starting Module Lister...");
gBrickListGenerator = new BrickListGenerator(mainApp); // Runnable
Thread moduleListerThread = new Thread(gBrickListGenerator,"");
moduleListerThread.start();
// Read the current list of modules from the GUI MainApp class
// Start the individual threads for each module | // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/BrickSimulator.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class BrickSimulator implements Runnable {
// private static final Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
// protected String mType;
// protected int mNumberOfPorts;
//
// protected final StringProperty mName;
// protected final StringProperty mSerial;
// protected IntegerProperty mPort;
// protected ServerSocket mServerSocket;
// protected Socket mClientSocket;
// protected DataOutputStream os = null;
// protected DataInputStream is = null;
// protected String mFXMLFileName;
//
// @XmlElementRef(name="Devices")
// protected Device[] mDevices;
//
// byte[] mReceiveData = new byte[1024];
// byte[] mSendData = new byte[1024];
//
// /** Default Constructor.
// *
// */
// public BrickSimulator() {
// mName = new SimpleStringProperty("");
// mPort = new SimpleIntegerProperty(0);
// mSerial = new SimpleStringProperty("");
// }
//
//
// @Override
// public void run() {
// byte[] packet;
// try {
// mServerSocket = new ServerSocket(mPort.intValue());
// mClientSocket = mServerSocket.accept();
//
// is = new DataInputStream(mClientSocket.getInputStream());
// os = new DataOutputStream(mClientSocket.getOutputStream());
//
// while (!Thread.currentThread().isInterrupted()) {
// packet = receivePacketFromPhone();
// handleIncomingPacket(packet, packet.length, false);
// }
// // Catch unhandled exceptions and cleanup
// } catch (IOException e) {
// e.printStackTrace();
// close();
// }
// }
//
// private byte[] receivePacketFromPhone() {
// // First byte in packet is the length
// int length;
// try {
// length = is.readByte() & 0xff;
//
// // Create a buffer to hold new packet
// byte[] mypacket = new byte[length];
// is.readFully(mypacket);
// return mypacket;
//
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// return null;
// }
//
// }
//
// public void close() {
// try {
// mServerSocket.close();
// } catch (Exception ex) {
// System.out.println("An error occurred while closing!");
// ex.printStackTrace();
// }
// }
//
// public abstract void setupDebugGuiVbox(VBox vbox);
//
// public abstract void updateDebugGuiVbox();
//
// public abstract void populateDetailsPane(Pane pane);
//
// public abstract void handleIncomingPacket(byte[] data, int length, boolean wait);
//
// public abstract List<DeviceType> getDeviceTypeList();
//
//
// //---------------------------------------------------------------
// //
// // Getters and Setters
// //
//
// public int getNumberOfPorts() {
// return mNumberOfPorts;
// }
//
// public String getType() {
// return mType;
// }
//
// public String getName() {
// return mName.get();
// }
//
// @XmlElement
// public void setName(String name) {
// mName.set(name);
// }
//
// public Integer getPort() {
// return mPort.get();
// }
//
// @XmlElement
// public void setPort(Integer port) {
// mPort.set(port);
// }
//
// public String getSerial() {
// return mSerial.get();
// }
//
// @XmlElement
// public void setSerial(String serial) {
// mSerial.set(serial);
// }
//
// public StringProperty nameProperty() {
// return mName;
// }
//
// public StringProperty serialProperty() {
// return mSerial;
// }
//
// public Device getPortDevice(int i) {
// // TODO add try catch for device length
// return mDevices[i];
// }
//
// public DeviceType getPortDeviceType(int i) {
// return mDevices[i].getType();
// }
//
// public void setPortDeviceType(int i, DeviceType type) {
// mDevices[i] = DeviceFactory.buildDevice(type);
// }
//
// public String getFXMLFileName() {
// return mFXMLFileName;
// }
//
// public Device[] getDevices() {
// return mDevices;
// }
//
// public void setDevices(Device[] dev) {
// mDevices = dev;
// }
//
// /**
// *
// */
// public SimData findSimDataByName(String name) {
// for (Device d: mDevices) {
// SimData s = d.findSimDataByName(name);
// if (s != null) {
// return s;
// }
// }
// return null;
// }
// }
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/RobotSimulator.java
import org.ftccommunity.simulator.modules.BrickSimulator;
import java.net.InetAddress;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;
package org.ftccommunity.simulator;
public class RobotSimulator {
private static final Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
private static BrickListGenerator gBrickListGenerator;
private static CoppeliaApiClient gCoppeliaApiClient;
private static volatile boolean gThreadsAreRunning = true;
private static LinkedList<Thread> threadLinkedList = new LinkedList<>();
private static int gPhonePort;
private static InetAddress gPhoneIPAddress;
private static boolean simulatorStarted = false;
private static boolean visualizerStarted = false;
static public void startSimulator(org.ftccommunity.gui.MainApp mainApp) {
simulatorStarted = true;
// Start the module info server
System.out.println("Starting Module Lister...");
gBrickListGenerator = new BrickListGenerator(mainApp); // Runnable
Thread moduleListerThread = new Thread(gBrickListGenerator,"");
moduleListerThread.start();
// Read the current list of modules from the GUI MainApp class
// Start the individual threads for each module | List<BrickSimulator> brickList = mainApp.getBrickData(); |
HagertyRobotics/ftc_app_networked_simulator | PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/ServoBrickSimulator.java | // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/Device.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class Device {
//
// protected DeviceType mType=null;
//
// @XmlElementRef(name="SimData")
// protected SimData[] mSimData;
//
// public Device() {
// }
//
// public Device(DeviceType type) {
// mType=type;
// }
//
// abstract public void processBuffer(byte[] currentStateBuffer, int portNum);
// abstract public void updateDebugGuiVbox();
// abstract public void setupDebugGuiVbox(VBox vbox);
//
// public DeviceType getType() {
// return mType;
// }
//
// public void setmSimData(SimData[] s) {
// mSimData = s;
// }
//
// public SimData[] getmSimData() {
// return mSimData;
// }
//
// public SimData[] getSimDataArray() {
// return mSimData;
// }
//
// public int getNumberOfPorts() {
// return mSimData.length;
// }
//
// public List<String> getPortNames() {
// List<String> names = new ArrayList<>();
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// names.add(mSimData[i].getName());
// }
// return names;
// }
//
// public void setDeviceNames(String[] names) {
// for (int i = 0; i < mSimData.length; i++) {
// mSimData[i].setName(names[i]);
// }
// }
//
// public SimData findSimDataByName(String name) {
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// if (mSimData[i].getName().equals(name)) {
// return mSimData[i];
// }
// }
// return null;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/DeviceType.java
// @XmlAccessorType(XmlAccessType.NONE)
// public enum DeviceType {
// NONE("None"),
// TETRIX_MOTOR("Tetrix Motor Controller"),
// TETRIX_SERVO("Tetrix Servo Controller"),
// LEGO_LIGHT("Lego Light Sensor"),
// LEGO_TOUCH("Lego Touch Sensor"),
// USB_MOTOR("USB Motor Controller"),
// USB_SERVO("USB Servo Controller");
//
// private final String mName;
// DeviceType(String name) {
// mName = name;
// }
//
// public String getName() {
// return mName;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/NullDevice.java
// @XmlRootElement(name="NullDevice")
// //@XmlAccessorType(XmlAccessType.NONE)
// public class NullDevice extends Device {
//
// public NullDevice() {
// super(DeviceType.NONE);
// mSimData = new SimData[1];
// mSimData[0] = new NullSimData(); // Add 1st motor
// }
//
// public void processBuffer(byte[] currentStateBuffer, int portNum) {
// }
//
// public void updateDebugGuiVbox() {
// }
//
// public void setupDebugGuiVbox(VBox vbox) {
// }
// }
| import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javax.xml.bind.annotation.XmlRootElement;
import org.ftccommunity.simulator.modules.devices.Device;
import org.ftccommunity.simulator.modules.devices.DeviceType;
import org.ftccommunity.simulator.modules.devices.NullDevice;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger; | package org.ftccommunity.simulator.modules;
/**
* Model class for a Motor Controller
*
* @author Hagerty High
*/
@XmlRootElement(name="Servo")
public class ServoBrickSimulator extends BrickSimulator {
private static final Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
public ServoBrickSimulator() {
mType = "Core Servo Controller";
mFXMLFileName = "view/EditDialog.fxml";
mNumberOfPorts = 6; | // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/Device.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class Device {
//
// protected DeviceType mType=null;
//
// @XmlElementRef(name="SimData")
// protected SimData[] mSimData;
//
// public Device() {
// }
//
// public Device(DeviceType type) {
// mType=type;
// }
//
// abstract public void processBuffer(byte[] currentStateBuffer, int portNum);
// abstract public void updateDebugGuiVbox();
// abstract public void setupDebugGuiVbox(VBox vbox);
//
// public DeviceType getType() {
// return mType;
// }
//
// public void setmSimData(SimData[] s) {
// mSimData = s;
// }
//
// public SimData[] getmSimData() {
// return mSimData;
// }
//
// public SimData[] getSimDataArray() {
// return mSimData;
// }
//
// public int getNumberOfPorts() {
// return mSimData.length;
// }
//
// public List<String> getPortNames() {
// List<String> names = new ArrayList<>();
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// names.add(mSimData[i].getName());
// }
// return names;
// }
//
// public void setDeviceNames(String[] names) {
// for (int i = 0; i < mSimData.length; i++) {
// mSimData[i].setName(names[i]);
// }
// }
//
// public SimData findSimDataByName(String name) {
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// if (mSimData[i].getName().equals(name)) {
// return mSimData[i];
// }
// }
// return null;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/DeviceType.java
// @XmlAccessorType(XmlAccessType.NONE)
// public enum DeviceType {
// NONE("None"),
// TETRIX_MOTOR("Tetrix Motor Controller"),
// TETRIX_SERVO("Tetrix Servo Controller"),
// LEGO_LIGHT("Lego Light Sensor"),
// LEGO_TOUCH("Lego Touch Sensor"),
// USB_MOTOR("USB Motor Controller"),
// USB_SERVO("USB Servo Controller");
//
// private final String mName;
// DeviceType(String name) {
// mName = name;
// }
//
// public String getName() {
// return mName;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/NullDevice.java
// @XmlRootElement(name="NullDevice")
// //@XmlAccessorType(XmlAccessType.NONE)
// public class NullDevice extends Device {
//
// public NullDevice() {
// super(DeviceType.NONE);
// mSimData = new SimData[1];
// mSimData[0] = new NullSimData(); // Add 1st motor
// }
//
// public void processBuffer(byte[] currentStateBuffer, int portNum) {
// }
//
// public void updateDebugGuiVbox() {
// }
//
// public void setupDebugGuiVbox(VBox vbox) {
// }
// }
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/ServoBrickSimulator.java
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javax.xml.bind.annotation.XmlRootElement;
import org.ftccommunity.simulator.modules.devices.Device;
import org.ftccommunity.simulator.modules.devices.DeviceType;
import org.ftccommunity.simulator.modules.devices.NullDevice;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
package org.ftccommunity.simulator.modules;
/**
* Model class for a Motor Controller
*
* @author Hagerty High
*/
@XmlRootElement(name="Servo")
public class ServoBrickSimulator extends BrickSimulator {
private static final Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
public ServoBrickSimulator() {
mType = "Core Servo Controller";
mFXMLFileName = "view/EditDialog.fxml";
mNumberOfPorts = 6; | mDevices = new Device[mNumberOfPorts]; |
HagertyRobotics/ftc_app_networked_simulator | PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/ServoBrickSimulator.java | // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/Device.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class Device {
//
// protected DeviceType mType=null;
//
// @XmlElementRef(name="SimData")
// protected SimData[] mSimData;
//
// public Device() {
// }
//
// public Device(DeviceType type) {
// mType=type;
// }
//
// abstract public void processBuffer(byte[] currentStateBuffer, int portNum);
// abstract public void updateDebugGuiVbox();
// abstract public void setupDebugGuiVbox(VBox vbox);
//
// public DeviceType getType() {
// return mType;
// }
//
// public void setmSimData(SimData[] s) {
// mSimData = s;
// }
//
// public SimData[] getmSimData() {
// return mSimData;
// }
//
// public SimData[] getSimDataArray() {
// return mSimData;
// }
//
// public int getNumberOfPorts() {
// return mSimData.length;
// }
//
// public List<String> getPortNames() {
// List<String> names = new ArrayList<>();
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// names.add(mSimData[i].getName());
// }
// return names;
// }
//
// public void setDeviceNames(String[] names) {
// for (int i = 0; i < mSimData.length; i++) {
// mSimData[i].setName(names[i]);
// }
// }
//
// public SimData findSimDataByName(String name) {
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// if (mSimData[i].getName().equals(name)) {
// return mSimData[i];
// }
// }
// return null;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/DeviceType.java
// @XmlAccessorType(XmlAccessType.NONE)
// public enum DeviceType {
// NONE("None"),
// TETRIX_MOTOR("Tetrix Motor Controller"),
// TETRIX_SERVO("Tetrix Servo Controller"),
// LEGO_LIGHT("Lego Light Sensor"),
// LEGO_TOUCH("Lego Touch Sensor"),
// USB_MOTOR("USB Motor Controller"),
// USB_SERVO("USB Servo Controller");
//
// private final String mName;
// DeviceType(String name) {
// mName = name;
// }
//
// public String getName() {
// return mName;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/NullDevice.java
// @XmlRootElement(name="NullDevice")
// //@XmlAccessorType(XmlAccessType.NONE)
// public class NullDevice extends Device {
//
// public NullDevice() {
// super(DeviceType.NONE);
// mSimData = new SimData[1];
// mSimData[0] = new NullSimData(); // Add 1st motor
// }
//
// public void processBuffer(byte[] currentStateBuffer, int portNum) {
// }
//
// public void updateDebugGuiVbox() {
// }
//
// public void setupDebugGuiVbox(VBox vbox) {
// }
// }
| import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javax.xml.bind.annotation.XmlRootElement;
import org.ftccommunity.simulator.modules.devices.Device;
import org.ftccommunity.simulator.modules.devices.DeviceType;
import org.ftccommunity.simulator.modules.devices.NullDevice;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger; | package org.ftccommunity.simulator.modules;
/**
* Model class for a Motor Controller
*
* @author Hagerty High
*/
@XmlRootElement(name="Servo")
public class ServoBrickSimulator extends BrickSimulator {
private static final Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
public ServoBrickSimulator() {
mType = "Core Servo Controller";
mFXMLFileName = "view/EditDialog.fxml";
mNumberOfPorts = 6;
mDevices = new Device[mNumberOfPorts];
for (int i=0;i<mNumberOfPorts;i++) { | // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/Device.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class Device {
//
// protected DeviceType mType=null;
//
// @XmlElementRef(name="SimData")
// protected SimData[] mSimData;
//
// public Device() {
// }
//
// public Device(DeviceType type) {
// mType=type;
// }
//
// abstract public void processBuffer(byte[] currentStateBuffer, int portNum);
// abstract public void updateDebugGuiVbox();
// abstract public void setupDebugGuiVbox(VBox vbox);
//
// public DeviceType getType() {
// return mType;
// }
//
// public void setmSimData(SimData[] s) {
// mSimData = s;
// }
//
// public SimData[] getmSimData() {
// return mSimData;
// }
//
// public SimData[] getSimDataArray() {
// return mSimData;
// }
//
// public int getNumberOfPorts() {
// return mSimData.length;
// }
//
// public List<String> getPortNames() {
// List<String> names = new ArrayList<>();
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// names.add(mSimData[i].getName());
// }
// return names;
// }
//
// public void setDeviceNames(String[] names) {
// for (int i = 0; i < mSimData.length; i++) {
// mSimData[i].setName(names[i]);
// }
// }
//
// public SimData findSimDataByName(String name) {
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// if (mSimData[i].getName().equals(name)) {
// return mSimData[i];
// }
// }
// return null;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/DeviceType.java
// @XmlAccessorType(XmlAccessType.NONE)
// public enum DeviceType {
// NONE("None"),
// TETRIX_MOTOR("Tetrix Motor Controller"),
// TETRIX_SERVO("Tetrix Servo Controller"),
// LEGO_LIGHT("Lego Light Sensor"),
// LEGO_TOUCH("Lego Touch Sensor"),
// USB_MOTOR("USB Motor Controller"),
// USB_SERVO("USB Servo Controller");
//
// private final String mName;
// DeviceType(String name) {
// mName = name;
// }
//
// public String getName() {
// return mName;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/NullDevice.java
// @XmlRootElement(name="NullDevice")
// //@XmlAccessorType(XmlAccessType.NONE)
// public class NullDevice extends Device {
//
// public NullDevice() {
// super(DeviceType.NONE);
// mSimData = new SimData[1];
// mSimData[0] = new NullSimData(); // Add 1st motor
// }
//
// public void processBuffer(byte[] currentStateBuffer, int portNum) {
// }
//
// public void updateDebugGuiVbox() {
// }
//
// public void setupDebugGuiVbox(VBox vbox) {
// }
// }
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/ServoBrickSimulator.java
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javax.xml.bind.annotation.XmlRootElement;
import org.ftccommunity.simulator.modules.devices.Device;
import org.ftccommunity.simulator.modules.devices.DeviceType;
import org.ftccommunity.simulator.modules.devices.NullDevice;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
package org.ftccommunity.simulator.modules;
/**
* Model class for a Motor Controller
*
* @author Hagerty High
*/
@XmlRootElement(name="Servo")
public class ServoBrickSimulator extends BrickSimulator {
private static final Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
public ServoBrickSimulator() {
mType = "Core Servo Controller";
mFXMLFileName = "view/EditDialog.fxml";
mNumberOfPorts = 6;
mDevices = new Device[mNumberOfPorts];
for (int i=0;i<mNumberOfPorts;i++) { | mDevices[i] = new NullDevice(); |
HagertyRobotics/ftc_app_networked_simulator | PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/ServoBrickSimulator.java | // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/Device.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class Device {
//
// protected DeviceType mType=null;
//
// @XmlElementRef(name="SimData")
// protected SimData[] mSimData;
//
// public Device() {
// }
//
// public Device(DeviceType type) {
// mType=type;
// }
//
// abstract public void processBuffer(byte[] currentStateBuffer, int portNum);
// abstract public void updateDebugGuiVbox();
// abstract public void setupDebugGuiVbox(VBox vbox);
//
// public DeviceType getType() {
// return mType;
// }
//
// public void setmSimData(SimData[] s) {
// mSimData = s;
// }
//
// public SimData[] getmSimData() {
// return mSimData;
// }
//
// public SimData[] getSimDataArray() {
// return mSimData;
// }
//
// public int getNumberOfPorts() {
// return mSimData.length;
// }
//
// public List<String> getPortNames() {
// List<String> names = new ArrayList<>();
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// names.add(mSimData[i].getName());
// }
// return names;
// }
//
// public void setDeviceNames(String[] names) {
// for (int i = 0; i < mSimData.length; i++) {
// mSimData[i].setName(names[i]);
// }
// }
//
// public SimData findSimDataByName(String name) {
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// if (mSimData[i].getName().equals(name)) {
// return mSimData[i];
// }
// }
// return null;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/DeviceType.java
// @XmlAccessorType(XmlAccessType.NONE)
// public enum DeviceType {
// NONE("None"),
// TETRIX_MOTOR("Tetrix Motor Controller"),
// TETRIX_SERVO("Tetrix Servo Controller"),
// LEGO_LIGHT("Lego Light Sensor"),
// LEGO_TOUCH("Lego Touch Sensor"),
// USB_MOTOR("USB Motor Controller"),
// USB_SERVO("USB Servo Controller");
//
// private final String mName;
// DeviceType(String name) {
// mName = name;
// }
//
// public String getName() {
// return mName;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/NullDevice.java
// @XmlRootElement(name="NullDevice")
// //@XmlAccessorType(XmlAccessType.NONE)
// public class NullDevice extends Device {
//
// public NullDevice() {
// super(DeviceType.NONE);
// mSimData = new SimData[1];
// mSimData[0] = new NullSimData(); // Add 1st motor
// }
//
// public void processBuffer(byte[] currentStateBuffer, int portNum) {
// }
//
// public void updateDebugGuiVbox() {
// }
//
// public void setupDebugGuiVbox(VBox vbox) {
// }
// }
| import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javax.xml.bind.annotation.XmlRootElement;
import org.ftccommunity.simulator.modules.devices.Device;
import org.ftccommunity.simulator.modules.devices.DeviceType;
import org.ftccommunity.simulator.modules.devices.NullDevice;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger; | package org.ftccommunity.simulator.modules;
/**
* Model class for a Motor Controller
*
* @author Hagerty High
*/
@XmlRootElement(name="Servo")
public class ServoBrickSimulator extends BrickSimulator {
private static final Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
public ServoBrickSimulator() {
mType = "Core Servo Controller";
mFXMLFileName = "view/EditDialog.fxml";
mNumberOfPorts = 6;
mDevices = new Device[mNumberOfPorts];
for (int i=0;i<mNumberOfPorts;i++) {
mDevices[i] = new NullDevice();
}
}
public void fixupUnMarshaling() {}
public void setupDebugGuiVbox(VBox vbox) {}
public void updateDebugGuiVbox() {}
public void populateDetailsPane(Pane pane) {}
public void handleIncomingPacket(byte[] data, int length, boolean wait) {
}
| // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/Device.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class Device {
//
// protected DeviceType mType=null;
//
// @XmlElementRef(name="SimData")
// protected SimData[] mSimData;
//
// public Device() {
// }
//
// public Device(DeviceType type) {
// mType=type;
// }
//
// abstract public void processBuffer(byte[] currentStateBuffer, int portNum);
// abstract public void updateDebugGuiVbox();
// abstract public void setupDebugGuiVbox(VBox vbox);
//
// public DeviceType getType() {
// return mType;
// }
//
// public void setmSimData(SimData[] s) {
// mSimData = s;
// }
//
// public SimData[] getmSimData() {
// return mSimData;
// }
//
// public SimData[] getSimDataArray() {
// return mSimData;
// }
//
// public int getNumberOfPorts() {
// return mSimData.length;
// }
//
// public List<String> getPortNames() {
// List<String> names = new ArrayList<>();
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// names.add(mSimData[i].getName());
// }
// return names;
// }
//
// public void setDeviceNames(String[] names) {
// for (int i = 0; i < mSimData.length; i++) {
// mSimData[i].setName(names[i]);
// }
// }
//
// public SimData findSimDataByName(String name) {
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// if (mSimData[i].getName().equals(name)) {
// return mSimData[i];
// }
// }
// return null;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/DeviceType.java
// @XmlAccessorType(XmlAccessType.NONE)
// public enum DeviceType {
// NONE("None"),
// TETRIX_MOTOR("Tetrix Motor Controller"),
// TETRIX_SERVO("Tetrix Servo Controller"),
// LEGO_LIGHT("Lego Light Sensor"),
// LEGO_TOUCH("Lego Touch Sensor"),
// USB_MOTOR("USB Motor Controller"),
// USB_SERVO("USB Servo Controller");
//
// private final String mName;
// DeviceType(String name) {
// mName = name;
// }
//
// public String getName() {
// return mName;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/NullDevice.java
// @XmlRootElement(name="NullDevice")
// //@XmlAccessorType(XmlAccessType.NONE)
// public class NullDevice extends Device {
//
// public NullDevice() {
// super(DeviceType.NONE);
// mSimData = new SimData[1];
// mSimData[0] = new NullSimData(); // Add 1st motor
// }
//
// public void processBuffer(byte[] currentStateBuffer, int portNum) {
// }
//
// public void updateDebugGuiVbox() {
// }
//
// public void setupDebugGuiVbox(VBox vbox) {
// }
// }
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/ServoBrickSimulator.java
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javax.xml.bind.annotation.XmlRootElement;
import org.ftccommunity.simulator.modules.devices.Device;
import org.ftccommunity.simulator.modules.devices.DeviceType;
import org.ftccommunity.simulator.modules.devices.NullDevice;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
package org.ftccommunity.simulator.modules;
/**
* Model class for a Motor Controller
*
* @author Hagerty High
*/
@XmlRootElement(name="Servo")
public class ServoBrickSimulator extends BrickSimulator {
private static final Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
public ServoBrickSimulator() {
mType = "Core Servo Controller";
mFXMLFileName = "view/EditDialog.fxml";
mNumberOfPorts = 6;
mDevices = new Device[mNumberOfPorts];
for (int i=0;i<mNumberOfPorts;i++) {
mDevices[i] = new NullDevice();
}
}
public void fixupUnMarshaling() {}
public void setupDebugGuiVbox(VBox vbox) {}
public void updateDebugGuiVbox() {}
public void populateDetailsPane(Pane pane) {}
public void handleIncomingPacket(byte[] data, int length, boolean wait) {
}
| public List<DeviceType> getDeviceTypeList() { |
HagertyRobotics/ftc_app_networked_simulator | PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/BrickSimulator.java | // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/SimData.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class SimData {
// public final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
//
// protected StringProperty mName = null;
//
// public SimData() {
// mName = new SimpleStringProperty("");
// }
//
// // Do subclass level processing in this method
// protected abstract void construct();
//
//
// public String getName() {
// return mName.getValue();
// }
//
// @XmlElement
// public void setName(String name) {
// mName.set(name);
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/Device.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class Device {
//
// protected DeviceType mType=null;
//
// @XmlElementRef(name="SimData")
// protected SimData[] mSimData;
//
// public Device() {
// }
//
// public Device(DeviceType type) {
// mType=type;
// }
//
// abstract public void processBuffer(byte[] currentStateBuffer, int portNum);
// abstract public void updateDebugGuiVbox();
// abstract public void setupDebugGuiVbox(VBox vbox);
//
// public DeviceType getType() {
// return mType;
// }
//
// public void setmSimData(SimData[] s) {
// mSimData = s;
// }
//
// public SimData[] getmSimData() {
// return mSimData;
// }
//
// public SimData[] getSimDataArray() {
// return mSimData;
// }
//
// public int getNumberOfPorts() {
// return mSimData.length;
// }
//
// public List<String> getPortNames() {
// List<String> names = new ArrayList<>();
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// names.add(mSimData[i].getName());
// }
// return names;
// }
//
// public void setDeviceNames(String[] names) {
// for (int i = 0; i < mSimData.length; i++) {
// mSimData[i].setName(names[i]);
// }
// }
//
// public SimData findSimDataByName(String name) {
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// if (mSimData[i].getName().equals(name)) {
// return mSimData[i];
// }
// }
// return null;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/DeviceFactory.java
// public class DeviceFactory {
// public static Device buildDevice(DeviceType type) {
// Device device;
// switch (type) {
// case NONE:
// device = new NullDevice();
// break;
// case TETRIX_MOTOR:
// device = new TetrixMotorControllerDevice();
// break;
// case USB_MOTOR:
// device = new USBMotorControllerDevice();
// break;
// case LEGO_LIGHT:
// device = new LegoLightSensorDevice();
// break;
//
// // fall through
// case TETRIX_SERVO:
// // fall through
// case USB_SERVO:
// throw new NotImplementedException();
// default:
// throw new AssertionError("You did not specify a valid type");
// }
// return device;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/DeviceType.java
// @XmlAccessorType(XmlAccessType.NONE)
// public enum DeviceType {
// NONE("None"),
// TETRIX_MOTOR("Tetrix Motor Controller"),
// TETRIX_SERVO("Tetrix Servo Controller"),
// LEGO_LIGHT("Lego Light Sensor"),
// LEGO_TOUCH("Lego Touch Sensor"),
// USB_MOTOR("USB Motor Controller"),
// USB_SERVO("USB Servo Controller");
//
// private final String mName;
// DeviceType(String name) {
// mName = name;
// }
//
// public String getName() {
// return mName;
// }
// }
| import org.ftccommunity.simulator.data.SimData;
import org.ftccommunity.simulator.modules.devices.Device;
import org.ftccommunity.simulator.modules.devices.DeviceFactory;
import org.ftccommunity.simulator.modules.devices.DeviceType;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.logging.Logger; | mPort.set(port);
}
public String getSerial() {
return mSerial.get();
}
@XmlElement
public void setSerial(String serial) {
mSerial.set(serial);
}
public StringProperty nameProperty() {
return mName;
}
public StringProperty serialProperty() {
return mSerial;
}
public Device getPortDevice(int i) {
// TODO add try catch for device length
return mDevices[i];
}
public DeviceType getPortDeviceType(int i) {
return mDevices[i].getType();
}
public void setPortDeviceType(int i, DeviceType type) { | // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/SimData.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class SimData {
// public final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
//
// protected StringProperty mName = null;
//
// public SimData() {
// mName = new SimpleStringProperty("");
// }
//
// // Do subclass level processing in this method
// protected abstract void construct();
//
//
// public String getName() {
// return mName.getValue();
// }
//
// @XmlElement
// public void setName(String name) {
// mName.set(name);
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/Device.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class Device {
//
// protected DeviceType mType=null;
//
// @XmlElementRef(name="SimData")
// protected SimData[] mSimData;
//
// public Device() {
// }
//
// public Device(DeviceType type) {
// mType=type;
// }
//
// abstract public void processBuffer(byte[] currentStateBuffer, int portNum);
// abstract public void updateDebugGuiVbox();
// abstract public void setupDebugGuiVbox(VBox vbox);
//
// public DeviceType getType() {
// return mType;
// }
//
// public void setmSimData(SimData[] s) {
// mSimData = s;
// }
//
// public SimData[] getmSimData() {
// return mSimData;
// }
//
// public SimData[] getSimDataArray() {
// return mSimData;
// }
//
// public int getNumberOfPorts() {
// return mSimData.length;
// }
//
// public List<String> getPortNames() {
// List<String> names = new ArrayList<>();
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// names.add(mSimData[i].getName());
// }
// return names;
// }
//
// public void setDeviceNames(String[] names) {
// for (int i = 0; i < mSimData.length; i++) {
// mSimData[i].setName(names[i]);
// }
// }
//
// public SimData findSimDataByName(String name) {
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// if (mSimData[i].getName().equals(name)) {
// return mSimData[i];
// }
// }
// return null;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/DeviceFactory.java
// public class DeviceFactory {
// public static Device buildDevice(DeviceType type) {
// Device device;
// switch (type) {
// case NONE:
// device = new NullDevice();
// break;
// case TETRIX_MOTOR:
// device = new TetrixMotorControllerDevice();
// break;
// case USB_MOTOR:
// device = new USBMotorControllerDevice();
// break;
// case LEGO_LIGHT:
// device = new LegoLightSensorDevice();
// break;
//
// // fall through
// case TETRIX_SERVO:
// // fall through
// case USB_SERVO:
// throw new NotImplementedException();
// default:
// throw new AssertionError("You did not specify a valid type");
// }
// return device;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/DeviceType.java
// @XmlAccessorType(XmlAccessType.NONE)
// public enum DeviceType {
// NONE("None"),
// TETRIX_MOTOR("Tetrix Motor Controller"),
// TETRIX_SERVO("Tetrix Servo Controller"),
// LEGO_LIGHT("Lego Light Sensor"),
// LEGO_TOUCH("Lego Touch Sensor"),
// USB_MOTOR("USB Motor Controller"),
// USB_SERVO("USB Servo Controller");
//
// private final String mName;
// DeviceType(String name) {
// mName = name;
// }
//
// public String getName() {
// return mName;
// }
// }
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/BrickSimulator.java
import org.ftccommunity.simulator.data.SimData;
import org.ftccommunity.simulator.modules.devices.Device;
import org.ftccommunity.simulator.modules.devices.DeviceFactory;
import org.ftccommunity.simulator.modules.devices.DeviceType;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.logging.Logger;
mPort.set(port);
}
public String getSerial() {
return mSerial.get();
}
@XmlElement
public void setSerial(String serial) {
mSerial.set(serial);
}
public StringProperty nameProperty() {
return mName;
}
public StringProperty serialProperty() {
return mSerial;
}
public Device getPortDevice(int i) {
// TODO add try catch for device length
return mDevices[i];
}
public DeviceType getPortDeviceType(int i) {
return mDevices[i].getType();
}
public void setPortDeviceType(int i, DeviceType type) { | mDevices[i] = DeviceFactory.buildDevice(type); |
HagertyRobotics/ftc_app_networked_simulator | PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/BrickSimulator.java | // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/SimData.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class SimData {
// public final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
//
// protected StringProperty mName = null;
//
// public SimData() {
// mName = new SimpleStringProperty("");
// }
//
// // Do subclass level processing in this method
// protected abstract void construct();
//
//
// public String getName() {
// return mName.getValue();
// }
//
// @XmlElement
// public void setName(String name) {
// mName.set(name);
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/Device.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class Device {
//
// protected DeviceType mType=null;
//
// @XmlElementRef(name="SimData")
// protected SimData[] mSimData;
//
// public Device() {
// }
//
// public Device(DeviceType type) {
// mType=type;
// }
//
// abstract public void processBuffer(byte[] currentStateBuffer, int portNum);
// abstract public void updateDebugGuiVbox();
// abstract public void setupDebugGuiVbox(VBox vbox);
//
// public DeviceType getType() {
// return mType;
// }
//
// public void setmSimData(SimData[] s) {
// mSimData = s;
// }
//
// public SimData[] getmSimData() {
// return mSimData;
// }
//
// public SimData[] getSimDataArray() {
// return mSimData;
// }
//
// public int getNumberOfPorts() {
// return mSimData.length;
// }
//
// public List<String> getPortNames() {
// List<String> names = new ArrayList<>();
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// names.add(mSimData[i].getName());
// }
// return names;
// }
//
// public void setDeviceNames(String[] names) {
// for (int i = 0; i < mSimData.length; i++) {
// mSimData[i].setName(names[i]);
// }
// }
//
// public SimData findSimDataByName(String name) {
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// if (mSimData[i].getName().equals(name)) {
// return mSimData[i];
// }
// }
// return null;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/DeviceFactory.java
// public class DeviceFactory {
// public static Device buildDevice(DeviceType type) {
// Device device;
// switch (type) {
// case NONE:
// device = new NullDevice();
// break;
// case TETRIX_MOTOR:
// device = new TetrixMotorControllerDevice();
// break;
// case USB_MOTOR:
// device = new USBMotorControllerDevice();
// break;
// case LEGO_LIGHT:
// device = new LegoLightSensorDevice();
// break;
//
// // fall through
// case TETRIX_SERVO:
// // fall through
// case USB_SERVO:
// throw new NotImplementedException();
// default:
// throw new AssertionError("You did not specify a valid type");
// }
// return device;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/DeviceType.java
// @XmlAccessorType(XmlAccessType.NONE)
// public enum DeviceType {
// NONE("None"),
// TETRIX_MOTOR("Tetrix Motor Controller"),
// TETRIX_SERVO("Tetrix Servo Controller"),
// LEGO_LIGHT("Lego Light Sensor"),
// LEGO_TOUCH("Lego Touch Sensor"),
// USB_MOTOR("USB Motor Controller"),
// USB_SERVO("USB Servo Controller");
//
// private final String mName;
// DeviceType(String name) {
// mName = name;
// }
//
// public String getName() {
// return mName;
// }
// }
| import org.ftccommunity.simulator.data.SimData;
import org.ftccommunity.simulator.modules.devices.Device;
import org.ftccommunity.simulator.modules.devices.DeviceFactory;
import org.ftccommunity.simulator.modules.devices.DeviceType;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.logging.Logger; | }
public Device getPortDevice(int i) {
// TODO add try catch for device length
return mDevices[i];
}
public DeviceType getPortDeviceType(int i) {
return mDevices[i].getType();
}
public void setPortDeviceType(int i, DeviceType type) {
mDevices[i] = DeviceFactory.buildDevice(type);
}
public String getFXMLFileName() {
return mFXMLFileName;
}
public Device[] getDevices() {
return mDevices;
}
public void setDevices(Device[] dev) {
mDevices = dev;
}
/**
*
*/ | // Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/data/SimData.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class SimData {
// public final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
//
// protected StringProperty mName = null;
//
// public SimData() {
// mName = new SimpleStringProperty("");
// }
//
// // Do subclass level processing in this method
// protected abstract void construct();
//
//
// public String getName() {
// return mName.getValue();
// }
//
// @XmlElement
// public void setName(String name) {
// mName.set(name);
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/Device.java
// @XmlAccessorType(XmlAccessType.NONE)
// public abstract class Device {
//
// protected DeviceType mType=null;
//
// @XmlElementRef(name="SimData")
// protected SimData[] mSimData;
//
// public Device() {
// }
//
// public Device(DeviceType type) {
// mType=type;
// }
//
// abstract public void processBuffer(byte[] currentStateBuffer, int portNum);
// abstract public void updateDebugGuiVbox();
// abstract public void setupDebugGuiVbox(VBox vbox);
//
// public DeviceType getType() {
// return mType;
// }
//
// public void setmSimData(SimData[] s) {
// mSimData = s;
// }
//
// public SimData[] getmSimData() {
// return mSimData;
// }
//
// public SimData[] getSimDataArray() {
// return mSimData;
// }
//
// public int getNumberOfPorts() {
// return mSimData.length;
// }
//
// public List<String> getPortNames() {
// List<String> names = new ArrayList<>();
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// names.add(mSimData[i].getName());
// }
// return names;
// }
//
// public void setDeviceNames(String[] names) {
// for (int i = 0; i < mSimData.length; i++) {
// mSimData[i].setName(names[i]);
// }
// }
//
// public SimData findSimDataByName(String name) {
// int len = mSimData.length;
// for (int i=0;i<len;i++) {
// if (mSimData[i].getName().equals(name)) {
// return mSimData[i];
// }
// }
// return null;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/DeviceFactory.java
// public class DeviceFactory {
// public static Device buildDevice(DeviceType type) {
// Device device;
// switch (type) {
// case NONE:
// device = new NullDevice();
// break;
// case TETRIX_MOTOR:
// device = new TetrixMotorControllerDevice();
// break;
// case USB_MOTOR:
// device = new USBMotorControllerDevice();
// break;
// case LEGO_LIGHT:
// device = new LegoLightSensorDevice();
// break;
//
// // fall through
// case TETRIX_SERVO:
// // fall through
// case USB_SERVO:
// throw new NotImplementedException();
// default:
// throw new AssertionError("You did not specify a valid type");
// }
// return device;
// }
// }
//
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/devices/DeviceType.java
// @XmlAccessorType(XmlAccessType.NONE)
// public enum DeviceType {
// NONE("None"),
// TETRIX_MOTOR("Tetrix Motor Controller"),
// TETRIX_SERVO("Tetrix Servo Controller"),
// LEGO_LIGHT("Lego Light Sensor"),
// LEGO_TOUCH("Lego Touch Sensor"),
// USB_MOTOR("USB Motor Controller"),
// USB_SERVO("USB Servo Controller");
//
// private final String mName;
// DeviceType(String name) {
// mName = name;
// }
//
// public String getName() {
// return mName;
// }
// }
// Path: PC/Java/RobotSimulator/src/org/ftccommunity/simulator/modules/BrickSimulator.java
import org.ftccommunity.simulator.data.SimData;
import org.ftccommunity.simulator.modules.devices.Device;
import org.ftccommunity.simulator.modules.devices.DeviceFactory;
import org.ftccommunity.simulator.modules.devices.DeviceType;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.logging.Logger;
}
public Device getPortDevice(int i) {
// TODO add try catch for device length
return mDevices[i];
}
public DeviceType getPortDeviceType(int i) {
return mDevices[i].getType();
}
public void setPortDeviceType(int i, DeviceType type) {
mDevices[i] = DeviceFactory.buildDevice(type);
}
public String getFXMLFileName() {
return mFXMLFileName;
}
public Device[] getDevices() {
return mDevices;
}
public void setDevices(Device[] dev) {
mDevices = dev;
}
/**
*
*/ | public SimData findSimDataByName(String name) { |
MaksTuev/ferro | sample/src/main/java/com/agna/ferro/sample/ui/common/navigation/Navigator.java | // Path: ferro-mvp/src/main/java/com/agna/ferro/mvp/component/provider/ActivityProvider.java
// public class ActivityProvider {
// private PersistentScreenScope screenScope;
//
// public ActivityProvider(PersistentScreenScope screenScope) {
// this.screenScope = screenScope;
// }
//
// /**
// * @return actual Activity
// */
// public Activity get() {
// return screenScope.getParentActivity();
// }
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/screen/book/BookActivity.java
// public class BookActivity extends BaseActivity {
// private static final String EXTRA_BOOK_ID = "EXTRA_BOOK_ID";
//
// public static void start(Activity activity, String bookId) {
// Intent i = new Intent(activity, BookActivity.class);
// i.putExtra(EXTRA_BOOK_ID, bookId);
// activity.startActivity(i);
// }
//
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_book);
// FragmentManager fm = getSupportFragmentManager();
// if (fm.findFragmentByTag(BookFragmentView.class.getSimpleName()) == null) {
// Fragment fragment = BookFragmentView.create(getIntent().getStringExtra(EXTRA_BOOK_ID));
// FragmentTransaction fragmentTransaction = fm.beginTransaction();
// fragmentTransaction.add(R.id.container, fragment, BookFragmentView.class.getSimpleName());
// fragmentTransaction.commit();
// }
// }
// }
| import com.agna.ferro.mvp.component.provider.ActivityProvider;
import com.agna.ferro.mvp.component.scope.PerScreen;
import com.agna.ferro.sample.ui.screen.book.BookActivity;
import javax.inject.Inject; | package com.agna.ferro.sample.ui.common.navigation;
/**
* Encapsulate navigation between screens
*
* Example of class, which used {@link ActivityProvider}
* Object of this class retained in {@link com.agna.ferro.core.PersistentScreenScope} because
* it part of ScreenComponent
*/
@PerScreen
public class Navigator {
| // Path: ferro-mvp/src/main/java/com/agna/ferro/mvp/component/provider/ActivityProvider.java
// public class ActivityProvider {
// private PersistentScreenScope screenScope;
//
// public ActivityProvider(PersistentScreenScope screenScope) {
// this.screenScope = screenScope;
// }
//
// /**
// * @return actual Activity
// */
// public Activity get() {
// return screenScope.getParentActivity();
// }
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/screen/book/BookActivity.java
// public class BookActivity extends BaseActivity {
// private static final String EXTRA_BOOK_ID = "EXTRA_BOOK_ID";
//
// public static void start(Activity activity, String bookId) {
// Intent i = new Intent(activity, BookActivity.class);
// i.putExtra(EXTRA_BOOK_ID, bookId);
// activity.startActivity(i);
// }
//
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_book);
// FragmentManager fm = getSupportFragmentManager();
// if (fm.findFragmentByTag(BookFragmentView.class.getSimpleName()) == null) {
// Fragment fragment = BookFragmentView.create(getIntent().getStringExtra(EXTRA_BOOK_ID));
// FragmentTransaction fragmentTransaction = fm.beginTransaction();
// fragmentTransaction.add(R.id.container, fragment, BookFragmentView.class.getSimpleName());
// fragmentTransaction.commit();
// }
// }
// }
// Path: sample/src/main/java/com/agna/ferro/sample/ui/common/navigation/Navigator.java
import com.agna.ferro.mvp.component.provider.ActivityProvider;
import com.agna.ferro.mvp.component.scope.PerScreen;
import com.agna.ferro.sample.ui.screen.book.BookActivity;
import javax.inject.Inject;
package com.agna.ferro.sample.ui.common.navigation;
/**
* Encapsulate navigation between screens
*
* Example of class, which used {@link ActivityProvider}
* Object of this class retained in {@link com.agna.ferro.core.PersistentScreenScope} because
* it part of ScreenComponent
*/
@PerScreen
public class Navigator {
| private final ActivityProvider activityProvider; |
MaksTuev/ferro | sample/src/main/java/com/agna/ferro/sample/ui/common/navigation/Navigator.java | // Path: ferro-mvp/src/main/java/com/agna/ferro/mvp/component/provider/ActivityProvider.java
// public class ActivityProvider {
// private PersistentScreenScope screenScope;
//
// public ActivityProvider(PersistentScreenScope screenScope) {
// this.screenScope = screenScope;
// }
//
// /**
// * @return actual Activity
// */
// public Activity get() {
// return screenScope.getParentActivity();
// }
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/screen/book/BookActivity.java
// public class BookActivity extends BaseActivity {
// private static final String EXTRA_BOOK_ID = "EXTRA_BOOK_ID";
//
// public static void start(Activity activity, String bookId) {
// Intent i = new Intent(activity, BookActivity.class);
// i.putExtra(EXTRA_BOOK_ID, bookId);
// activity.startActivity(i);
// }
//
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_book);
// FragmentManager fm = getSupportFragmentManager();
// if (fm.findFragmentByTag(BookFragmentView.class.getSimpleName()) == null) {
// Fragment fragment = BookFragmentView.create(getIntent().getStringExtra(EXTRA_BOOK_ID));
// FragmentTransaction fragmentTransaction = fm.beginTransaction();
// fragmentTransaction.add(R.id.container, fragment, BookFragmentView.class.getSimpleName());
// fragmentTransaction.commit();
// }
// }
// }
| import com.agna.ferro.mvp.component.provider.ActivityProvider;
import com.agna.ferro.mvp.component.scope.PerScreen;
import com.agna.ferro.sample.ui.screen.book.BookActivity;
import javax.inject.Inject; | package com.agna.ferro.sample.ui.common.navigation;
/**
* Encapsulate navigation between screens
*
* Example of class, which used {@link ActivityProvider}
* Object of this class retained in {@link com.agna.ferro.core.PersistentScreenScope} because
* it part of ScreenComponent
*/
@PerScreen
public class Navigator {
private final ActivityProvider activityProvider;
@Inject
public Navigator(ActivityProvider activityProvider) {
this.activityProvider = activityProvider;
}
public void openBookScreen(String bookId){ | // Path: ferro-mvp/src/main/java/com/agna/ferro/mvp/component/provider/ActivityProvider.java
// public class ActivityProvider {
// private PersistentScreenScope screenScope;
//
// public ActivityProvider(PersistentScreenScope screenScope) {
// this.screenScope = screenScope;
// }
//
// /**
// * @return actual Activity
// */
// public Activity get() {
// return screenScope.getParentActivity();
// }
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/screen/book/BookActivity.java
// public class BookActivity extends BaseActivity {
// private static final String EXTRA_BOOK_ID = "EXTRA_BOOK_ID";
//
// public static void start(Activity activity, String bookId) {
// Intent i = new Intent(activity, BookActivity.class);
// i.putExtra(EXTRA_BOOK_ID, bookId);
// activity.startActivity(i);
// }
//
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_book);
// FragmentManager fm = getSupportFragmentManager();
// if (fm.findFragmentByTag(BookFragmentView.class.getSimpleName()) == null) {
// Fragment fragment = BookFragmentView.create(getIntent().getStringExtra(EXTRA_BOOK_ID));
// FragmentTransaction fragmentTransaction = fm.beginTransaction();
// fragmentTransaction.add(R.id.container, fragment, BookFragmentView.class.getSimpleName());
// fragmentTransaction.commit();
// }
// }
// }
// Path: sample/src/main/java/com/agna/ferro/sample/ui/common/navigation/Navigator.java
import com.agna.ferro.mvp.component.provider.ActivityProvider;
import com.agna.ferro.mvp.component.scope.PerScreen;
import com.agna.ferro.sample.ui.screen.book.BookActivity;
import javax.inject.Inject;
package com.agna.ferro.sample.ui.common.navigation;
/**
* Encapsulate navigation between screens
*
* Example of class, which used {@link ActivityProvider}
* Object of this class retained in {@link com.agna.ferro.core.PersistentScreenScope} because
* it part of ScreenComponent
*/
@PerScreen
public class Navigator {
private final ActivityProvider activityProvider;
@Inject
public Navigator(ActivityProvider activityProvider) {
this.activityProvider = activityProvider;
}
public void openBookScreen(String bookId){ | BookActivity.start(activityProvider.get(), bookId); |
MaksTuev/ferro | sample/src/main/java/com/agna/ferro/sample/interactor/book/BookRepository.java | // Path: sample/src/main/java/com/agna/ferro/sample/domain/Book.java
// public class Book {
// private String id;
// private String name;
// private int downloadProgress;
// private String imageUrl;
//
// public Book(String id, String name, String imageUrl) {
// this.id = id;
// this.name = name;
// this.imageUrl = imageUrl;
// this.downloadProgress = -1;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getImageUrl() {
// return imageUrl;
// }
//
// public boolean isDownloaded() {
// return downloadProgress == 100;
// }
//
// public boolean isDownloading() {
// return downloadProgress >= 0;
// }
//
// public int getDownloadProgress() {
// return downloadProgress;
// }
//
// public void setDownloadProgress(int downloadProgress) {
// this.downloadProgress = downloadProgress;
// }
// }
| import android.content.Context;
import com.agna.ferro.mvp.component.scope.PerApplication;
import com.agna.ferro.sample.R;
import com.agna.ferro.sample.domain.Book;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import rx.Observable;
import rx.subjects.PublishSubject; | package com.agna.ferro.sample.interactor.book;
/**
* Repository of books
*/
@PerApplication
public class BookRepository {
private final Context appContext;
| // Path: sample/src/main/java/com/agna/ferro/sample/domain/Book.java
// public class Book {
// private String id;
// private String name;
// private int downloadProgress;
// private String imageUrl;
//
// public Book(String id, String name, String imageUrl) {
// this.id = id;
// this.name = name;
// this.imageUrl = imageUrl;
// this.downloadProgress = -1;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getImageUrl() {
// return imageUrl;
// }
//
// public boolean isDownloaded() {
// return downloadProgress == 100;
// }
//
// public boolean isDownloading() {
// return downloadProgress >= 0;
// }
//
// public int getDownloadProgress() {
// return downloadProgress;
// }
//
// public void setDownloadProgress(int downloadProgress) {
// this.downloadProgress = downloadProgress;
// }
// }
// Path: sample/src/main/java/com/agna/ferro/sample/interactor/book/BookRepository.java
import android.content.Context;
import com.agna.ferro.mvp.component.scope.PerApplication;
import com.agna.ferro.sample.R;
import com.agna.ferro.sample.domain.Book;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import rx.Observable;
import rx.subjects.PublishSubject;
package com.agna.ferro.sample.interactor.book;
/**
* Repository of books
*/
@PerApplication
public class BookRepository {
private final Context appContext;
| private CopyOnWriteArrayList<Book> books; |
MaksTuev/ferro | sample/src/main/java/com/agna/ferro/sample/ui/screen/catalog/CatalogScreenComponent.java | // Path: ferro-mvp/src/main/java/com/agna/ferro/mvp/component/ScreenComponent.java
// public interface ScreenComponent<V extends BaseView> {
// void inject(V view);
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/app/AppComponent.java
// @PerApplication
// @Component(modules = AppModule.class)
// public interface AppComponent {
//
// //Exposed to sub-graphs.
// Context context();
//
// BookRepository bookRepository();
//
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/common/dagger/ActivityModule.java
// @Module
// public class ActivityModule {
//
// private PersistentScreenScope persistentScreenScope;
//
// public ActivityModule(PersistentScreenScope persistentScreenScope) {
// this.persistentScreenScope = persistentScreenScope;
// }
//
// @Provides
// @PerScreen
// ActivityProvider provideActivityProvider() {
// return new ActivityProvider(persistentScreenScope);
// }
//
// }
| import com.agna.ferro.mvp.component.ScreenComponent;
import com.agna.ferro.mvp.component.scope.PerScreen;
import com.agna.ferro.sample.app.AppComponent;
import com.agna.ferro.sample.ui.common.dagger.ActivityModule;
import dagger.Component; | package com.agna.ferro.sample.ui.screen.catalog;
/**
* Component for Catalog screen
*/
@PerScreen
@Component(dependencies = AppComponent.class, modules = ActivityModule.class) | // Path: ferro-mvp/src/main/java/com/agna/ferro/mvp/component/ScreenComponent.java
// public interface ScreenComponent<V extends BaseView> {
// void inject(V view);
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/app/AppComponent.java
// @PerApplication
// @Component(modules = AppModule.class)
// public interface AppComponent {
//
// //Exposed to sub-graphs.
// Context context();
//
// BookRepository bookRepository();
//
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/common/dagger/ActivityModule.java
// @Module
// public class ActivityModule {
//
// private PersistentScreenScope persistentScreenScope;
//
// public ActivityModule(PersistentScreenScope persistentScreenScope) {
// this.persistentScreenScope = persistentScreenScope;
// }
//
// @Provides
// @PerScreen
// ActivityProvider provideActivityProvider() {
// return new ActivityProvider(persistentScreenScope);
// }
//
// }
// Path: sample/src/main/java/com/agna/ferro/sample/ui/screen/catalog/CatalogScreenComponent.java
import com.agna.ferro.mvp.component.ScreenComponent;
import com.agna.ferro.mvp.component.scope.PerScreen;
import com.agna.ferro.sample.app.AppComponent;
import com.agna.ferro.sample.ui.common.dagger.ActivityModule;
import dagger.Component;
package com.agna.ferro.sample.ui.screen.catalog;
/**
* Component for Catalog screen
*/
@PerScreen
@Component(dependencies = AppComponent.class, modules = ActivityModule.class) | interface CatalogScreenComponent extends ScreenComponent<CatalogActivityView> { |
MaksTuev/ferro | ferro-mvp/src/main/java/com/agna/ferro/mvp/view/BaseView.java | // Path: ferro-core/src/main/java/com/agna/ferro/core/HasName.java
// public interface HasName {
// /**
// * @return name
// */
// String getName();
// }
//
// Path: ferro-mvp/src/main/java/com/agna/ferro/mvp/component/ScreenComponent.java
// public interface ScreenComponent<V extends BaseView> {
// void inject(V view);
// }
//
// Path: ferro-mvp/src/main/java/com/agna/ferro/mvp/presenter/MvpPresenter.java
// public class MvpPresenter<V extends BaseView> implements
// PersistentScreenScope.OnScopeDestroyListener {
//
// private V view;
//
// public void attachView(V view) {
// this.view = view;
// }
//
// /**
// * @return screen's view
// */
// protected V getView() {
// return view;
// }
//
// /**
// * This method is called, when view is ready
// * @param viewRecreated - show whether view created in first time or recreated after
// * changing configuration
// */
// public void onLoad(boolean viewRecreated) {
// }
//
// /**
// * Called after {@link this#onLoad}
// */
// public void onLoadFinished() {
//
// }
//
// /**
// * Called when view is started
// */
// public void onStart(){
//
// }
//
// /**
// * Called when view is resumed
// */
// public void onResume(){
//
// }
//
// /**
// * Called when view is paused
// */
// public void onPause(){
//
// }
//
// /**
// * Called when view is stopped
// */
// public void onStop(){
//
// }
//
// public final void detachView() {
// view = null;
// onViewDetached();
// }
//
// /**
// * Called when view is detached
// */
// protected void onViewDetached() {
//
// }
//
// /**
// * Called when screen is finally destroyed
// */
// public void onDestroy() {
//
// }
// }
| import com.agna.ferro.core.HasName;
import com.agna.ferro.mvp.component.ScreenComponent;
import com.agna.ferro.mvp.presenter.MvpPresenter; | /*
* Copyright 2016 Maxim Tuev.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.agna.ferro.mvp.view;
public interface BaseView extends HasName {
/**
* @return presenter of the screen
*/
MvpPresenter getPresenter();
/**
* Bind presenter to this view
*/
void bindPresenter();
/**
* @return screen component
*/ | // Path: ferro-core/src/main/java/com/agna/ferro/core/HasName.java
// public interface HasName {
// /**
// * @return name
// */
// String getName();
// }
//
// Path: ferro-mvp/src/main/java/com/agna/ferro/mvp/component/ScreenComponent.java
// public interface ScreenComponent<V extends BaseView> {
// void inject(V view);
// }
//
// Path: ferro-mvp/src/main/java/com/agna/ferro/mvp/presenter/MvpPresenter.java
// public class MvpPresenter<V extends BaseView> implements
// PersistentScreenScope.OnScopeDestroyListener {
//
// private V view;
//
// public void attachView(V view) {
// this.view = view;
// }
//
// /**
// * @return screen's view
// */
// protected V getView() {
// return view;
// }
//
// /**
// * This method is called, when view is ready
// * @param viewRecreated - show whether view created in first time or recreated after
// * changing configuration
// */
// public void onLoad(boolean viewRecreated) {
// }
//
// /**
// * Called after {@link this#onLoad}
// */
// public void onLoadFinished() {
//
// }
//
// /**
// * Called when view is started
// */
// public void onStart(){
//
// }
//
// /**
// * Called when view is resumed
// */
// public void onResume(){
//
// }
//
// /**
// * Called when view is paused
// */
// public void onPause(){
//
// }
//
// /**
// * Called when view is stopped
// */
// public void onStop(){
//
// }
//
// public final void detachView() {
// view = null;
// onViewDetached();
// }
//
// /**
// * Called when view is detached
// */
// protected void onViewDetached() {
//
// }
//
// /**
// * Called when screen is finally destroyed
// */
// public void onDestroy() {
//
// }
// }
// Path: ferro-mvp/src/main/java/com/agna/ferro/mvp/view/BaseView.java
import com.agna.ferro.core.HasName;
import com.agna.ferro.mvp.component.ScreenComponent;
import com.agna.ferro.mvp.presenter.MvpPresenter;
/*
* Copyright 2016 Maxim Tuev.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.agna.ferro.mvp.view;
public interface BaseView extends HasName {
/**
* @return presenter of the screen
*/
MvpPresenter getPresenter();
/**
* Bind presenter to this view
*/
void bindPresenter();
/**
* @return screen component
*/ | ScreenComponent getScreenComponent(); |
MaksTuev/ferro | sample/src/main/java/com/agna/ferro/sample/ui/screen/book/BookScreenComponent.java | // Path: ferro-mvp/src/main/java/com/agna/ferro/mvp/component/ScreenComponent.java
// public interface ScreenComponent<V extends BaseView> {
// void inject(V view);
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/app/AppComponent.java
// @PerApplication
// @Component(modules = AppModule.class)
// public interface AppComponent {
//
// //Exposed to sub-graphs.
// Context context();
//
// BookRepository bookRepository();
//
// }
| import com.agna.ferro.mvp.component.ScreenComponent;
import com.agna.ferro.mvp.component.scope.PerScreen;
import com.agna.ferro.sample.app.AppComponent;
import dagger.Component; | package com.agna.ferro.sample.ui.screen.book;
/**
* component for Book screen
*/
@PerScreen
@Component(dependencies = AppComponent.class, modules = BookScreenModule.class) | // Path: ferro-mvp/src/main/java/com/agna/ferro/mvp/component/ScreenComponent.java
// public interface ScreenComponent<V extends BaseView> {
// void inject(V view);
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/app/AppComponent.java
// @PerApplication
// @Component(modules = AppModule.class)
// public interface AppComponent {
//
// //Exposed to sub-graphs.
// Context context();
//
// BookRepository bookRepository();
//
// }
// Path: sample/src/main/java/com/agna/ferro/sample/ui/screen/book/BookScreenComponent.java
import com.agna.ferro.mvp.component.ScreenComponent;
import com.agna.ferro.mvp.component.scope.PerScreen;
import com.agna.ferro.sample.app.AppComponent;
import dagger.Component;
package com.agna.ferro.sample.ui.screen.book;
/**
* component for Book screen
*/
@PerScreen
@Component(dependencies = AppComponent.class, modules = BookScreenModule.class) | interface BookScreenComponent extends ScreenComponent<BookFragmentView> { |
MaksTuev/ferro | sample/src/main/java/com/agna/ferro/sample/ui/screen/catalog/CatalogActivityView.java | // Path: ferro-mvp/src/main/java/com/agna/ferro/mvp/component/ScreenComponent.java
// public interface ScreenComponent<V extends BaseView> {
// void inject(V view);
// }
//
// Path: ferro-mvp/src/main/java/com/agna/ferro/mvp/presenter/MvpPresenter.java
// public class MvpPresenter<V extends BaseView> implements
// PersistentScreenScope.OnScopeDestroyListener {
//
// private V view;
//
// public void attachView(V view) {
// this.view = view;
// }
//
// /**
// * @return screen's view
// */
// protected V getView() {
// return view;
// }
//
// /**
// * This method is called, when view is ready
// * @param viewRecreated - show whether view created in first time or recreated after
// * changing configuration
// */
// public void onLoad(boolean viewRecreated) {
// }
//
// /**
// * Called after {@link this#onLoad}
// */
// public void onLoadFinished() {
//
// }
//
// /**
// * Called when view is started
// */
// public void onStart(){
//
// }
//
// /**
// * Called when view is resumed
// */
// public void onResume(){
//
// }
//
// /**
// * Called when view is paused
// */
// public void onPause(){
//
// }
//
// /**
// * Called when view is stopped
// */
// public void onStop(){
//
// }
//
// public final void detachView() {
// view = null;
// onViewDetached();
// }
//
// /**
// * Called when view is detached
// */
// protected void onViewDetached() {
//
// }
//
// /**
// * Called when screen is finally destroyed
// */
// public void onDestroy() {
//
// }
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/domain/Book.java
// public class Book {
// private String id;
// private String name;
// private int downloadProgress;
// private String imageUrl;
//
// public Book(String id, String name, String imageUrl) {
// this.id = id;
// this.name = name;
// this.imageUrl = imageUrl;
// this.downloadProgress = -1;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getImageUrl() {
// return imageUrl;
// }
//
// public boolean isDownloaded() {
// return downloadProgress == 100;
// }
//
// public boolean isDownloading() {
// return downloadProgress >= 0;
// }
//
// public int getDownloadProgress() {
// return downloadProgress;
// }
//
// public void setDownloadProgress(int downloadProgress) {
// this.downloadProgress = downloadProgress;
// }
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/base/BaseActivityView.java
// public abstract class BaseActivityView extends MvpActivityView {
//
// protected AppComponent getAppComponent() {
// return ((App) getApplication()).getAppComponent();
// }
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/common/dagger/ActivityModule.java
// @Module
// public class ActivityModule {
//
// private PersistentScreenScope persistentScreenScope;
//
// public ActivityModule(PersistentScreenScope persistentScreenScope) {
// this.persistentScreenScope = persistentScreenScope;
// }
//
// @Provides
// @PerScreen
// ActivityProvider provideActivityProvider() {
// return new ActivityProvider(persistentScreenScope);
// }
//
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/screen/catalog/grid/BookItemListener.java
// public interface BookItemListener {
// void onDownloadClick(Book book);
// void onReadClick(Book book);
// void onClick(Book book);
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/screen/catalog/grid/BooksAdapter.java
// public class BooksAdapter extends RecyclerView.Adapter<BookHolder> {
//
// private List<Book> books = new ArrayList<>();
// private final BookItemListener itemListener;
//
// public BooksAdapter(BookItemListener bookItemListener) {
// this.itemListener = bookItemListener;
// }
//
// @Override
// public BookHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// return BookHolder.newInstance(parent, itemListener);
// }
//
// @Override
// public void onBindViewHolder(BookHolder holder, int position) {
// holder.bind(books.get(position));
// }
//
// @Override
// public int getItemCount() {
// return books.size();
// }
//
// public void updateBooksData(List<Book> books) {
// this.books = books;
// }
// }
| import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.agna.ferro.mvp.component.ScreenComponent;
import com.agna.ferro.mvp.presenter.MvpPresenter;
import com.agna.ferro.sample.R;
import com.agna.ferro.sample.domain.Book;
import com.agna.ferro.sample.ui.base.BaseActivityView;
import com.agna.ferro.sample.ui.common.dagger.ActivityModule;
import com.agna.ferro.sample.ui.screen.catalog.grid.BookItemListener;
import com.agna.ferro.sample.ui.screen.catalog.grid.BooksAdapter;
import java.util.List;
import javax.inject.Inject; | package com.agna.ferro.sample.ui.screen.catalog;
/**
* view for Catalog screen
*/
public class CatalogActivityView extends BaseActivityView {
@Inject
CatalogPresenter presenter;
private Handler handler = new Handler();
private SwipeRefreshLayout swipeRefreshLayout;
private RecyclerView booksRw; | // Path: ferro-mvp/src/main/java/com/agna/ferro/mvp/component/ScreenComponent.java
// public interface ScreenComponent<V extends BaseView> {
// void inject(V view);
// }
//
// Path: ferro-mvp/src/main/java/com/agna/ferro/mvp/presenter/MvpPresenter.java
// public class MvpPresenter<V extends BaseView> implements
// PersistentScreenScope.OnScopeDestroyListener {
//
// private V view;
//
// public void attachView(V view) {
// this.view = view;
// }
//
// /**
// * @return screen's view
// */
// protected V getView() {
// return view;
// }
//
// /**
// * This method is called, when view is ready
// * @param viewRecreated - show whether view created in first time or recreated after
// * changing configuration
// */
// public void onLoad(boolean viewRecreated) {
// }
//
// /**
// * Called after {@link this#onLoad}
// */
// public void onLoadFinished() {
//
// }
//
// /**
// * Called when view is started
// */
// public void onStart(){
//
// }
//
// /**
// * Called when view is resumed
// */
// public void onResume(){
//
// }
//
// /**
// * Called when view is paused
// */
// public void onPause(){
//
// }
//
// /**
// * Called when view is stopped
// */
// public void onStop(){
//
// }
//
// public final void detachView() {
// view = null;
// onViewDetached();
// }
//
// /**
// * Called when view is detached
// */
// protected void onViewDetached() {
//
// }
//
// /**
// * Called when screen is finally destroyed
// */
// public void onDestroy() {
//
// }
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/domain/Book.java
// public class Book {
// private String id;
// private String name;
// private int downloadProgress;
// private String imageUrl;
//
// public Book(String id, String name, String imageUrl) {
// this.id = id;
// this.name = name;
// this.imageUrl = imageUrl;
// this.downloadProgress = -1;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getImageUrl() {
// return imageUrl;
// }
//
// public boolean isDownloaded() {
// return downloadProgress == 100;
// }
//
// public boolean isDownloading() {
// return downloadProgress >= 0;
// }
//
// public int getDownloadProgress() {
// return downloadProgress;
// }
//
// public void setDownloadProgress(int downloadProgress) {
// this.downloadProgress = downloadProgress;
// }
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/base/BaseActivityView.java
// public abstract class BaseActivityView extends MvpActivityView {
//
// protected AppComponent getAppComponent() {
// return ((App) getApplication()).getAppComponent();
// }
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/common/dagger/ActivityModule.java
// @Module
// public class ActivityModule {
//
// private PersistentScreenScope persistentScreenScope;
//
// public ActivityModule(PersistentScreenScope persistentScreenScope) {
// this.persistentScreenScope = persistentScreenScope;
// }
//
// @Provides
// @PerScreen
// ActivityProvider provideActivityProvider() {
// return new ActivityProvider(persistentScreenScope);
// }
//
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/screen/catalog/grid/BookItemListener.java
// public interface BookItemListener {
// void onDownloadClick(Book book);
// void onReadClick(Book book);
// void onClick(Book book);
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/screen/catalog/grid/BooksAdapter.java
// public class BooksAdapter extends RecyclerView.Adapter<BookHolder> {
//
// private List<Book> books = new ArrayList<>();
// private final BookItemListener itemListener;
//
// public BooksAdapter(BookItemListener bookItemListener) {
// this.itemListener = bookItemListener;
// }
//
// @Override
// public BookHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// return BookHolder.newInstance(parent, itemListener);
// }
//
// @Override
// public void onBindViewHolder(BookHolder holder, int position) {
// holder.bind(books.get(position));
// }
//
// @Override
// public int getItemCount() {
// return books.size();
// }
//
// public void updateBooksData(List<Book> books) {
// this.books = books;
// }
// }
// Path: sample/src/main/java/com/agna/ferro/sample/ui/screen/catalog/CatalogActivityView.java
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.agna.ferro.mvp.component.ScreenComponent;
import com.agna.ferro.mvp.presenter.MvpPresenter;
import com.agna.ferro.sample.R;
import com.agna.ferro.sample.domain.Book;
import com.agna.ferro.sample.ui.base.BaseActivityView;
import com.agna.ferro.sample.ui.common.dagger.ActivityModule;
import com.agna.ferro.sample.ui.screen.catalog.grid.BookItemListener;
import com.agna.ferro.sample.ui.screen.catalog.grid.BooksAdapter;
import java.util.List;
import javax.inject.Inject;
package com.agna.ferro.sample.ui.screen.catalog;
/**
* view for Catalog screen
*/
public class CatalogActivityView extends BaseActivityView {
@Inject
CatalogPresenter presenter;
private Handler handler = new Handler();
private SwipeRefreshLayout swipeRefreshLayout;
private RecyclerView booksRw; | private BooksAdapter adapter; |
MaksTuev/ferro | sample/src/main/java/com/agna/ferro/sample/ui/screen/catalog/CatalogActivityView.java | // Path: ferro-mvp/src/main/java/com/agna/ferro/mvp/component/ScreenComponent.java
// public interface ScreenComponent<V extends BaseView> {
// void inject(V view);
// }
//
// Path: ferro-mvp/src/main/java/com/agna/ferro/mvp/presenter/MvpPresenter.java
// public class MvpPresenter<V extends BaseView> implements
// PersistentScreenScope.OnScopeDestroyListener {
//
// private V view;
//
// public void attachView(V view) {
// this.view = view;
// }
//
// /**
// * @return screen's view
// */
// protected V getView() {
// return view;
// }
//
// /**
// * This method is called, when view is ready
// * @param viewRecreated - show whether view created in first time or recreated after
// * changing configuration
// */
// public void onLoad(boolean viewRecreated) {
// }
//
// /**
// * Called after {@link this#onLoad}
// */
// public void onLoadFinished() {
//
// }
//
// /**
// * Called when view is started
// */
// public void onStart(){
//
// }
//
// /**
// * Called when view is resumed
// */
// public void onResume(){
//
// }
//
// /**
// * Called when view is paused
// */
// public void onPause(){
//
// }
//
// /**
// * Called when view is stopped
// */
// public void onStop(){
//
// }
//
// public final void detachView() {
// view = null;
// onViewDetached();
// }
//
// /**
// * Called when view is detached
// */
// protected void onViewDetached() {
//
// }
//
// /**
// * Called when screen is finally destroyed
// */
// public void onDestroy() {
//
// }
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/domain/Book.java
// public class Book {
// private String id;
// private String name;
// private int downloadProgress;
// private String imageUrl;
//
// public Book(String id, String name, String imageUrl) {
// this.id = id;
// this.name = name;
// this.imageUrl = imageUrl;
// this.downloadProgress = -1;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getImageUrl() {
// return imageUrl;
// }
//
// public boolean isDownloaded() {
// return downloadProgress == 100;
// }
//
// public boolean isDownloading() {
// return downloadProgress >= 0;
// }
//
// public int getDownloadProgress() {
// return downloadProgress;
// }
//
// public void setDownloadProgress(int downloadProgress) {
// this.downloadProgress = downloadProgress;
// }
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/base/BaseActivityView.java
// public abstract class BaseActivityView extends MvpActivityView {
//
// protected AppComponent getAppComponent() {
// return ((App) getApplication()).getAppComponent();
// }
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/common/dagger/ActivityModule.java
// @Module
// public class ActivityModule {
//
// private PersistentScreenScope persistentScreenScope;
//
// public ActivityModule(PersistentScreenScope persistentScreenScope) {
// this.persistentScreenScope = persistentScreenScope;
// }
//
// @Provides
// @PerScreen
// ActivityProvider provideActivityProvider() {
// return new ActivityProvider(persistentScreenScope);
// }
//
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/screen/catalog/grid/BookItemListener.java
// public interface BookItemListener {
// void onDownloadClick(Book book);
// void onReadClick(Book book);
// void onClick(Book book);
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/screen/catalog/grid/BooksAdapter.java
// public class BooksAdapter extends RecyclerView.Adapter<BookHolder> {
//
// private List<Book> books = new ArrayList<>();
// private final BookItemListener itemListener;
//
// public BooksAdapter(BookItemListener bookItemListener) {
// this.itemListener = bookItemListener;
// }
//
// @Override
// public BookHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// return BookHolder.newInstance(parent, itemListener);
// }
//
// @Override
// public void onBindViewHolder(BookHolder holder, int position) {
// holder.bind(books.get(position));
// }
//
// @Override
// public int getItemCount() {
// return books.size();
// }
//
// public void updateBooksData(List<Book> books) {
// this.books = books;
// }
// }
| import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.agna.ferro.mvp.component.ScreenComponent;
import com.agna.ferro.mvp.presenter.MvpPresenter;
import com.agna.ferro.sample.R;
import com.agna.ferro.sample.domain.Book;
import com.agna.ferro.sample.ui.base.BaseActivityView;
import com.agna.ferro.sample.ui.common.dagger.ActivityModule;
import com.agna.ferro.sample.ui.screen.catalog.grid.BookItemListener;
import com.agna.ferro.sample.ui.screen.catalog.grid.BooksAdapter;
import java.util.List;
import javax.inject.Inject; | package com.agna.ferro.sample.ui.screen.catalog;
/**
* view for Catalog screen
*/
public class CatalogActivityView extends BaseActivityView {
@Inject
CatalogPresenter presenter;
private Handler handler = new Handler();
private SwipeRefreshLayout swipeRefreshLayout;
private RecyclerView booksRw;
private BooksAdapter adapter;
@Override
protected int getContentView() {
return R.layout.activity_catalog;
}
@Override | // Path: ferro-mvp/src/main/java/com/agna/ferro/mvp/component/ScreenComponent.java
// public interface ScreenComponent<V extends BaseView> {
// void inject(V view);
// }
//
// Path: ferro-mvp/src/main/java/com/agna/ferro/mvp/presenter/MvpPresenter.java
// public class MvpPresenter<V extends BaseView> implements
// PersistentScreenScope.OnScopeDestroyListener {
//
// private V view;
//
// public void attachView(V view) {
// this.view = view;
// }
//
// /**
// * @return screen's view
// */
// protected V getView() {
// return view;
// }
//
// /**
// * This method is called, when view is ready
// * @param viewRecreated - show whether view created in first time or recreated after
// * changing configuration
// */
// public void onLoad(boolean viewRecreated) {
// }
//
// /**
// * Called after {@link this#onLoad}
// */
// public void onLoadFinished() {
//
// }
//
// /**
// * Called when view is started
// */
// public void onStart(){
//
// }
//
// /**
// * Called when view is resumed
// */
// public void onResume(){
//
// }
//
// /**
// * Called when view is paused
// */
// public void onPause(){
//
// }
//
// /**
// * Called when view is stopped
// */
// public void onStop(){
//
// }
//
// public final void detachView() {
// view = null;
// onViewDetached();
// }
//
// /**
// * Called when view is detached
// */
// protected void onViewDetached() {
//
// }
//
// /**
// * Called when screen is finally destroyed
// */
// public void onDestroy() {
//
// }
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/domain/Book.java
// public class Book {
// private String id;
// private String name;
// private int downloadProgress;
// private String imageUrl;
//
// public Book(String id, String name, String imageUrl) {
// this.id = id;
// this.name = name;
// this.imageUrl = imageUrl;
// this.downloadProgress = -1;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getImageUrl() {
// return imageUrl;
// }
//
// public boolean isDownloaded() {
// return downloadProgress == 100;
// }
//
// public boolean isDownloading() {
// return downloadProgress >= 0;
// }
//
// public int getDownloadProgress() {
// return downloadProgress;
// }
//
// public void setDownloadProgress(int downloadProgress) {
// this.downloadProgress = downloadProgress;
// }
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/base/BaseActivityView.java
// public abstract class BaseActivityView extends MvpActivityView {
//
// protected AppComponent getAppComponent() {
// return ((App) getApplication()).getAppComponent();
// }
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/common/dagger/ActivityModule.java
// @Module
// public class ActivityModule {
//
// private PersistentScreenScope persistentScreenScope;
//
// public ActivityModule(PersistentScreenScope persistentScreenScope) {
// this.persistentScreenScope = persistentScreenScope;
// }
//
// @Provides
// @PerScreen
// ActivityProvider provideActivityProvider() {
// return new ActivityProvider(persistentScreenScope);
// }
//
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/screen/catalog/grid/BookItemListener.java
// public interface BookItemListener {
// void onDownloadClick(Book book);
// void onReadClick(Book book);
// void onClick(Book book);
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/screen/catalog/grid/BooksAdapter.java
// public class BooksAdapter extends RecyclerView.Adapter<BookHolder> {
//
// private List<Book> books = new ArrayList<>();
// private final BookItemListener itemListener;
//
// public BooksAdapter(BookItemListener bookItemListener) {
// this.itemListener = bookItemListener;
// }
//
// @Override
// public BookHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// return BookHolder.newInstance(parent, itemListener);
// }
//
// @Override
// public void onBindViewHolder(BookHolder holder, int position) {
// holder.bind(books.get(position));
// }
//
// @Override
// public int getItemCount() {
// return books.size();
// }
//
// public void updateBooksData(List<Book> books) {
// this.books = books;
// }
// }
// Path: sample/src/main/java/com/agna/ferro/sample/ui/screen/catalog/CatalogActivityView.java
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.agna.ferro.mvp.component.ScreenComponent;
import com.agna.ferro.mvp.presenter.MvpPresenter;
import com.agna.ferro.sample.R;
import com.agna.ferro.sample.domain.Book;
import com.agna.ferro.sample.ui.base.BaseActivityView;
import com.agna.ferro.sample.ui.common.dagger.ActivityModule;
import com.agna.ferro.sample.ui.screen.catalog.grid.BookItemListener;
import com.agna.ferro.sample.ui.screen.catalog.grid.BooksAdapter;
import java.util.List;
import javax.inject.Inject;
package com.agna.ferro.sample.ui.screen.catalog;
/**
* view for Catalog screen
*/
public class CatalogActivityView extends BaseActivityView {
@Inject
CatalogPresenter presenter;
private Handler handler = new Handler();
private SwipeRefreshLayout swipeRefreshLayout;
private RecyclerView booksRw;
private BooksAdapter adapter;
@Override
protected int getContentView() {
return R.layout.activity_catalog;
}
@Override | protected ScreenComponent createScreenComponent() { |
MaksTuev/ferro | sample/src/main/java/com/agna/ferro/sample/ui/screen/catalog/CatalogActivityView.java | // Path: ferro-mvp/src/main/java/com/agna/ferro/mvp/component/ScreenComponent.java
// public interface ScreenComponent<V extends BaseView> {
// void inject(V view);
// }
//
// Path: ferro-mvp/src/main/java/com/agna/ferro/mvp/presenter/MvpPresenter.java
// public class MvpPresenter<V extends BaseView> implements
// PersistentScreenScope.OnScopeDestroyListener {
//
// private V view;
//
// public void attachView(V view) {
// this.view = view;
// }
//
// /**
// * @return screen's view
// */
// protected V getView() {
// return view;
// }
//
// /**
// * This method is called, when view is ready
// * @param viewRecreated - show whether view created in first time or recreated after
// * changing configuration
// */
// public void onLoad(boolean viewRecreated) {
// }
//
// /**
// * Called after {@link this#onLoad}
// */
// public void onLoadFinished() {
//
// }
//
// /**
// * Called when view is started
// */
// public void onStart(){
//
// }
//
// /**
// * Called when view is resumed
// */
// public void onResume(){
//
// }
//
// /**
// * Called when view is paused
// */
// public void onPause(){
//
// }
//
// /**
// * Called when view is stopped
// */
// public void onStop(){
//
// }
//
// public final void detachView() {
// view = null;
// onViewDetached();
// }
//
// /**
// * Called when view is detached
// */
// protected void onViewDetached() {
//
// }
//
// /**
// * Called when screen is finally destroyed
// */
// public void onDestroy() {
//
// }
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/domain/Book.java
// public class Book {
// private String id;
// private String name;
// private int downloadProgress;
// private String imageUrl;
//
// public Book(String id, String name, String imageUrl) {
// this.id = id;
// this.name = name;
// this.imageUrl = imageUrl;
// this.downloadProgress = -1;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getImageUrl() {
// return imageUrl;
// }
//
// public boolean isDownloaded() {
// return downloadProgress == 100;
// }
//
// public boolean isDownloading() {
// return downloadProgress >= 0;
// }
//
// public int getDownloadProgress() {
// return downloadProgress;
// }
//
// public void setDownloadProgress(int downloadProgress) {
// this.downloadProgress = downloadProgress;
// }
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/base/BaseActivityView.java
// public abstract class BaseActivityView extends MvpActivityView {
//
// protected AppComponent getAppComponent() {
// return ((App) getApplication()).getAppComponent();
// }
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/common/dagger/ActivityModule.java
// @Module
// public class ActivityModule {
//
// private PersistentScreenScope persistentScreenScope;
//
// public ActivityModule(PersistentScreenScope persistentScreenScope) {
// this.persistentScreenScope = persistentScreenScope;
// }
//
// @Provides
// @PerScreen
// ActivityProvider provideActivityProvider() {
// return new ActivityProvider(persistentScreenScope);
// }
//
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/screen/catalog/grid/BookItemListener.java
// public interface BookItemListener {
// void onDownloadClick(Book book);
// void onReadClick(Book book);
// void onClick(Book book);
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/screen/catalog/grid/BooksAdapter.java
// public class BooksAdapter extends RecyclerView.Adapter<BookHolder> {
//
// private List<Book> books = new ArrayList<>();
// private final BookItemListener itemListener;
//
// public BooksAdapter(BookItemListener bookItemListener) {
// this.itemListener = bookItemListener;
// }
//
// @Override
// public BookHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// return BookHolder.newInstance(parent, itemListener);
// }
//
// @Override
// public void onBindViewHolder(BookHolder holder, int position) {
// holder.bind(books.get(position));
// }
//
// @Override
// public int getItemCount() {
// return books.size();
// }
//
// public void updateBooksData(List<Book> books) {
// this.books = books;
// }
// }
| import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.agna.ferro.mvp.component.ScreenComponent;
import com.agna.ferro.mvp.presenter.MvpPresenter;
import com.agna.ferro.sample.R;
import com.agna.ferro.sample.domain.Book;
import com.agna.ferro.sample.ui.base.BaseActivityView;
import com.agna.ferro.sample.ui.common.dagger.ActivityModule;
import com.agna.ferro.sample.ui.screen.catalog.grid.BookItemListener;
import com.agna.ferro.sample.ui.screen.catalog.grid.BooksAdapter;
import java.util.List;
import javax.inject.Inject; | package com.agna.ferro.sample.ui.screen.catalog;
/**
* view for Catalog screen
*/
public class CatalogActivityView extends BaseActivityView {
@Inject
CatalogPresenter presenter;
private Handler handler = new Handler();
private SwipeRefreshLayout swipeRefreshLayout;
private RecyclerView booksRw;
private BooksAdapter adapter;
@Override
protected int getContentView() {
return R.layout.activity_catalog;
}
@Override
protected ScreenComponent createScreenComponent() {
//creating Screen Component, you needn't call ScreenComponent#inject(this)
return DaggerCatalogScreenComponent.builder()
.appComponent(getAppComponent()) | // Path: ferro-mvp/src/main/java/com/agna/ferro/mvp/component/ScreenComponent.java
// public interface ScreenComponent<V extends BaseView> {
// void inject(V view);
// }
//
// Path: ferro-mvp/src/main/java/com/agna/ferro/mvp/presenter/MvpPresenter.java
// public class MvpPresenter<V extends BaseView> implements
// PersistentScreenScope.OnScopeDestroyListener {
//
// private V view;
//
// public void attachView(V view) {
// this.view = view;
// }
//
// /**
// * @return screen's view
// */
// protected V getView() {
// return view;
// }
//
// /**
// * This method is called, when view is ready
// * @param viewRecreated - show whether view created in first time or recreated after
// * changing configuration
// */
// public void onLoad(boolean viewRecreated) {
// }
//
// /**
// * Called after {@link this#onLoad}
// */
// public void onLoadFinished() {
//
// }
//
// /**
// * Called when view is started
// */
// public void onStart(){
//
// }
//
// /**
// * Called when view is resumed
// */
// public void onResume(){
//
// }
//
// /**
// * Called when view is paused
// */
// public void onPause(){
//
// }
//
// /**
// * Called when view is stopped
// */
// public void onStop(){
//
// }
//
// public final void detachView() {
// view = null;
// onViewDetached();
// }
//
// /**
// * Called when view is detached
// */
// protected void onViewDetached() {
//
// }
//
// /**
// * Called when screen is finally destroyed
// */
// public void onDestroy() {
//
// }
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/domain/Book.java
// public class Book {
// private String id;
// private String name;
// private int downloadProgress;
// private String imageUrl;
//
// public Book(String id, String name, String imageUrl) {
// this.id = id;
// this.name = name;
// this.imageUrl = imageUrl;
// this.downloadProgress = -1;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getImageUrl() {
// return imageUrl;
// }
//
// public boolean isDownloaded() {
// return downloadProgress == 100;
// }
//
// public boolean isDownloading() {
// return downloadProgress >= 0;
// }
//
// public int getDownloadProgress() {
// return downloadProgress;
// }
//
// public void setDownloadProgress(int downloadProgress) {
// this.downloadProgress = downloadProgress;
// }
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/base/BaseActivityView.java
// public abstract class BaseActivityView extends MvpActivityView {
//
// protected AppComponent getAppComponent() {
// return ((App) getApplication()).getAppComponent();
// }
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/common/dagger/ActivityModule.java
// @Module
// public class ActivityModule {
//
// private PersistentScreenScope persistentScreenScope;
//
// public ActivityModule(PersistentScreenScope persistentScreenScope) {
// this.persistentScreenScope = persistentScreenScope;
// }
//
// @Provides
// @PerScreen
// ActivityProvider provideActivityProvider() {
// return new ActivityProvider(persistentScreenScope);
// }
//
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/screen/catalog/grid/BookItemListener.java
// public interface BookItemListener {
// void onDownloadClick(Book book);
// void onReadClick(Book book);
// void onClick(Book book);
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/ui/screen/catalog/grid/BooksAdapter.java
// public class BooksAdapter extends RecyclerView.Adapter<BookHolder> {
//
// private List<Book> books = new ArrayList<>();
// private final BookItemListener itemListener;
//
// public BooksAdapter(BookItemListener bookItemListener) {
// this.itemListener = bookItemListener;
// }
//
// @Override
// public BookHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// return BookHolder.newInstance(parent, itemListener);
// }
//
// @Override
// public void onBindViewHolder(BookHolder holder, int position) {
// holder.bind(books.get(position));
// }
//
// @Override
// public int getItemCount() {
// return books.size();
// }
//
// public void updateBooksData(List<Book> books) {
// this.books = books;
// }
// }
// Path: sample/src/main/java/com/agna/ferro/sample/ui/screen/catalog/CatalogActivityView.java
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import com.agna.ferro.mvp.component.ScreenComponent;
import com.agna.ferro.mvp.presenter.MvpPresenter;
import com.agna.ferro.sample.R;
import com.agna.ferro.sample.domain.Book;
import com.agna.ferro.sample.ui.base.BaseActivityView;
import com.agna.ferro.sample.ui.common.dagger.ActivityModule;
import com.agna.ferro.sample.ui.screen.catalog.grid.BookItemListener;
import com.agna.ferro.sample.ui.screen.catalog.grid.BooksAdapter;
import java.util.List;
import javax.inject.Inject;
package com.agna.ferro.sample.ui.screen.catalog;
/**
* view for Catalog screen
*/
public class CatalogActivityView extends BaseActivityView {
@Inject
CatalogPresenter presenter;
private Handler handler = new Handler();
private SwipeRefreshLayout swipeRefreshLayout;
private RecyclerView booksRw;
private BooksAdapter adapter;
@Override
protected int getContentView() {
return R.layout.activity_catalog;
}
@Override
protected ScreenComponent createScreenComponent() {
//creating Screen Component, you needn't call ScreenComponent#inject(this)
return DaggerCatalogScreenComponent.builder()
.appComponent(getAppComponent()) | .activityModule(new ActivityModule(getPersistentScreenScope())) |
MaksTuev/ferro | sample/src/main/java/com/agna/ferro/sample/ui/base/BaseActivityView.java | // Path: ferro-mvp/src/main/java/com/agna/ferro/mvp/view/activity/MvpActivityView.java
// public abstract class MvpActivityView extends PSSActivity implements BaseView {
//
// /**
// * @return unique screen name
// */
// public abstract String getName();
//
// /**
// * @return layout resource of the screen
// */
// @LayoutRes
// protected abstract int getContentView();
//
// /**
// * @return screen component
// */
// protected abstract ScreenComponent createScreenComponent();
//
// @Override
// protected final void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// onPreCreate(savedInstanceState, isScreenRecreated());
// setContentView(getContentView());
// satisfyDependencies();
// bindPresenter();
// onCreate(savedInstanceState, isScreenRecreated());
// getPresenter().onLoad(isScreenRecreated());
// getPresenter().onLoadFinished();
// }
//
// /**
// * Override this instead {@link #onCreate(Bundle)}
// * @param viewRecreated show whether view created in first time or recreated after
// * changing configuration
// */
// protected void onCreate(Bundle savedInstanceState, boolean viewRecreated) {
//
// }
//
// /**
// * Called before Presenter and ScreenScope are bound to the View and content view is created
// * @param savedInstanceState
// * @param viewRecreated
// */
// protected void onPreCreate(Bundle savedInstanceState, boolean viewRecreated) {
//
// }
//
// @Override
// protected void onStart() {
// super.onStart();
// getPresenter().onStart();
// }
//
// @Override
// public Object onRetainCustomNonConfigurationInstance() {
// return super.onRetainCustomNonConfigurationInstance();
// }
//
// @Override
// protected void onResume() {
// super.onResume();
// getPresenter().onResume();
// }
//
// @Override
// protected void onPause() {
// super.onPause();
// getPresenter().onPause();
// }
//
// @Override
// protected void onStop() {
// super.onStop();
// getPresenter().onStop();
// }
//
// /**
// * Satisfy dependencies
// */
// protected void satisfyDependencies() {
// PersistentScreenScope screenScope = getPersistentScreenScope();
// ScreenComponent component = getScreenComponent();
// if (component == null) {
// component = createScreenComponent();
// screenScope.putObject(component, ScreenComponent.class);
// }
// component.inject(this);
// }
//
// public ScreenComponent getScreenComponent() {
// PersistentScreenScope screenScope = getPersistentScreenScope();
// return screenScope.getObject(ScreenComponent.class);
// }
//
// /**
// * Bind presenter to this view
// */
// @Override
// public final void bindPresenter() {
// getPresenter().attachView(this);
// if(!isScreenRecreated()) {
// getPersistentScreenScope().addOnScopeDestroyListener(getPresenter());
// }
// }
//
// @Override
// protected void onDestroy() {
// super.onDestroy();
// getPresenter().detachView();
// }
//
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/app/App.java
// public class App extends Application {
//
// private AppComponent appComponent;
//
// @Override
// public void onCreate() {
// super.onCreate();
// initInjector();
// initLog();
// }
//
// private void initLog() {
// Timber.plant(new Timber.DebugTree());
// }
//
// private void initInjector() {
// appComponent = DaggerAppComponent.builder()
// .appModule(new AppModule(this))
// .build();
// }
//
// public AppComponent getAppComponent() {
// return this.appComponent;
// }
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/app/AppComponent.java
// @PerApplication
// @Component(modules = AppModule.class)
// public interface AppComponent {
//
// //Exposed to sub-graphs.
// Context context();
//
// BookRepository bookRepository();
//
// }
| import com.agna.ferro.mvp.view.activity.MvpActivityView;
import com.agna.ferro.sample.app.App;
import com.agna.ferro.sample.app.AppComponent; | package com.agna.ferro.sample.ui.base;
/**
* Base class for view, based on Activity
*/
public abstract class BaseActivityView extends MvpActivityView {
protected AppComponent getAppComponent() { | // Path: ferro-mvp/src/main/java/com/agna/ferro/mvp/view/activity/MvpActivityView.java
// public abstract class MvpActivityView extends PSSActivity implements BaseView {
//
// /**
// * @return unique screen name
// */
// public abstract String getName();
//
// /**
// * @return layout resource of the screen
// */
// @LayoutRes
// protected abstract int getContentView();
//
// /**
// * @return screen component
// */
// protected abstract ScreenComponent createScreenComponent();
//
// @Override
// protected final void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// onPreCreate(savedInstanceState, isScreenRecreated());
// setContentView(getContentView());
// satisfyDependencies();
// bindPresenter();
// onCreate(savedInstanceState, isScreenRecreated());
// getPresenter().onLoad(isScreenRecreated());
// getPresenter().onLoadFinished();
// }
//
// /**
// * Override this instead {@link #onCreate(Bundle)}
// * @param viewRecreated show whether view created in first time or recreated after
// * changing configuration
// */
// protected void onCreate(Bundle savedInstanceState, boolean viewRecreated) {
//
// }
//
// /**
// * Called before Presenter and ScreenScope are bound to the View and content view is created
// * @param savedInstanceState
// * @param viewRecreated
// */
// protected void onPreCreate(Bundle savedInstanceState, boolean viewRecreated) {
//
// }
//
// @Override
// protected void onStart() {
// super.onStart();
// getPresenter().onStart();
// }
//
// @Override
// public Object onRetainCustomNonConfigurationInstance() {
// return super.onRetainCustomNonConfigurationInstance();
// }
//
// @Override
// protected void onResume() {
// super.onResume();
// getPresenter().onResume();
// }
//
// @Override
// protected void onPause() {
// super.onPause();
// getPresenter().onPause();
// }
//
// @Override
// protected void onStop() {
// super.onStop();
// getPresenter().onStop();
// }
//
// /**
// * Satisfy dependencies
// */
// protected void satisfyDependencies() {
// PersistentScreenScope screenScope = getPersistentScreenScope();
// ScreenComponent component = getScreenComponent();
// if (component == null) {
// component = createScreenComponent();
// screenScope.putObject(component, ScreenComponent.class);
// }
// component.inject(this);
// }
//
// public ScreenComponent getScreenComponent() {
// PersistentScreenScope screenScope = getPersistentScreenScope();
// return screenScope.getObject(ScreenComponent.class);
// }
//
// /**
// * Bind presenter to this view
// */
// @Override
// public final void bindPresenter() {
// getPresenter().attachView(this);
// if(!isScreenRecreated()) {
// getPersistentScreenScope().addOnScopeDestroyListener(getPresenter());
// }
// }
//
// @Override
// protected void onDestroy() {
// super.onDestroy();
// getPresenter().detachView();
// }
//
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/app/App.java
// public class App extends Application {
//
// private AppComponent appComponent;
//
// @Override
// public void onCreate() {
// super.onCreate();
// initInjector();
// initLog();
// }
//
// private void initLog() {
// Timber.plant(new Timber.DebugTree());
// }
//
// private void initInjector() {
// appComponent = DaggerAppComponent.builder()
// .appModule(new AppModule(this))
// .build();
// }
//
// public AppComponent getAppComponent() {
// return this.appComponent;
// }
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/app/AppComponent.java
// @PerApplication
// @Component(modules = AppModule.class)
// public interface AppComponent {
//
// //Exposed to sub-graphs.
// Context context();
//
// BookRepository bookRepository();
//
// }
// Path: sample/src/main/java/com/agna/ferro/sample/ui/base/BaseActivityView.java
import com.agna.ferro.mvp.view.activity.MvpActivityView;
import com.agna.ferro.sample.app.App;
import com.agna.ferro.sample.app.AppComponent;
package com.agna.ferro.sample.ui.base;
/**
* Base class for view, based on Activity
*/
public abstract class BaseActivityView extends MvpActivityView {
protected AppComponent getAppComponent() { | return ((App) getApplication()).getAppComponent(); |
MaksTuev/ferro | sample/src/main/java/com/agna/ferro/sample/ui/base/BaseActivity.java | // Path: sample/src/main/java/com/agna/ferro/sample/app/App.java
// public class App extends Application {
//
// private AppComponent appComponent;
//
// @Override
// public void onCreate() {
// super.onCreate();
// initInjector();
// initLog();
// }
//
// private void initLog() {
// Timber.plant(new Timber.DebugTree());
// }
//
// private void initInjector() {
// appComponent = DaggerAppComponent.builder()
// .appModule(new AppModule(this))
// .build();
// }
//
// public AppComponent getAppComponent() {
// return this.appComponent;
// }
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/app/AppComponent.java
// @PerApplication
// @Component(modules = AppModule.class)
// public interface AppComponent {
//
// //Exposed to sub-graphs.
// Context context();
//
// BookRepository bookRepository();
//
// }
| import android.support.v7.app.AppCompatActivity;
import com.agna.ferro.sample.app.App;
import com.agna.ferro.sample.app.AppComponent; | package com.agna.ferro.sample.ui.base;
/**
* Base class for Activity, which used how container for fragment
*/
public abstract class BaseActivity extends AppCompatActivity {
public AppComponent getAppComponent() { | // Path: sample/src/main/java/com/agna/ferro/sample/app/App.java
// public class App extends Application {
//
// private AppComponent appComponent;
//
// @Override
// public void onCreate() {
// super.onCreate();
// initInjector();
// initLog();
// }
//
// private void initLog() {
// Timber.plant(new Timber.DebugTree());
// }
//
// private void initInjector() {
// appComponent = DaggerAppComponent.builder()
// .appModule(new AppModule(this))
// .build();
// }
//
// public AppComponent getAppComponent() {
// return this.appComponent;
// }
// }
//
// Path: sample/src/main/java/com/agna/ferro/sample/app/AppComponent.java
// @PerApplication
// @Component(modules = AppModule.class)
// public interface AppComponent {
//
// //Exposed to sub-graphs.
// Context context();
//
// BookRepository bookRepository();
//
// }
// Path: sample/src/main/java/com/agna/ferro/sample/ui/base/BaseActivity.java
import android.support.v7.app.AppCompatActivity;
import com.agna.ferro.sample.app.App;
import com.agna.ferro.sample.app.AppComponent;
package com.agna.ferro.sample.ui.base;
/**
* Base class for Activity, which used how container for fragment
*/
public abstract class BaseActivity extends AppCompatActivity {
public AppComponent getAppComponent() { | return ((App) getApplication()).getAppComponent(); |
MaksTuev/ferro | sample/src/main/java/com/agna/ferro/sample/ui/screen/catalog/grid/BookHolder.java | // Path: sample/src/main/java/com/agna/ferro/sample/domain/Book.java
// public class Book {
// private String id;
// private String name;
// private int downloadProgress;
// private String imageUrl;
//
// public Book(String id, String name, String imageUrl) {
// this.id = id;
// this.name = name;
// this.imageUrl = imageUrl;
// this.downloadProgress = -1;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getImageUrl() {
// return imageUrl;
// }
//
// public boolean isDownloaded() {
// return downloadProgress == 100;
// }
//
// public boolean isDownloading() {
// return downloadProgress >= 0;
// }
//
// public int getDownloadProgress() {
// return downloadProgress;
// }
//
// public void setDownloadProgress(int downloadProgress) {
// this.downloadProgress = downloadProgress;
// }
// }
| import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.agna.ferro.sample.R;
import com.agna.ferro.sample.domain.Book;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target; | package com.agna.ferro.sample.ui.screen.catalog.grid;
/**
* ViewHolder for Book
*/
public class BookHolder extends RecyclerView.ViewHolder {
private final TextView name;
private final ImageView image;
private final Button downloadBtn;
private final View readBtn; | // Path: sample/src/main/java/com/agna/ferro/sample/domain/Book.java
// public class Book {
// private String id;
// private String name;
// private int downloadProgress;
// private String imageUrl;
//
// public Book(String id, String name, String imageUrl) {
// this.id = id;
// this.name = name;
// this.imageUrl = imageUrl;
// this.downloadProgress = -1;
// }
//
// public String getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getImageUrl() {
// return imageUrl;
// }
//
// public boolean isDownloaded() {
// return downloadProgress == 100;
// }
//
// public boolean isDownloading() {
// return downloadProgress >= 0;
// }
//
// public int getDownloadProgress() {
// return downloadProgress;
// }
//
// public void setDownloadProgress(int downloadProgress) {
// this.downloadProgress = downloadProgress;
// }
// }
// Path: sample/src/main/java/com/agna/ferro/sample/ui/screen/catalog/grid/BookHolder.java
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.agna.ferro.sample.R;
import com.agna.ferro.sample.domain.Book;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
package com.agna.ferro.sample.ui.screen.catalog.grid;
/**
* ViewHolder for Book
*/
public class BookHolder extends RecyclerView.ViewHolder {
private final TextView name;
private final ImageView image;
private final Button downloadBtn;
private final View readBtn; | private Book book; |
isel-leic-mpd/mpd-2017-i41d | aula05-generic-methods/src/main/java/weather/WeatherWebApi.java | // Path: aula33-weather-async/src/main/java/util/IRequest.java
// public interface IRequest extends AutoCloseable{
// CompletableFuture<Stream<String>> getContent(String path);
//
// @Override
// public default void close() {
// }
// }
//
// Path: aula09-composition-and-decorator/src/main/java/weather/model/Location.java
// public class Location {
// private final String country;
// private final String region;
// private final double latitude;
// private final double longitude;
//
// public Location(String country, String region, double latitude, double longitude) {
// this.country = country;
// this.region = region;
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getRegion() {
// return region;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public static Location valueOf(String line) {
// String[] data = line.split("\t");
// return new Location(
// data[1],
// data[2],
// Double.parseDouble(data[3]),
// Double.parseDouble(data[4]));
// }
//
// @Override
// public String toString() {
// return "Location{" +
// "country='" + country + '\'' +
// ", region='" + region + '\'' +
// ", latitude=" + latitude +
// ", longitude=" + longitude +
// '}';
// }
// }
//
// Path: aula09-composition-and-decorator/src/main/java/weather/model/WeatherInfo.java
// public class WeatherInfo {
// private final LocalDate date; // index 0
// private final int tempC; // index 2
// private final String description; // index 10
// private final double precipMM; // index 11
// private final int feelsLikeC; // index 24
//
// public WeatherInfo(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {
// this.date = date;
// this.tempC = tempC;
// this.description = description;
// this.precipMM = precipMM;
// this.feelsLikeC = feelsLikeC;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public int getTempC() {
// return tempC;
// }
//
// public String getDescription() {
// return description;
// }
//
// public double getPrecipMM() {
// return precipMM;
// }
//
// public int getFeelsLikeC() {
// return feelsLikeC;
// }
//
// @Override
// public String toString() {
// return "WeatherInfo{" +
// date +
// ", tempC=" + tempC +
// ", '" + description + '\'' +
// ", precipMM=" + precipMM +
// ", feelsLikeC=" + feelsLikeC +
// '}';
// }
//
// /**
// * Hourly information follows below the day according to the format of
// * /past weather resource of the World Weather Online API
// */
// public static WeatherInfo valueOf(String line) {
// String[] data = line.split(",");
// return new WeatherInfo(
// LocalDate.parse(data[0]),
// Integer.parseInt(data[2]),
// data[10],
// Double.parseDouble(data[11]),
// Integer.parseInt(data[24]));
// }
// }
| import java.util.List;
import util.IRequest;
import weather.dto.Location;
import weather.dto.WeatherInfo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.net.URL;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Iterator; | /*
* Copyright (c) 2017, Miguel Gamboa
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package weather;
/**
* @author Miguel Gamboa
* created on 07-03-2017
*/
public class WeatherWebApi {
private static final String WEATHER_TOKEN;
private static final String WEATHER_HOST = "http://data.worldweatheronline.com";
private static final String WEATHER_PAST = "/premium/v1/past-weather.ashx";
private static final String WEATHER_PAST_ARGS =
"?q=%s&date=%s&enddate=%s&tp=24&format=csv&key=%s";
private static final String WEATHER_SEARCH="/premium/v1/search.ashx?query=%s";
private static final String WEATHER_SEARCH_ARGS="&format=tab&key=%s";
static {
try {
URL keyFile = ClassLoader.getSystemResource("worldweatheronline-app-key.txt");
if(keyFile == null) {
throw new IllegalStateException(
"YOU MUST GOT a KEY in developer.worldweatheronline.com and place it in src/main/resources/worldweatheronline-app-key.txt");
} else {
InputStream keyStream = keyFile.openStream();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(keyStream))) {
WEATHER_TOKEN = reader.readLine();
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
| // Path: aula33-weather-async/src/main/java/util/IRequest.java
// public interface IRequest extends AutoCloseable{
// CompletableFuture<Stream<String>> getContent(String path);
//
// @Override
// public default void close() {
// }
// }
//
// Path: aula09-composition-and-decorator/src/main/java/weather/model/Location.java
// public class Location {
// private final String country;
// private final String region;
// private final double latitude;
// private final double longitude;
//
// public Location(String country, String region, double latitude, double longitude) {
// this.country = country;
// this.region = region;
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getRegion() {
// return region;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public static Location valueOf(String line) {
// String[] data = line.split("\t");
// return new Location(
// data[1],
// data[2],
// Double.parseDouble(data[3]),
// Double.parseDouble(data[4]));
// }
//
// @Override
// public String toString() {
// return "Location{" +
// "country='" + country + '\'' +
// ", region='" + region + '\'' +
// ", latitude=" + latitude +
// ", longitude=" + longitude +
// '}';
// }
// }
//
// Path: aula09-composition-and-decorator/src/main/java/weather/model/WeatherInfo.java
// public class WeatherInfo {
// private final LocalDate date; // index 0
// private final int tempC; // index 2
// private final String description; // index 10
// private final double precipMM; // index 11
// private final int feelsLikeC; // index 24
//
// public WeatherInfo(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {
// this.date = date;
// this.tempC = tempC;
// this.description = description;
// this.precipMM = precipMM;
// this.feelsLikeC = feelsLikeC;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public int getTempC() {
// return tempC;
// }
//
// public String getDescription() {
// return description;
// }
//
// public double getPrecipMM() {
// return precipMM;
// }
//
// public int getFeelsLikeC() {
// return feelsLikeC;
// }
//
// @Override
// public String toString() {
// return "WeatherInfo{" +
// date +
// ", tempC=" + tempC +
// ", '" + description + '\'' +
// ", precipMM=" + precipMM +
// ", feelsLikeC=" + feelsLikeC +
// '}';
// }
//
// /**
// * Hourly information follows below the day according to the format of
// * /past weather resource of the World Weather Online API
// */
// public static WeatherInfo valueOf(String line) {
// String[] data = line.split(",");
// return new WeatherInfo(
// LocalDate.parse(data[0]),
// Integer.parseInt(data[2]),
// data[10],
// Double.parseDouble(data[11]),
// Integer.parseInt(data[24]));
// }
// }
// Path: aula05-generic-methods/src/main/java/weather/WeatherWebApi.java
import java.util.List;
import util.IRequest;
import weather.dto.Location;
import weather.dto.WeatherInfo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.net.URL;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Iterator;
/*
* Copyright (c) 2017, Miguel Gamboa
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package weather;
/**
* @author Miguel Gamboa
* created on 07-03-2017
*/
public class WeatherWebApi {
private static final String WEATHER_TOKEN;
private static final String WEATHER_HOST = "http://data.worldweatheronline.com";
private static final String WEATHER_PAST = "/premium/v1/past-weather.ashx";
private static final String WEATHER_PAST_ARGS =
"?q=%s&date=%s&enddate=%s&tp=24&format=csv&key=%s";
private static final String WEATHER_SEARCH="/premium/v1/search.ashx?query=%s";
private static final String WEATHER_SEARCH_ARGS="&format=tab&key=%s";
static {
try {
URL keyFile = ClassLoader.getSystemResource("worldweatheronline-app-key.txt");
if(keyFile == null) {
throw new IllegalStateException(
"YOU MUST GOT a KEY in developer.worldweatheronline.com and place it in src/main/resources/worldweatheronline-app-key.txt");
} else {
InputStream keyStream = keyFile.openStream();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(keyStream))) {
WEATHER_TOKEN = reader.readLine();
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
| private final IRequest req; |
isel-leic-mpd/mpd-2017-i41d | aula05-generic-methods/src/main/java/weather/WeatherWebApi.java | // Path: aula33-weather-async/src/main/java/util/IRequest.java
// public interface IRequest extends AutoCloseable{
// CompletableFuture<Stream<String>> getContent(String path);
//
// @Override
// public default void close() {
// }
// }
//
// Path: aula09-composition-and-decorator/src/main/java/weather/model/Location.java
// public class Location {
// private final String country;
// private final String region;
// private final double latitude;
// private final double longitude;
//
// public Location(String country, String region, double latitude, double longitude) {
// this.country = country;
// this.region = region;
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getRegion() {
// return region;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public static Location valueOf(String line) {
// String[] data = line.split("\t");
// return new Location(
// data[1],
// data[2],
// Double.parseDouble(data[3]),
// Double.parseDouble(data[4]));
// }
//
// @Override
// public String toString() {
// return "Location{" +
// "country='" + country + '\'' +
// ", region='" + region + '\'' +
// ", latitude=" + latitude +
// ", longitude=" + longitude +
// '}';
// }
// }
//
// Path: aula09-composition-and-decorator/src/main/java/weather/model/WeatherInfo.java
// public class WeatherInfo {
// private final LocalDate date; // index 0
// private final int tempC; // index 2
// private final String description; // index 10
// private final double precipMM; // index 11
// private final int feelsLikeC; // index 24
//
// public WeatherInfo(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {
// this.date = date;
// this.tempC = tempC;
// this.description = description;
// this.precipMM = precipMM;
// this.feelsLikeC = feelsLikeC;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public int getTempC() {
// return tempC;
// }
//
// public String getDescription() {
// return description;
// }
//
// public double getPrecipMM() {
// return precipMM;
// }
//
// public int getFeelsLikeC() {
// return feelsLikeC;
// }
//
// @Override
// public String toString() {
// return "WeatherInfo{" +
// date +
// ", tempC=" + tempC +
// ", '" + description + '\'' +
// ", precipMM=" + precipMM +
// ", feelsLikeC=" + feelsLikeC +
// '}';
// }
//
// /**
// * Hourly information follows below the day according to the format of
// * /past weather resource of the World Weather Online API
// */
// public static WeatherInfo valueOf(String line) {
// String[] data = line.split(",");
// return new WeatherInfo(
// LocalDate.parse(data[0]),
// Integer.parseInt(data[2]),
// data[10],
// Double.parseDouble(data[11]),
// Integer.parseInt(data[24]));
// }
// }
| import java.util.List;
import util.IRequest;
import weather.dto.Location;
import weather.dto.WeatherInfo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.net.URL;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Iterator; | /*
* Copyright (c) 2017, Miguel Gamboa
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package weather;
/**
* @author Miguel Gamboa
* created on 07-03-2017
*/
public class WeatherWebApi {
private static final String WEATHER_TOKEN;
private static final String WEATHER_HOST = "http://data.worldweatheronline.com";
private static final String WEATHER_PAST = "/premium/v1/past-weather.ashx";
private static final String WEATHER_PAST_ARGS =
"?q=%s&date=%s&enddate=%s&tp=24&format=csv&key=%s";
private static final String WEATHER_SEARCH="/premium/v1/search.ashx?query=%s";
private static final String WEATHER_SEARCH_ARGS="&format=tab&key=%s";
static {
try {
URL keyFile = ClassLoader.getSystemResource("worldweatheronline-app-key.txt");
if(keyFile == null) {
throw new IllegalStateException(
"YOU MUST GOT a KEY in developer.worldweatheronline.com and place it in src/main/resources/worldweatheronline-app-key.txt");
} else {
InputStream keyStream = keyFile.openStream();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(keyStream))) {
WEATHER_TOKEN = reader.readLine();
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private final IRequest req;
public WeatherWebApi(IRequest req) {
this.req = req;
}
/**
* E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****
*/
| // Path: aula33-weather-async/src/main/java/util/IRequest.java
// public interface IRequest extends AutoCloseable{
// CompletableFuture<Stream<String>> getContent(String path);
//
// @Override
// public default void close() {
// }
// }
//
// Path: aula09-composition-and-decorator/src/main/java/weather/model/Location.java
// public class Location {
// private final String country;
// private final String region;
// private final double latitude;
// private final double longitude;
//
// public Location(String country, String region, double latitude, double longitude) {
// this.country = country;
// this.region = region;
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getRegion() {
// return region;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public static Location valueOf(String line) {
// String[] data = line.split("\t");
// return new Location(
// data[1],
// data[2],
// Double.parseDouble(data[3]),
// Double.parseDouble(data[4]));
// }
//
// @Override
// public String toString() {
// return "Location{" +
// "country='" + country + '\'' +
// ", region='" + region + '\'' +
// ", latitude=" + latitude +
// ", longitude=" + longitude +
// '}';
// }
// }
//
// Path: aula09-composition-and-decorator/src/main/java/weather/model/WeatherInfo.java
// public class WeatherInfo {
// private final LocalDate date; // index 0
// private final int tempC; // index 2
// private final String description; // index 10
// private final double precipMM; // index 11
// private final int feelsLikeC; // index 24
//
// public WeatherInfo(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {
// this.date = date;
// this.tempC = tempC;
// this.description = description;
// this.precipMM = precipMM;
// this.feelsLikeC = feelsLikeC;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public int getTempC() {
// return tempC;
// }
//
// public String getDescription() {
// return description;
// }
//
// public double getPrecipMM() {
// return precipMM;
// }
//
// public int getFeelsLikeC() {
// return feelsLikeC;
// }
//
// @Override
// public String toString() {
// return "WeatherInfo{" +
// date +
// ", tempC=" + tempC +
// ", '" + description + '\'' +
// ", precipMM=" + precipMM +
// ", feelsLikeC=" + feelsLikeC +
// '}';
// }
//
// /**
// * Hourly information follows below the day according to the format of
// * /past weather resource of the World Weather Online API
// */
// public static WeatherInfo valueOf(String line) {
// String[] data = line.split(",");
// return new WeatherInfo(
// LocalDate.parse(data[0]),
// Integer.parseInt(data[2]),
// data[10],
// Double.parseDouble(data[11]),
// Integer.parseInt(data[24]));
// }
// }
// Path: aula05-generic-methods/src/main/java/weather/WeatherWebApi.java
import java.util.List;
import util.IRequest;
import weather.dto.Location;
import weather.dto.WeatherInfo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.net.URL;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Iterator;
/*
* Copyright (c) 2017, Miguel Gamboa
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package weather;
/**
* @author Miguel Gamboa
* created on 07-03-2017
*/
public class WeatherWebApi {
private static final String WEATHER_TOKEN;
private static final String WEATHER_HOST = "http://data.worldweatheronline.com";
private static final String WEATHER_PAST = "/premium/v1/past-weather.ashx";
private static final String WEATHER_PAST_ARGS =
"?q=%s&date=%s&enddate=%s&tp=24&format=csv&key=%s";
private static final String WEATHER_SEARCH="/premium/v1/search.ashx?query=%s";
private static final String WEATHER_SEARCH_ARGS="&format=tab&key=%s";
static {
try {
URL keyFile = ClassLoader.getSystemResource("worldweatheronline-app-key.txt");
if(keyFile == null) {
throw new IllegalStateException(
"YOU MUST GOT a KEY in developer.worldweatheronline.com and place it in src/main/resources/worldweatheronline-app-key.txt");
} else {
InputStream keyStream = keyFile.openStream();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(keyStream))) {
WEATHER_TOKEN = reader.readLine();
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private final IRequest req;
public WeatherWebApi(IRequest req) {
this.req = req;
}
/**
* E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****
*/
| public Iterable<Location> search(String query) { |
isel-leic-mpd/mpd-2017-i41d | aula05-generic-methods/src/main/java/weather/WeatherWebApi.java | // Path: aula33-weather-async/src/main/java/util/IRequest.java
// public interface IRequest extends AutoCloseable{
// CompletableFuture<Stream<String>> getContent(String path);
//
// @Override
// public default void close() {
// }
// }
//
// Path: aula09-composition-and-decorator/src/main/java/weather/model/Location.java
// public class Location {
// private final String country;
// private final String region;
// private final double latitude;
// private final double longitude;
//
// public Location(String country, String region, double latitude, double longitude) {
// this.country = country;
// this.region = region;
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getRegion() {
// return region;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public static Location valueOf(String line) {
// String[] data = line.split("\t");
// return new Location(
// data[1],
// data[2],
// Double.parseDouble(data[3]),
// Double.parseDouble(data[4]));
// }
//
// @Override
// public String toString() {
// return "Location{" +
// "country='" + country + '\'' +
// ", region='" + region + '\'' +
// ", latitude=" + latitude +
// ", longitude=" + longitude +
// '}';
// }
// }
//
// Path: aula09-composition-and-decorator/src/main/java/weather/model/WeatherInfo.java
// public class WeatherInfo {
// private final LocalDate date; // index 0
// private final int tempC; // index 2
// private final String description; // index 10
// private final double precipMM; // index 11
// private final int feelsLikeC; // index 24
//
// public WeatherInfo(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {
// this.date = date;
// this.tempC = tempC;
// this.description = description;
// this.precipMM = precipMM;
// this.feelsLikeC = feelsLikeC;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public int getTempC() {
// return tempC;
// }
//
// public String getDescription() {
// return description;
// }
//
// public double getPrecipMM() {
// return precipMM;
// }
//
// public int getFeelsLikeC() {
// return feelsLikeC;
// }
//
// @Override
// public String toString() {
// return "WeatherInfo{" +
// date +
// ", tempC=" + tempC +
// ", '" + description + '\'' +
// ", precipMM=" + precipMM +
// ", feelsLikeC=" + feelsLikeC +
// '}';
// }
//
// /**
// * Hourly information follows below the day according to the format of
// * /past weather resource of the World Weather Online API
// */
// public static WeatherInfo valueOf(String line) {
// String[] data = line.split(",");
// return new WeatherInfo(
// LocalDate.parse(data[0]),
// Integer.parseInt(data[2]),
// data[10],
// Double.parseDouble(data[11]),
// Integer.parseInt(data[24]));
// }
// }
| import java.util.List;
import util.IRequest;
import weather.dto.Location;
import weather.dto.WeatherInfo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.net.URL;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Iterator; | } catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private final IRequest req;
public WeatherWebApi(IRequest req) {
this.req = req;
}
/**
* E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****
*/
public Iterable<Location> search(String query) {
String url=WEATHER_HOST + WEATHER_SEARCH + WEATHER_SEARCH_ARGS;
url = String.format(url, query, WEATHER_TOKEN);
List<Location> locations= new ArrayList<>();
Iterator<String> iteratorString= req.getContent(url).iterator();
while(iteratorString.hasNext()) {
String line = iteratorString.next();
if(!line.startsWith("#")) locations.add(Location.valueOf(line));
}
return locations;
}
/**
* E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****
*/ | // Path: aula33-weather-async/src/main/java/util/IRequest.java
// public interface IRequest extends AutoCloseable{
// CompletableFuture<Stream<String>> getContent(String path);
//
// @Override
// public default void close() {
// }
// }
//
// Path: aula09-composition-and-decorator/src/main/java/weather/model/Location.java
// public class Location {
// private final String country;
// private final String region;
// private final double latitude;
// private final double longitude;
//
// public Location(String country, String region, double latitude, double longitude) {
// this.country = country;
// this.region = region;
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getRegion() {
// return region;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public static Location valueOf(String line) {
// String[] data = line.split("\t");
// return new Location(
// data[1],
// data[2],
// Double.parseDouble(data[3]),
// Double.parseDouble(data[4]));
// }
//
// @Override
// public String toString() {
// return "Location{" +
// "country='" + country + '\'' +
// ", region='" + region + '\'' +
// ", latitude=" + latitude +
// ", longitude=" + longitude +
// '}';
// }
// }
//
// Path: aula09-composition-and-decorator/src/main/java/weather/model/WeatherInfo.java
// public class WeatherInfo {
// private final LocalDate date; // index 0
// private final int tempC; // index 2
// private final String description; // index 10
// private final double precipMM; // index 11
// private final int feelsLikeC; // index 24
//
// public WeatherInfo(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {
// this.date = date;
// this.tempC = tempC;
// this.description = description;
// this.precipMM = precipMM;
// this.feelsLikeC = feelsLikeC;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public int getTempC() {
// return tempC;
// }
//
// public String getDescription() {
// return description;
// }
//
// public double getPrecipMM() {
// return precipMM;
// }
//
// public int getFeelsLikeC() {
// return feelsLikeC;
// }
//
// @Override
// public String toString() {
// return "WeatherInfo{" +
// date +
// ", tempC=" + tempC +
// ", '" + description + '\'' +
// ", precipMM=" + precipMM +
// ", feelsLikeC=" + feelsLikeC +
// '}';
// }
//
// /**
// * Hourly information follows below the day according to the format of
// * /past weather resource of the World Weather Online API
// */
// public static WeatherInfo valueOf(String line) {
// String[] data = line.split(",");
// return new WeatherInfo(
// LocalDate.parse(data[0]),
// Integer.parseInt(data[2]),
// data[10],
// Double.parseDouble(data[11]),
// Integer.parseInt(data[24]));
// }
// }
// Path: aula05-generic-methods/src/main/java/weather/WeatherWebApi.java
import java.util.List;
import util.IRequest;
import weather.dto.Location;
import weather.dto.WeatherInfo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.net.URL;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Iterator;
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private final IRequest req;
public WeatherWebApi(IRequest req) {
this.req = req;
}
/**
* E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****
*/
public Iterable<Location> search(String query) {
String url=WEATHER_HOST + WEATHER_SEARCH + WEATHER_SEARCH_ARGS;
url = String.format(url, query, WEATHER_TOKEN);
List<Location> locations= new ArrayList<>();
Iterator<String> iteratorString= req.getContent(url).iterator();
while(iteratorString.hasNext()) {
String line = iteratorString.next();
if(!line.startsWith("#")) locations.add(Location.valueOf(line));
}
return locations;
}
/**
* E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****
*/ | public Iterable<WeatherInfo> pastWeather( |
isel-leic-mpd/mpd-2017-i41d | aula21-iterator-vs-stream/src/main/java/util/Request.java | // Path: aula21-iterator-vs-stream/src/main/java/util/queries/IteratorFromInputStream.java
// public class IteratorFromInputStream implements Iterator<String> {
// final BufferedReader reader;
// final InputStream in;
// private String nextLine;
//
// public IteratorFromInputStream(InputStream in) {
// this.in = in;
// this.reader = new BufferedReader(new InputStreamReader(in));
// this.nextLine = moveNext();
// }
//
// private String moveNext() {
// try {
// String line = reader.readLine();
// if(line == null) {
// in.close();
// reader.close();
// }
// return line;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// @Override
// public boolean hasNext() {
// return nextLine != null;
// }
//
// @Override
// public String next() {
// String curr = nextLine;
// nextLine = moveNext();
// return curr;
// }
// }
| import util.queries.IteratorFromInputStream;
import java.io.InputStream;
import java.util.function.Function; | /*
* Copyright (c) 2017, Miguel Gamboa
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package util;
/**
* @author Miguel Gamboa
* created on 22-03-2017
*/
public class Request implements IRequest {
final Function<String, InputStream> getStream;
public Request(Function<String, InputStream> getStream) {
this.getStream = getStream;
}
@Override
public final Iterable<String> getContent(String path) { | // Path: aula21-iterator-vs-stream/src/main/java/util/queries/IteratorFromInputStream.java
// public class IteratorFromInputStream implements Iterator<String> {
// final BufferedReader reader;
// final InputStream in;
// private String nextLine;
//
// public IteratorFromInputStream(InputStream in) {
// this.in = in;
// this.reader = new BufferedReader(new InputStreamReader(in));
// this.nextLine = moveNext();
// }
//
// private String moveNext() {
// try {
// String line = reader.readLine();
// if(line == null) {
// in.close();
// reader.close();
// }
// return line;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// @Override
// public boolean hasNext() {
// return nextLine != null;
// }
//
// @Override
// public String next() {
// String curr = nextLine;
// nextLine = moveNext();
// return curr;
// }
// }
// Path: aula21-iterator-vs-stream/src/main/java/util/Request.java
import util.queries.IteratorFromInputStream;
import java.io.InputStream;
import java.util.function.Function;
/*
* Copyright (c) 2017, Miguel Gamboa
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package util;
/**
* @author Miguel Gamboa
* created on 22-03-2017
*/
public class Request implements IRequest {
final Function<String, InputStream> getStream;
public Request(Function<String, InputStream> getStream) {
this.getStream = getStream;
}
@Override
public final Iterable<String> getContent(String path) { | return () -> new IteratorFromInputStream(getStream.apply(path)); |
isel-leic-mpd/mpd-2017-i41d | aula02-weather-api/src/main/java/weather/WeatherWebApi.java | // Path: aula33-weather-async/src/main/java/util/IRequest.java
// public interface IRequest extends AutoCloseable{
// CompletableFuture<Stream<String>> getContent(String path);
//
// @Override
// public default void close() {
// }
// }
//
// Path: aula09-composition-and-decorator/src/main/java/weather/model/Location.java
// public class Location {
// private final String country;
// private final String region;
// private final double latitude;
// private final double longitude;
//
// public Location(String country, String region, double latitude, double longitude) {
// this.country = country;
// this.region = region;
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getRegion() {
// return region;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public static Location valueOf(String line) {
// String[] data = line.split("\t");
// return new Location(
// data[1],
// data[2],
// Double.parseDouble(data[3]),
// Double.parseDouble(data[4]));
// }
//
// @Override
// public String toString() {
// return "Location{" +
// "country='" + country + '\'' +
// ", region='" + region + '\'' +
// ", latitude=" + latitude +
// ", longitude=" + longitude +
// '}';
// }
// }
//
// Path: aula09-composition-and-decorator/src/main/java/weather/model/WeatherInfo.java
// public class WeatherInfo {
// private final LocalDate date; // index 0
// private final int tempC; // index 2
// private final String description; // index 10
// private final double precipMM; // index 11
// private final int feelsLikeC; // index 24
//
// public WeatherInfo(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {
// this.date = date;
// this.tempC = tempC;
// this.description = description;
// this.precipMM = precipMM;
// this.feelsLikeC = feelsLikeC;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public int getTempC() {
// return tempC;
// }
//
// public String getDescription() {
// return description;
// }
//
// public double getPrecipMM() {
// return precipMM;
// }
//
// public int getFeelsLikeC() {
// return feelsLikeC;
// }
//
// @Override
// public String toString() {
// return "WeatherInfo{" +
// date +
// ", tempC=" + tempC +
// ", '" + description + '\'' +
// ", precipMM=" + precipMM +
// ", feelsLikeC=" + feelsLikeC +
// '}';
// }
//
// /**
// * Hourly information follows below the day according to the format of
// * /past weather resource of the World Weather Online API
// */
// public static WeatherInfo valueOf(String line) {
// String[] data = line.split(",");
// return new WeatherInfo(
// LocalDate.parse(data[0]),
// Integer.parseInt(data[2]),
// data[10],
// Double.parseDouble(data[11]),
// Integer.parseInt(data[24]));
// }
// }
| import java.util.List;
import util.IRequest;
import weather.dto.Location;
import weather.dto.WeatherInfo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.net.URL;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Iterator; | /*
* Copyright (c) 2017, Miguel Gamboa
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package weather;
/**
* @author Miguel Gamboa
* created on 07-03-2017
*/
public class WeatherWebApi {
private static final String WEATHER_TOKEN;
private static final String WEATHER_HOST = "http://data.worldweatheronline.com";
private static final String WEATHER_PAST = "/premium/v1/past-weather.ashx";
private static final String WEATHER_PAST_ARGS =
"?q=%s&date=%s&enddate=%s&tp=24&format=csv&key=%s";
static {
try {
URL keyFile = ClassLoader.getSystemResource("worldweatheronline-app-key.txt");
if(keyFile == null) {
throw new IllegalStateException(
"YOU MUST GOT a KEY in developer.worldweatheronline.com and place it in src/main/resources/worldweatheronline-app-key.txt");
} else {
InputStream keyStream = keyFile.openStream();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(keyStream))) {
WEATHER_TOKEN = reader.readLine();
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
| // Path: aula33-weather-async/src/main/java/util/IRequest.java
// public interface IRequest extends AutoCloseable{
// CompletableFuture<Stream<String>> getContent(String path);
//
// @Override
// public default void close() {
// }
// }
//
// Path: aula09-composition-and-decorator/src/main/java/weather/model/Location.java
// public class Location {
// private final String country;
// private final String region;
// private final double latitude;
// private final double longitude;
//
// public Location(String country, String region, double latitude, double longitude) {
// this.country = country;
// this.region = region;
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getRegion() {
// return region;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public static Location valueOf(String line) {
// String[] data = line.split("\t");
// return new Location(
// data[1],
// data[2],
// Double.parseDouble(data[3]),
// Double.parseDouble(data[4]));
// }
//
// @Override
// public String toString() {
// return "Location{" +
// "country='" + country + '\'' +
// ", region='" + region + '\'' +
// ", latitude=" + latitude +
// ", longitude=" + longitude +
// '}';
// }
// }
//
// Path: aula09-composition-and-decorator/src/main/java/weather/model/WeatherInfo.java
// public class WeatherInfo {
// private final LocalDate date; // index 0
// private final int tempC; // index 2
// private final String description; // index 10
// private final double precipMM; // index 11
// private final int feelsLikeC; // index 24
//
// public WeatherInfo(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {
// this.date = date;
// this.tempC = tempC;
// this.description = description;
// this.precipMM = precipMM;
// this.feelsLikeC = feelsLikeC;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public int getTempC() {
// return tempC;
// }
//
// public String getDescription() {
// return description;
// }
//
// public double getPrecipMM() {
// return precipMM;
// }
//
// public int getFeelsLikeC() {
// return feelsLikeC;
// }
//
// @Override
// public String toString() {
// return "WeatherInfo{" +
// date +
// ", tempC=" + tempC +
// ", '" + description + '\'' +
// ", precipMM=" + precipMM +
// ", feelsLikeC=" + feelsLikeC +
// '}';
// }
//
// /**
// * Hourly information follows below the day according to the format of
// * /past weather resource of the World Weather Online API
// */
// public static WeatherInfo valueOf(String line) {
// String[] data = line.split(",");
// return new WeatherInfo(
// LocalDate.parse(data[0]),
// Integer.parseInt(data[2]),
// data[10],
// Double.parseDouble(data[11]),
// Integer.parseInt(data[24]));
// }
// }
// Path: aula02-weather-api/src/main/java/weather/WeatherWebApi.java
import java.util.List;
import util.IRequest;
import weather.dto.Location;
import weather.dto.WeatherInfo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.net.URL;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Iterator;
/*
* Copyright (c) 2017, Miguel Gamboa
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package weather;
/**
* @author Miguel Gamboa
* created on 07-03-2017
*/
public class WeatherWebApi {
private static final String WEATHER_TOKEN;
private static final String WEATHER_HOST = "http://data.worldweatheronline.com";
private static final String WEATHER_PAST = "/premium/v1/past-weather.ashx";
private static final String WEATHER_PAST_ARGS =
"?q=%s&date=%s&enddate=%s&tp=24&format=csv&key=%s";
static {
try {
URL keyFile = ClassLoader.getSystemResource("worldweatheronline-app-key.txt");
if(keyFile == null) {
throw new IllegalStateException(
"YOU MUST GOT a KEY in developer.worldweatheronline.com and place it in src/main/resources/worldweatheronline-app-key.txt");
} else {
InputStream keyStream = keyFile.openStream();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(keyStream))) {
WEATHER_TOKEN = reader.readLine();
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
| private final IRequest req; |
isel-leic-mpd/mpd-2017-i41d | aula02-weather-api/src/main/java/weather/WeatherWebApi.java | // Path: aula33-weather-async/src/main/java/util/IRequest.java
// public interface IRequest extends AutoCloseable{
// CompletableFuture<Stream<String>> getContent(String path);
//
// @Override
// public default void close() {
// }
// }
//
// Path: aula09-composition-and-decorator/src/main/java/weather/model/Location.java
// public class Location {
// private final String country;
// private final String region;
// private final double latitude;
// private final double longitude;
//
// public Location(String country, String region, double latitude, double longitude) {
// this.country = country;
// this.region = region;
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getRegion() {
// return region;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public static Location valueOf(String line) {
// String[] data = line.split("\t");
// return new Location(
// data[1],
// data[2],
// Double.parseDouble(data[3]),
// Double.parseDouble(data[4]));
// }
//
// @Override
// public String toString() {
// return "Location{" +
// "country='" + country + '\'' +
// ", region='" + region + '\'' +
// ", latitude=" + latitude +
// ", longitude=" + longitude +
// '}';
// }
// }
//
// Path: aula09-composition-and-decorator/src/main/java/weather/model/WeatherInfo.java
// public class WeatherInfo {
// private final LocalDate date; // index 0
// private final int tempC; // index 2
// private final String description; // index 10
// private final double precipMM; // index 11
// private final int feelsLikeC; // index 24
//
// public WeatherInfo(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {
// this.date = date;
// this.tempC = tempC;
// this.description = description;
// this.precipMM = precipMM;
// this.feelsLikeC = feelsLikeC;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public int getTempC() {
// return tempC;
// }
//
// public String getDescription() {
// return description;
// }
//
// public double getPrecipMM() {
// return precipMM;
// }
//
// public int getFeelsLikeC() {
// return feelsLikeC;
// }
//
// @Override
// public String toString() {
// return "WeatherInfo{" +
// date +
// ", tempC=" + tempC +
// ", '" + description + '\'' +
// ", precipMM=" + precipMM +
// ", feelsLikeC=" + feelsLikeC +
// '}';
// }
//
// /**
// * Hourly information follows below the day according to the format of
// * /past weather resource of the World Weather Online API
// */
// public static WeatherInfo valueOf(String line) {
// String[] data = line.split(",");
// return new WeatherInfo(
// LocalDate.parse(data[0]),
// Integer.parseInt(data[2]),
// data[10],
// Double.parseDouble(data[11]),
// Integer.parseInt(data[24]));
// }
// }
| import java.util.List;
import util.IRequest;
import weather.dto.Location;
import weather.dto.WeatherInfo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.net.URL;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Iterator; | /*
* Copyright (c) 2017, Miguel Gamboa
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package weather;
/**
* @author Miguel Gamboa
* created on 07-03-2017
*/
public class WeatherWebApi {
private static final String WEATHER_TOKEN;
private static final String WEATHER_HOST = "http://data.worldweatheronline.com";
private static final String WEATHER_PAST = "/premium/v1/past-weather.ashx";
private static final String WEATHER_PAST_ARGS =
"?q=%s&date=%s&enddate=%s&tp=24&format=csv&key=%s";
static {
try {
URL keyFile = ClassLoader.getSystemResource("worldweatheronline-app-key.txt");
if(keyFile == null) {
throw new IllegalStateException(
"YOU MUST GOT a KEY in developer.worldweatheronline.com and place it in src/main/resources/worldweatheronline-app-key.txt");
} else {
InputStream keyStream = keyFile.openStream();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(keyStream))) {
WEATHER_TOKEN = reader.readLine();
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private final IRequest req;
public WeatherWebApi(IRequest req) {
this.req = req;
}
/**
* E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****
*/
| // Path: aula33-weather-async/src/main/java/util/IRequest.java
// public interface IRequest extends AutoCloseable{
// CompletableFuture<Stream<String>> getContent(String path);
//
// @Override
// public default void close() {
// }
// }
//
// Path: aula09-composition-and-decorator/src/main/java/weather/model/Location.java
// public class Location {
// private final String country;
// private final String region;
// private final double latitude;
// private final double longitude;
//
// public Location(String country, String region, double latitude, double longitude) {
// this.country = country;
// this.region = region;
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getRegion() {
// return region;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public static Location valueOf(String line) {
// String[] data = line.split("\t");
// return new Location(
// data[1],
// data[2],
// Double.parseDouble(data[3]),
// Double.parseDouble(data[4]));
// }
//
// @Override
// public String toString() {
// return "Location{" +
// "country='" + country + '\'' +
// ", region='" + region + '\'' +
// ", latitude=" + latitude +
// ", longitude=" + longitude +
// '}';
// }
// }
//
// Path: aula09-composition-and-decorator/src/main/java/weather/model/WeatherInfo.java
// public class WeatherInfo {
// private final LocalDate date; // index 0
// private final int tempC; // index 2
// private final String description; // index 10
// private final double precipMM; // index 11
// private final int feelsLikeC; // index 24
//
// public WeatherInfo(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {
// this.date = date;
// this.tempC = tempC;
// this.description = description;
// this.precipMM = precipMM;
// this.feelsLikeC = feelsLikeC;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public int getTempC() {
// return tempC;
// }
//
// public String getDescription() {
// return description;
// }
//
// public double getPrecipMM() {
// return precipMM;
// }
//
// public int getFeelsLikeC() {
// return feelsLikeC;
// }
//
// @Override
// public String toString() {
// return "WeatherInfo{" +
// date +
// ", tempC=" + tempC +
// ", '" + description + '\'' +
// ", precipMM=" + precipMM +
// ", feelsLikeC=" + feelsLikeC +
// '}';
// }
//
// /**
// * Hourly information follows below the day according to the format of
// * /past weather resource of the World Weather Online API
// */
// public static WeatherInfo valueOf(String line) {
// String[] data = line.split(",");
// return new WeatherInfo(
// LocalDate.parse(data[0]),
// Integer.parseInt(data[2]),
// data[10],
// Double.parseDouble(data[11]),
// Integer.parseInt(data[24]));
// }
// }
// Path: aula02-weather-api/src/main/java/weather/WeatherWebApi.java
import java.util.List;
import util.IRequest;
import weather.dto.Location;
import weather.dto.WeatherInfo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.net.URL;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Iterator;
/*
* Copyright (c) 2017, Miguel Gamboa
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package weather;
/**
* @author Miguel Gamboa
* created on 07-03-2017
*/
public class WeatherWebApi {
private static final String WEATHER_TOKEN;
private static final String WEATHER_HOST = "http://data.worldweatheronline.com";
private static final String WEATHER_PAST = "/premium/v1/past-weather.ashx";
private static final String WEATHER_PAST_ARGS =
"?q=%s&date=%s&enddate=%s&tp=24&format=csv&key=%s";
static {
try {
URL keyFile = ClassLoader.getSystemResource("worldweatheronline-app-key.txt");
if(keyFile == null) {
throw new IllegalStateException(
"YOU MUST GOT a KEY in developer.worldweatheronline.com and place it in src/main/resources/worldweatheronline-app-key.txt");
} else {
InputStream keyStream = keyFile.openStream();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(keyStream))) {
WEATHER_TOKEN = reader.readLine();
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private final IRequest req;
public WeatherWebApi(IRequest req) {
this.req = req;
}
/**
* E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****
*/
| public Iterable<Location> search(String query) { |
isel-leic-mpd/mpd-2017-i41d | aula02-weather-api/src/main/java/weather/WeatherWebApi.java | // Path: aula33-weather-async/src/main/java/util/IRequest.java
// public interface IRequest extends AutoCloseable{
// CompletableFuture<Stream<String>> getContent(String path);
//
// @Override
// public default void close() {
// }
// }
//
// Path: aula09-composition-and-decorator/src/main/java/weather/model/Location.java
// public class Location {
// private final String country;
// private final String region;
// private final double latitude;
// private final double longitude;
//
// public Location(String country, String region, double latitude, double longitude) {
// this.country = country;
// this.region = region;
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getRegion() {
// return region;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public static Location valueOf(String line) {
// String[] data = line.split("\t");
// return new Location(
// data[1],
// data[2],
// Double.parseDouble(data[3]),
// Double.parseDouble(data[4]));
// }
//
// @Override
// public String toString() {
// return "Location{" +
// "country='" + country + '\'' +
// ", region='" + region + '\'' +
// ", latitude=" + latitude +
// ", longitude=" + longitude +
// '}';
// }
// }
//
// Path: aula09-composition-and-decorator/src/main/java/weather/model/WeatherInfo.java
// public class WeatherInfo {
// private final LocalDate date; // index 0
// private final int tempC; // index 2
// private final String description; // index 10
// private final double precipMM; // index 11
// private final int feelsLikeC; // index 24
//
// public WeatherInfo(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {
// this.date = date;
// this.tempC = tempC;
// this.description = description;
// this.precipMM = precipMM;
// this.feelsLikeC = feelsLikeC;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public int getTempC() {
// return tempC;
// }
//
// public String getDescription() {
// return description;
// }
//
// public double getPrecipMM() {
// return precipMM;
// }
//
// public int getFeelsLikeC() {
// return feelsLikeC;
// }
//
// @Override
// public String toString() {
// return "WeatherInfo{" +
// date +
// ", tempC=" + tempC +
// ", '" + description + '\'' +
// ", precipMM=" + precipMM +
// ", feelsLikeC=" + feelsLikeC +
// '}';
// }
//
// /**
// * Hourly information follows below the day according to the format of
// * /past weather resource of the World Weather Online API
// */
// public static WeatherInfo valueOf(String line) {
// String[] data = line.split(",");
// return new WeatherInfo(
// LocalDate.parse(data[0]),
// Integer.parseInt(data[2]),
// data[10],
// Double.parseDouble(data[11]),
// Integer.parseInt(data[24]));
// }
// }
| import java.util.List;
import util.IRequest;
import weather.dto.Location;
import weather.dto.WeatherInfo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.net.URL;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Iterator; | /*
* Copyright (c) 2017, Miguel Gamboa
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package weather;
/**
* @author Miguel Gamboa
* created on 07-03-2017
*/
public class WeatherWebApi {
private static final String WEATHER_TOKEN;
private static final String WEATHER_HOST = "http://data.worldweatheronline.com";
private static final String WEATHER_PAST = "/premium/v1/past-weather.ashx";
private static final String WEATHER_PAST_ARGS =
"?q=%s&date=%s&enddate=%s&tp=24&format=csv&key=%s";
static {
try {
URL keyFile = ClassLoader.getSystemResource("worldweatheronline-app-key.txt");
if(keyFile == null) {
throw new IllegalStateException(
"YOU MUST GOT a KEY in developer.worldweatheronline.com and place it in src/main/resources/worldweatheronline-app-key.txt");
} else {
InputStream keyStream = keyFile.openStream();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(keyStream))) {
WEATHER_TOKEN = reader.readLine();
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private final IRequest req;
public WeatherWebApi(IRequest req) {
this.req = req;
}
/**
* E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****
*/
public Iterable<Location> search(String query) {
return null;
}
/**
* E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****
*/ | // Path: aula33-weather-async/src/main/java/util/IRequest.java
// public interface IRequest extends AutoCloseable{
// CompletableFuture<Stream<String>> getContent(String path);
//
// @Override
// public default void close() {
// }
// }
//
// Path: aula09-composition-and-decorator/src/main/java/weather/model/Location.java
// public class Location {
// private final String country;
// private final String region;
// private final double latitude;
// private final double longitude;
//
// public Location(String country, String region, double latitude, double longitude) {
// this.country = country;
// this.region = region;
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getRegion() {
// return region;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public static Location valueOf(String line) {
// String[] data = line.split("\t");
// return new Location(
// data[1],
// data[2],
// Double.parseDouble(data[3]),
// Double.parseDouble(data[4]));
// }
//
// @Override
// public String toString() {
// return "Location{" +
// "country='" + country + '\'' +
// ", region='" + region + '\'' +
// ", latitude=" + latitude +
// ", longitude=" + longitude +
// '}';
// }
// }
//
// Path: aula09-composition-and-decorator/src/main/java/weather/model/WeatherInfo.java
// public class WeatherInfo {
// private final LocalDate date; // index 0
// private final int tempC; // index 2
// private final String description; // index 10
// private final double precipMM; // index 11
// private final int feelsLikeC; // index 24
//
// public WeatherInfo(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {
// this.date = date;
// this.tempC = tempC;
// this.description = description;
// this.precipMM = precipMM;
// this.feelsLikeC = feelsLikeC;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public int getTempC() {
// return tempC;
// }
//
// public String getDescription() {
// return description;
// }
//
// public double getPrecipMM() {
// return precipMM;
// }
//
// public int getFeelsLikeC() {
// return feelsLikeC;
// }
//
// @Override
// public String toString() {
// return "WeatherInfo{" +
// date +
// ", tempC=" + tempC +
// ", '" + description + '\'' +
// ", precipMM=" + precipMM +
// ", feelsLikeC=" + feelsLikeC +
// '}';
// }
//
// /**
// * Hourly information follows below the day according to the format of
// * /past weather resource of the World Weather Online API
// */
// public static WeatherInfo valueOf(String line) {
// String[] data = line.split(",");
// return new WeatherInfo(
// LocalDate.parse(data[0]),
// Integer.parseInt(data[2]),
// data[10],
// Double.parseDouble(data[11]),
// Integer.parseInt(data[24]));
// }
// }
// Path: aula02-weather-api/src/main/java/weather/WeatherWebApi.java
import java.util.List;
import util.IRequest;
import weather.dto.Location;
import weather.dto.WeatherInfo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.net.URL;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Iterator;
/*
* Copyright (c) 2017, Miguel Gamboa
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package weather;
/**
* @author Miguel Gamboa
* created on 07-03-2017
*/
public class WeatherWebApi {
private static final String WEATHER_TOKEN;
private static final String WEATHER_HOST = "http://data.worldweatheronline.com";
private static final String WEATHER_PAST = "/premium/v1/past-weather.ashx";
private static final String WEATHER_PAST_ARGS =
"?q=%s&date=%s&enddate=%s&tp=24&format=csv&key=%s";
static {
try {
URL keyFile = ClassLoader.getSystemResource("worldweatheronline-app-key.txt");
if(keyFile == null) {
throw new IllegalStateException(
"YOU MUST GOT a KEY in developer.worldweatheronline.com and place it in src/main/resources/worldweatheronline-app-key.txt");
} else {
InputStream keyStream = keyFile.openStream();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(keyStream))) {
WEATHER_TOKEN = reader.readLine();
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private final IRequest req;
public WeatherWebApi(IRequest req) {
this.req = req;
}
/**
* E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****
*/
public Iterable<Location> search(String query) {
return null;
}
/**
* E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****
*/ | public Iterable<WeatherInfo> pastWeather( |
isel-leic-mpd/mpd-2017-i41d | aula19-optional-and-default-methods/src/main/java/util/queries/NaiveQueries.java | // Path: aula04-queries/src/main/java/util/WeatherPredicate.java
// public interface WeatherPredicate {
// boolean test(WeatherInfo item);
// }
//
// Path: aula33-weather-async/src/main/java/weather/data/dto/WeatherInfoDto.java
// public class WeatherInfoDto {
// private final LocalDate date; // index 0
// private final int tempC; // index 2
// private final String description; // index 10
// private final double precipMM; // index 11
// private final int feelsLikeC; // index 24
//
// public WeatherInfoDto(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {
// this.date = date;
// this.tempC = tempC;
// this.description = description;
// this.precipMM = precipMM;
// this.feelsLikeC = feelsLikeC;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public int getTempC() {
// return tempC;
// }
//
// public String getDescription() {
// return description;
// }
//
// public double getPrecipMM() {
// return precipMM;
// }
//
// public int getFeelsLikeC() {
// return feelsLikeC;
// }
//
// @Override
// public String toString() {
// return "WeatherInfoDto{" +
// date +
// ", tempC=" + tempC +
// ", '" + description + '\'' +
// ", precipMM=" + precipMM +
// ", feelsLikeC=" + feelsLikeC +
// '}';
// }
//
// /**
// * Hourly information follows below the day according to the format of
// * /past weather resource of the World Weather Online API
// */
// public static WeatherInfoDto valueOf(String line) {
// String[] data = line.split(",");
// return new WeatherInfoDto(
// LocalDate.parse(data[0]),
// Integer.parseInt(data[2]),
// data[10],
// Double.parseDouble(data[11]),
// Integer.parseInt(data[24]));
// }
// }
| import util.WeatherPredicate;
import weather.data.dto.WeatherInfoDto;
import java.util.ArrayList;
import java.util.List; | /*
* Copyright (c) 2017, Miguel Gamboa
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package util.queries;
/**
* NaiveQueries provide utility methods that make queries over a sequence
* of elements.
* A sequence is considered an Iterable.
*
* @author Miguel Gamboa
* created on 14-03-2017
*/
public class NaiveQueries {
/**
* v1- Auxiliary method to filter cloudy days. Returns a new sequence with
* WeatherInfoDto objects that were cloudy.
* Eager approach.
*/
public static Iterable<WeatherInfoDto> filterCloudy(Iterable<WeatherInfoDto> data) {
List<WeatherInfoDto> res = new ArrayList<>();
for (WeatherInfoDto item: data) {
if(item.getDescription().toLowerCase().contains("cloud"))
res.add(item);
}
return res;
}
public static Iterable<WeatherInfoDto> filterRainy(Iterable<WeatherInfoDto> data) {
List<WeatherInfoDto> res = new ArrayList<>();
for (WeatherInfoDto item: data) {
if(item.getDescription().toLowerCase().contains("rain"))
res.add(item);
}
return res;
}
/**
* v2-
*/
public static Iterable<WeatherInfoDto> filterDesc(Iterable<WeatherInfoDto> data, String query) {
List<WeatherInfoDto> res = new ArrayList<>();
for (WeatherInfoDto item: data) {
if(item.getDescription().toLowerCase().contains(query))
res.add(item);
}
return res;
}
/**
* v3 -
*/ | // Path: aula04-queries/src/main/java/util/WeatherPredicate.java
// public interface WeatherPredicate {
// boolean test(WeatherInfo item);
// }
//
// Path: aula33-weather-async/src/main/java/weather/data/dto/WeatherInfoDto.java
// public class WeatherInfoDto {
// private final LocalDate date; // index 0
// private final int tempC; // index 2
// private final String description; // index 10
// private final double precipMM; // index 11
// private final int feelsLikeC; // index 24
//
// public WeatherInfoDto(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {
// this.date = date;
// this.tempC = tempC;
// this.description = description;
// this.precipMM = precipMM;
// this.feelsLikeC = feelsLikeC;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public int getTempC() {
// return tempC;
// }
//
// public String getDescription() {
// return description;
// }
//
// public double getPrecipMM() {
// return precipMM;
// }
//
// public int getFeelsLikeC() {
// return feelsLikeC;
// }
//
// @Override
// public String toString() {
// return "WeatherInfoDto{" +
// date +
// ", tempC=" + tempC +
// ", '" + description + '\'' +
// ", precipMM=" + precipMM +
// ", feelsLikeC=" + feelsLikeC +
// '}';
// }
//
// /**
// * Hourly information follows below the day according to the format of
// * /past weather resource of the World Weather Online API
// */
// public static WeatherInfoDto valueOf(String line) {
// String[] data = line.split(",");
// return new WeatherInfoDto(
// LocalDate.parse(data[0]),
// Integer.parseInt(data[2]),
// data[10],
// Double.parseDouble(data[11]),
// Integer.parseInt(data[24]));
// }
// }
// Path: aula19-optional-and-default-methods/src/main/java/util/queries/NaiveQueries.java
import util.WeatherPredicate;
import weather.data.dto.WeatherInfoDto;
import java.util.ArrayList;
import java.util.List;
/*
* Copyright (c) 2017, Miguel Gamboa
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package util.queries;
/**
* NaiveQueries provide utility methods that make queries over a sequence
* of elements.
* A sequence is considered an Iterable.
*
* @author Miguel Gamboa
* created on 14-03-2017
*/
public class NaiveQueries {
/**
* v1- Auxiliary method to filter cloudy days. Returns a new sequence with
* WeatherInfoDto objects that were cloudy.
* Eager approach.
*/
public static Iterable<WeatherInfoDto> filterCloudy(Iterable<WeatherInfoDto> data) {
List<WeatherInfoDto> res = new ArrayList<>();
for (WeatherInfoDto item: data) {
if(item.getDescription().toLowerCase().contains("cloud"))
res.add(item);
}
return res;
}
public static Iterable<WeatherInfoDto> filterRainy(Iterable<WeatherInfoDto> data) {
List<WeatherInfoDto> res = new ArrayList<>();
for (WeatherInfoDto item: data) {
if(item.getDescription().toLowerCase().contains("rain"))
res.add(item);
}
return res;
}
/**
* v2-
*/
public static Iterable<WeatherInfoDto> filterDesc(Iterable<WeatherInfoDto> data, String query) {
List<WeatherInfoDto> res = new ArrayList<>();
for (WeatherInfoDto item: data) {
if(item.getDescription().toLowerCase().contains(query))
res.add(item);
}
return res;
}
/**
* v3 -
*/ | public static Iterable<WeatherInfoDto> filter(Iterable<WeatherInfoDto> data, WeatherPredicate p) { |
isel-leic-mpd/mpd-2017-i41d | aula09-composition-and-decorator/src/main/java/util/WeatherPredicate.java | // Path: aula09-composition-and-decorator/src/main/java/weather/model/WeatherInfo.java
// public class WeatherInfo {
// private final LocalDate date; // index 0
// private final int tempC; // index 2
// private final String description; // index 10
// private final double precipMM; // index 11
// private final int feelsLikeC; // index 24
//
// public WeatherInfo(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {
// this.date = date;
// this.tempC = tempC;
// this.description = description;
// this.precipMM = precipMM;
// this.feelsLikeC = feelsLikeC;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public int getTempC() {
// return tempC;
// }
//
// public String getDescription() {
// return description;
// }
//
// public double getPrecipMM() {
// return precipMM;
// }
//
// public int getFeelsLikeC() {
// return feelsLikeC;
// }
//
// @Override
// public String toString() {
// return "WeatherInfo{" +
// date +
// ", tempC=" + tempC +
// ", '" + description + '\'' +
// ", precipMM=" + precipMM +
// ", feelsLikeC=" + feelsLikeC +
// '}';
// }
//
// /**
// * Hourly information follows below the day according to the format of
// * /past weather resource of the World Weather Online API
// */
// public static WeatherInfo valueOf(String line) {
// String[] data = line.split(",");
// return new WeatherInfo(
// LocalDate.parse(data[0]),
// Integer.parseInt(data[2]),
// data[10],
// Double.parseDouble(data[11]),
// Integer.parseInt(data[24]));
// }
// }
| import weather.dto.WeatherInfo; | /*
* Copyright (c) 2017, Miguel Gamboa
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package util;
/**
* @author Miguel Gamboa
* created on 14-03-2017
*/
/**
* This is a functional interface because it has one and only one method.
* Thus we can assign a lambda expression to every place of WeatherPredicate
* type.
*/
@FunctionalInterface
public interface WeatherPredicate {
| // Path: aula09-composition-and-decorator/src/main/java/weather/model/WeatherInfo.java
// public class WeatherInfo {
// private final LocalDate date; // index 0
// private final int tempC; // index 2
// private final String description; // index 10
// private final double precipMM; // index 11
// private final int feelsLikeC; // index 24
//
// public WeatherInfo(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {
// this.date = date;
// this.tempC = tempC;
// this.description = description;
// this.precipMM = precipMM;
// this.feelsLikeC = feelsLikeC;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public int getTempC() {
// return tempC;
// }
//
// public String getDescription() {
// return description;
// }
//
// public double getPrecipMM() {
// return precipMM;
// }
//
// public int getFeelsLikeC() {
// return feelsLikeC;
// }
//
// @Override
// public String toString() {
// return "WeatherInfo{" +
// date +
// ", tempC=" + tempC +
// ", '" + description + '\'' +
// ", precipMM=" + precipMM +
// ", feelsLikeC=" + feelsLikeC +
// '}';
// }
//
// /**
// * Hourly information follows below the day according to the format of
// * /past weather resource of the World Weather Online API
// */
// public static WeatherInfo valueOf(String line) {
// String[] data = line.split(",");
// return new WeatherInfo(
// LocalDate.parse(data[0]),
// Integer.parseInt(data[2]),
// data[10],
// Double.parseDouble(data[11]),
// Integer.parseInt(data[24]));
// }
// }
// Path: aula09-composition-and-decorator/src/main/java/util/WeatherPredicate.java
import weather.dto.WeatherInfo;
/*
* Copyright (c) 2017, Miguel Gamboa
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package util;
/**
* @author Miguel Gamboa
* created on 14-03-2017
*/
/**
* This is a functional interface because it has one and only one method.
* Thus we can assign a lambda expression to every place of WeatherPredicate
* type.
*/
@FunctionalInterface
public interface WeatherPredicate {
| boolean test(WeatherInfo item); |
isel-leic-mpd/mpd-2017-i41d | aula31-weather-groupingBy/src/main/java/weather/WeatherServiceCache.java | // Path: aula21-iterator-vs-stream/src/main/java/weather/data/WeatherWebApi.java
// public class WeatherWebApi {
//
// private static final String WEATHER_TOKEN;
// private static final String WEATHER_HOST = "http://api.worldweatheronline.com";
// private static final String WEATHER_PAST = "/premium/v1/past-weather.ashx";
// private static final String WEATHER_PAST_ARGS =
// "?q=%s&date=%s&enddate=%s&tp=24&format=csv&key=%s";
// private static final String WEATHER_SEARCH="/premium/v1/search.ashx?query=%s";
// private static final String WEATHER_SEARCH_ARGS="&format=tab&key=%s";
//
// static {
// try {
// URL keyFile = ClassLoader.getSystemResource("worldweatheronline-app-key.txt");
// if(keyFile == null) {
// throw new IllegalStateException(
// "YOU MUST GOT a KEY in developer.worldweatheronline.com and place it in src/main/resources/worldweatheronline-app-key.txt");
// } else {
// InputStream keyStream = keyFile.openStream();
// try (BufferedReader reader = new BufferedReader(new InputStreamReader(keyStream))) {
// WEATHER_TOKEN = reader.readLine();
// }
// }
// } catch (IOException e) {
// throw new UncheckedIOException(e);
// }
// }
//
// private final IRequest req;
//
// public WeatherWebApi(IRequest req) {
// this.req = req;
// }
//
// /**
// * E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****
// */
//
// public Iterable<LocationDto> search(String query) {
// String path = WEATHER_HOST + WEATHER_SEARCH + WEATHER_SEARCH_ARGS;
// String url = String.format(path, query, WEATHER_TOKEN);
// Iterable<String> content = () -> req.getContent(url).iterator();
// Iterable<String> iterable = filter(content, (String s) -> !s.startsWith("#"));
// return map(iterable, LocationDto::valueOf);
// }
//
// /**
// * E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****
// */
// public Iterable<WeatherInfoDto> pastWeather(
// double lat,
// double log,
// LocalDate from,
// LocalDate to
// ) {
// String query = lat + "," + log;
// String path = WEATHER_HOST + WEATHER_PAST +
// String.format(WEATHER_PAST_ARGS, query, from, to, WEATHER_TOKEN);
// Iterable<String> content = () -> req.getContent(path).iterator();
// Iterable<String> stringIterable = filter(content, s->!s.startsWith("#"));
// Iterable<String>filtered = skip(stringIterable,1); // Skip line: Not Available
// int[] counter = {0};
// Predicate<String> isEvenLine = item -> ++counter[0] % 2==0;
// filtered = filter(filtered,isEvenLine);//even lines filter
// return map(filtered, WeatherInfoDto::valueOf); //to weatherinfo objects
// }
// }
//
// Path: aula33-weather-async/src/main/java/weather/model/WeatherInfo.java
// public class WeatherInfo {
// private final LocalDate date;
// private final int tempC;
// private final String description;
// private final double precipMM;
// private final int feelsLikeC;
//
// public WeatherInfo(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {
// this.date = date;
// this.tempC = tempC;
// this.description = description;
// this.precipMM = precipMM;
// this.feelsLikeC = feelsLikeC;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public int getTempC() {
// return tempC;
// }
//
// public String getDescription() {
// return description;
// }
//
// public double getPrecipMM() {
// return precipMM;
// }
//
// public int getFeelsLikeC() {
// return feelsLikeC;
// }
//
// @Override
// public String toString() {
// return "WeatherInfo{" +
// "date=" + date +
// ", tempC=" + tempC +
// ", description='" + description + '\'' +
// ", precipMM=" + precipMM +
// ", feelsLikeC=" + feelsLikeC +
// '}';
// }
// }
| import weather.data.WeatherWebApi;
import weather.model.WeatherInfo;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.stream.Collectors.*; | /*
* Copyright (c) 2017, Miguel Gamboa
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package weather;
/**
* @author Miguel Gamboa
* created on 18-04-2017
*/
public class WeatherServiceCache extends WeatherService{
public WeatherServiceCache(WeatherWebApi api) {
super(api);
}
| // Path: aula21-iterator-vs-stream/src/main/java/weather/data/WeatherWebApi.java
// public class WeatherWebApi {
//
// private static final String WEATHER_TOKEN;
// private static final String WEATHER_HOST = "http://api.worldweatheronline.com";
// private static final String WEATHER_PAST = "/premium/v1/past-weather.ashx";
// private static final String WEATHER_PAST_ARGS =
// "?q=%s&date=%s&enddate=%s&tp=24&format=csv&key=%s";
// private static final String WEATHER_SEARCH="/premium/v1/search.ashx?query=%s";
// private static final String WEATHER_SEARCH_ARGS="&format=tab&key=%s";
//
// static {
// try {
// URL keyFile = ClassLoader.getSystemResource("worldweatheronline-app-key.txt");
// if(keyFile == null) {
// throw new IllegalStateException(
// "YOU MUST GOT a KEY in developer.worldweatheronline.com and place it in src/main/resources/worldweatheronline-app-key.txt");
// } else {
// InputStream keyStream = keyFile.openStream();
// try (BufferedReader reader = new BufferedReader(new InputStreamReader(keyStream))) {
// WEATHER_TOKEN = reader.readLine();
// }
// }
// } catch (IOException e) {
// throw new UncheckedIOException(e);
// }
// }
//
// private final IRequest req;
//
// public WeatherWebApi(IRequest req) {
// this.req = req;
// }
//
// /**
// * E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****
// */
//
// public Iterable<LocationDto> search(String query) {
// String path = WEATHER_HOST + WEATHER_SEARCH + WEATHER_SEARCH_ARGS;
// String url = String.format(path, query, WEATHER_TOKEN);
// Iterable<String> content = () -> req.getContent(url).iterator();
// Iterable<String> iterable = filter(content, (String s) -> !s.startsWith("#"));
// return map(iterable, LocationDto::valueOf);
// }
//
// /**
// * E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****
// */
// public Iterable<WeatherInfoDto> pastWeather(
// double lat,
// double log,
// LocalDate from,
// LocalDate to
// ) {
// String query = lat + "," + log;
// String path = WEATHER_HOST + WEATHER_PAST +
// String.format(WEATHER_PAST_ARGS, query, from, to, WEATHER_TOKEN);
// Iterable<String> content = () -> req.getContent(path).iterator();
// Iterable<String> stringIterable = filter(content, s->!s.startsWith("#"));
// Iterable<String>filtered = skip(stringIterable,1); // Skip line: Not Available
// int[] counter = {0};
// Predicate<String> isEvenLine = item -> ++counter[0] % 2==0;
// filtered = filter(filtered,isEvenLine);//even lines filter
// return map(filtered, WeatherInfoDto::valueOf); //to weatherinfo objects
// }
// }
//
// Path: aula33-weather-async/src/main/java/weather/model/WeatherInfo.java
// public class WeatherInfo {
// private final LocalDate date;
// private final int tempC;
// private final String description;
// private final double precipMM;
// private final int feelsLikeC;
//
// public WeatherInfo(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {
// this.date = date;
// this.tempC = tempC;
// this.description = description;
// this.precipMM = precipMM;
// this.feelsLikeC = feelsLikeC;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public int getTempC() {
// return tempC;
// }
//
// public String getDescription() {
// return description;
// }
//
// public double getPrecipMM() {
// return precipMM;
// }
//
// public int getFeelsLikeC() {
// return feelsLikeC;
// }
//
// @Override
// public String toString() {
// return "WeatherInfo{" +
// "date=" + date +
// ", tempC=" + tempC +
// ", description='" + description + '\'' +
// ", precipMM=" + precipMM +
// ", feelsLikeC=" + feelsLikeC +
// '}';
// }
// }
// Path: aula31-weather-groupingBy/src/main/java/weather/WeatherServiceCache.java
import weather.data.WeatherWebApi;
import weather.model.WeatherInfo;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.stream.Collectors.*;
/*
* Copyright (c) 2017, Miguel Gamboa
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package weather;
/**
* @author Miguel Gamboa
* created on 18-04-2017
*/
public class WeatherServiceCache extends WeatherService{
public WeatherServiceCache(WeatherWebApi api) {
super(api);
}
| private final Map<Coords, Map<LocalDate, WeatherInfo>> cache = new HashMap<>(); |
isel-leic-mpd/mpd-2017-i41d | aula34-weather-webapp/src/main/java/weather/controllers/WeatherController.java | // Path: aula33-weather-async/src/main/java/weather/WeatherService.java
// public class WeatherService implements AutoCloseable{
//
// private final WeatherWebApi api;
//
// public WeatherService(WeatherWebApi api) {
// this.api = api;
// }
//
// public WeatherService() {
// api = new WeatherWebApi(new HttpRequest());
// }
//
// public CompletableFuture<Stream<Location>> search(String query) {
// return api.search(query)
// .thenApply(str -> str
// .map(this::dtoToLocation));
// }
//
// protected Location dtoToLocation(LocationDto loc) {
// return new Location(
// loc.getCountry(),
// loc.getRegion(),
// loc.getLatitude(),
// loc.getLongitude(),
// last30daysWeather(loc.getLatitude(), loc.getLongitude())::join,
// (from, to) -> pastWeather(loc.getLatitude(), loc.getLongitude(), from, to).join());
// }
//
// public CompletableFuture<Stream<WeatherInfo>> last30daysWeather(double lat, double log) {
// return this.pastWeather(lat, log, now().minusDays(30), now().minusDays(1));
// }
//
// private static WeatherInfo dtoToWeatherInfo(WeatherInfoDto dto) {
// return new WeatherInfo(
// dto.getDate(),
// dto.getTempC(),
// dto.getDescription(),
// dto.getPrecipMM(),
// dto.getFeelsLikeC());
// }
//
// public CompletableFuture<Stream<WeatherInfo>> pastWeather(double lat, double log, LocalDate from, LocalDate to) {
// return api
// .pastWeather(lat, log, from, to)
// .thenApply(str -> str
// .map(dto -> dtoToWeatherInfo(dto)));
// }
//
// @Override
// public void close() throws Exception {
// api.close();
// }
// }
//
// Path: aula19-optional-and-default-methods/src/main/java/weather/model/Location.java
// public class Location {
// private final String country;
// private final String region;
// private final double latitude;
// private final double longitude;
// private final Iterable<WeatherInfo> last30daysWeather;
// private final BiFunction<LocalDate, LocalDate, Iterable<WeatherInfo>> pastWeather;
//
// public Location(String country, String region, double latitude, double longitude, Iterable<WeatherInfo> last30daysWeather, BiFunction<LocalDate, LocalDate, Iterable<WeatherInfo>> pastWeather) {
// this.country = country;
// this.region = region;
// this.latitude = latitude;
// this.longitude = longitude;
// this.last30daysWeather = last30daysWeather;
// this.pastWeather = pastWeather;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getRegion() {
// return region;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public Iterable<WeatherInfo> getLast30daysWeather() {
// return last30daysWeather;
// }
//
// public Iterable<WeatherInfo> getPastWeather(LocalDate from, LocalDate to) {
// return pastWeather.apply(from, to);
// }
//
// @Override
// public String toString() {
// return "Location{" +
// "country='" + country + '\'' +
// ", region='" + region + '\'' +
// ", latitude=" + latitude +
// ", longitude=" + longitude +
// ", last30daysWeather=" + last30daysWeather +
// '}';
// }
// }
| import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import static java.lang.ClassLoader.getSystemResource;
import static java.nio.file.Files.lines;
import weather.WeatherService;
import weather.model.Location;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.CompletableFuture; | /*
* Copyright (c) 2017, Miguel Gamboa
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package weather.controllers;
/**
* @author Miguel Gamboa
* created on 06-06-2017
*/
public class WeatherController {
private final String root;
| // Path: aula33-weather-async/src/main/java/weather/WeatherService.java
// public class WeatherService implements AutoCloseable{
//
// private final WeatherWebApi api;
//
// public WeatherService(WeatherWebApi api) {
// this.api = api;
// }
//
// public WeatherService() {
// api = new WeatherWebApi(new HttpRequest());
// }
//
// public CompletableFuture<Stream<Location>> search(String query) {
// return api.search(query)
// .thenApply(str -> str
// .map(this::dtoToLocation));
// }
//
// protected Location dtoToLocation(LocationDto loc) {
// return new Location(
// loc.getCountry(),
// loc.getRegion(),
// loc.getLatitude(),
// loc.getLongitude(),
// last30daysWeather(loc.getLatitude(), loc.getLongitude())::join,
// (from, to) -> pastWeather(loc.getLatitude(), loc.getLongitude(), from, to).join());
// }
//
// public CompletableFuture<Stream<WeatherInfo>> last30daysWeather(double lat, double log) {
// return this.pastWeather(lat, log, now().minusDays(30), now().minusDays(1));
// }
//
// private static WeatherInfo dtoToWeatherInfo(WeatherInfoDto dto) {
// return new WeatherInfo(
// dto.getDate(),
// dto.getTempC(),
// dto.getDescription(),
// dto.getPrecipMM(),
// dto.getFeelsLikeC());
// }
//
// public CompletableFuture<Stream<WeatherInfo>> pastWeather(double lat, double log, LocalDate from, LocalDate to) {
// return api
// .pastWeather(lat, log, from, to)
// .thenApply(str -> str
// .map(dto -> dtoToWeatherInfo(dto)));
// }
//
// @Override
// public void close() throws Exception {
// api.close();
// }
// }
//
// Path: aula19-optional-and-default-methods/src/main/java/weather/model/Location.java
// public class Location {
// private final String country;
// private final String region;
// private final double latitude;
// private final double longitude;
// private final Iterable<WeatherInfo> last30daysWeather;
// private final BiFunction<LocalDate, LocalDate, Iterable<WeatherInfo>> pastWeather;
//
// public Location(String country, String region, double latitude, double longitude, Iterable<WeatherInfo> last30daysWeather, BiFunction<LocalDate, LocalDate, Iterable<WeatherInfo>> pastWeather) {
// this.country = country;
// this.region = region;
// this.latitude = latitude;
// this.longitude = longitude;
// this.last30daysWeather = last30daysWeather;
// this.pastWeather = pastWeather;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getRegion() {
// return region;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public Iterable<WeatherInfo> getLast30daysWeather() {
// return last30daysWeather;
// }
//
// public Iterable<WeatherInfo> getPastWeather(LocalDate from, LocalDate to) {
// return pastWeather.apply(from, to);
// }
//
// @Override
// public String toString() {
// return "Location{" +
// "country='" + country + '\'' +
// ", region='" + region + '\'' +
// ", latitude=" + latitude +
// ", longitude=" + longitude +
// ", last30daysWeather=" + last30daysWeather +
// '}';
// }
// }
// Path: aula34-weather-webapp/src/main/java/weather/controllers/WeatherController.java
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import static java.lang.ClassLoader.getSystemResource;
import static java.nio.file.Files.lines;
import weather.WeatherService;
import weather.model.Location;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.CompletableFuture;
/*
* Copyright (c) 2017, Miguel Gamboa
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package weather.controllers;
/**
* @author Miguel Gamboa
* created on 06-06-2017
*/
public class WeatherController {
private final String root;
| private final WeatherService api; |
isel-leic-mpd/mpd-2017-i41d | aula34-weather-webapp/src/main/java/weather/controllers/WeatherController.java | // Path: aula33-weather-async/src/main/java/weather/WeatherService.java
// public class WeatherService implements AutoCloseable{
//
// private final WeatherWebApi api;
//
// public WeatherService(WeatherWebApi api) {
// this.api = api;
// }
//
// public WeatherService() {
// api = new WeatherWebApi(new HttpRequest());
// }
//
// public CompletableFuture<Stream<Location>> search(String query) {
// return api.search(query)
// .thenApply(str -> str
// .map(this::dtoToLocation));
// }
//
// protected Location dtoToLocation(LocationDto loc) {
// return new Location(
// loc.getCountry(),
// loc.getRegion(),
// loc.getLatitude(),
// loc.getLongitude(),
// last30daysWeather(loc.getLatitude(), loc.getLongitude())::join,
// (from, to) -> pastWeather(loc.getLatitude(), loc.getLongitude(), from, to).join());
// }
//
// public CompletableFuture<Stream<WeatherInfo>> last30daysWeather(double lat, double log) {
// return this.pastWeather(lat, log, now().minusDays(30), now().minusDays(1));
// }
//
// private static WeatherInfo dtoToWeatherInfo(WeatherInfoDto dto) {
// return new WeatherInfo(
// dto.getDate(),
// dto.getTempC(),
// dto.getDescription(),
// dto.getPrecipMM(),
// dto.getFeelsLikeC());
// }
//
// public CompletableFuture<Stream<WeatherInfo>> pastWeather(double lat, double log, LocalDate from, LocalDate to) {
// return api
// .pastWeather(lat, log, from, to)
// .thenApply(str -> str
// .map(dto -> dtoToWeatherInfo(dto)));
// }
//
// @Override
// public void close() throws Exception {
// api.close();
// }
// }
//
// Path: aula19-optional-and-default-methods/src/main/java/weather/model/Location.java
// public class Location {
// private final String country;
// private final String region;
// private final double latitude;
// private final double longitude;
// private final Iterable<WeatherInfo> last30daysWeather;
// private final BiFunction<LocalDate, LocalDate, Iterable<WeatherInfo>> pastWeather;
//
// public Location(String country, String region, double latitude, double longitude, Iterable<WeatherInfo> last30daysWeather, BiFunction<LocalDate, LocalDate, Iterable<WeatherInfo>> pastWeather) {
// this.country = country;
// this.region = region;
// this.latitude = latitude;
// this.longitude = longitude;
// this.last30daysWeather = last30daysWeather;
// this.pastWeather = pastWeather;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getRegion() {
// return region;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public Iterable<WeatherInfo> getLast30daysWeather() {
// return last30daysWeather;
// }
//
// public Iterable<WeatherInfo> getPastWeather(LocalDate from, LocalDate to) {
// return pastWeather.apply(from, to);
// }
//
// @Override
// public String toString() {
// return "Location{" +
// "country='" + country + '\'' +
// ", region='" + region + '\'' +
// ", latitude=" + latitude +
// ", longitude=" + longitude +
// ", last30daysWeather=" + last30daysWeather +
// '}';
// }
// }
| import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import static java.lang.ClassLoader.getSystemResource;
import static java.nio.file.Files.lines;
import weather.WeatherService;
import weather.model.Location;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.CompletableFuture; | }
else { // Already in File System
last30days = new CompletableFuture<>();
last30days.complete(view);
}
last30daysViewsCache.putIfAbsent(coords, last30days); // Save on cache
}
return last30days;
}
private String loadLast30daysWeather(double lat, double log) {
String path = root + lat + "-" + log + ".html";
File file = new File(path);
URI uri = !file.exists() ? null : file.toURI();
return uri == null ? null : load(uri);
}
private String writeLast30daysWeather(double lat, double log, String view) {
try {
String path = root + lat + "-" + log + ".html";
try (FileWriter fw = new FileWriter(path)) {
fw.write(view);
fw.flush();
}
}catch (IOException e) {
throw new RuntimeException(e);
}
return view;
}
| // Path: aula33-weather-async/src/main/java/weather/WeatherService.java
// public class WeatherService implements AutoCloseable{
//
// private final WeatherWebApi api;
//
// public WeatherService(WeatherWebApi api) {
// this.api = api;
// }
//
// public WeatherService() {
// api = new WeatherWebApi(new HttpRequest());
// }
//
// public CompletableFuture<Stream<Location>> search(String query) {
// return api.search(query)
// .thenApply(str -> str
// .map(this::dtoToLocation));
// }
//
// protected Location dtoToLocation(LocationDto loc) {
// return new Location(
// loc.getCountry(),
// loc.getRegion(),
// loc.getLatitude(),
// loc.getLongitude(),
// last30daysWeather(loc.getLatitude(), loc.getLongitude())::join,
// (from, to) -> pastWeather(loc.getLatitude(), loc.getLongitude(), from, to).join());
// }
//
// public CompletableFuture<Stream<WeatherInfo>> last30daysWeather(double lat, double log) {
// return this.pastWeather(lat, log, now().minusDays(30), now().minusDays(1));
// }
//
// private static WeatherInfo dtoToWeatherInfo(WeatherInfoDto dto) {
// return new WeatherInfo(
// dto.getDate(),
// dto.getTempC(),
// dto.getDescription(),
// dto.getPrecipMM(),
// dto.getFeelsLikeC());
// }
//
// public CompletableFuture<Stream<WeatherInfo>> pastWeather(double lat, double log, LocalDate from, LocalDate to) {
// return api
// .pastWeather(lat, log, from, to)
// .thenApply(str -> str
// .map(dto -> dtoToWeatherInfo(dto)));
// }
//
// @Override
// public void close() throws Exception {
// api.close();
// }
// }
//
// Path: aula19-optional-and-default-methods/src/main/java/weather/model/Location.java
// public class Location {
// private final String country;
// private final String region;
// private final double latitude;
// private final double longitude;
// private final Iterable<WeatherInfo> last30daysWeather;
// private final BiFunction<LocalDate, LocalDate, Iterable<WeatherInfo>> pastWeather;
//
// public Location(String country, String region, double latitude, double longitude, Iterable<WeatherInfo> last30daysWeather, BiFunction<LocalDate, LocalDate, Iterable<WeatherInfo>> pastWeather) {
// this.country = country;
// this.region = region;
// this.latitude = latitude;
// this.longitude = longitude;
// this.last30daysWeather = last30daysWeather;
// this.pastWeather = pastWeather;
// }
//
// public String getCountry() {
// return country;
// }
//
// public String getRegion() {
// return region;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public Iterable<WeatherInfo> getLast30daysWeather() {
// return last30daysWeather;
// }
//
// public Iterable<WeatherInfo> getPastWeather(LocalDate from, LocalDate to) {
// return pastWeather.apply(from, to);
// }
//
// @Override
// public String toString() {
// return "Location{" +
// "country='" + country + '\'' +
// ", region='" + region + '\'' +
// ", latitude=" + latitude +
// ", longitude=" + longitude +
// ", last30daysWeather=" + last30daysWeather +
// '}';
// }
// }
// Path: aula34-weather-webapp/src/main/java/weather/controllers/WeatherController.java
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import static java.lang.ClassLoader.getSystemResource;
import static java.nio.file.Files.lines;
import weather.WeatherService;
import weather.model.Location;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.CompletableFuture;
}
else { // Already in File System
last30days = new CompletableFuture<>();
last30days.complete(view);
}
last30daysViewsCache.putIfAbsent(coords, last30days); // Save on cache
}
return last30days;
}
private String loadLast30daysWeather(double lat, double log) {
String path = root + lat + "-" + log + ".html";
File file = new File(path);
URI uri = !file.exists() ? null : file.toURI();
return uri == null ? null : load(uri);
}
private String writeLast30daysWeather(double lat, double log, String view) {
try {
String path = root + lat + "-" + log + ".html";
try (FileWriter fw = new FileWriter(path)) {
fw.write(view);
fw.flush();
}
}catch (IOException e) {
throw new RuntimeException(e);
}
return view;
}
| private static String linkForLocation(Location l) { |
isel-leic-mpd/mpd-2017-i41d | aula09-composition-and-decorator/src/main/java/util/queries/NaiveQueries.java | // Path: aula04-queries/src/main/java/util/WeatherPredicate.java
// public interface WeatherPredicate {
// boolean test(WeatherInfo item);
// }
//
// Path: aula09-composition-and-decorator/src/main/java/weather/model/WeatherInfo.java
// public class WeatherInfo {
// private final LocalDate date; // index 0
// private final int tempC; // index 2
// private final String description; // index 10
// private final double precipMM; // index 11
// private final int feelsLikeC; // index 24
//
// public WeatherInfo(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {
// this.date = date;
// this.tempC = tempC;
// this.description = description;
// this.precipMM = precipMM;
// this.feelsLikeC = feelsLikeC;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public int getTempC() {
// return tempC;
// }
//
// public String getDescription() {
// return description;
// }
//
// public double getPrecipMM() {
// return precipMM;
// }
//
// public int getFeelsLikeC() {
// return feelsLikeC;
// }
//
// @Override
// public String toString() {
// return "WeatherInfo{" +
// date +
// ", tempC=" + tempC +
// ", '" + description + '\'' +
// ", precipMM=" + precipMM +
// ", feelsLikeC=" + feelsLikeC +
// '}';
// }
//
// /**
// * Hourly information follows below the day according to the format of
// * /past weather resource of the World Weather Online API
// */
// public static WeatherInfo valueOf(String line) {
// String[] data = line.split(",");
// return new WeatherInfo(
// LocalDate.parse(data[0]),
// Integer.parseInt(data[2]),
// data[10],
// Double.parseDouble(data[11]),
// Integer.parseInt(data[24]));
// }
// }
| import util.WeatherPredicate;
import weather.dto.WeatherInfo;
import java.util.ArrayList;
import java.util.List; | /*
* Copyright (c) 2017, Miguel Gamboa
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package util.queries;
/**
* NaiveQueries provide utility methods that make queries over a sequence
* of elements.
* A sequence is considered an Iterable.
*
* @author Miguel Gamboa
* created on 14-03-2017
*/
public class NaiveQueries {
/**
* v1- Auxiliary method to filter cloudy days. Returns a new sequence with
* WeatherInfo objects that were cloudy.
* Eager approach.
*/
public static Iterable<WeatherInfo> filterCloudy(Iterable<WeatherInfo> data) {
List<WeatherInfo> res = new ArrayList<>();
for (WeatherInfo item: data) {
if(item.getDescription().toLowerCase().contains("cloud"))
res.add(item);
}
return res;
}
public static Iterable<WeatherInfo> filterRainy(Iterable<WeatherInfo> data) {
List<WeatherInfo> res = new ArrayList<>();
for (WeatherInfo item: data) {
if(item.getDescription().toLowerCase().contains("rain"))
res.add(item);
}
return res;
}
/**
* v2-
*/
public static Iterable<WeatherInfo> filterDesc(Iterable<WeatherInfo> data, String query) {
List<WeatherInfo> res = new ArrayList<>();
for (WeatherInfo item: data) {
if(item.getDescription().toLowerCase().contains(query))
res.add(item);
}
return res;
}
/**
* v3 -
*/ | // Path: aula04-queries/src/main/java/util/WeatherPredicate.java
// public interface WeatherPredicate {
// boolean test(WeatherInfo item);
// }
//
// Path: aula09-composition-and-decorator/src/main/java/weather/model/WeatherInfo.java
// public class WeatherInfo {
// private final LocalDate date; // index 0
// private final int tempC; // index 2
// private final String description; // index 10
// private final double precipMM; // index 11
// private final int feelsLikeC; // index 24
//
// public WeatherInfo(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {
// this.date = date;
// this.tempC = tempC;
// this.description = description;
// this.precipMM = precipMM;
// this.feelsLikeC = feelsLikeC;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public int getTempC() {
// return tempC;
// }
//
// public String getDescription() {
// return description;
// }
//
// public double getPrecipMM() {
// return precipMM;
// }
//
// public int getFeelsLikeC() {
// return feelsLikeC;
// }
//
// @Override
// public String toString() {
// return "WeatherInfo{" +
// date +
// ", tempC=" + tempC +
// ", '" + description + '\'' +
// ", precipMM=" + precipMM +
// ", feelsLikeC=" + feelsLikeC +
// '}';
// }
//
// /**
// * Hourly information follows below the day according to the format of
// * /past weather resource of the World Weather Online API
// */
// public static WeatherInfo valueOf(String line) {
// String[] data = line.split(",");
// return new WeatherInfo(
// LocalDate.parse(data[0]),
// Integer.parseInt(data[2]),
// data[10],
// Double.parseDouble(data[11]),
// Integer.parseInt(data[24]));
// }
// }
// Path: aula09-composition-and-decorator/src/main/java/util/queries/NaiveQueries.java
import util.WeatherPredicate;
import weather.dto.WeatherInfo;
import java.util.ArrayList;
import java.util.List;
/*
* Copyright (c) 2017, Miguel Gamboa
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package util.queries;
/**
* NaiveQueries provide utility methods that make queries over a sequence
* of elements.
* A sequence is considered an Iterable.
*
* @author Miguel Gamboa
* created on 14-03-2017
*/
public class NaiveQueries {
/**
* v1- Auxiliary method to filter cloudy days. Returns a new sequence with
* WeatherInfo objects that were cloudy.
* Eager approach.
*/
public static Iterable<WeatherInfo> filterCloudy(Iterable<WeatherInfo> data) {
List<WeatherInfo> res = new ArrayList<>();
for (WeatherInfo item: data) {
if(item.getDescription().toLowerCase().contains("cloud"))
res.add(item);
}
return res;
}
public static Iterable<WeatherInfo> filterRainy(Iterable<WeatherInfo> data) {
List<WeatherInfo> res = new ArrayList<>();
for (WeatherInfo item: data) {
if(item.getDescription().toLowerCase().contains("rain"))
res.add(item);
}
return res;
}
/**
* v2-
*/
public static Iterable<WeatherInfo> filterDesc(Iterable<WeatherInfo> data, String query) {
List<WeatherInfo> res = new ArrayList<>();
for (WeatherInfo item: data) {
if(item.getDescription().toLowerCase().contains(query))
res.add(item);
}
return res;
}
/**
* v3 -
*/ | public static Iterable<WeatherInfo> filter(Iterable<WeatherInfo> data, WeatherPredicate p) { |
isel-leic-mpd/mpd-2017-i41d | aula33-weather-async/src/main/java/weather/data/WeatherWebApi.java | // Path: aula33-weather-async/src/main/java/util/IRequest.java
// public interface IRequest extends AutoCloseable{
// CompletableFuture<Stream<String>> getContent(String path);
//
// @Override
// public default void close() {
// }
// }
//
// Path: aula33-weather-async/src/main/java/weather/data/dto/LocationDto.java
// public class LocationDto {
// private final ContainerDto[] country;
// private final ContainerDto[] region;
// private final double latitude;
// private final double longitude;
//
// public LocationDto(ContainerDto[] country, ContainerDto[] region, double latitude, double longitude) {
// this.country = country;
// this.region = region;
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// public String getCountry() {
// return country[0].value;
// }
//
// public String getRegion() {
// return region[0].value;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public static LocationDto valueOf(String line) {
// String[] data = line.split("\t");
// return new LocationDto(
// ContainerDto.arrayOf(data[1]),
// ContainerDto.arrayOf(data[2]),
// Double.parseDouble(data[3]),
// Double.parseDouble(data[4]));
// }
//
// @Override
// public String toString() {
// return "LocationDto{" +
// "country='" + getCountry() + '\'' +
// ", region='" + getRegion() + '\'' +
// ", latitude=" + latitude +
// ", longitude=" + longitude +
// '}';
// }
//
// static class ContainerDto {
// final String value;
//
// public ContainerDto(String value) {
// this.value = value;
// }
//
// @Override
// public String toString() {
// return value;
// }
//
// public static ContainerDto[] arrayOf(String s) {
// ContainerDto dto = new ContainerDto(s);
// return new ContainerDto[]{dto};
// }
// }
// }
//
// Path: aula33-weather-async/src/main/java/weather/data/dto/WeatherInfoDto.java
// public class WeatherInfoDto {
// private final LocalDate date; // index 0
// private final int tempC; // index 2
// private final String description; // index 10
// private final double precipMM; // index 11
// private final int feelsLikeC; // index 24
//
// public WeatherInfoDto(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {
// this.date = date;
// this.tempC = tempC;
// this.description = description;
// this.precipMM = precipMM;
// this.feelsLikeC = feelsLikeC;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public int getTempC() {
// return tempC;
// }
//
// public String getDescription() {
// return description;
// }
//
// public double getPrecipMM() {
// return precipMM;
// }
//
// public int getFeelsLikeC() {
// return feelsLikeC;
// }
//
// @Override
// public String toString() {
// return "WeatherInfoDto{" +
// date +
// ", tempC=" + tempC +
// ", '" + description + '\'' +
// ", precipMM=" + precipMM +
// ", feelsLikeC=" + feelsLikeC +
// '}';
// }
//
// /**
// * Hourly information follows below the day according to the format of
// * /past weather resource of the World Weather Online API
// */
// public static WeatherInfoDto valueOf(String line) {
// String[] data = line.split(",");
// return new WeatherInfoDto(
// LocalDate.parse(data[0]),
// Integer.parseInt(data[2]),
// data[10],
// Double.parseDouble(data[11]),
// Integer.parseInt(data[24]));
// }
// }
| import java.util.stream.Stream;
import util.IRequest;
import weather.data.dto.LocationDto;
import weather.data.dto.WeatherInfoDto;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.net.URL;
import java.time.LocalDate;
import java.util.concurrent.CompletableFuture;
import java.util.function.Predicate; | WEATHER_TOKEN = reader.readLine();
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private final IRequest req;
public WeatherWebApi(IRequest req) {
this.req = req;
}
/**
* E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****
*/
public CompletableFuture<Stream<LocationDto>> search(String query) {
String path = WEATHER_HOST + WEATHER_SEARCH + WEATHER_SEARCH_ARGS;
String url = String.format(path, query, WEATHER_TOKEN);
return req.getContent(url)
.thenApply(str -> str
.filter((String s) -> !s.startsWith("#"))
.map(LocationDto::valueOf));
}
/**
* E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****
*/ | // Path: aula33-weather-async/src/main/java/util/IRequest.java
// public interface IRequest extends AutoCloseable{
// CompletableFuture<Stream<String>> getContent(String path);
//
// @Override
// public default void close() {
// }
// }
//
// Path: aula33-weather-async/src/main/java/weather/data/dto/LocationDto.java
// public class LocationDto {
// private final ContainerDto[] country;
// private final ContainerDto[] region;
// private final double latitude;
// private final double longitude;
//
// public LocationDto(ContainerDto[] country, ContainerDto[] region, double latitude, double longitude) {
// this.country = country;
// this.region = region;
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// public String getCountry() {
// return country[0].value;
// }
//
// public String getRegion() {
// return region[0].value;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public static LocationDto valueOf(String line) {
// String[] data = line.split("\t");
// return new LocationDto(
// ContainerDto.arrayOf(data[1]),
// ContainerDto.arrayOf(data[2]),
// Double.parseDouble(data[3]),
// Double.parseDouble(data[4]));
// }
//
// @Override
// public String toString() {
// return "LocationDto{" +
// "country='" + getCountry() + '\'' +
// ", region='" + getRegion() + '\'' +
// ", latitude=" + latitude +
// ", longitude=" + longitude +
// '}';
// }
//
// static class ContainerDto {
// final String value;
//
// public ContainerDto(String value) {
// this.value = value;
// }
//
// @Override
// public String toString() {
// return value;
// }
//
// public static ContainerDto[] arrayOf(String s) {
// ContainerDto dto = new ContainerDto(s);
// return new ContainerDto[]{dto};
// }
// }
// }
//
// Path: aula33-weather-async/src/main/java/weather/data/dto/WeatherInfoDto.java
// public class WeatherInfoDto {
// private final LocalDate date; // index 0
// private final int tempC; // index 2
// private final String description; // index 10
// private final double precipMM; // index 11
// private final int feelsLikeC; // index 24
//
// public WeatherInfoDto(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {
// this.date = date;
// this.tempC = tempC;
// this.description = description;
// this.precipMM = precipMM;
// this.feelsLikeC = feelsLikeC;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public int getTempC() {
// return tempC;
// }
//
// public String getDescription() {
// return description;
// }
//
// public double getPrecipMM() {
// return precipMM;
// }
//
// public int getFeelsLikeC() {
// return feelsLikeC;
// }
//
// @Override
// public String toString() {
// return "WeatherInfoDto{" +
// date +
// ", tempC=" + tempC +
// ", '" + description + '\'' +
// ", precipMM=" + precipMM +
// ", feelsLikeC=" + feelsLikeC +
// '}';
// }
//
// /**
// * Hourly information follows below the day according to the format of
// * /past weather resource of the World Weather Online API
// */
// public static WeatherInfoDto valueOf(String line) {
// String[] data = line.split(",");
// return new WeatherInfoDto(
// LocalDate.parse(data[0]),
// Integer.parseInt(data[2]),
// data[10],
// Double.parseDouble(data[11]),
// Integer.parseInt(data[24]));
// }
// }
// Path: aula33-weather-async/src/main/java/weather/data/WeatherWebApi.java
import java.util.stream.Stream;
import util.IRequest;
import weather.data.dto.LocationDto;
import weather.data.dto.WeatherInfoDto;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.net.URL;
import java.time.LocalDate;
import java.util.concurrent.CompletableFuture;
import java.util.function.Predicate;
WEATHER_TOKEN = reader.readLine();
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private final IRequest req;
public WeatherWebApi(IRequest req) {
this.req = req;
}
/**
* E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****
*/
public CompletableFuture<Stream<LocationDto>> search(String query) {
String path = WEATHER_HOST + WEATHER_SEARCH + WEATHER_SEARCH_ARGS;
String url = String.format(path, query, WEATHER_TOKEN);
return req.getContent(url)
.thenApply(str -> str
.filter((String s) -> !s.startsWith("#"))
.map(LocationDto::valueOf));
}
/**
* E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****
*/ | public CompletableFuture<Stream<WeatherInfoDto>> pastWeather( |
isel-leic-mpd/mpd-2017-i41d | aula23-reduction/src/main/java/App.java | // Path: aula23-reduction/src/main/java/util/StreamUtils.java
// public static <T> Stream<T> filterEvenLine(Stream<T> src) {
// Spliterator<T> iter = src.spliterator();
// Spliterator<T> res = new AbstractSpliterator<T>(Long.MAX_VALUE, Spliterator.ORDERED ) {
// @Override
// public boolean tryAdvance(Consumer<? super T> action) {
// return iter.tryAdvance(item -> {})
// ? iter.tryAdvance(action)
// : false;
// }
// };
// return StreamSupport.stream(res, false);
// }
| import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static java.lang.System.out;
import static java.util.Arrays.stream;
import static util.StreamUtils.filterEvenLine; | }
static double streamAverage3(IntStream temperatures) {
Averager avg = temperatures
.mapToObj(nr -> new Averager(nr))
.parallel()
.reduce((prev, curr) -> prev.add(curr))
.get();
return ((double)avg.sum)/avg.count;
}
static class Averager{
final int sum;
final int count;
public Averager(int sum, int count) {
this.sum = sum;
this.count = count;
}
public Averager(int nr) {
sum = nr; count = 1;
}
public Averager add(Averager other) {
return new Averager(this.sum + other.sum, this.count + other.count);
}
}
static int streamMax(Stream<String> lines) { | // Path: aula23-reduction/src/main/java/util/StreamUtils.java
// public static <T> Stream<T> filterEvenLine(Stream<T> src) {
// Spliterator<T> iter = src.spliterator();
// Spliterator<T> res = new AbstractSpliterator<T>(Long.MAX_VALUE, Spliterator.ORDERED ) {
// @Override
// public boolean tryAdvance(Consumer<? super T> action) {
// return iter.tryAdvance(item -> {})
// ? iter.tryAdvance(action)
// : false;
// }
// };
// return StreamSupport.stream(res, false);
// }
// Path: aula23-reduction/src/main/java/App.java
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static java.lang.System.out;
import static java.util.Arrays.stream;
import static util.StreamUtils.filterEvenLine;
}
static double streamAverage3(IntStream temperatures) {
Averager avg = temperatures
.mapToObj(nr -> new Averager(nr))
.parallel()
.reduce((prev, curr) -> prev.add(curr))
.get();
return ((double)avg.sum)/avg.count;
}
static class Averager{
final int sum;
final int count;
public Averager(int sum, int count) {
this.sum = sum;
this.count = count;
}
public Averager(int nr) {
sum = nr; count = 1;
}
public Averager add(Averager other) {
return new Averager(this.sum + other.sum, this.count + other.count);
}
}
static int streamMax(Stream<String> lines) { | return filterEvenLine(lines |
isel-leic-mpd/mpd-2017-i41d | aula31-weather-groupingBy/src/main/java/weather/data/WeatherWebApi.java | // Path: aula33-weather-async/src/main/java/util/IRequest.java
// public interface IRequest extends AutoCloseable{
// CompletableFuture<Stream<String>> getContent(String path);
//
// @Override
// public default void close() {
// }
// }
//
// Path: aula33-weather-async/src/main/java/weather/data/dto/LocationDto.java
// public class LocationDto {
// private final ContainerDto[] country;
// private final ContainerDto[] region;
// private final double latitude;
// private final double longitude;
//
// public LocationDto(ContainerDto[] country, ContainerDto[] region, double latitude, double longitude) {
// this.country = country;
// this.region = region;
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// public String getCountry() {
// return country[0].value;
// }
//
// public String getRegion() {
// return region[0].value;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public static LocationDto valueOf(String line) {
// String[] data = line.split("\t");
// return new LocationDto(
// ContainerDto.arrayOf(data[1]),
// ContainerDto.arrayOf(data[2]),
// Double.parseDouble(data[3]),
// Double.parseDouble(data[4]));
// }
//
// @Override
// public String toString() {
// return "LocationDto{" +
// "country='" + getCountry() + '\'' +
// ", region='" + getRegion() + '\'' +
// ", latitude=" + latitude +
// ", longitude=" + longitude +
// '}';
// }
//
// static class ContainerDto {
// final String value;
//
// public ContainerDto(String value) {
// this.value = value;
// }
//
// @Override
// public String toString() {
// return value;
// }
//
// public static ContainerDto[] arrayOf(String s) {
// ContainerDto dto = new ContainerDto(s);
// return new ContainerDto[]{dto};
// }
// }
// }
//
// Path: aula33-weather-async/src/main/java/weather/data/dto/WeatherInfoDto.java
// public class WeatherInfoDto {
// private final LocalDate date; // index 0
// private final int tempC; // index 2
// private final String description; // index 10
// private final double precipMM; // index 11
// private final int feelsLikeC; // index 24
//
// public WeatherInfoDto(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {
// this.date = date;
// this.tempC = tempC;
// this.description = description;
// this.precipMM = precipMM;
// this.feelsLikeC = feelsLikeC;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public int getTempC() {
// return tempC;
// }
//
// public String getDescription() {
// return description;
// }
//
// public double getPrecipMM() {
// return precipMM;
// }
//
// public int getFeelsLikeC() {
// return feelsLikeC;
// }
//
// @Override
// public String toString() {
// return "WeatherInfoDto{" +
// date +
// ", tempC=" + tempC +
// ", '" + description + '\'' +
// ", precipMM=" + precipMM +
// ", feelsLikeC=" + feelsLikeC +
// '}';
// }
//
// /**
// * Hourly information follows below the day according to the format of
// * /past weather resource of the World Weather Online API
// */
// public static WeatherInfoDto valueOf(String line) {
// String[] data = line.split(",");
// return new WeatherInfoDto(
// LocalDate.parse(data[0]),
// Integer.parseInt(data[2]),
// data[10],
// Double.parseDouble(data[11]),
// Integer.parseInt(data[24]));
// }
// }
| import util.IRequest;
import weather.data.dto.LocationDto;
import weather.data.dto.WeatherInfoDto;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.net.URL;
import java.time.LocalDate;
import java.util.function.Predicate;
import java.util.stream.Stream; | /*
* Copyright (c) 2017, Miguel Gamboa
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package weather.data;
/**
* @author Miguel Gamboa
* created on 07-03-2017
*/
public class WeatherWebApi {
private static final String WEATHER_TOKEN;
private static final String WEATHER_HOST = "http://api.worldweatheronline.com";
private static final String WEATHER_PAST = "/premium/v1/past-weather.ashx";
private static final String WEATHER_PAST_ARGS =
"?q=%s&date=%s&enddate=%s&tp=24&format=csv&key=%s";
private static final String WEATHER_SEARCH="/premium/v1/search.ashx?query=%s";
private static final String WEATHER_SEARCH_ARGS="&format=tab&key=%s";
static {
try {
URL keyFile = ClassLoader.getSystemResource("worldweatheronline-app-key.txt");
if(keyFile == null) {
throw new IllegalStateException(
"YOU MUST GOT a KEY in developer.worldweatheronline.com and place it in src/main/resources/worldweatheronline-app-key.txt");
} else {
InputStream keyStream = keyFile.openStream();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(keyStream))) {
WEATHER_TOKEN = reader.readLine();
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
| // Path: aula33-weather-async/src/main/java/util/IRequest.java
// public interface IRequest extends AutoCloseable{
// CompletableFuture<Stream<String>> getContent(String path);
//
// @Override
// public default void close() {
// }
// }
//
// Path: aula33-weather-async/src/main/java/weather/data/dto/LocationDto.java
// public class LocationDto {
// private final ContainerDto[] country;
// private final ContainerDto[] region;
// private final double latitude;
// private final double longitude;
//
// public LocationDto(ContainerDto[] country, ContainerDto[] region, double latitude, double longitude) {
// this.country = country;
// this.region = region;
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// public String getCountry() {
// return country[0].value;
// }
//
// public String getRegion() {
// return region[0].value;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public static LocationDto valueOf(String line) {
// String[] data = line.split("\t");
// return new LocationDto(
// ContainerDto.arrayOf(data[1]),
// ContainerDto.arrayOf(data[2]),
// Double.parseDouble(data[3]),
// Double.parseDouble(data[4]));
// }
//
// @Override
// public String toString() {
// return "LocationDto{" +
// "country='" + getCountry() + '\'' +
// ", region='" + getRegion() + '\'' +
// ", latitude=" + latitude +
// ", longitude=" + longitude +
// '}';
// }
//
// static class ContainerDto {
// final String value;
//
// public ContainerDto(String value) {
// this.value = value;
// }
//
// @Override
// public String toString() {
// return value;
// }
//
// public static ContainerDto[] arrayOf(String s) {
// ContainerDto dto = new ContainerDto(s);
// return new ContainerDto[]{dto};
// }
// }
// }
//
// Path: aula33-weather-async/src/main/java/weather/data/dto/WeatherInfoDto.java
// public class WeatherInfoDto {
// private final LocalDate date; // index 0
// private final int tempC; // index 2
// private final String description; // index 10
// private final double precipMM; // index 11
// private final int feelsLikeC; // index 24
//
// public WeatherInfoDto(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {
// this.date = date;
// this.tempC = tempC;
// this.description = description;
// this.precipMM = precipMM;
// this.feelsLikeC = feelsLikeC;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public int getTempC() {
// return tempC;
// }
//
// public String getDescription() {
// return description;
// }
//
// public double getPrecipMM() {
// return precipMM;
// }
//
// public int getFeelsLikeC() {
// return feelsLikeC;
// }
//
// @Override
// public String toString() {
// return "WeatherInfoDto{" +
// date +
// ", tempC=" + tempC +
// ", '" + description + '\'' +
// ", precipMM=" + precipMM +
// ", feelsLikeC=" + feelsLikeC +
// '}';
// }
//
// /**
// * Hourly information follows below the day according to the format of
// * /past weather resource of the World Weather Online API
// */
// public static WeatherInfoDto valueOf(String line) {
// String[] data = line.split(",");
// return new WeatherInfoDto(
// LocalDate.parse(data[0]),
// Integer.parseInt(data[2]),
// data[10],
// Double.parseDouble(data[11]),
// Integer.parseInt(data[24]));
// }
// }
// Path: aula31-weather-groupingBy/src/main/java/weather/data/WeatherWebApi.java
import util.IRequest;
import weather.data.dto.LocationDto;
import weather.data.dto.WeatherInfoDto;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.net.URL;
import java.time.LocalDate;
import java.util.function.Predicate;
import java.util.stream.Stream;
/*
* Copyright (c) 2017, Miguel Gamboa
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package weather.data;
/**
* @author Miguel Gamboa
* created on 07-03-2017
*/
public class WeatherWebApi {
private static final String WEATHER_TOKEN;
private static final String WEATHER_HOST = "http://api.worldweatheronline.com";
private static final String WEATHER_PAST = "/premium/v1/past-weather.ashx";
private static final String WEATHER_PAST_ARGS =
"?q=%s&date=%s&enddate=%s&tp=24&format=csv&key=%s";
private static final String WEATHER_SEARCH="/premium/v1/search.ashx?query=%s";
private static final String WEATHER_SEARCH_ARGS="&format=tab&key=%s";
static {
try {
URL keyFile = ClassLoader.getSystemResource("worldweatheronline-app-key.txt");
if(keyFile == null) {
throw new IllegalStateException(
"YOU MUST GOT a KEY in developer.worldweatheronline.com and place it in src/main/resources/worldweatheronline-app-key.txt");
} else {
InputStream keyStream = keyFile.openStream();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(keyStream))) {
WEATHER_TOKEN = reader.readLine();
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
| private final IRequest req; |
isel-leic-mpd/mpd-2017-i41d | aula31-weather-groupingBy/src/main/java/weather/data/WeatherWebApi.java | // Path: aula33-weather-async/src/main/java/util/IRequest.java
// public interface IRequest extends AutoCloseable{
// CompletableFuture<Stream<String>> getContent(String path);
//
// @Override
// public default void close() {
// }
// }
//
// Path: aula33-weather-async/src/main/java/weather/data/dto/LocationDto.java
// public class LocationDto {
// private final ContainerDto[] country;
// private final ContainerDto[] region;
// private final double latitude;
// private final double longitude;
//
// public LocationDto(ContainerDto[] country, ContainerDto[] region, double latitude, double longitude) {
// this.country = country;
// this.region = region;
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// public String getCountry() {
// return country[0].value;
// }
//
// public String getRegion() {
// return region[0].value;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public static LocationDto valueOf(String line) {
// String[] data = line.split("\t");
// return new LocationDto(
// ContainerDto.arrayOf(data[1]),
// ContainerDto.arrayOf(data[2]),
// Double.parseDouble(data[3]),
// Double.parseDouble(data[4]));
// }
//
// @Override
// public String toString() {
// return "LocationDto{" +
// "country='" + getCountry() + '\'' +
// ", region='" + getRegion() + '\'' +
// ", latitude=" + latitude +
// ", longitude=" + longitude +
// '}';
// }
//
// static class ContainerDto {
// final String value;
//
// public ContainerDto(String value) {
// this.value = value;
// }
//
// @Override
// public String toString() {
// return value;
// }
//
// public static ContainerDto[] arrayOf(String s) {
// ContainerDto dto = new ContainerDto(s);
// return new ContainerDto[]{dto};
// }
// }
// }
//
// Path: aula33-weather-async/src/main/java/weather/data/dto/WeatherInfoDto.java
// public class WeatherInfoDto {
// private final LocalDate date; // index 0
// private final int tempC; // index 2
// private final String description; // index 10
// private final double precipMM; // index 11
// private final int feelsLikeC; // index 24
//
// public WeatherInfoDto(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {
// this.date = date;
// this.tempC = tempC;
// this.description = description;
// this.precipMM = precipMM;
// this.feelsLikeC = feelsLikeC;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public int getTempC() {
// return tempC;
// }
//
// public String getDescription() {
// return description;
// }
//
// public double getPrecipMM() {
// return precipMM;
// }
//
// public int getFeelsLikeC() {
// return feelsLikeC;
// }
//
// @Override
// public String toString() {
// return "WeatherInfoDto{" +
// date +
// ", tempC=" + tempC +
// ", '" + description + '\'' +
// ", precipMM=" + precipMM +
// ", feelsLikeC=" + feelsLikeC +
// '}';
// }
//
// /**
// * Hourly information follows below the day according to the format of
// * /past weather resource of the World Weather Online API
// */
// public static WeatherInfoDto valueOf(String line) {
// String[] data = line.split(",");
// return new WeatherInfoDto(
// LocalDate.parse(data[0]),
// Integer.parseInt(data[2]),
// data[10],
// Double.parseDouble(data[11]),
// Integer.parseInt(data[24]));
// }
// }
| import util.IRequest;
import weather.data.dto.LocationDto;
import weather.data.dto.WeatherInfoDto;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.net.URL;
import java.time.LocalDate;
import java.util.function.Predicate;
import java.util.stream.Stream; | try (BufferedReader reader = new BufferedReader(new InputStreamReader(keyStream))) {
WEATHER_TOKEN = reader.readLine();
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private final IRequest req;
public WeatherWebApi(IRequest req) {
this.req = req;
}
/**
* E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****
*/
public Stream<LocationDto> search(String query) {
String path = WEATHER_HOST + WEATHER_SEARCH + WEATHER_SEARCH_ARGS;
String url = String.format(path, query, WEATHER_TOKEN);
return req.getContent(url)
.filter((String s) -> !s.startsWith("#"))
.map(LocationDto::valueOf);
}
/**
* E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****
*/ | // Path: aula33-weather-async/src/main/java/util/IRequest.java
// public interface IRequest extends AutoCloseable{
// CompletableFuture<Stream<String>> getContent(String path);
//
// @Override
// public default void close() {
// }
// }
//
// Path: aula33-weather-async/src/main/java/weather/data/dto/LocationDto.java
// public class LocationDto {
// private final ContainerDto[] country;
// private final ContainerDto[] region;
// private final double latitude;
// private final double longitude;
//
// public LocationDto(ContainerDto[] country, ContainerDto[] region, double latitude, double longitude) {
// this.country = country;
// this.region = region;
// this.latitude = latitude;
// this.longitude = longitude;
// }
//
// public String getCountry() {
// return country[0].value;
// }
//
// public String getRegion() {
// return region[0].value;
// }
//
// public double getLatitude() {
// return latitude;
// }
//
// public double getLongitude() {
// return longitude;
// }
//
// public static LocationDto valueOf(String line) {
// String[] data = line.split("\t");
// return new LocationDto(
// ContainerDto.arrayOf(data[1]),
// ContainerDto.arrayOf(data[2]),
// Double.parseDouble(data[3]),
// Double.parseDouble(data[4]));
// }
//
// @Override
// public String toString() {
// return "LocationDto{" +
// "country='" + getCountry() + '\'' +
// ", region='" + getRegion() + '\'' +
// ", latitude=" + latitude +
// ", longitude=" + longitude +
// '}';
// }
//
// static class ContainerDto {
// final String value;
//
// public ContainerDto(String value) {
// this.value = value;
// }
//
// @Override
// public String toString() {
// return value;
// }
//
// public static ContainerDto[] arrayOf(String s) {
// ContainerDto dto = new ContainerDto(s);
// return new ContainerDto[]{dto};
// }
// }
// }
//
// Path: aula33-weather-async/src/main/java/weather/data/dto/WeatherInfoDto.java
// public class WeatherInfoDto {
// private final LocalDate date; // index 0
// private final int tempC; // index 2
// private final String description; // index 10
// private final double precipMM; // index 11
// private final int feelsLikeC; // index 24
//
// public WeatherInfoDto(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {
// this.date = date;
// this.tempC = tempC;
// this.description = description;
// this.precipMM = precipMM;
// this.feelsLikeC = feelsLikeC;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public int getTempC() {
// return tempC;
// }
//
// public String getDescription() {
// return description;
// }
//
// public double getPrecipMM() {
// return precipMM;
// }
//
// public int getFeelsLikeC() {
// return feelsLikeC;
// }
//
// @Override
// public String toString() {
// return "WeatherInfoDto{" +
// date +
// ", tempC=" + tempC +
// ", '" + description + '\'' +
// ", precipMM=" + precipMM +
// ", feelsLikeC=" + feelsLikeC +
// '}';
// }
//
// /**
// * Hourly information follows below the day according to the format of
// * /past weather resource of the World Weather Online API
// */
// public static WeatherInfoDto valueOf(String line) {
// String[] data = line.split(",");
// return new WeatherInfoDto(
// LocalDate.parse(data[0]),
// Integer.parseInt(data[2]),
// data[10],
// Double.parseDouble(data[11]),
// Integer.parseInt(data[24]));
// }
// }
// Path: aula31-weather-groupingBy/src/main/java/weather/data/WeatherWebApi.java
import util.IRequest;
import weather.data.dto.LocationDto;
import weather.data.dto.WeatherInfoDto;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.net.URL;
import java.time.LocalDate;
import java.util.function.Predicate;
import java.util.stream.Stream;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(keyStream))) {
WEATHER_TOKEN = reader.readLine();
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private final IRequest req;
public WeatherWebApi(IRequest req) {
this.req = req;
}
/**
* E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****
*/
public Stream<LocationDto> search(String query) {
String path = WEATHER_HOST + WEATHER_SEARCH + WEATHER_SEARCH_ARGS;
String url = String.format(path, query, WEATHER_TOKEN);
return req.getContent(url)
.filter((String s) -> !s.startsWith("#"))
.map(LocationDto::valueOf);
}
/**
* E.g. http://api.worldweatheronline.com/free/v2/search.ashx?query=oporto&format=tab&key=*****
*/ | public Stream<WeatherInfoDto> pastWeather( |
isel-leic-mpd/mpd-2017-i41d | aula33-weather-async/src/main/java/util/WeatherPredicate.java | // Path: aula33-weather-async/src/main/java/weather/data/dto/WeatherInfoDto.java
// public class WeatherInfoDto {
// private final LocalDate date; // index 0
// private final int tempC; // index 2
// private final String description; // index 10
// private final double precipMM; // index 11
// private final int feelsLikeC; // index 24
//
// public WeatherInfoDto(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {
// this.date = date;
// this.tempC = tempC;
// this.description = description;
// this.precipMM = precipMM;
// this.feelsLikeC = feelsLikeC;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public int getTempC() {
// return tempC;
// }
//
// public String getDescription() {
// return description;
// }
//
// public double getPrecipMM() {
// return precipMM;
// }
//
// public int getFeelsLikeC() {
// return feelsLikeC;
// }
//
// @Override
// public String toString() {
// return "WeatherInfoDto{" +
// date +
// ", tempC=" + tempC +
// ", '" + description + '\'' +
// ", precipMM=" + precipMM +
// ", feelsLikeC=" + feelsLikeC +
// '}';
// }
//
// /**
// * Hourly information follows below the day according to the format of
// * /past weather resource of the World Weather Online API
// */
// public static WeatherInfoDto valueOf(String line) {
// String[] data = line.split(",");
// return new WeatherInfoDto(
// LocalDate.parse(data[0]),
// Integer.parseInt(data[2]),
// data[10],
// Double.parseDouble(data[11]),
// Integer.parseInt(data[24]));
// }
// }
| import weather.data.dto.WeatherInfoDto; | /*
* Copyright (c) 2017, Miguel Gamboa
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package util;
/**
* @author Miguel Gamboa
* created on 14-03-2017
*/
/**
* This is a functional interface because it has one and only one method.
* Thus we can assign a lambda expression to every place of WeatherPredicate
* type.
*/
@FunctionalInterface
public interface WeatherPredicate {
| // Path: aula33-weather-async/src/main/java/weather/data/dto/WeatherInfoDto.java
// public class WeatherInfoDto {
// private final LocalDate date; // index 0
// private final int tempC; // index 2
// private final String description; // index 10
// private final double precipMM; // index 11
// private final int feelsLikeC; // index 24
//
// public WeatherInfoDto(LocalDate date, int tempC, String description, double precipMM, int feelsLikeC) {
// this.date = date;
// this.tempC = tempC;
// this.description = description;
// this.precipMM = precipMM;
// this.feelsLikeC = feelsLikeC;
// }
//
// public LocalDate getDate() {
// return date;
// }
//
// public int getTempC() {
// return tempC;
// }
//
// public String getDescription() {
// return description;
// }
//
// public double getPrecipMM() {
// return precipMM;
// }
//
// public int getFeelsLikeC() {
// return feelsLikeC;
// }
//
// @Override
// public String toString() {
// return "WeatherInfoDto{" +
// date +
// ", tempC=" + tempC +
// ", '" + description + '\'' +
// ", precipMM=" + precipMM +
// ", feelsLikeC=" + feelsLikeC +
// '}';
// }
//
// /**
// * Hourly information follows below the day according to the format of
// * /past weather resource of the World Weather Online API
// */
// public static WeatherInfoDto valueOf(String line) {
// String[] data = line.split(",");
// return new WeatherInfoDto(
// LocalDate.parse(data[0]),
// Integer.parseInt(data[2]),
// data[10],
// Double.parseDouble(data[11]),
// Integer.parseInt(data[24]));
// }
// }
// Path: aula33-weather-async/src/main/java/util/WeatherPredicate.java
import weather.data.dto.WeatherInfoDto;
/*
* Copyright (c) 2017, Miguel Gamboa
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package util;
/**
* @author Miguel Gamboa
* created on 14-03-2017
*/
/**
* This is a functional interface because it has one and only one method.
* Thus we can assign a lambda expression to every place of WeatherPredicate
* type.
*/
@FunctionalInterface
public interface WeatherPredicate {
| boolean test(WeatherInfoDto item); |
google-cloudsearch/sharepoint-connector | src/main/java/com/google/enterprise/cloudsearch/sharepoint/ActiveDirectoryClient.java | // Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/ActiveDirectoryPrincipal.java
// static enum PrincipalFormat {
// NONE,
// DNS,
// NETBIOS,
// ;
//
// String format(String plainName, String domain) {
// checkArgument(
// !Strings.isNullOrEmpty(domain) || this == PrincipalFormat.NONE,
// "Domain can not be empty if PrincipalFormat is not NONE");
// switch (this) {
// case NONE:
// return plainName;
// case DNS:
// return plainName + "@" + domain;
// case NETBIOS:
// return domain + "\\" + plainName;
// default:
// throw new AssertionError("Unsupported PrincipalFormat " + this);
// }
// }
// }
| import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.enterprise.cloudsearch.sdk.config.Configuration;
import com.google.enterprise.cloudsearch.sharepoint.ActiveDirectoryPrincipal.PrincipalFormat;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.CommunicationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext; | @Override
public Optional<String> getUserAccountBySid(String sid) throws IOException {
try {
Optional<SearchResult> results = getSidLookupResult(sid);
if (!results.isPresent()) {
return Optional.empty();
}
SearchResult sr = results.get();
Attributes attrbs = sr.getAttributes();
// use sAMAccountName when available
String sAMAccountName = (String) getAttribute(attrbs, ATTR_SAMACCOUNTNAME);
if (!Strings.isNullOrEmpty(sAMAccountName)) {
return Optional.of(sAMAccountName);
}
log.log(Level.FINER, "sAMAccountName is null for SID {0}. This might"
+ " be domain object.", sid);
String name = (String) getAttribute(attrbs, ATTR_NAME);
if (Strings.isNullOrEmpty(name)) {
log.log(Level.WARNING, "name is null for SID {0}. Returing empty.", sid);
return Optional.empty();
}
return Optional.of(name);
} catch (NamingException ne) {
throw new IOException(ne);
}
}
@Override
public Optional<String> getEmailByPrincipal(ActiveDirectoryPrincipal principal)
throws IOException { | // Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/ActiveDirectoryPrincipal.java
// static enum PrincipalFormat {
// NONE,
// DNS,
// NETBIOS,
// ;
//
// String format(String plainName, String domain) {
// checkArgument(
// !Strings.isNullOrEmpty(domain) || this == PrincipalFormat.NONE,
// "Domain can not be empty if PrincipalFormat is not NONE");
// switch (this) {
// case NONE:
// return plainName;
// case DNS:
// return plainName + "@" + domain;
// case NETBIOS:
// return domain + "\\" + plainName;
// default:
// throw new AssertionError("Unsupported PrincipalFormat " + this);
// }
// }
// }
// Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/ActiveDirectoryClient.java
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.enterprise.cloudsearch.sdk.config.Configuration;
import com.google.enterprise.cloudsearch.sharepoint.ActiveDirectoryPrincipal.PrincipalFormat;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.CommunicationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
@Override
public Optional<String> getUserAccountBySid(String sid) throws IOException {
try {
Optional<SearchResult> results = getSidLookupResult(sid);
if (!results.isPresent()) {
return Optional.empty();
}
SearchResult sr = results.get();
Attributes attrbs = sr.getAttributes();
// use sAMAccountName when available
String sAMAccountName = (String) getAttribute(attrbs, ATTR_SAMACCOUNTNAME);
if (!Strings.isNullOrEmpty(sAMAccountName)) {
return Optional.of(sAMAccountName);
}
log.log(Level.FINER, "sAMAccountName is null for SID {0}. This might"
+ " be domain object.", sid);
String name = (String) getAttribute(attrbs, ATTR_NAME);
if (Strings.isNullOrEmpty(name)) {
log.log(Level.WARNING, "name is null for SID {0}. Returing empty.", sid);
return Optional.empty();
}
return Optional.of(name);
} catch (NamingException ne) {
throw new IOException(ne);
}
}
@Override
public Optional<String> getEmailByPrincipal(ActiveDirectoryPrincipal principal)
throws IOException { | if (principal.getFormat() == PrincipalFormat.NETBIOS) { |
google-cloudsearch/sharepoint-connector | src/main/java/com/google/enterprise/cloudsearch/sharepoint/SiteConnector.java | // Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/ActiveDirectoryPrincipal.java
// static enum PrincipalFormat {
// NONE,
// DNS,
// NETBIOS,
// ;
//
// String format(String plainName, String domain) {
// checkArgument(
// !Strings.isNullOrEmpty(domain) || this == PrincipalFormat.NONE,
// "Domain can not be empty if PrincipalFormat is not NONE");
// switch (this) {
// case NONE:
// return plainName;
// case DNS:
// return plainName + "@" + domain;
// case NETBIOS:
// return domain + "\\" + plainName;
// default:
// throw new AssertionError("Unsupported PrincipalFormat " + this);
// }
// }
// }
//
// Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/SharePointConfiguration.java
// enum SharePointDeploymentType {
// ONLINE,
// ON_PREMISES;
// }
| import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.api.services.cloudidentity.v1.model.EntityKey;
import com.google.api.services.cloudidentity.v1.model.Membership;
import com.google.api.services.cloudidentity.v1.model.MembershipRole;
import com.google.api.services.cloudsearch.v1.model.Principal;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.enterprise.cloudsearch.sdk.identity.IdentityGroup;
import com.google.enterprise.cloudsearch.sdk.identity.IdentitySourceConfiguration;
import com.google.enterprise.cloudsearch.sdk.identity.RepositoryContext;
import com.google.enterprise.cloudsearch.sdk.indexing.Acl;
import com.google.enterprise.cloudsearch.sharepoint.ActiveDirectoryPrincipal.PrincipalFormat;
import com.google.enterprise.cloudsearch.sharepoint.SharePointConfiguration.SharePointDeploymentType;
import com.microsoft.schemas.sharepoint.soap.GroupMembership;
import com.microsoft.schemas.sharepoint.soap.Permission;
import com.microsoft.schemas.sharepoint.soap.PolicyUser;
import com.microsoft.schemas.sharepoint.soap.Scopes.Scope;
import com.microsoft.schemas.sharepoint.soap.Site;
import com.microsoft.schemas.sharepoint.soap.TrueFalseType;
import com.microsoft.schemas.sharepoint.soap.UserDescription;
import com.microsoft.schemas.sharepoint.soap.Users;
import com.microsoft.schemas.sharepoint.soap.VirtualServer;
import com.microsoft.schemas.sharepoint.soap.Web;
import com.microsoft.schemas.sharepoint.soap.directory.GetUserCollectionFromSiteResponse;
import com.microsoft.schemas.sharepoint.soap.directory.GetUserCollectionFromSiteResponse.GetUserCollectionFromSiteResult;
import com.microsoft.schemas.sharepoint.soap.directory.User;
import com.microsoft.schemas.sharepoint.soap.directory.UserGroupSoap;
import com.microsoft.schemas.sharepoint.soap.people.ArrayOfPrincipalInfo;
import com.microsoft.schemas.sharepoint.soap.people.ArrayOfString;
import com.microsoft.schemas.sharepoint.soap.people.PeopleSoap;
import com.microsoft.schemas.sharepoint.soap.people.PrincipalInfo;
import com.microsoft.schemas.sharepoint.soap.people.SPPrincipalType;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern; | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.google.enterprise.cloudsearch.sharepoint;
class SiteConnector {
private static final Logger log = Logger.getLogger(SiteConnector.class.getName());
private static final String IDENTITY_CLAIMS_PREFIX = "i:0";
private static final String OTHER_CLAIMS_PREFIX = "c:0";
private static final String SHAREPOINT_LOCAL_GROUP_FORMAT = "[%s]%s";
private static final Supplier<Set<Membership>> EMPTY_MEMBERSHIP = () -> ImmutableSet.of();
private static final ImmutableList<MembershipRole> MEMBER_ROLES =
ImmutableList.of(new MembershipRole().setName("MEMBER"));
static final long LIST_ITEM_MASK =
SPBasePermissions.OPEN | SPBasePermissions.VIEWPAGES | SPBasePermissions.VIEWLISTITEMS;
/** Default identity source for external principals when no domain information is available */
static final String DEFAULT_REFERENCE_IDENTITY_SOURCE_NAME = "defaultIdentitySource";
private final SiteDataClient siteDataClient;
private final UserGroupSoap userGroup;
private final PeopleSoap people;
private final String siteUrl;
private final String webUrl;
private final Optional<ActiveDirectoryClient> activeDirectoryClient; | // Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/ActiveDirectoryPrincipal.java
// static enum PrincipalFormat {
// NONE,
// DNS,
// NETBIOS,
// ;
//
// String format(String plainName, String domain) {
// checkArgument(
// !Strings.isNullOrEmpty(domain) || this == PrincipalFormat.NONE,
// "Domain can not be empty if PrincipalFormat is not NONE");
// switch (this) {
// case NONE:
// return plainName;
// case DNS:
// return plainName + "@" + domain;
// case NETBIOS:
// return domain + "\\" + plainName;
// default:
// throw new AssertionError("Unsupported PrincipalFormat " + this);
// }
// }
// }
//
// Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/SharePointConfiguration.java
// enum SharePointDeploymentType {
// ONLINE,
// ON_PREMISES;
// }
// Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/SiteConnector.java
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.api.services.cloudidentity.v1.model.EntityKey;
import com.google.api.services.cloudidentity.v1.model.Membership;
import com.google.api.services.cloudidentity.v1.model.MembershipRole;
import com.google.api.services.cloudsearch.v1.model.Principal;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.enterprise.cloudsearch.sdk.identity.IdentityGroup;
import com.google.enterprise.cloudsearch.sdk.identity.IdentitySourceConfiguration;
import com.google.enterprise.cloudsearch.sdk.identity.RepositoryContext;
import com.google.enterprise.cloudsearch.sdk.indexing.Acl;
import com.google.enterprise.cloudsearch.sharepoint.ActiveDirectoryPrincipal.PrincipalFormat;
import com.google.enterprise.cloudsearch.sharepoint.SharePointConfiguration.SharePointDeploymentType;
import com.microsoft.schemas.sharepoint.soap.GroupMembership;
import com.microsoft.schemas.sharepoint.soap.Permission;
import com.microsoft.schemas.sharepoint.soap.PolicyUser;
import com.microsoft.schemas.sharepoint.soap.Scopes.Scope;
import com.microsoft.schemas.sharepoint.soap.Site;
import com.microsoft.schemas.sharepoint.soap.TrueFalseType;
import com.microsoft.schemas.sharepoint.soap.UserDescription;
import com.microsoft.schemas.sharepoint.soap.Users;
import com.microsoft.schemas.sharepoint.soap.VirtualServer;
import com.microsoft.schemas.sharepoint.soap.Web;
import com.microsoft.schemas.sharepoint.soap.directory.GetUserCollectionFromSiteResponse;
import com.microsoft.schemas.sharepoint.soap.directory.GetUserCollectionFromSiteResponse.GetUserCollectionFromSiteResult;
import com.microsoft.schemas.sharepoint.soap.directory.User;
import com.microsoft.schemas.sharepoint.soap.directory.UserGroupSoap;
import com.microsoft.schemas.sharepoint.soap.people.ArrayOfPrincipalInfo;
import com.microsoft.schemas.sharepoint.soap.people.ArrayOfString;
import com.microsoft.schemas.sharepoint.soap.people.PeopleSoap;
import com.microsoft.schemas.sharepoint.soap.people.PrincipalInfo;
import com.microsoft.schemas.sharepoint.soap.people.SPPrincipalType;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.google.enterprise.cloudsearch.sharepoint;
class SiteConnector {
private static final Logger log = Logger.getLogger(SiteConnector.class.getName());
private static final String IDENTITY_CLAIMS_PREFIX = "i:0";
private static final String OTHER_CLAIMS_PREFIX = "c:0";
private static final String SHAREPOINT_LOCAL_GROUP_FORMAT = "[%s]%s";
private static final Supplier<Set<Membership>> EMPTY_MEMBERSHIP = () -> ImmutableSet.of();
private static final ImmutableList<MembershipRole> MEMBER_ROLES =
ImmutableList.of(new MembershipRole().setName("MEMBER"));
static final long LIST_ITEM_MASK =
SPBasePermissions.OPEN | SPBasePermissions.VIEWPAGES | SPBasePermissions.VIEWLISTITEMS;
/** Default identity source for external principals when no domain information is available */
static final String DEFAULT_REFERENCE_IDENTITY_SOURCE_NAME = "defaultIdentitySource";
private final SiteDataClient siteDataClient;
private final UserGroupSoap userGroup;
private final PeopleSoap people;
private final String siteUrl;
private final String webUrl;
private final Optional<ActiveDirectoryClient> activeDirectoryClient; | private final SharePointDeploymentType sharePointDeploymentType; |
google-cloudsearch/sharepoint-connector | src/main/java/com/google/enterprise/cloudsearch/sharepoint/SiteConnector.java | // Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/ActiveDirectoryPrincipal.java
// static enum PrincipalFormat {
// NONE,
// DNS,
// NETBIOS,
// ;
//
// String format(String plainName, String domain) {
// checkArgument(
// !Strings.isNullOrEmpty(domain) || this == PrincipalFormat.NONE,
// "Domain can not be empty if PrincipalFormat is not NONE");
// switch (this) {
// case NONE:
// return plainName;
// case DNS:
// return plainName + "@" + domain;
// case NETBIOS:
// return domain + "\\" + plainName;
// default:
// throw new AssertionError("Unsupported PrincipalFormat " + this);
// }
// }
// }
//
// Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/SharePointConfiguration.java
// enum SharePointDeploymentType {
// ONLINE,
// ON_PREMISES;
// }
| import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.api.services.cloudidentity.v1.model.EntityKey;
import com.google.api.services.cloudidentity.v1.model.Membership;
import com.google.api.services.cloudidentity.v1.model.MembershipRole;
import com.google.api.services.cloudsearch.v1.model.Principal;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.enterprise.cloudsearch.sdk.identity.IdentityGroup;
import com.google.enterprise.cloudsearch.sdk.identity.IdentitySourceConfiguration;
import com.google.enterprise.cloudsearch.sdk.identity.RepositoryContext;
import com.google.enterprise.cloudsearch.sdk.indexing.Acl;
import com.google.enterprise.cloudsearch.sharepoint.ActiveDirectoryPrincipal.PrincipalFormat;
import com.google.enterprise.cloudsearch.sharepoint.SharePointConfiguration.SharePointDeploymentType;
import com.microsoft.schemas.sharepoint.soap.GroupMembership;
import com.microsoft.schemas.sharepoint.soap.Permission;
import com.microsoft.schemas.sharepoint.soap.PolicyUser;
import com.microsoft.schemas.sharepoint.soap.Scopes.Scope;
import com.microsoft.schemas.sharepoint.soap.Site;
import com.microsoft.schemas.sharepoint.soap.TrueFalseType;
import com.microsoft.schemas.sharepoint.soap.UserDescription;
import com.microsoft.schemas.sharepoint.soap.Users;
import com.microsoft.schemas.sharepoint.soap.VirtualServer;
import com.microsoft.schemas.sharepoint.soap.Web;
import com.microsoft.schemas.sharepoint.soap.directory.GetUserCollectionFromSiteResponse;
import com.microsoft.schemas.sharepoint.soap.directory.GetUserCollectionFromSiteResponse.GetUserCollectionFromSiteResult;
import com.microsoft.schemas.sharepoint.soap.directory.User;
import com.microsoft.schemas.sharepoint.soap.directory.UserGroupSoap;
import com.microsoft.schemas.sharepoint.soap.people.ArrayOfPrincipalInfo;
import com.microsoft.schemas.sharepoint.soap.people.ArrayOfString;
import com.microsoft.schemas.sharepoint.soap.people.PeopleSoap;
import com.microsoft.schemas.sharepoint.soap.people.PrincipalInfo;
import com.microsoft.schemas.sharepoint.soap.people.SPPrincipalType;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern; | if (isDomainGroup
&& activeDirectoryClient.isPresent()
&& loginName.startsWith("c:0+.w|")
&& !Strings.isNullOrEmpty(sid)) {
try {
return activeDirectoryClient.get().getUserAccountBySid(sid);
} catch (IOException ex) {
log.log(
Level.WARNING,
String.format(
"Error performing SID lookup for "
+ "User %s. Returing display name %s as fallback.",
loginName, displayName),
ex);
return displayName;
}
}
return isSharePointOnlineDeployment()
? decodeSharePointOnlineClaim(loginName)
: decodeClaim(loginName, displayName);
}
private Optional<Principal> getPrincipal(String id, boolean isGroup) {
return isSharePointOnlineDeployment()
? getSharePointOnlinePrincipal(id, isGroup)
: getActiveDirectoryPrincipal(id, isGroup);
}
private Optional<Principal> getActiveDirectoryPrincipal(String id, boolean isGroup) {
ActiveDirectoryPrincipal adPrincipal = ActiveDirectoryPrincipal.parse(id); | // Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/ActiveDirectoryPrincipal.java
// static enum PrincipalFormat {
// NONE,
// DNS,
// NETBIOS,
// ;
//
// String format(String plainName, String domain) {
// checkArgument(
// !Strings.isNullOrEmpty(domain) || this == PrincipalFormat.NONE,
// "Domain can not be empty if PrincipalFormat is not NONE");
// switch (this) {
// case NONE:
// return plainName;
// case DNS:
// return plainName + "@" + domain;
// case NETBIOS:
// return domain + "\\" + plainName;
// default:
// throw new AssertionError("Unsupported PrincipalFormat " + this);
// }
// }
// }
//
// Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/SharePointConfiguration.java
// enum SharePointDeploymentType {
// ONLINE,
// ON_PREMISES;
// }
// Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/SiteConnector.java
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.api.services.cloudidentity.v1.model.EntityKey;
import com.google.api.services.cloudidentity.v1.model.Membership;
import com.google.api.services.cloudidentity.v1.model.MembershipRole;
import com.google.api.services.cloudsearch.v1.model.Principal;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.enterprise.cloudsearch.sdk.identity.IdentityGroup;
import com.google.enterprise.cloudsearch.sdk.identity.IdentitySourceConfiguration;
import com.google.enterprise.cloudsearch.sdk.identity.RepositoryContext;
import com.google.enterprise.cloudsearch.sdk.indexing.Acl;
import com.google.enterprise.cloudsearch.sharepoint.ActiveDirectoryPrincipal.PrincipalFormat;
import com.google.enterprise.cloudsearch.sharepoint.SharePointConfiguration.SharePointDeploymentType;
import com.microsoft.schemas.sharepoint.soap.GroupMembership;
import com.microsoft.schemas.sharepoint.soap.Permission;
import com.microsoft.schemas.sharepoint.soap.PolicyUser;
import com.microsoft.schemas.sharepoint.soap.Scopes.Scope;
import com.microsoft.schemas.sharepoint.soap.Site;
import com.microsoft.schemas.sharepoint.soap.TrueFalseType;
import com.microsoft.schemas.sharepoint.soap.UserDescription;
import com.microsoft.schemas.sharepoint.soap.Users;
import com.microsoft.schemas.sharepoint.soap.VirtualServer;
import com.microsoft.schemas.sharepoint.soap.Web;
import com.microsoft.schemas.sharepoint.soap.directory.GetUserCollectionFromSiteResponse;
import com.microsoft.schemas.sharepoint.soap.directory.GetUserCollectionFromSiteResponse.GetUserCollectionFromSiteResult;
import com.microsoft.schemas.sharepoint.soap.directory.User;
import com.microsoft.schemas.sharepoint.soap.directory.UserGroupSoap;
import com.microsoft.schemas.sharepoint.soap.people.ArrayOfPrincipalInfo;
import com.microsoft.schemas.sharepoint.soap.people.ArrayOfString;
import com.microsoft.schemas.sharepoint.soap.people.PeopleSoap;
import com.microsoft.schemas.sharepoint.soap.people.PrincipalInfo;
import com.microsoft.schemas.sharepoint.soap.people.SPPrincipalType;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
if (isDomainGroup
&& activeDirectoryClient.isPresent()
&& loginName.startsWith("c:0+.w|")
&& !Strings.isNullOrEmpty(sid)) {
try {
return activeDirectoryClient.get().getUserAccountBySid(sid);
} catch (IOException ex) {
log.log(
Level.WARNING,
String.format(
"Error performing SID lookup for "
+ "User %s. Returing display name %s as fallback.",
loginName, displayName),
ex);
return displayName;
}
}
return isSharePointOnlineDeployment()
? decodeSharePointOnlineClaim(loginName)
: decodeClaim(loginName, displayName);
}
private Optional<Principal> getPrincipal(String id, boolean isGroup) {
return isSharePointOnlineDeployment()
? getSharePointOnlinePrincipal(id, isGroup)
: getActiveDirectoryPrincipal(id, isGroup);
}
private Optional<Principal> getActiveDirectoryPrincipal(String id, boolean isGroup) {
ActiveDirectoryPrincipal adPrincipal = ActiveDirectoryPrincipal.parse(id); | if (adPrincipal.getFormat() == PrincipalFormat.NONE) { |
google-cloudsearch/sharepoint-connector | src/main/java/com/google/enterprise/cloudsearch/sharepoint/LiveAuthenticationHandshakeManager.java | // Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class HttpPostClientImpl implements HttpPostClient{
// @Override
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException {
//
// // Handle Unicode. Java does not properly encode the GET.
// try {
// url = new URL(url.toURI().toASCIIString());
// } catch (URISyntaxException ex) {
// throw new IOException(ex);
// }
//
// HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// try {
// connection.setDoOutput(true);
// connection.setDoInput(true);
// connection.setRequestMethod("POST");
// connection.setInstanceFollowRedirects(false);
//
// for (String key : connectionProperties.keySet()) {
// connection.addRequestProperty(key, connectionProperties.get(key));
// }
//
// if (!connectionProperties.containsKey("Content-Length")) {
// connection.addRequestProperty("Content-Length",
// Integer.toString(requestBody.length()));
// }
//
// OutputStream out = connection.getOutputStream();
// Writer wout = new OutputStreamWriter(out);
// wout.write(requestBody);
// wout.flush();
// wout.close();
// InputStream in = connection.getInputStream();
// String result = readInputStreamToString(in, CHARSET);
// return new PostResponseInfo(result, connection.getHeaderFields());
// } finally {
// InputStream inputStream = connection.getResponseCode() >= 400
// ? connection.getErrorStream() : connection.getInputStream();
// if (inputStream != null) {
// inputStream.close();
// }
// }
// }
//
// private String readInputStreamToString(InputStream in, Charset charset) throws IOException {
// return new String(ByteStreams.toByteArray(in), charset);
// }
// }
| import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.google.common.annotations.VisibleForTesting;
import com.google.enterprise.cloudsearch.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.cloudsearch.sharepoint.SamlAuthenticationHandler.HttpPostClientImpl;
import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.DOMException; | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.google.enterprise.cloudsearch.sharepoint;
/**
* SamlHandshakeManager implementation for Live Authentication to request Live authentication token
* and extract authentication cookie.
*/
class LiveAuthenticationHandshakeManager extends AdfsHandshakeManager {
private static final Logger log
= Logger.getLogger(LiveAuthenticationHandshakeManager.class.getName());
private static final String LIVE_STS
= "https://login.microsoftonline.com/extSTS.srf";
private static final String LIVE_LOGIN_URL
= "/_forms/default.aspx?wa=wsignin1.0";
public static class Builder {
private final String username;
private final String password;
private final String sharePointUrl;
private String stsendpoint; | // Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class HttpPostClientImpl implements HttpPostClient{
// @Override
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException {
//
// // Handle Unicode. Java does not properly encode the GET.
// try {
// url = new URL(url.toURI().toASCIIString());
// } catch (URISyntaxException ex) {
// throw new IOException(ex);
// }
//
// HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// try {
// connection.setDoOutput(true);
// connection.setDoInput(true);
// connection.setRequestMethod("POST");
// connection.setInstanceFollowRedirects(false);
//
// for (String key : connectionProperties.keySet()) {
// connection.addRequestProperty(key, connectionProperties.get(key));
// }
//
// if (!connectionProperties.containsKey("Content-Length")) {
// connection.addRequestProperty("Content-Length",
// Integer.toString(requestBody.length()));
// }
//
// OutputStream out = connection.getOutputStream();
// Writer wout = new OutputStreamWriter(out);
// wout.write(requestBody);
// wout.flush();
// wout.close();
// InputStream in = connection.getInputStream();
// String result = readInputStreamToString(in, CHARSET);
// return new PostResponseInfo(result, connection.getHeaderFields());
// } finally {
// InputStream inputStream = connection.getResponseCode() >= 400
// ? connection.getErrorStream() : connection.getInputStream();
// if (inputStream != null) {
// inputStream.close();
// }
// }
// }
//
// private String readInputStreamToString(InputStream in, Charset charset) throws IOException {
// return new String(ByteStreams.toByteArray(in), charset);
// }
// }
// Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/LiveAuthenticationHandshakeManager.java
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.google.common.annotations.VisibleForTesting;
import com.google.enterprise.cloudsearch.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.cloudsearch.sharepoint.SamlAuthenticationHandler.HttpPostClientImpl;
import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.DOMException;
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.google.enterprise.cloudsearch.sharepoint;
/**
* SamlHandshakeManager implementation for Live Authentication to request Live authentication token
* and extract authentication cookie.
*/
class LiveAuthenticationHandshakeManager extends AdfsHandshakeManager {
private static final Logger log
= Logger.getLogger(LiveAuthenticationHandshakeManager.class.getName());
private static final String LIVE_STS
= "https://login.microsoftonline.com/extSTS.srf";
private static final String LIVE_LOGIN_URL
= "/_forms/default.aspx?wa=wsignin1.0";
public static class Builder {
private final String username;
private final String password;
private final String sharePointUrl;
private String stsendpoint; | private HttpPostClient httpClient; |
google-cloudsearch/sharepoint-connector | src/main/java/com/google/enterprise/cloudsearch/sharepoint/LiveAuthenticationHandshakeManager.java | // Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class HttpPostClientImpl implements HttpPostClient{
// @Override
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException {
//
// // Handle Unicode. Java does not properly encode the GET.
// try {
// url = new URL(url.toURI().toASCIIString());
// } catch (URISyntaxException ex) {
// throw new IOException(ex);
// }
//
// HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// try {
// connection.setDoOutput(true);
// connection.setDoInput(true);
// connection.setRequestMethod("POST");
// connection.setInstanceFollowRedirects(false);
//
// for (String key : connectionProperties.keySet()) {
// connection.addRequestProperty(key, connectionProperties.get(key));
// }
//
// if (!connectionProperties.containsKey("Content-Length")) {
// connection.addRequestProperty("Content-Length",
// Integer.toString(requestBody.length()));
// }
//
// OutputStream out = connection.getOutputStream();
// Writer wout = new OutputStreamWriter(out);
// wout.write(requestBody);
// wout.flush();
// wout.close();
// InputStream in = connection.getInputStream();
// String result = readInputStreamToString(in, CHARSET);
// return new PostResponseInfo(result, connection.getHeaderFields());
// } finally {
// InputStream inputStream = connection.getResponseCode() >= 400
// ? connection.getErrorStream() : connection.getInputStream();
// if (inputStream != null) {
// inputStream.close();
// }
// }
// }
//
// private String readInputStreamToString(InputStream in, Charset charset) throws IOException {
// return new String(ByteStreams.toByteArray(in), charset);
// }
// }
| import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.google.common.annotations.VisibleForTesting;
import com.google.enterprise.cloudsearch.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.cloudsearch.sharepoint.SamlAuthenticationHandler.HttpPostClientImpl;
import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.DOMException; | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.google.enterprise.cloudsearch.sharepoint;
/**
* SamlHandshakeManager implementation for Live Authentication to request Live authentication token
* and extract authentication cookie.
*/
class LiveAuthenticationHandshakeManager extends AdfsHandshakeManager {
private static final Logger log
= Logger.getLogger(LiveAuthenticationHandshakeManager.class.getName());
private static final String LIVE_STS
= "https://login.microsoftonline.com/extSTS.srf";
private static final String LIVE_LOGIN_URL
= "/_forms/default.aspx?wa=wsignin1.0";
public static class Builder {
private final String username;
private final String password;
private final String sharePointUrl;
private String stsendpoint;
private HttpPostClient httpClient;
private String login;
private String trustLocation;
public Builder(String sharePointUrl, String username, String password) {
this.sharePointUrl = sharePointUrl;
this.username = username;
this.password = password; | // Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class HttpPostClientImpl implements HttpPostClient{
// @Override
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException {
//
// // Handle Unicode. Java does not properly encode the GET.
// try {
// url = new URL(url.toURI().toASCIIString());
// } catch (URISyntaxException ex) {
// throw new IOException(ex);
// }
//
// HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// try {
// connection.setDoOutput(true);
// connection.setDoInput(true);
// connection.setRequestMethod("POST");
// connection.setInstanceFollowRedirects(false);
//
// for (String key : connectionProperties.keySet()) {
// connection.addRequestProperty(key, connectionProperties.get(key));
// }
//
// if (!connectionProperties.containsKey("Content-Length")) {
// connection.addRequestProperty("Content-Length",
// Integer.toString(requestBody.length()));
// }
//
// OutputStream out = connection.getOutputStream();
// Writer wout = new OutputStreamWriter(out);
// wout.write(requestBody);
// wout.flush();
// wout.close();
// InputStream in = connection.getInputStream();
// String result = readInputStreamToString(in, CHARSET);
// return new PostResponseInfo(result, connection.getHeaderFields());
// } finally {
// InputStream inputStream = connection.getResponseCode() >= 400
// ? connection.getErrorStream() : connection.getInputStream();
// if (inputStream != null) {
// inputStream.close();
// }
// }
// }
//
// private String readInputStreamToString(InputStream in, Charset charset) throws IOException {
// return new String(ByteStreams.toByteArray(in), charset);
// }
// }
// Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/LiveAuthenticationHandshakeManager.java
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.google.common.annotations.VisibleForTesting;
import com.google.enterprise.cloudsearch.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.cloudsearch.sharepoint.SamlAuthenticationHandler.HttpPostClientImpl;
import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.DOMException;
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.google.enterprise.cloudsearch.sharepoint;
/**
* SamlHandshakeManager implementation for Live Authentication to request Live authentication token
* and extract authentication cookie.
*/
class LiveAuthenticationHandshakeManager extends AdfsHandshakeManager {
private static final Logger log
= Logger.getLogger(LiveAuthenticationHandshakeManager.class.getName());
private static final String LIVE_STS
= "https://login.microsoftonline.com/extSTS.srf";
private static final String LIVE_LOGIN_URL
= "/_forms/default.aspx?wa=wsignin1.0";
public static class Builder {
private final String username;
private final String password;
private final String sharePointUrl;
private String stsendpoint;
private HttpPostClient httpClient;
private String login;
private String trustLocation;
public Builder(String sharePointUrl, String username, String password) {
this.sharePointUrl = sharePointUrl;
this.username = username;
this.password = password; | this.httpClient = new HttpPostClientImpl(); |
google-cloudsearch/sharepoint-connector | src/main/java/com/google/enterprise/cloudsearch/sharepoint/AdfsHandshakeManager.java | // Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class HttpPostClientImpl implements HttpPostClient{
// @Override
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException {
//
// // Handle Unicode. Java does not properly encode the GET.
// try {
// url = new URL(url.toURI().toASCIIString());
// } catch (URISyntaxException ex) {
// throw new IOException(ex);
// }
//
// HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// try {
// connection.setDoOutput(true);
// connection.setDoInput(true);
// connection.setRequestMethod("POST");
// connection.setInstanceFollowRedirects(false);
//
// for (String key : connectionProperties.keySet()) {
// connection.addRequestProperty(key, connectionProperties.get(key));
// }
//
// if (!connectionProperties.containsKey("Content-Length")) {
// connection.addRequestProperty("Content-Length",
// Integer.toString(requestBody.length()));
// }
//
// OutputStream out = connection.getOutputStream();
// Writer wout = new OutputStreamWriter(out);
// wout.write(requestBody);
// wout.flush();
// wout.close();
// InputStream in = connection.getInputStream();
// String result = readInputStreamToString(in, CHARSET);
// return new PostResponseInfo(result, connection.getHeaderFields());
// } finally {
// InputStream inputStream = connection.getResponseCode() >= 400
// ? connection.getErrorStream() : connection.getInputStream();
// if (inputStream != null) {
// inputStream.close();
// }
// }
// }
//
// private String readInputStreamToString(InputStream in, Charset charset) throws IOException {
// return new String(ByteStreams.toByteArray(in), charset);
// }
// }
//
// Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class PostResponseInfo {
// /** Non-null contents. */
// private final String contents;
// /** Non-null headers. */
// private final Map<String, List<String>> headers;
//
// PostResponseInfo(
// String contents, Map<String, List<String>> headers) {
// this.contents = contents;
// this.headers = (headers == null)
// ? new HashMap<String, List<String>>()
// : new HashMap<String, List<String>>(headers);
// }
//
// public String getPostContents() {
// return contents;
// }
//
// public Map<String, List<String>> getPostResponseHeaders() {
// return Collections.unmodifiableMap(headers);
// }
//
// public String getPostResponseHeaderField(String header) {
// if ((headers == null) || !headers.containsKey(header)) {
// return null;
// }
// if ((headers.get(header) == null) || headers.get(header).isEmpty()) {
// return null;
// }
// StringBuilder sbValues = new StringBuilder();
// for (String value : headers.get(header)) {
// if ("".equals(value)) {
// continue;
// }
// sbValues.append(value);
// sbValues.append(";");
// }
// return sbValues.toString();
// }
// }
//
// Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface SamlHandshakeManager {
// public String requestToken() throws IOException;
// public String getAuthenticationCookie(String token) throws IOException;
// }
| import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.enterprise.cloudsearch.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.cloudsearch.sharepoint.SamlAuthenticationHandler.HttpPostClientImpl;
import com.google.enterprise.cloudsearch.sharepoint.SamlAuthenticationHandler.PostResponseInfo;
import com.google.enterprise.cloudsearch.sharepoint.SamlAuthenticationHandler.SamlHandshakeManager;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException; |
public Builder setLoginUrl(String login) {
this.login = login;
return this;
}
public Builder setTrustLocation(String trustLocation) {
this.trustLocation = trustLocation;
return this;
}
@VisibleForTesting
Builder setHttpClient(HttpPostClient httpClient) {
this.httpClient = httpClient;
return this;
}
public AdfsHandshakeManager build() {
return new AdfsHandshakeManager(this);
}
}
@Override
public String requestToken() throws IOException {
String saml = generateSamlRequest();
URL u = new URL(stsendpoint);
Map<String, String> requestHeaders = new HashMap<String, String>();
requestHeaders.put("SOAPAction", stsendpoint);
requestHeaders.put("Content-Type",
"application/soap+xml; charset=utf-8"); | // Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface HttpPostClient {
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException;
// }
//
// Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class HttpPostClientImpl implements HttpPostClient{
// @Override
// public PostResponseInfo issuePostRequest(URL url,
// Map<String, String> connectionProperties, String requestBody)
// throws IOException {
//
// // Handle Unicode. Java does not properly encode the GET.
// try {
// url = new URL(url.toURI().toASCIIString());
// } catch (URISyntaxException ex) {
// throw new IOException(ex);
// }
//
// HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// try {
// connection.setDoOutput(true);
// connection.setDoInput(true);
// connection.setRequestMethod("POST");
// connection.setInstanceFollowRedirects(false);
//
// for (String key : connectionProperties.keySet()) {
// connection.addRequestProperty(key, connectionProperties.get(key));
// }
//
// if (!connectionProperties.containsKey("Content-Length")) {
// connection.addRequestProperty("Content-Length",
// Integer.toString(requestBody.length()));
// }
//
// OutputStream out = connection.getOutputStream();
// Writer wout = new OutputStreamWriter(out);
// wout.write(requestBody);
// wout.flush();
// wout.close();
// InputStream in = connection.getInputStream();
// String result = readInputStreamToString(in, CHARSET);
// return new PostResponseInfo(result, connection.getHeaderFields());
// } finally {
// InputStream inputStream = connection.getResponseCode() >= 400
// ? connection.getErrorStream() : connection.getInputStream();
// if (inputStream != null) {
// inputStream.close();
// }
// }
// }
//
// private String readInputStreamToString(InputStream in, Charset charset) throws IOException {
// return new String(ByteStreams.toByteArray(in), charset);
// }
// }
//
// Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public static class PostResponseInfo {
// /** Non-null contents. */
// private final String contents;
// /** Non-null headers. */
// private final Map<String, List<String>> headers;
//
// PostResponseInfo(
// String contents, Map<String, List<String>> headers) {
// this.contents = contents;
// this.headers = (headers == null)
// ? new HashMap<String, List<String>>()
// : new HashMap<String, List<String>>(headers);
// }
//
// public String getPostContents() {
// return contents;
// }
//
// public Map<String, List<String>> getPostResponseHeaders() {
// return Collections.unmodifiableMap(headers);
// }
//
// public String getPostResponseHeaderField(String header) {
// if ((headers == null) || !headers.containsKey(header)) {
// return null;
// }
// if ((headers.get(header) == null) || headers.get(header).isEmpty()) {
// return null;
// }
// StringBuilder sbValues = new StringBuilder();
// for (String value : headers.get(header)) {
// if ("".equals(value)) {
// continue;
// }
// sbValues.append(value);
// sbValues.append(";");
// }
// return sbValues.toString();
// }
// }
//
// Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/SamlAuthenticationHandler.java
// @VisibleForTesting
// public interface SamlHandshakeManager {
// public String requestToken() throws IOException;
// public String getAuthenticationCookie(String token) throws IOException;
// }
// Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/AdfsHandshakeManager.java
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.enterprise.cloudsearch.sharepoint.SamlAuthenticationHandler.HttpPostClient;
import com.google.enterprise.cloudsearch.sharepoint.SamlAuthenticationHandler.HttpPostClientImpl;
import com.google.enterprise.cloudsearch.sharepoint.SamlAuthenticationHandler.PostResponseInfo;
import com.google.enterprise.cloudsearch.sharepoint.SamlAuthenticationHandler.SamlHandshakeManager;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public Builder setLoginUrl(String login) {
this.login = login;
return this;
}
public Builder setTrustLocation(String trustLocation) {
this.trustLocation = trustLocation;
return this;
}
@VisibleForTesting
Builder setHttpClient(HttpPostClient httpClient) {
this.httpClient = httpClient;
return this;
}
public AdfsHandshakeManager build() {
return new AdfsHandshakeManager(this);
}
}
@Override
public String requestToken() throws IOException {
String saml = generateSamlRequest();
URL u = new URL(stsendpoint);
Map<String, String> requestHeaders = new HashMap<String, String>();
requestHeaders.put("SOAPAction", stsendpoint);
requestHeaders.put("Content-Type",
"application/soap+xml; charset=utf-8"); | PostResponseInfo postResponse |
google-cloudsearch/sharepoint-connector | src/main/java/com/google/enterprise/cloudsearch/sharepoint/SiteConnectorFactoryImpl.java | // Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/SharePointConfiguration.java
// enum SharePointDeploymentType {
// ONLINE,
// ON_PREMISES;
// }
| import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMap;
import com.google.enterprise.cloudsearch.sdk.identity.IdentitySourceConfiguration;
import com.google.enterprise.cloudsearch.sharepoint.SharePointConfiguration.SharePointDeploymentType;
import com.microsoft.schemas.sharepoint.soap.SiteDataSoap;
import com.microsoft.schemas.sharepoint.soap.directory.UserGroupSoap;
import com.microsoft.schemas.sharepoint.soap.people.PeopleSoap;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentSkipListMap;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.EndpointReference;
import javax.xml.ws.Service;
import javax.xml.ws.wsaddressing.W3CEndpointReferenceBuilder; | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.google.enterprise.cloudsearch.sharepoint;
class SiteConnectorFactoryImpl implements SiteConnectorFactory {
private static final String XMLNS_DIRECTORY =
"http://schemas.microsoft.com/sharepoint/soap/directory/";
private static final String XMLNS = "http://schemas.microsoft.com/sharepoint/soap/";
/** Map from Site or Web URL to SiteConnector object used to communicate with that Site/Web. */
private final ConcurrentMap<String, SiteConnector> siteConnectors =
new ConcurrentSkipListMap<String, SiteConnector>();
private final SoapFactory soapFactory;
private final SharePointRequestContext requestContext;
private final boolean xmlValidation;
private final Optional<ActiveDirectoryClient> activeDirectoryClient;
private final ImmutableMap<String, IdentitySourceConfiguration>
referenceIdentitySourceConfiguration;
private final boolean stripDomainInUserPrincipals; | // Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/SharePointConfiguration.java
// enum SharePointDeploymentType {
// ONLINE,
// ON_PREMISES;
// }
// Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/SiteConnectorFactoryImpl.java
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMap;
import com.google.enterprise.cloudsearch.sdk.identity.IdentitySourceConfiguration;
import com.google.enterprise.cloudsearch.sharepoint.SharePointConfiguration.SharePointDeploymentType;
import com.microsoft.schemas.sharepoint.soap.SiteDataSoap;
import com.microsoft.schemas.sharepoint.soap.directory.UserGroupSoap;
import com.microsoft.schemas.sharepoint.soap.people.PeopleSoap;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentSkipListMap;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.EndpointReference;
import javax.xml.ws.Service;
import javax.xml.ws.wsaddressing.W3CEndpointReferenceBuilder;
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.google.enterprise.cloudsearch.sharepoint;
class SiteConnectorFactoryImpl implements SiteConnectorFactory {
private static final String XMLNS_DIRECTORY =
"http://schemas.microsoft.com/sharepoint/soap/directory/";
private static final String XMLNS = "http://schemas.microsoft.com/sharepoint/soap/";
/** Map from Site or Web URL to SiteConnector object used to communicate with that Site/Web. */
private final ConcurrentMap<String, SiteConnector> siteConnectors =
new ConcurrentSkipListMap<String, SiteConnector>();
private final SoapFactory soapFactory;
private final SharePointRequestContext requestContext;
private final boolean xmlValidation;
private final Optional<ActiveDirectoryClient> activeDirectoryClient;
private final ImmutableMap<String, IdentitySourceConfiguration>
referenceIdentitySourceConfiguration;
private final boolean stripDomainInUserPrincipals; | private final SharePointDeploymentType sharePointDeploymentType; |
google-cloudsearch/sharepoint-connector | src/main/java/com/google/enterprise/cloudsearch/sharepoint/SharePointConfiguration.java | // Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/SharePointUrl.java
// static String getCanonicalUrl(String url) {
// if (!url.endsWith("/")) {
// return url;
// }
// return url.substring(0, url.length() - 1);
// }
| import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.enterprise.cloudsearch.sharepoint.SharePointUrl.Builder.getCanonicalUrl;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.enterprise.cloudsearch.sdk.InvalidConfigurationException;
import com.google.enterprise.cloudsearch.sdk.config.Configuration;
import com.google.enterprise.cloudsearch.sdk.identity.IdentitySourceConfiguration;
import java.net.URISyntaxException;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger; | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.google.enterprise.cloudsearch.sharepoint;
class SharePointConfiguration {
private static final Logger log = Logger.getLogger(SharePointRepository.class.getName());
private static final String DEFAULT_USER_NAME = isCredentialOptional() ? "" : null;
private static final String DEFAULT_PASSWORD = isCredentialOptional() ? "" : null;
private final SharePointUrl sharePointUrl;
private final String virtualServerUrl;
private final boolean siteCollectionOnly;
private final ImmutableSet<String> siteCollectionsToInclude;
private final String userName;
private final String password;
private final String sharePointUserAgent;
private final int webservicesSocketTimeoutMills;
private final int webservicesReadTimeoutMills;
private final boolean performXmlValidation;
private final boolean performBrowserLeniency;
private final ImmutableMap<String, IdentitySourceConfiguration>
referenceIdentitySourceConfiguration;
private final boolean stripDomainInUserPrincipals;
private static boolean isCredentialOptional() {
return System.getProperty("os.name", "").contains("Windows");
}
enum SharePointDeploymentType {
ONLINE,
ON_PREMISES;
}
private final SharePointDeploymentType sharePointDeploymentType;
public boolean isSiteCollectionIncluded(String siteCollectionUrl) {
Preconditions.checkNotNull(siteCollectionUrl, "Site Collection URL may not be null"); | // Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/SharePointUrl.java
// static String getCanonicalUrl(String url) {
// if (!url.endsWith("/")) {
// return url;
// }
// return url.substring(0, url.length() - 1);
// }
// Path: src/main/java/com/google/enterprise/cloudsearch/sharepoint/SharePointConfiguration.java
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.enterprise.cloudsearch.sharepoint.SharePointUrl.Builder.getCanonicalUrl;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.enterprise.cloudsearch.sdk.InvalidConfigurationException;
import com.google.enterprise.cloudsearch.sdk.config.Configuration;
import com.google.enterprise.cloudsearch.sdk.identity.IdentitySourceConfiguration;
import java.net.URISyntaxException;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES 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.google.enterprise.cloudsearch.sharepoint;
class SharePointConfiguration {
private static final Logger log = Logger.getLogger(SharePointRepository.class.getName());
private static final String DEFAULT_USER_NAME = isCredentialOptional() ? "" : null;
private static final String DEFAULT_PASSWORD = isCredentialOptional() ? "" : null;
private final SharePointUrl sharePointUrl;
private final String virtualServerUrl;
private final boolean siteCollectionOnly;
private final ImmutableSet<String> siteCollectionsToInclude;
private final String userName;
private final String password;
private final String sharePointUserAgent;
private final int webservicesSocketTimeoutMills;
private final int webservicesReadTimeoutMills;
private final boolean performXmlValidation;
private final boolean performBrowserLeniency;
private final ImmutableMap<String, IdentitySourceConfiguration>
referenceIdentitySourceConfiguration;
private final boolean stripDomainInUserPrincipals;
private static boolean isCredentialOptional() {
return System.getProperty("os.name", "").contains("Windows");
}
enum SharePointDeploymentType {
ONLINE,
ON_PREMISES;
}
private final SharePointDeploymentType sharePointDeploymentType;
public boolean isSiteCollectionIncluded(String siteCollectionUrl) {
Preconditions.checkNotNull(siteCollectionUrl, "Site Collection URL may not be null"); | String url = getCanonicalUrl(siteCollectionUrl); |
Grover-c13/PokeGOAPI-Java | library/src/main/java/com/pokegoapi/auth/GoogleAutoCredentialProvider.java | // Path: library/src/main/java/com/pokegoapi/exceptions/request/InvalidCredentialsException.java
// public class InvalidCredentialsException extends RequestFailedException {
// public InvalidCredentialsException() {
// super();
// }
//
// public InvalidCredentialsException(String reason) {
// super(reason);
// }
//
// public InvalidCredentialsException(Throwable exception) {
// super(exception);
// }
//
// public InvalidCredentialsException(String reason, Throwable exception) {
// super(reason, exception);
// }
// }
| import POGOProtos.Networking.Envelopes.RequestEnvelopeOuterClass.RequestEnvelope.AuthInfo;
import com.pokegoapi.exceptions.request.InvalidCredentialsException;
import com.pokegoapi.exceptions.request.LoginFailedException;
import com.pokegoapi.util.SystemTimeImpl;
import com.pokegoapi.util.Time;
import lombok.Getter;
import okhttp3.OkHttpClient;
import svarzee.gps.gpsoauth.AuthToken;
import svarzee.gps.gpsoauth.Gpsoauth;
import java.io.IOException; | package com.pokegoapi.auth;
/**
* Use to login with google username and password
*/
public class GoogleAutoCredentialProvider extends CredentialProvider {
// from https://github.com/tejado/pgoapi/blob/master/pgoapi/auth_google.py
private static String GOOGLE_LOGIN_ANDROID_ID = "9774d56d682e549c";
private static String GOOGLE_LOGIN_SERVICE =
"audience:server:client_id:848232511240-7so421jotr2609rmqakceuu1luuq0ptb.apps.googleusercontent.com";
private static String GOOGLE_LOGIN_APP = "com.nianticlabs.pokemongo";
private static String GOOGLE_LOGIN_CLIENT_SIG = "321187995bc7cdc2b5fc91b11a96e2baa8602c62";
private final Gpsoauth gpsoauth;
private final String username;
private Time time;
@Getter
private TokenInfo tokenInfo;
/**
* Constructs credential provider using username and password
*
* @param httpClient OkHttp client
* @param username google username
* @param password google password
* @throws LoginFailedException if an exception occurs while attempting to log in
* @throws InvalidCredentialsException if invalid credentials are used
*/
public GoogleAutoCredentialProvider(OkHttpClient httpClient, String username, String password) | // Path: library/src/main/java/com/pokegoapi/exceptions/request/InvalidCredentialsException.java
// public class InvalidCredentialsException extends RequestFailedException {
// public InvalidCredentialsException() {
// super();
// }
//
// public InvalidCredentialsException(String reason) {
// super(reason);
// }
//
// public InvalidCredentialsException(Throwable exception) {
// super(exception);
// }
//
// public InvalidCredentialsException(String reason, Throwable exception) {
// super(reason, exception);
// }
// }
// Path: library/src/main/java/com/pokegoapi/auth/GoogleAutoCredentialProvider.java
import POGOProtos.Networking.Envelopes.RequestEnvelopeOuterClass.RequestEnvelope.AuthInfo;
import com.pokegoapi.exceptions.request.InvalidCredentialsException;
import com.pokegoapi.exceptions.request.LoginFailedException;
import com.pokegoapi.util.SystemTimeImpl;
import com.pokegoapi.util.Time;
import lombok.Getter;
import okhttp3.OkHttpClient;
import svarzee.gps.gpsoauth.AuthToken;
import svarzee.gps.gpsoauth.Gpsoauth;
import java.io.IOException;
package com.pokegoapi.auth;
/**
* Use to login with google username and password
*/
public class GoogleAutoCredentialProvider extends CredentialProvider {
// from https://github.com/tejado/pgoapi/blob/master/pgoapi/auth_google.py
private static String GOOGLE_LOGIN_ANDROID_ID = "9774d56d682e549c";
private static String GOOGLE_LOGIN_SERVICE =
"audience:server:client_id:848232511240-7so421jotr2609rmqakceuu1luuq0ptb.apps.googleusercontent.com";
private static String GOOGLE_LOGIN_APP = "com.nianticlabs.pokemongo";
private static String GOOGLE_LOGIN_CLIENT_SIG = "321187995bc7cdc2b5fc91b11a96e2baa8602c62";
private final Gpsoauth gpsoauth;
private final String username;
private Time time;
@Getter
private TokenInfo tokenInfo;
/**
* Constructs credential provider using username and password
*
* @param httpClient OkHttp client
* @param username google username
* @param password google password
* @throws LoginFailedException if an exception occurs while attempting to log in
* @throws InvalidCredentialsException if invalid credentials are used
*/
public GoogleAutoCredentialProvider(OkHttpClient httpClient, String username, String password) | throws LoginFailedException, InvalidCredentialsException { |
Grover-c13/PokeGOAPI-Java | library/src/main/java/com/pokegoapi/auth/GoogleCredentialProvider.java | // Path: library/src/main/java/com/pokegoapi/exceptions/request/InvalidCredentialsException.java
// public class InvalidCredentialsException extends RequestFailedException {
// public InvalidCredentialsException() {
// super();
// }
//
// public InvalidCredentialsException(String reason) {
// super(reason);
// }
//
// public InvalidCredentialsException(Throwable exception) {
// super(exception);
// }
//
// public InvalidCredentialsException(String reason, Throwable exception) {
// super(reason, exception);
// }
// }
| import POGOProtos.Networking.Envelopes.RequestEnvelopeOuterClass.RequestEnvelope.AuthInfo;
import com.pokegoapi.exceptions.request.InvalidCredentialsException;
import com.pokegoapi.exceptions.request.LoginFailedException;
import com.pokegoapi.util.Log;
import com.squareup.moshi.Moshi;
import lombok.Getter;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import java.io.IOException;
import java.net.URISyntaxException; | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.pokegoapi.auth;
/**
* @deprecated use {@link GoogleAutoCredentialProvider}
*/
@Deprecated
public class GoogleCredentialProvider extends CredentialProvider {
public static final String SECRET = "NCjF1TLi2CcY6t5mt0ZveuL7";
public static final String CLIENT_ID = "848232511240-73ri3t7plvk96pj4f85uj8otdat2alem.apps.googleusercontent.com";
public static final String OAUTH_ENDPOINT = "https://accounts.google.com/o/oauth2/device/code";
public static final String OAUTH_TOKEN_ENDPOINT = "https://www.googleapis.com/oauth2/v4/token";
private static final String TAG = GoogleCredentialProvider.class.getSimpleName();
//We try and refresh token 5 minutes before it actually expires
private static final long REFRESH_TOKEN_BUFFER_TIME = 5 * 60 * 1000;
private final OkHttpClient client;
private final OnGoogleLoginOAuthCompleteListener onGoogleLoginOAuthCompleteListener;
private long expiresTimestamp;
private String tokenId;
@Getter
private String refreshToken;
private AuthInfo.Builder authbuilder;
/**
* Used for logging in when one has a persisted refreshToken.
*
* @param client OkHttp client
* @param refreshToken Refresh Token Persisted by user
* @throws LoginFailedException if an exception occurs while attempting to log in
* @throws InvalidCredentialsException if invalid credentials are used
*/
public GoogleCredentialProvider(OkHttpClient client, String refreshToken) | // Path: library/src/main/java/com/pokegoapi/exceptions/request/InvalidCredentialsException.java
// public class InvalidCredentialsException extends RequestFailedException {
// public InvalidCredentialsException() {
// super();
// }
//
// public InvalidCredentialsException(String reason) {
// super(reason);
// }
//
// public InvalidCredentialsException(Throwable exception) {
// super(exception);
// }
//
// public InvalidCredentialsException(String reason, Throwable exception) {
// super(reason, exception);
// }
// }
// Path: library/src/main/java/com/pokegoapi/auth/GoogleCredentialProvider.java
import POGOProtos.Networking.Envelopes.RequestEnvelopeOuterClass.RequestEnvelope.AuthInfo;
import com.pokegoapi.exceptions.request.InvalidCredentialsException;
import com.pokegoapi.exceptions.request.LoginFailedException;
import com.pokegoapi.util.Log;
import com.squareup.moshi.Moshi;
import lombok.Getter;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import java.io.IOException;
import java.net.URISyntaxException;
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.pokegoapi.auth;
/**
* @deprecated use {@link GoogleAutoCredentialProvider}
*/
@Deprecated
public class GoogleCredentialProvider extends CredentialProvider {
public static final String SECRET = "NCjF1TLi2CcY6t5mt0ZveuL7";
public static final String CLIENT_ID = "848232511240-73ri3t7plvk96pj4f85uj8otdat2alem.apps.googleusercontent.com";
public static final String OAUTH_ENDPOINT = "https://accounts.google.com/o/oauth2/device/code";
public static final String OAUTH_TOKEN_ENDPOINT = "https://www.googleapis.com/oauth2/v4/token";
private static final String TAG = GoogleCredentialProvider.class.getSimpleName();
//We try and refresh token 5 minutes before it actually expires
private static final long REFRESH_TOKEN_BUFFER_TIME = 5 * 60 * 1000;
private final OkHttpClient client;
private final OnGoogleLoginOAuthCompleteListener onGoogleLoginOAuthCompleteListener;
private long expiresTimestamp;
private String tokenId;
@Getter
private String refreshToken;
private AuthInfo.Builder authbuilder;
/**
* Used for logging in when one has a persisted refreshToken.
*
* @param client OkHttp client
* @param refreshToken Refresh Token Persisted by user
* @throws LoginFailedException if an exception occurs while attempting to log in
* @throws InvalidCredentialsException if invalid credentials are used
*/
public GoogleCredentialProvider(OkHttpClient client, String refreshToken) | throws LoginFailedException, InvalidCredentialsException { |
Grover-c13/PokeGOAPI-Java | library/src/main/java/com/pokegoapi/util/hash/pokehash/PokeHashProvider.java | // Path: library/src/main/java/com/pokegoapi/util/hash/Hash.java
// public class Hash {
// @Getter
// public final int locationAuthHash;
// @Getter
// public final int locationHash;
// @Getter
// public final List<Long> requestHashes;
//
// /**
// * Creates a hash object
// *
// * @param locationAuthHash the hash of the location and auth ticket
// * @param locationHash the hash of the location
// * @param requestHashes the hash of each request
// */
// public Hash(int locationAuthHash, int locationHash, List<Long> requestHashes) {
// this.locationAuthHash = locationAuthHash;
// this.locationHash = locationHash;
// this.requestHashes = requestHashes;
// }
// }
| import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import com.pokegoapi.exceptions.request.HashException;
import com.pokegoapi.exceptions.request.HashLimitExceededException;
import com.pokegoapi.exceptions.request.HashUnauthorizedException;
import com.pokegoapi.util.hash.Hash;
import com.pokegoapi.util.hash.HashProvider;
import com.squareup.moshi.Moshi;
import com.squareup.moshi.Moshi.Builder;
import lombok.Getter;
import lombok.Setter;
import net.iharder.Base64;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader; | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.pokegoapi.util.hash.pokehash;
/**
* Hash provider on latest version, using the PokeHash hashing service.
* This requires a key and is not free like the legacy provider.
* @see <a href="https://hashing.pogodev.org/">https://hashing.pogodev.org/</a>
*/
public class PokeHashProvider implements HashProvider {
private static final String DEFAULT_ENDPOINT = "https://pokehash.buddyauth.com/api/v159_1/hash";
@Getter
@Setter
private String endpoint = DEFAULT_ENDPOINT;
private static final int VERSION = 9100;
private static final long UNK25 = -782790124105039914L;
private static final Moshi MOSHI = new Builder().build();
@Getter
private final PokeHashKey key;
@Getter
private final boolean awaitRequests;
/**
* Creates a PokeHashProvider with the given key
*
* @param key the key for the PokeHash API
* @param awaitRequest true if the API should, when the rate limit has been exceeded, wait until the current
* period ends, or false to throw a HashLimitExceededException
*/
public PokeHashProvider(PokeHashKey key, boolean awaitRequest) {
this.key = key;
this.awaitRequests = awaitRequest;
if (key == null || key.key == null) {
throw new IllegalArgumentException("Key cannot be null!");
}
}
/**
* Provides a hash for the given arguments
*
* @param timestamp timestamp to hash
* @param latitude latitude to hash
* @param longitude longitude to hash
* @param altitude altitude to hash
* @param authTicket auth ticket to hash
* @param sessionData session data to hash
* @param requests request data to hash
* @return the hash provider
* @throws HashException if an exception occurs while providing this hash
*/
@Override | // Path: library/src/main/java/com/pokegoapi/util/hash/Hash.java
// public class Hash {
// @Getter
// public final int locationAuthHash;
// @Getter
// public final int locationHash;
// @Getter
// public final List<Long> requestHashes;
//
// /**
// * Creates a hash object
// *
// * @param locationAuthHash the hash of the location and auth ticket
// * @param locationHash the hash of the location
// * @param requestHashes the hash of each request
// */
// public Hash(int locationAuthHash, int locationHash, List<Long> requestHashes) {
// this.locationAuthHash = locationAuthHash;
// this.locationHash = locationHash;
// this.requestHashes = requestHashes;
// }
// }
// Path: library/src/main/java/com/pokegoapi/util/hash/pokehash/PokeHashProvider.java
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import com.pokegoapi.exceptions.request.HashException;
import com.pokegoapi.exceptions.request.HashLimitExceededException;
import com.pokegoapi.exceptions.request.HashUnauthorizedException;
import com.pokegoapi.util.hash.Hash;
import com.pokegoapi.util.hash.HashProvider;
import com.squareup.moshi.Moshi;
import com.squareup.moshi.Moshi.Builder;
import lombok.Getter;
import lombok.Setter;
import net.iharder.Base64;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.pokegoapi.util.hash.pokehash;
/**
* Hash provider on latest version, using the PokeHash hashing service.
* This requires a key and is not free like the legacy provider.
* @see <a href="https://hashing.pogodev.org/">https://hashing.pogodev.org/</a>
*/
public class PokeHashProvider implements HashProvider {
private static final String DEFAULT_ENDPOINT = "https://pokehash.buddyauth.com/api/v159_1/hash";
@Getter
@Setter
private String endpoint = DEFAULT_ENDPOINT;
private static final int VERSION = 9100;
private static final long UNK25 = -782790124105039914L;
private static final Moshi MOSHI = new Builder().build();
@Getter
private final PokeHashKey key;
@Getter
private final boolean awaitRequests;
/**
* Creates a PokeHashProvider with the given key
*
* @param key the key for the PokeHash API
* @param awaitRequest true if the API should, when the rate limit has been exceeded, wait until the current
* period ends, or false to throw a HashLimitExceededException
*/
public PokeHashProvider(PokeHashKey key, boolean awaitRequest) {
this.key = key;
this.awaitRequests = awaitRequest;
if (key == null || key.key == null) {
throw new IllegalArgumentException("Key cannot be null!");
}
}
/**
* Provides a hash for the given arguments
*
* @param timestamp timestamp to hash
* @param latitude latitude to hash
* @param longitude longitude to hash
* @param altitude altitude to hash
* @param authTicket auth ticket to hash
* @param sessionData session data to hash
* @param requests request data to hash
* @return the hash provider
* @throws HashException if an exception occurs while providing this hash
*/
@Override | public Hash provide(long timestamp, double latitude, double longitude, double altitude, byte[] authTicket, |
Grover-c13/PokeGOAPI-Java | library/src/main/java/com/pokegoapi/api/settings/PokeballSelector.java | // Path: library/src/main/java/com/pokegoapi/api/inventory/Pokeball.java
// public enum Pokeball {
// POKEBALL(ItemId.ITEM_POKE_BALL, 1.0),
// GREATBALL(ItemId.ITEM_GREAT_BALL, 0.4),
// ULTRABALL(ItemId.ITEM_ULTRA_BALL, 0.2),
// MASTERBALL(ItemId.ITEM_MASTER_BALL, 0.0);
//
// @Getter
// public final ItemId ballType;
// @Getter
// public final double captureProbability;
//
// Pokeball(ItemId type, double probability) {
// ballType = type;
// captureProbability = probability;
// }
// }
| import com.pokegoapi.api.inventory.Pokeball;
import java.util.List; | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.pokegoapi.api.settings;
public interface PokeballSelector {
/**
* Selects the lowest possible pokeball
*/
PokeballSelector LOWEST = new PokeballSelector() {
@Override | // Path: library/src/main/java/com/pokegoapi/api/inventory/Pokeball.java
// public enum Pokeball {
// POKEBALL(ItemId.ITEM_POKE_BALL, 1.0),
// GREATBALL(ItemId.ITEM_GREAT_BALL, 0.4),
// ULTRABALL(ItemId.ITEM_ULTRA_BALL, 0.2),
// MASTERBALL(ItemId.ITEM_MASTER_BALL, 0.0);
//
// @Getter
// public final ItemId ballType;
// @Getter
// public final double captureProbability;
//
// Pokeball(ItemId type, double probability) {
// ballType = type;
// captureProbability = probability;
// }
// }
// Path: library/src/main/java/com/pokegoapi/api/settings/PokeballSelector.java
import com.pokegoapi.api.inventory.Pokeball;
import java.util.List;
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.pokegoapi.api.settings;
public interface PokeballSelector {
/**
* Selects the lowest possible pokeball
*/
PokeballSelector LOWEST = new PokeballSelector() {
@Override | public Pokeball select(List<Pokeball> pokeballs, double captureProbability) { |
Grover-c13/PokeGOAPI-Java | library/src/main/java/com/pokegoapi/auth/GoogleUserCredentialProvider.java | // Path: library/src/main/java/com/pokegoapi/exceptions/request/InvalidCredentialsException.java
// public class InvalidCredentialsException extends RequestFailedException {
// public InvalidCredentialsException() {
// super();
// }
//
// public InvalidCredentialsException(String reason) {
// super(reason);
// }
//
// public InvalidCredentialsException(Throwable exception) {
// super(exception);
// }
//
// public InvalidCredentialsException(String reason, Throwable exception) {
// super(reason, exception);
// }
// }
| import POGOProtos.Networking.Envelopes.RequestEnvelopeOuterClass.RequestEnvelope.AuthInfo;
import com.pokegoapi.exceptions.request.InvalidCredentialsException;
import com.pokegoapi.exceptions.request.LoginFailedException;
import com.pokegoapi.util.Log;
import com.pokegoapi.util.SystemTimeImpl;
import com.pokegoapi.util.Time;
import com.squareup.moshi.Moshi;
import lombok.Getter;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import java.io.IOException; | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.pokegoapi.auth;
/**
* @deprecated Use {@link GoogleAutoCredentialProvider}
*/
@Deprecated
public class GoogleUserCredentialProvider extends CredentialProvider {
public static final String SECRET = "NCjF1TLi2CcY6t5mt0ZveuL7";
public static final String CLIENT_ID = "848232511240-73ri3t7plvk96pj4f85uj8otdat2alem.apps.googleusercontent.com";
public static final String OAUTH_TOKEN_ENDPOINT = "https://www.googleapis.com/oauth2/v4/token";
public static final String LOGIN_URL = "https://accounts.google"
+ ".com/o/oauth2/auth?client_id=848232511240-73ri3t7plvk96pj4f85uj8otdat2alem.apps.googleusercontent"
+ ".com&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&response_type=code&scope=openid%20email%20https"
+ "%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email";
private static final String TAG = GoogleUserCredentialProvider.class.getSimpleName();
//We try and refresh token 5 minutes before it actually expires
protected static final long REFRESH_TOKEN_BUFFER_TIME = 5 * 60 * 1000;
protected final OkHttpClient client;
protected final Time time;
protected long expiresTimestamp;
protected String tokenId;
@Getter
public String refreshToken;
protected AuthInfo.Builder authbuilder;
/**
* Used for logging in when one has a persisted refreshToken.
*
* @param client OkHttp client
* @param refreshToken Refresh Token Persisted by user
* @param time a Time implementation
* @throws LoginFailedException if an exception occurs while attempting to log in
* @throws InvalidCredentialsException if invalid credentials are used
*/
public GoogleUserCredentialProvider(OkHttpClient client, String refreshToken, Time time) | // Path: library/src/main/java/com/pokegoapi/exceptions/request/InvalidCredentialsException.java
// public class InvalidCredentialsException extends RequestFailedException {
// public InvalidCredentialsException() {
// super();
// }
//
// public InvalidCredentialsException(String reason) {
// super(reason);
// }
//
// public InvalidCredentialsException(Throwable exception) {
// super(exception);
// }
//
// public InvalidCredentialsException(String reason, Throwable exception) {
// super(reason, exception);
// }
// }
// Path: library/src/main/java/com/pokegoapi/auth/GoogleUserCredentialProvider.java
import POGOProtos.Networking.Envelopes.RequestEnvelopeOuterClass.RequestEnvelope.AuthInfo;
import com.pokegoapi.exceptions.request.InvalidCredentialsException;
import com.pokegoapi.exceptions.request.LoginFailedException;
import com.pokegoapi.util.Log;
import com.pokegoapi.util.SystemTimeImpl;
import com.pokegoapi.util.Time;
import com.squareup.moshi.Moshi;
import lombok.Getter;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import java.io.IOException;
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.pokegoapi.auth;
/**
* @deprecated Use {@link GoogleAutoCredentialProvider}
*/
@Deprecated
public class GoogleUserCredentialProvider extends CredentialProvider {
public static final String SECRET = "NCjF1TLi2CcY6t5mt0ZveuL7";
public static final String CLIENT_ID = "848232511240-73ri3t7plvk96pj4f85uj8otdat2alem.apps.googleusercontent.com";
public static final String OAUTH_TOKEN_ENDPOINT = "https://www.googleapis.com/oauth2/v4/token";
public static final String LOGIN_URL = "https://accounts.google"
+ ".com/o/oauth2/auth?client_id=848232511240-73ri3t7plvk96pj4f85uj8otdat2alem.apps.googleusercontent"
+ ".com&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&response_type=code&scope=openid%20email%20https"
+ "%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email";
private static final String TAG = GoogleUserCredentialProvider.class.getSimpleName();
//We try and refresh token 5 minutes before it actually expires
protected static final long REFRESH_TOKEN_BUFFER_TIME = 5 * 60 * 1000;
protected final OkHttpClient client;
protected final Time time;
protected long expiresTimestamp;
protected String tokenId;
@Getter
public String refreshToken;
protected AuthInfo.Builder authbuilder;
/**
* Used for logging in when one has a persisted refreshToken.
*
* @param client OkHttp client
* @param refreshToken Refresh Token Persisted by user
* @param time a Time implementation
* @throws LoginFailedException if an exception occurs while attempting to log in
* @throws InvalidCredentialsException if invalid credentials are used
*/
public GoogleUserCredentialProvider(OkHttpClient client, String refreshToken, Time time) | throws LoginFailedException, InvalidCredentialsException { |
Grover-c13/PokeGOAPI-Java | library/src/main/java/com/pokegoapi/auth/PtcCredentialProvider.java | // Path: library/src/main/java/com/pokegoapi/exceptions/request/InvalidCredentialsException.java
// public class InvalidCredentialsException extends RequestFailedException {
// public InvalidCredentialsException() {
// super();
// }
//
// public InvalidCredentialsException(String reason) {
// super(reason);
// }
//
// public InvalidCredentialsException(Throwable exception) {
// super(exception);
// }
//
// public InvalidCredentialsException(String reason, Throwable exception) {
// super(reason, exception);
// }
// }
| import POGOProtos.Networking.Envelopes.RequestEnvelopeOuterClass.RequestEnvelope.AuthInfo;
import com.pokegoapi.exceptions.request.InvalidCredentialsException;
import com.pokegoapi.exceptions.request.LoginFailedException;
import com.pokegoapi.util.SystemTimeImpl;
import com.pokegoapi.util.Time;
import com.squareup.moshi.Moshi;
import lombok.Setter;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.FormBody;
import okhttp3.FormBody.Builder;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.pokegoapi.auth;
public class PtcCredentialProvider extends CredentialProvider {
public static final String CLIENT_SECRET = "w8ScCUXJQc6kXKw8FiOhd8Fixzht18Dq3PEVkUCP5ZPxtgyWsbTvWHFLm2wNY0JR";
public static final String REDIRECT_URI = "https://www.nianticlabs.com/pokemongo/error";
public static final String CLIENT_ID = "mobile-app_pokemon-go";
public static final String SERVICE_URL = "https://sso.pokemon.com/sso/oauth2.0/callbackAuthorize";
public static final String LOGIN_URL = "https://sso.pokemon.com/sso/login";
public static final String LOGIN_OAUTH = "https://sso.pokemon.com/sso/oauth2.0/accessToken";
public static final String USER_AGENT = "pokemongo/1 CFNetwork/897.1 Darwin/17.5.0"; //Lasted iOS 11.3.0
//We try and refresh token 5 minutes before it actually expires
protected static final long REFRESH_TOKEN_BUFFER_TIME = 5 * 60 * 1000;
protected static final int MAXIMUM_RETRIES = 5;
protected static final int[] UK2_VALUES = new int[]{2, 8, 21, 24, 28, 37, 56, 58, 59};
protected final OkHttpClient client;
protected final String username;
protected final String password;
protected final Time time;
protected String tokenId;
protected long expiresTimestamp;
protected AuthInfo.Builder authbuilder;
protected SecureRandom random = new SecureRandom();
@Setter
protected boolean shouldRetry = true;
/**
* Instantiates a new Ptc login.
*
* @param client the client
* @param username Username
* @param password password
* @param time a Time implementation
* @throws LoginFailedException if an exception occurs while attempting to log in
* @throws InvalidCredentialsException if invalid credentials are used
*/
public PtcCredentialProvider(OkHttpClient client, String username, String password, Time time) | // Path: library/src/main/java/com/pokegoapi/exceptions/request/InvalidCredentialsException.java
// public class InvalidCredentialsException extends RequestFailedException {
// public InvalidCredentialsException() {
// super();
// }
//
// public InvalidCredentialsException(String reason) {
// super(reason);
// }
//
// public InvalidCredentialsException(Throwable exception) {
// super(exception);
// }
//
// public InvalidCredentialsException(String reason, Throwable exception) {
// super(reason, exception);
// }
// }
// Path: library/src/main/java/com/pokegoapi/auth/PtcCredentialProvider.java
import POGOProtos.Networking.Envelopes.RequestEnvelopeOuterClass.RequestEnvelope.AuthInfo;
import com.pokegoapi.exceptions.request.InvalidCredentialsException;
import com.pokegoapi.exceptions.request.LoginFailedException;
import com.pokegoapi.util.SystemTimeImpl;
import com.pokegoapi.util.Time;
import com.squareup.moshi.Moshi;
import lombok.Setter;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.FormBody;
import okhttp3.FormBody.Builder;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.pokegoapi.auth;
public class PtcCredentialProvider extends CredentialProvider {
public static final String CLIENT_SECRET = "w8ScCUXJQc6kXKw8FiOhd8Fixzht18Dq3PEVkUCP5ZPxtgyWsbTvWHFLm2wNY0JR";
public static final String REDIRECT_URI = "https://www.nianticlabs.com/pokemongo/error";
public static final String CLIENT_ID = "mobile-app_pokemon-go";
public static final String SERVICE_URL = "https://sso.pokemon.com/sso/oauth2.0/callbackAuthorize";
public static final String LOGIN_URL = "https://sso.pokemon.com/sso/login";
public static final String LOGIN_OAUTH = "https://sso.pokemon.com/sso/oauth2.0/accessToken";
public static final String USER_AGENT = "pokemongo/1 CFNetwork/897.1 Darwin/17.5.0"; //Lasted iOS 11.3.0
//We try and refresh token 5 minutes before it actually expires
protected static final long REFRESH_TOKEN_BUFFER_TIME = 5 * 60 * 1000;
protected static final int MAXIMUM_RETRIES = 5;
protected static final int[] UK2_VALUES = new int[]{2, 8, 21, 24, 28, 37, 56, 58, 59};
protected final OkHttpClient client;
protected final String username;
protected final String password;
protected final Time time;
protected String tokenId;
protected long expiresTimestamp;
protected AuthInfo.Builder authbuilder;
protected SecureRandom random = new SecureRandom();
@Setter
protected boolean shouldRetry = true;
/**
* Instantiates a new Ptc login.
*
* @param client the client
* @param username Username
* @param password password
* @param time a Time implementation
* @throws LoginFailedException if an exception occurs while attempting to log in
* @throws InvalidCredentialsException if invalid credentials are used
*/
public PtcCredentialProvider(OkHttpClient client, String username, String password, Time time) | throws LoginFailedException, InvalidCredentialsException { |
UKHomeOffice/email-api | src/main/java/uk/gov/homeoffice/emailapi/resources/TemplatePopulatorParsingExceptionMapper.java | // Path: src/main/java/uk/gov/homeoffice/emailapi/entities/EmailApiStatus.java
// public enum EmailApiStatus implements StatusType {
// InvalidEmail(422, "Invalid recipient email"),
// TemplateUnreadable(422, "Template does not exist"),
// TemplateInvalid(422, "Template Invalid"),
// SendingEmailFailed(Status.INTERNAL_SERVER_ERROR.getStatusCode(),
// "Failed sending email to SMTP server.");
//
// private final Status.Family family;
//
// private final String reason;
//
// private final int code;
//
// EmailApiStatus(final int statusCode, final String reasonPhrase) {
// this.code = statusCode;
// this.reason = reasonPhrase;
// this.family = Status.Family.familyOf(statusCode);
// }
//
// @JsonValue
// public Map<String, List<String>> toEntity() {
//
// final Map<String, List<String>> map = new HashMap<>();
// List<String> errors = new ArrayList<>();
// errors.add(reason);
// map.put("errors", errors);
//
// return map;
// }
//
// @Override
// public int getStatusCode() {
// return code;
// }
//
// @Override
// public Status.Family getFamily() {
// return family;
// }
//
// @Override
// public String getReasonPhrase() {
// return reason;
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorParsingException.java
// public class TemplatePopulatorParsingException extends Exception {
// public TemplatePopulatorParsingException(Throwable cause) {
// super(cause);
// }
//
// public TemplatePopulatorParsingException(String message) {
// super(message);
// }
// }
| import org.slf4j.LoggerFactory;
import uk.gov.homeoffice.emailapi.entities.EmailApiStatus;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorParsingException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider; | package uk.gov.homeoffice.emailapi.resources;
@Provider
public class TemplatePopulatorParsingExceptionMapper | // Path: src/main/java/uk/gov/homeoffice/emailapi/entities/EmailApiStatus.java
// public enum EmailApiStatus implements StatusType {
// InvalidEmail(422, "Invalid recipient email"),
// TemplateUnreadable(422, "Template does not exist"),
// TemplateInvalid(422, "Template Invalid"),
// SendingEmailFailed(Status.INTERNAL_SERVER_ERROR.getStatusCode(),
// "Failed sending email to SMTP server.");
//
// private final Status.Family family;
//
// private final String reason;
//
// private final int code;
//
// EmailApiStatus(final int statusCode, final String reasonPhrase) {
// this.code = statusCode;
// this.reason = reasonPhrase;
// this.family = Status.Family.familyOf(statusCode);
// }
//
// @JsonValue
// public Map<String, List<String>> toEntity() {
//
// final Map<String, List<String>> map = new HashMap<>();
// List<String> errors = new ArrayList<>();
// errors.add(reason);
// map.put("errors", errors);
//
// return map;
// }
//
// @Override
// public int getStatusCode() {
// return code;
// }
//
// @Override
// public Status.Family getFamily() {
// return family;
// }
//
// @Override
// public String getReasonPhrase() {
// return reason;
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorParsingException.java
// public class TemplatePopulatorParsingException extends Exception {
// public TemplatePopulatorParsingException(Throwable cause) {
// super(cause);
// }
//
// public TemplatePopulatorParsingException(String message) {
// super(message);
// }
// }
// Path: src/main/java/uk/gov/homeoffice/emailapi/resources/TemplatePopulatorParsingExceptionMapper.java
import org.slf4j.LoggerFactory;
import uk.gov.homeoffice.emailapi.entities.EmailApiStatus;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorParsingException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
package uk.gov.homeoffice.emailapi.resources;
@Provider
public class TemplatePopulatorParsingExceptionMapper | implements ExceptionMapper<TemplatePopulatorParsingException> { |
UKHomeOffice/email-api | src/main/java/uk/gov/homeoffice/emailapi/resources/TemplatePopulatorParsingExceptionMapper.java | // Path: src/main/java/uk/gov/homeoffice/emailapi/entities/EmailApiStatus.java
// public enum EmailApiStatus implements StatusType {
// InvalidEmail(422, "Invalid recipient email"),
// TemplateUnreadable(422, "Template does not exist"),
// TemplateInvalid(422, "Template Invalid"),
// SendingEmailFailed(Status.INTERNAL_SERVER_ERROR.getStatusCode(),
// "Failed sending email to SMTP server.");
//
// private final Status.Family family;
//
// private final String reason;
//
// private final int code;
//
// EmailApiStatus(final int statusCode, final String reasonPhrase) {
// this.code = statusCode;
// this.reason = reasonPhrase;
// this.family = Status.Family.familyOf(statusCode);
// }
//
// @JsonValue
// public Map<String, List<String>> toEntity() {
//
// final Map<String, List<String>> map = new HashMap<>();
// List<String> errors = new ArrayList<>();
// errors.add(reason);
// map.put("errors", errors);
//
// return map;
// }
//
// @Override
// public int getStatusCode() {
// return code;
// }
//
// @Override
// public Status.Family getFamily() {
// return family;
// }
//
// @Override
// public String getReasonPhrase() {
// return reason;
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorParsingException.java
// public class TemplatePopulatorParsingException extends Exception {
// public TemplatePopulatorParsingException(Throwable cause) {
// super(cause);
// }
//
// public TemplatePopulatorParsingException(String message) {
// super(message);
// }
// }
| import org.slf4j.LoggerFactory;
import uk.gov.homeoffice.emailapi.entities.EmailApiStatus;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorParsingException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider; | package uk.gov.homeoffice.emailapi.resources;
@Provider
public class TemplatePopulatorParsingExceptionMapper
implements ExceptionMapper<TemplatePopulatorParsingException> {
private static final org.slf4j.Logger LOGGER =
LoggerFactory.getLogger(TemplatePopulatorParsingExceptionMapper.class);
@Override
public Response toResponse(TemplatePopulatorParsingException exception) {
LOGGER.error("Template is broken", exception);
| // Path: src/main/java/uk/gov/homeoffice/emailapi/entities/EmailApiStatus.java
// public enum EmailApiStatus implements StatusType {
// InvalidEmail(422, "Invalid recipient email"),
// TemplateUnreadable(422, "Template does not exist"),
// TemplateInvalid(422, "Template Invalid"),
// SendingEmailFailed(Status.INTERNAL_SERVER_ERROR.getStatusCode(),
// "Failed sending email to SMTP server.");
//
// private final Status.Family family;
//
// private final String reason;
//
// private final int code;
//
// EmailApiStatus(final int statusCode, final String reasonPhrase) {
// this.code = statusCode;
// this.reason = reasonPhrase;
// this.family = Status.Family.familyOf(statusCode);
// }
//
// @JsonValue
// public Map<String, List<String>> toEntity() {
//
// final Map<String, List<String>> map = new HashMap<>();
// List<String> errors = new ArrayList<>();
// errors.add(reason);
// map.put("errors", errors);
//
// return map;
// }
//
// @Override
// public int getStatusCode() {
// return code;
// }
//
// @Override
// public Status.Family getFamily() {
// return family;
// }
//
// @Override
// public String getReasonPhrase() {
// return reason;
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorParsingException.java
// public class TemplatePopulatorParsingException extends Exception {
// public TemplatePopulatorParsingException(Throwable cause) {
// super(cause);
// }
//
// public TemplatePopulatorParsingException(String message) {
// super(message);
// }
// }
// Path: src/main/java/uk/gov/homeoffice/emailapi/resources/TemplatePopulatorParsingExceptionMapper.java
import org.slf4j.LoggerFactory;
import uk.gov.homeoffice.emailapi.entities.EmailApiStatus;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorParsingException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
package uk.gov.homeoffice.emailapi.resources;
@Provider
public class TemplatePopulatorParsingExceptionMapper
implements ExceptionMapper<TemplatePopulatorParsingException> {
private static final org.slf4j.Logger LOGGER =
LoggerFactory.getLogger(TemplatePopulatorParsingExceptionMapper.class);
@Override
public Response toResponse(TemplatePopulatorParsingException exception) {
LOGGER.error("Template is broken", exception);
| return Response.status(EmailApiStatus.TemplateInvalid).encoding(MediaType.APPLICATION_JSON) |
UKHomeOffice/email-api | src/main/java/uk/gov/homeoffice/emailapi/service/TemplatedEmailSenderImpl.java | // Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmail.java
// @ApiModel(description = "Enough information to populate and send and email based on a template")
// @JsonDeserialize(as = TemplatedEmailImpl.class)
// @JsonSerialize(as = TemplatedEmailImpl.class)
// public interface TemplatedEmail {
// @ApiModelProperty(value = "Sender of the email in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// String getSender();
//
// @ApiModelProperty(value = "Subject of the email", required = true)
// String getSubject();
//
// @ApiModelProperty(value = "If a recipient uses HTML to view their they will see this template", required = true)
// String getHtmlTemplate();
//
// @ApiModelProperty(value = "If a recipient uses TXT to view their they will see this template", required = true)
// String getTextTemplate();
//
// @ApiModelProperty(value = "Variables to pass to both templates with string keys, and any JSON Number, String, Array, Object as the value ", required = true)
// Map<String, Object> getVariables();
//
// @ApiModelProperty(value = "Array of recipients in an array of strings in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// Collection<String> getRecipients();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/TemplatedEmailFactory.java
// public interface TemplatedEmailFactory {
// Email build(TemplatedEmail templatedEmail)
// throws EmailException, TemplatePopulatorParsingException, TemplatePopulatorIOException,
// InternetAddressParsingException;
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParsingException.java
// public class InternetAddressParsingException extends Exception {
// public InternetAddressParsingException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorIOException.java
// public class TemplatePopulatorIOException extends Exception {
// public TemplatePopulatorIOException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorParsingException.java
// public class TemplatePopulatorParsingException extends Exception {
// public TemplatePopulatorParsingException(Throwable cause) {
// super(cause);
// }
//
// public TemplatePopulatorParsingException(String message) {
// super(message);
// }
// }
| import org.apache.commons.mail.EmailException;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmail;
import uk.gov.homeoffice.emailapi.templatedemailfactory.TemplatedEmailFactory;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParsingException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorIOException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorParsingException; | package uk.gov.homeoffice.emailapi.service;
public class TemplatedEmailSenderImpl implements TemplatedEmailSender {
private final TemplatedEmailFactory templatedEmailFactory;
public TemplatedEmailSenderImpl(TemplatedEmailFactory templatedEmailFactory) {
this.templatedEmailFactory = templatedEmailFactory;
}
@Override | // Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmail.java
// @ApiModel(description = "Enough information to populate and send and email based on a template")
// @JsonDeserialize(as = TemplatedEmailImpl.class)
// @JsonSerialize(as = TemplatedEmailImpl.class)
// public interface TemplatedEmail {
// @ApiModelProperty(value = "Sender of the email in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// String getSender();
//
// @ApiModelProperty(value = "Subject of the email", required = true)
// String getSubject();
//
// @ApiModelProperty(value = "If a recipient uses HTML to view their they will see this template", required = true)
// String getHtmlTemplate();
//
// @ApiModelProperty(value = "If a recipient uses TXT to view their they will see this template", required = true)
// String getTextTemplate();
//
// @ApiModelProperty(value = "Variables to pass to both templates with string keys, and any JSON Number, String, Array, Object as the value ", required = true)
// Map<String, Object> getVariables();
//
// @ApiModelProperty(value = "Array of recipients in an array of strings in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// Collection<String> getRecipients();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/TemplatedEmailFactory.java
// public interface TemplatedEmailFactory {
// Email build(TemplatedEmail templatedEmail)
// throws EmailException, TemplatePopulatorParsingException, TemplatePopulatorIOException,
// InternetAddressParsingException;
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParsingException.java
// public class InternetAddressParsingException extends Exception {
// public InternetAddressParsingException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorIOException.java
// public class TemplatePopulatorIOException extends Exception {
// public TemplatePopulatorIOException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorParsingException.java
// public class TemplatePopulatorParsingException extends Exception {
// public TemplatePopulatorParsingException(Throwable cause) {
// super(cause);
// }
//
// public TemplatePopulatorParsingException(String message) {
// super(message);
// }
// }
// Path: src/main/java/uk/gov/homeoffice/emailapi/service/TemplatedEmailSenderImpl.java
import org.apache.commons.mail.EmailException;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmail;
import uk.gov.homeoffice.emailapi.templatedemailfactory.TemplatedEmailFactory;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParsingException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorIOException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorParsingException;
package uk.gov.homeoffice.emailapi.service;
public class TemplatedEmailSenderImpl implements TemplatedEmailSender {
private final TemplatedEmailFactory templatedEmailFactory;
public TemplatedEmailSenderImpl(TemplatedEmailFactory templatedEmailFactory) {
this.templatedEmailFactory = templatedEmailFactory;
}
@Override | public void sendEmail(TemplatedEmail templatedEmail) |
UKHomeOffice/email-api | src/main/java/uk/gov/homeoffice/emailapi/service/TemplatedEmailSenderImpl.java | // Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmail.java
// @ApiModel(description = "Enough information to populate and send and email based on a template")
// @JsonDeserialize(as = TemplatedEmailImpl.class)
// @JsonSerialize(as = TemplatedEmailImpl.class)
// public interface TemplatedEmail {
// @ApiModelProperty(value = "Sender of the email in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// String getSender();
//
// @ApiModelProperty(value = "Subject of the email", required = true)
// String getSubject();
//
// @ApiModelProperty(value = "If a recipient uses HTML to view their they will see this template", required = true)
// String getHtmlTemplate();
//
// @ApiModelProperty(value = "If a recipient uses TXT to view their they will see this template", required = true)
// String getTextTemplate();
//
// @ApiModelProperty(value = "Variables to pass to both templates with string keys, and any JSON Number, String, Array, Object as the value ", required = true)
// Map<String, Object> getVariables();
//
// @ApiModelProperty(value = "Array of recipients in an array of strings in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// Collection<String> getRecipients();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/TemplatedEmailFactory.java
// public interface TemplatedEmailFactory {
// Email build(TemplatedEmail templatedEmail)
// throws EmailException, TemplatePopulatorParsingException, TemplatePopulatorIOException,
// InternetAddressParsingException;
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParsingException.java
// public class InternetAddressParsingException extends Exception {
// public InternetAddressParsingException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorIOException.java
// public class TemplatePopulatorIOException extends Exception {
// public TemplatePopulatorIOException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorParsingException.java
// public class TemplatePopulatorParsingException extends Exception {
// public TemplatePopulatorParsingException(Throwable cause) {
// super(cause);
// }
//
// public TemplatePopulatorParsingException(String message) {
// super(message);
// }
// }
| import org.apache.commons.mail.EmailException;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmail;
import uk.gov.homeoffice.emailapi.templatedemailfactory.TemplatedEmailFactory;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParsingException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorIOException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorParsingException; | package uk.gov.homeoffice.emailapi.service;
public class TemplatedEmailSenderImpl implements TemplatedEmailSender {
private final TemplatedEmailFactory templatedEmailFactory;
public TemplatedEmailSenderImpl(TemplatedEmailFactory templatedEmailFactory) {
this.templatedEmailFactory = templatedEmailFactory;
}
@Override
public void sendEmail(TemplatedEmail templatedEmail) | // Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmail.java
// @ApiModel(description = "Enough information to populate and send and email based on a template")
// @JsonDeserialize(as = TemplatedEmailImpl.class)
// @JsonSerialize(as = TemplatedEmailImpl.class)
// public interface TemplatedEmail {
// @ApiModelProperty(value = "Sender of the email in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// String getSender();
//
// @ApiModelProperty(value = "Subject of the email", required = true)
// String getSubject();
//
// @ApiModelProperty(value = "If a recipient uses HTML to view their they will see this template", required = true)
// String getHtmlTemplate();
//
// @ApiModelProperty(value = "If a recipient uses TXT to view their they will see this template", required = true)
// String getTextTemplate();
//
// @ApiModelProperty(value = "Variables to pass to both templates with string keys, and any JSON Number, String, Array, Object as the value ", required = true)
// Map<String, Object> getVariables();
//
// @ApiModelProperty(value = "Array of recipients in an array of strings in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// Collection<String> getRecipients();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/TemplatedEmailFactory.java
// public interface TemplatedEmailFactory {
// Email build(TemplatedEmail templatedEmail)
// throws EmailException, TemplatePopulatorParsingException, TemplatePopulatorIOException,
// InternetAddressParsingException;
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParsingException.java
// public class InternetAddressParsingException extends Exception {
// public InternetAddressParsingException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorIOException.java
// public class TemplatePopulatorIOException extends Exception {
// public TemplatePopulatorIOException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorParsingException.java
// public class TemplatePopulatorParsingException extends Exception {
// public TemplatePopulatorParsingException(Throwable cause) {
// super(cause);
// }
//
// public TemplatePopulatorParsingException(String message) {
// super(message);
// }
// }
// Path: src/main/java/uk/gov/homeoffice/emailapi/service/TemplatedEmailSenderImpl.java
import org.apache.commons.mail.EmailException;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmail;
import uk.gov.homeoffice.emailapi.templatedemailfactory.TemplatedEmailFactory;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParsingException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorIOException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorParsingException;
package uk.gov.homeoffice.emailapi.service;
public class TemplatedEmailSenderImpl implements TemplatedEmailSender {
private final TemplatedEmailFactory templatedEmailFactory;
public TemplatedEmailSenderImpl(TemplatedEmailFactory templatedEmailFactory) {
this.templatedEmailFactory = templatedEmailFactory;
}
@Override
public void sendEmail(TemplatedEmail templatedEmail) | throws EmailException, TemplatePopulatorParsingException, TemplatePopulatorIOException, |
UKHomeOffice/email-api | src/main/java/uk/gov/homeoffice/emailapi/service/TemplatedEmailSenderImpl.java | // Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmail.java
// @ApiModel(description = "Enough information to populate and send and email based on a template")
// @JsonDeserialize(as = TemplatedEmailImpl.class)
// @JsonSerialize(as = TemplatedEmailImpl.class)
// public interface TemplatedEmail {
// @ApiModelProperty(value = "Sender of the email in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// String getSender();
//
// @ApiModelProperty(value = "Subject of the email", required = true)
// String getSubject();
//
// @ApiModelProperty(value = "If a recipient uses HTML to view their they will see this template", required = true)
// String getHtmlTemplate();
//
// @ApiModelProperty(value = "If a recipient uses TXT to view their they will see this template", required = true)
// String getTextTemplate();
//
// @ApiModelProperty(value = "Variables to pass to both templates with string keys, and any JSON Number, String, Array, Object as the value ", required = true)
// Map<String, Object> getVariables();
//
// @ApiModelProperty(value = "Array of recipients in an array of strings in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// Collection<String> getRecipients();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/TemplatedEmailFactory.java
// public interface TemplatedEmailFactory {
// Email build(TemplatedEmail templatedEmail)
// throws EmailException, TemplatePopulatorParsingException, TemplatePopulatorIOException,
// InternetAddressParsingException;
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParsingException.java
// public class InternetAddressParsingException extends Exception {
// public InternetAddressParsingException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorIOException.java
// public class TemplatePopulatorIOException extends Exception {
// public TemplatePopulatorIOException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorParsingException.java
// public class TemplatePopulatorParsingException extends Exception {
// public TemplatePopulatorParsingException(Throwable cause) {
// super(cause);
// }
//
// public TemplatePopulatorParsingException(String message) {
// super(message);
// }
// }
| import org.apache.commons.mail.EmailException;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmail;
import uk.gov.homeoffice.emailapi.templatedemailfactory.TemplatedEmailFactory;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParsingException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorIOException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorParsingException; | package uk.gov.homeoffice.emailapi.service;
public class TemplatedEmailSenderImpl implements TemplatedEmailSender {
private final TemplatedEmailFactory templatedEmailFactory;
public TemplatedEmailSenderImpl(TemplatedEmailFactory templatedEmailFactory) {
this.templatedEmailFactory = templatedEmailFactory;
}
@Override
public void sendEmail(TemplatedEmail templatedEmail) | // Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmail.java
// @ApiModel(description = "Enough information to populate and send and email based on a template")
// @JsonDeserialize(as = TemplatedEmailImpl.class)
// @JsonSerialize(as = TemplatedEmailImpl.class)
// public interface TemplatedEmail {
// @ApiModelProperty(value = "Sender of the email in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// String getSender();
//
// @ApiModelProperty(value = "Subject of the email", required = true)
// String getSubject();
//
// @ApiModelProperty(value = "If a recipient uses HTML to view their they will see this template", required = true)
// String getHtmlTemplate();
//
// @ApiModelProperty(value = "If a recipient uses TXT to view their they will see this template", required = true)
// String getTextTemplate();
//
// @ApiModelProperty(value = "Variables to pass to both templates with string keys, and any JSON Number, String, Array, Object as the value ", required = true)
// Map<String, Object> getVariables();
//
// @ApiModelProperty(value = "Array of recipients in an array of strings in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// Collection<String> getRecipients();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/TemplatedEmailFactory.java
// public interface TemplatedEmailFactory {
// Email build(TemplatedEmail templatedEmail)
// throws EmailException, TemplatePopulatorParsingException, TemplatePopulatorIOException,
// InternetAddressParsingException;
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParsingException.java
// public class InternetAddressParsingException extends Exception {
// public InternetAddressParsingException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorIOException.java
// public class TemplatePopulatorIOException extends Exception {
// public TemplatePopulatorIOException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorParsingException.java
// public class TemplatePopulatorParsingException extends Exception {
// public TemplatePopulatorParsingException(Throwable cause) {
// super(cause);
// }
//
// public TemplatePopulatorParsingException(String message) {
// super(message);
// }
// }
// Path: src/main/java/uk/gov/homeoffice/emailapi/service/TemplatedEmailSenderImpl.java
import org.apache.commons.mail.EmailException;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmail;
import uk.gov.homeoffice.emailapi.templatedemailfactory.TemplatedEmailFactory;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParsingException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorIOException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorParsingException;
package uk.gov.homeoffice.emailapi.service;
public class TemplatedEmailSenderImpl implements TemplatedEmailSender {
private final TemplatedEmailFactory templatedEmailFactory;
public TemplatedEmailSenderImpl(TemplatedEmailFactory templatedEmailFactory) {
this.templatedEmailFactory = templatedEmailFactory;
}
@Override
public void sendEmail(TemplatedEmail templatedEmail) | throws EmailException, TemplatePopulatorParsingException, TemplatePopulatorIOException, |
UKHomeOffice/email-api | src/main/java/uk/gov/homeoffice/emailapi/service/TemplatedEmailSenderImpl.java | // Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmail.java
// @ApiModel(description = "Enough information to populate and send and email based on a template")
// @JsonDeserialize(as = TemplatedEmailImpl.class)
// @JsonSerialize(as = TemplatedEmailImpl.class)
// public interface TemplatedEmail {
// @ApiModelProperty(value = "Sender of the email in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// String getSender();
//
// @ApiModelProperty(value = "Subject of the email", required = true)
// String getSubject();
//
// @ApiModelProperty(value = "If a recipient uses HTML to view their they will see this template", required = true)
// String getHtmlTemplate();
//
// @ApiModelProperty(value = "If a recipient uses TXT to view their they will see this template", required = true)
// String getTextTemplate();
//
// @ApiModelProperty(value = "Variables to pass to both templates with string keys, and any JSON Number, String, Array, Object as the value ", required = true)
// Map<String, Object> getVariables();
//
// @ApiModelProperty(value = "Array of recipients in an array of strings in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// Collection<String> getRecipients();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/TemplatedEmailFactory.java
// public interface TemplatedEmailFactory {
// Email build(TemplatedEmail templatedEmail)
// throws EmailException, TemplatePopulatorParsingException, TemplatePopulatorIOException,
// InternetAddressParsingException;
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParsingException.java
// public class InternetAddressParsingException extends Exception {
// public InternetAddressParsingException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorIOException.java
// public class TemplatePopulatorIOException extends Exception {
// public TemplatePopulatorIOException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorParsingException.java
// public class TemplatePopulatorParsingException extends Exception {
// public TemplatePopulatorParsingException(Throwable cause) {
// super(cause);
// }
//
// public TemplatePopulatorParsingException(String message) {
// super(message);
// }
// }
| import org.apache.commons.mail.EmailException;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmail;
import uk.gov.homeoffice.emailapi.templatedemailfactory.TemplatedEmailFactory;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParsingException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorIOException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorParsingException; | package uk.gov.homeoffice.emailapi.service;
public class TemplatedEmailSenderImpl implements TemplatedEmailSender {
private final TemplatedEmailFactory templatedEmailFactory;
public TemplatedEmailSenderImpl(TemplatedEmailFactory templatedEmailFactory) {
this.templatedEmailFactory = templatedEmailFactory;
}
@Override
public void sendEmail(TemplatedEmail templatedEmail)
throws EmailException, TemplatePopulatorParsingException, TemplatePopulatorIOException, | // Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmail.java
// @ApiModel(description = "Enough information to populate and send and email based on a template")
// @JsonDeserialize(as = TemplatedEmailImpl.class)
// @JsonSerialize(as = TemplatedEmailImpl.class)
// public interface TemplatedEmail {
// @ApiModelProperty(value = "Sender of the email in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// String getSender();
//
// @ApiModelProperty(value = "Subject of the email", required = true)
// String getSubject();
//
// @ApiModelProperty(value = "If a recipient uses HTML to view their they will see this template", required = true)
// String getHtmlTemplate();
//
// @ApiModelProperty(value = "If a recipient uses TXT to view their they will see this template", required = true)
// String getTextTemplate();
//
// @ApiModelProperty(value = "Variables to pass to both templates with string keys, and any JSON Number, String, Array, Object as the value ", required = true)
// Map<String, Object> getVariables();
//
// @ApiModelProperty(value = "Array of recipients in an array of strings in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// Collection<String> getRecipients();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/TemplatedEmailFactory.java
// public interface TemplatedEmailFactory {
// Email build(TemplatedEmail templatedEmail)
// throws EmailException, TemplatePopulatorParsingException, TemplatePopulatorIOException,
// InternetAddressParsingException;
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParsingException.java
// public class InternetAddressParsingException extends Exception {
// public InternetAddressParsingException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorIOException.java
// public class TemplatePopulatorIOException extends Exception {
// public TemplatePopulatorIOException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorParsingException.java
// public class TemplatePopulatorParsingException extends Exception {
// public TemplatePopulatorParsingException(Throwable cause) {
// super(cause);
// }
//
// public TemplatePopulatorParsingException(String message) {
// super(message);
// }
// }
// Path: src/main/java/uk/gov/homeoffice/emailapi/service/TemplatedEmailSenderImpl.java
import org.apache.commons.mail.EmailException;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmail;
import uk.gov.homeoffice.emailapi.templatedemailfactory.TemplatedEmailFactory;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParsingException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorIOException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorParsingException;
package uk.gov.homeoffice.emailapi.service;
public class TemplatedEmailSenderImpl implements TemplatedEmailSender {
private final TemplatedEmailFactory templatedEmailFactory;
public TemplatedEmailSenderImpl(TemplatedEmailFactory templatedEmailFactory) {
this.templatedEmailFactory = templatedEmailFactory;
}
@Override
public void sendEmail(TemplatedEmail templatedEmail)
throws EmailException, TemplatePopulatorParsingException, TemplatePopulatorIOException, | InternetAddressParsingException { |
UKHomeOffice/email-api | src/main/java/uk/gov/homeoffice/emailapi/resources/EmailSendingResource.java | // Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmail.java
// @ApiModel(description = "Enough information to populate and send and email based on a template")
// @JsonDeserialize(as = TemplatedEmailImpl.class)
// @JsonSerialize(as = TemplatedEmailImpl.class)
// public interface TemplatedEmail {
// @ApiModelProperty(value = "Sender of the email in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// String getSender();
//
// @ApiModelProperty(value = "Subject of the email", required = true)
// String getSubject();
//
// @ApiModelProperty(value = "If a recipient uses HTML to view their they will see this template", required = true)
// String getHtmlTemplate();
//
// @ApiModelProperty(value = "If a recipient uses TXT to view their they will see this template", required = true)
// String getTextTemplate();
//
// @ApiModelProperty(value = "Variables to pass to both templates with string keys, and any JSON Number, String, Array, Object as the value ", required = true)
// Map<String, Object> getVariables();
//
// @ApiModelProperty(value = "Array of recipients in an array of strings in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// Collection<String> getRecipients();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/service/TemplatedEmailSender.java
// public interface TemplatedEmailSender {
// void sendEmail(TemplatedEmail templatedEmail)
// throws EmailException, TemplatePopulatorParsingException, TemplatePopulatorIOException,
// InternetAddressParsingException;
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParsingException.java
// public class InternetAddressParsingException extends Exception {
// public InternetAddressParsingException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorIOException.java
// public class TemplatePopulatorIOException extends Exception {
// public TemplatePopulatorIOException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorParsingException.java
// public class TemplatePopulatorParsingException extends Exception {
// public TemplatePopulatorParsingException(Throwable cause) {
// super(cause);
// }
//
// public TemplatePopulatorParsingException(String message) {
// super(message);
// }
// }
| import com.codahale.metrics.annotation.Timed;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
import org.apache.commons.mail.EmailException;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmail;
import uk.gov.homeoffice.emailapi.service.TemplatedEmailSender;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParsingException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorIOException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorParsingException;
import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType; | package uk.gov.homeoffice.emailapi.resources;
@Path("/outbound")
@Api("/outbound")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class EmailSendingResource {
| // Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmail.java
// @ApiModel(description = "Enough information to populate and send and email based on a template")
// @JsonDeserialize(as = TemplatedEmailImpl.class)
// @JsonSerialize(as = TemplatedEmailImpl.class)
// public interface TemplatedEmail {
// @ApiModelProperty(value = "Sender of the email in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// String getSender();
//
// @ApiModelProperty(value = "Subject of the email", required = true)
// String getSubject();
//
// @ApiModelProperty(value = "If a recipient uses HTML to view their they will see this template", required = true)
// String getHtmlTemplate();
//
// @ApiModelProperty(value = "If a recipient uses TXT to view their they will see this template", required = true)
// String getTextTemplate();
//
// @ApiModelProperty(value = "Variables to pass to both templates with string keys, and any JSON Number, String, Array, Object as the value ", required = true)
// Map<String, Object> getVariables();
//
// @ApiModelProperty(value = "Array of recipients in an array of strings in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// Collection<String> getRecipients();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/service/TemplatedEmailSender.java
// public interface TemplatedEmailSender {
// void sendEmail(TemplatedEmail templatedEmail)
// throws EmailException, TemplatePopulatorParsingException, TemplatePopulatorIOException,
// InternetAddressParsingException;
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParsingException.java
// public class InternetAddressParsingException extends Exception {
// public InternetAddressParsingException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorIOException.java
// public class TemplatePopulatorIOException extends Exception {
// public TemplatePopulatorIOException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorParsingException.java
// public class TemplatePopulatorParsingException extends Exception {
// public TemplatePopulatorParsingException(Throwable cause) {
// super(cause);
// }
//
// public TemplatePopulatorParsingException(String message) {
// super(message);
// }
// }
// Path: src/main/java/uk/gov/homeoffice/emailapi/resources/EmailSendingResource.java
import com.codahale.metrics.annotation.Timed;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
import org.apache.commons.mail.EmailException;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmail;
import uk.gov.homeoffice.emailapi.service.TemplatedEmailSender;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParsingException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorIOException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorParsingException;
import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
package uk.gov.homeoffice.emailapi.resources;
@Path("/outbound")
@Api("/outbound")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class EmailSendingResource {
| private final TemplatedEmailSender templatedEmailSender; |
UKHomeOffice/email-api | src/main/java/uk/gov/homeoffice/emailapi/resources/EmailSendingResource.java | // Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmail.java
// @ApiModel(description = "Enough information to populate and send and email based on a template")
// @JsonDeserialize(as = TemplatedEmailImpl.class)
// @JsonSerialize(as = TemplatedEmailImpl.class)
// public interface TemplatedEmail {
// @ApiModelProperty(value = "Sender of the email in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// String getSender();
//
// @ApiModelProperty(value = "Subject of the email", required = true)
// String getSubject();
//
// @ApiModelProperty(value = "If a recipient uses HTML to view their they will see this template", required = true)
// String getHtmlTemplate();
//
// @ApiModelProperty(value = "If a recipient uses TXT to view their they will see this template", required = true)
// String getTextTemplate();
//
// @ApiModelProperty(value = "Variables to pass to both templates with string keys, and any JSON Number, String, Array, Object as the value ", required = true)
// Map<String, Object> getVariables();
//
// @ApiModelProperty(value = "Array of recipients in an array of strings in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// Collection<String> getRecipients();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/service/TemplatedEmailSender.java
// public interface TemplatedEmailSender {
// void sendEmail(TemplatedEmail templatedEmail)
// throws EmailException, TemplatePopulatorParsingException, TemplatePopulatorIOException,
// InternetAddressParsingException;
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParsingException.java
// public class InternetAddressParsingException extends Exception {
// public InternetAddressParsingException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorIOException.java
// public class TemplatePopulatorIOException extends Exception {
// public TemplatePopulatorIOException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorParsingException.java
// public class TemplatePopulatorParsingException extends Exception {
// public TemplatePopulatorParsingException(Throwable cause) {
// super(cause);
// }
//
// public TemplatePopulatorParsingException(String message) {
// super(message);
// }
// }
| import com.codahale.metrics.annotation.Timed;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
import org.apache.commons.mail.EmailException;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmail;
import uk.gov.homeoffice.emailapi.service.TemplatedEmailSender;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParsingException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorIOException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorParsingException;
import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType; | package uk.gov.homeoffice.emailapi.resources;
@Path("/outbound")
@Api("/outbound")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class EmailSendingResource {
private final TemplatedEmailSender templatedEmailSender;
public EmailSendingResource(TemplatedEmailSender templatedEmailSender) {
this.templatedEmailSender = templatedEmailSender;
}
@ApiResponses(value = {@ApiResponse(code = 204, message = "Successfully sent"),
@ApiResponse(code = 442, message = "Posted entity is not valid in some way (See message for details)"),
@ApiResponse(code = 500, message = "Email failed to send")})
@POST
@Timed
@ApiOperation("Send an email based on a template")
public void sendEmail( | // Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmail.java
// @ApiModel(description = "Enough information to populate and send and email based on a template")
// @JsonDeserialize(as = TemplatedEmailImpl.class)
// @JsonSerialize(as = TemplatedEmailImpl.class)
// public interface TemplatedEmail {
// @ApiModelProperty(value = "Sender of the email in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// String getSender();
//
// @ApiModelProperty(value = "Subject of the email", required = true)
// String getSubject();
//
// @ApiModelProperty(value = "If a recipient uses HTML to view their they will see this template", required = true)
// String getHtmlTemplate();
//
// @ApiModelProperty(value = "If a recipient uses TXT to view their they will see this template", required = true)
// String getTextTemplate();
//
// @ApiModelProperty(value = "Variables to pass to both templates with string keys, and any JSON Number, String, Array, Object as the value ", required = true)
// Map<String, Object> getVariables();
//
// @ApiModelProperty(value = "Array of recipients in an array of strings in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// Collection<String> getRecipients();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/service/TemplatedEmailSender.java
// public interface TemplatedEmailSender {
// void sendEmail(TemplatedEmail templatedEmail)
// throws EmailException, TemplatePopulatorParsingException, TemplatePopulatorIOException,
// InternetAddressParsingException;
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParsingException.java
// public class InternetAddressParsingException extends Exception {
// public InternetAddressParsingException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorIOException.java
// public class TemplatePopulatorIOException extends Exception {
// public TemplatePopulatorIOException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorParsingException.java
// public class TemplatePopulatorParsingException extends Exception {
// public TemplatePopulatorParsingException(Throwable cause) {
// super(cause);
// }
//
// public TemplatePopulatorParsingException(String message) {
// super(message);
// }
// }
// Path: src/main/java/uk/gov/homeoffice/emailapi/resources/EmailSendingResource.java
import com.codahale.metrics.annotation.Timed;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
import org.apache.commons.mail.EmailException;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmail;
import uk.gov.homeoffice.emailapi.service.TemplatedEmailSender;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParsingException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorIOException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorParsingException;
import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
package uk.gov.homeoffice.emailapi.resources;
@Path("/outbound")
@Api("/outbound")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class EmailSendingResource {
private final TemplatedEmailSender templatedEmailSender;
public EmailSendingResource(TemplatedEmailSender templatedEmailSender) {
this.templatedEmailSender = templatedEmailSender;
}
@ApiResponses(value = {@ApiResponse(code = 204, message = "Successfully sent"),
@ApiResponse(code = 442, message = "Posted entity is not valid in some way (See message for details)"),
@ApiResponse(code = 500, message = "Email failed to send")})
@POST
@Timed
@ApiOperation("Send an email based on a template")
public void sendEmail( | @ApiParam("Email template and params") @Valid TemplatedEmail templatedEmail) |
UKHomeOffice/email-api | src/main/java/uk/gov/homeoffice/emailapi/resources/EmailSendingResource.java | // Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmail.java
// @ApiModel(description = "Enough information to populate and send and email based on a template")
// @JsonDeserialize(as = TemplatedEmailImpl.class)
// @JsonSerialize(as = TemplatedEmailImpl.class)
// public interface TemplatedEmail {
// @ApiModelProperty(value = "Sender of the email in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// String getSender();
//
// @ApiModelProperty(value = "Subject of the email", required = true)
// String getSubject();
//
// @ApiModelProperty(value = "If a recipient uses HTML to view their they will see this template", required = true)
// String getHtmlTemplate();
//
// @ApiModelProperty(value = "If a recipient uses TXT to view their they will see this template", required = true)
// String getTextTemplate();
//
// @ApiModelProperty(value = "Variables to pass to both templates with string keys, and any JSON Number, String, Array, Object as the value ", required = true)
// Map<String, Object> getVariables();
//
// @ApiModelProperty(value = "Array of recipients in an array of strings in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// Collection<String> getRecipients();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/service/TemplatedEmailSender.java
// public interface TemplatedEmailSender {
// void sendEmail(TemplatedEmail templatedEmail)
// throws EmailException, TemplatePopulatorParsingException, TemplatePopulatorIOException,
// InternetAddressParsingException;
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParsingException.java
// public class InternetAddressParsingException extends Exception {
// public InternetAddressParsingException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorIOException.java
// public class TemplatePopulatorIOException extends Exception {
// public TemplatePopulatorIOException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorParsingException.java
// public class TemplatePopulatorParsingException extends Exception {
// public TemplatePopulatorParsingException(Throwable cause) {
// super(cause);
// }
//
// public TemplatePopulatorParsingException(String message) {
// super(message);
// }
// }
| import com.codahale.metrics.annotation.Timed;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
import org.apache.commons.mail.EmailException;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmail;
import uk.gov.homeoffice.emailapi.service.TemplatedEmailSender;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParsingException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorIOException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorParsingException;
import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType; | package uk.gov.homeoffice.emailapi.resources;
@Path("/outbound")
@Api("/outbound")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class EmailSendingResource {
private final TemplatedEmailSender templatedEmailSender;
public EmailSendingResource(TemplatedEmailSender templatedEmailSender) {
this.templatedEmailSender = templatedEmailSender;
}
@ApiResponses(value = {@ApiResponse(code = 204, message = "Successfully sent"),
@ApiResponse(code = 442, message = "Posted entity is not valid in some way (See message for details)"),
@ApiResponse(code = 500, message = "Email failed to send")})
@POST
@Timed
@ApiOperation("Send an email based on a template")
public void sendEmail(
@ApiParam("Email template and params") @Valid TemplatedEmail templatedEmail) | // Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmail.java
// @ApiModel(description = "Enough information to populate and send and email based on a template")
// @JsonDeserialize(as = TemplatedEmailImpl.class)
// @JsonSerialize(as = TemplatedEmailImpl.class)
// public interface TemplatedEmail {
// @ApiModelProperty(value = "Sender of the email in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// String getSender();
//
// @ApiModelProperty(value = "Subject of the email", required = true)
// String getSubject();
//
// @ApiModelProperty(value = "If a recipient uses HTML to view their they will see this template", required = true)
// String getHtmlTemplate();
//
// @ApiModelProperty(value = "If a recipient uses TXT to view their they will see this template", required = true)
// String getTextTemplate();
//
// @ApiModelProperty(value = "Variables to pass to both templates with string keys, and any JSON Number, String, Array, Object as the value ", required = true)
// Map<String, Object> getVariables();
//
// @ApiModelProperty(value = "Array of recipients in an array of strings in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// Collection<String> getRecipients();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/service/TemplatedEmailSender.java
// public interface TemplatedEmailSender {
// void sendEmail(TemplatedEmail templatedEmail)
// throws EmailException, TemplatePopulatorParsingException, TemplatePopulatorIOException,
// InternetAddressParsingException;
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParsingException.java
// public class InternetAddressParsingException extends Exception {
// public InternetAddressParsingException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorIOException.java
// public class TemplatePopulatorIOException extends Exception {
// public TemplatePopulatorIOException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorParsingException.java
// public class TemplatePopulatorParsingException extends Exception {
// public TemplatePopulatorParsingException(Throwable cause) {
// super(cause);
// }
//
// public TemplatePopulatorParsingException(String message) {
// super(message);
// }
// }
// Path: src/main/java/uk/gov/homeoffice/emailapi/resources/EmailSendingResource.java
import com.codahale.metrics.annotation.Timed;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
import org.apache.commons.mail.EmailException;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmail;
import uk.gov.homeoffice.emailapi.service.TemplatedEmailSender;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParsingException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorIOException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorParsingException;
import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
package uk.gov.homeoffice.emailapi.resources;
@Path("/outbound")
@Api("/outbound")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class EmailSendingResource {
private final TemplatedEmailSender templatedEmailSender;
public EmailSendingResource(TemplatedEmailSender templatedEmailSender) {
this.templatedEmailSender = templatedEmailSender;
}
@ApiResponses(value = {@ApiResponse(code = 204, message = "Successfully sent"),
@ApiResponse(code = 442, message = "Posted entity is not valid in some way (See message for details)"),
@ApiResponse(code = 500, message = "Email failed to send")})
@POST
@Timed
@ApiOperation("Send an email based on a template")
public void sendEmail(
@ApiParam("Email template and params") @Valid TemplatedEmail templatedEmail) | throws EmailException, TemplatePopulatorParsingException, TemplatePopulatorIOException, |
UKHomeOffice/email-api | src/main/java/uk/gov/homeoffice/emailapi/resources/EmailSendingResource.java | // Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmail.java
// @ApiModel(description = "Enough information to populate and send and email based on a template")
// @JsonDeserialize(as = TemplatedEmailImpl.class)
// @JsonSerialize(as = TemplatedEmailImpl.class)
// public interface TemplatedEmail {
// @ApiModelProperty(value = "Sender of the email in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// String getSender();
//
// @ApiModelProperty(value = "Subject of the email", required = true)
// String getSubject();
//
// @ApiModelProperty(value = "If a recipient uses HTML to view their they will see this template", required = true)
// String getHtmlTemplate();
//
// @ApiModelProperty(value = "If a recipient uses TXT to view their they will see this template", required = true)
// String getTextTemplate();
//
// @ApiModelProperty(value = "Variables to pass to both templates with string keys, and any JSON Number, String, Array, Object as the value ", required = true)
// Map<String, Object> getVariables();
//
// @ApiModelProperty(value = "Array of recipients in an array of strings in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// Collection<String> getRecipients();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/service/TemplatedEmailSender.java
// public interface TemplatedEmailSender {
// void sendEmail(TemplatedEmail templatedEmail)
// throws EmailException, TemplatePopulatorParsingException, TemplatePopulatorIOException,
// InternetAddressParsingException;
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParsingException.java
// public class InternetAddressParsingException extends Exception {
// public InternetAddressParsingException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorIOException.java
// public class TemplatePopulatorIOException extends Exception {
// public TemplatePopulatorIOException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorParsingException.java
// public class TemplatePopulatorParsingException extends Exception {
// public TemplatePopulatorParsingException(Throwable cause) {
// super(cause);
// }
//
// public TemplatePopulatorParsingException(String message) {
// super(message);
// }
// }
| import com.codahale.metrics.annotation.Timed;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
import org.apache.commons.mail.EmailException;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmail;
import uk.gov.homeoffice.emailapi.service.TemplatedEmailSender;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParsingException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorIOException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorParsingException;
import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType; | package uk.gov.homeoffice.emailapi.resources;
@Path("/outbound")
@Api("/outbound")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class EmailSendingResource {
private final TemplatedEmailSender templatedEmailSender;
public EmailSendingResource(TemplatedEmailSender templatedEmailSender) {
this.templatedEmailSender = templatedEmailSender;
}
@ApiResponses(value = {@ApiResponse(code = 204, message = "Successfully sent"),
@ApiResponse(code = 442, message = "Posted entity is not valid in some way (See message for details)"),
@ApiResponse(code = 500, message = "Email failed to send")})
@POST
@Timed
@ApiOperation("Send an email based on a template")
public void sendEmail(
@ApiParam("Email template and params") @Valid TemplatedEmail templatedEmail) | // Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmail.java
// @ApiModel(description = "Enough information to populate and send and email based on a template")
// @JsonDeserialize(as = TemplatedEmailImpl.class)
// @JsonSerialize(as = TemplatedEmailImpl.class)
// public interface TemplatedEmail {
// @ApiModelProperty(value = "Sender of the email in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// String getSender();
//
// @ApiModelProperty(value = "Subject of the email", required = true)
// String getSubject();
//
// @ApiModelProperty(value = "If a recipient uses HTML to view their they will see this template", required = true)
// String getHtmlTemplate();
//
// @ApiModelProperty(value = "If a recipient uses TXT to view their they will see this template", required = true)
// String getTextTemplate();
//
// @ApiModelProperty(value = "Variables to pass to both templates with string keys, and any JSON Number, String, Array, Object as the value ", required = true)
// Map<String, Object> getVariables();
//
// @ApiModelProperty(value = "Array of recipients in an array of strings in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// Collection<String> getRecipients();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/service/TemplatedEmailSender.java
// public interface TemplatedEmailSender {
// void sendEmail(TemplatedEmail templatedEmail)
// throws EmailException, TemplatePopulatorParsingException, TemplatePopulatorIOException,
// InternetAddressParsingException;
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParsingException.java
// public class InternetAddressParsingException extends Exception {
// public InternetAddressParsingException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorIOException.java
// public class TemplatePopulatorIOException extends Exception {
// public TemplatePopulatorIOException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorParsingException.java
// public class TemplatePopulatorParsingException extends Exception {
// public TemplatePopulatorParsingException(Throwable cause) {
// super(cause);
// }
//
// public TemplatePopulatorParsingException(String message) {
// super(message);
// }
// }
// Path: src/main/java/uk/gov/homeoffice/emailapi/resources/EmailSendingResource.java
import com.codahale.metrics.annotation.Timed;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
import org.apache.commons.mail.EmailException;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmail;
import uk.gov.homeoffice.emailapi.service.TemplatedEmailSender;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParsingException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorIOException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorParsingException;
import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
package uk.gov.homeoffice.emailapi.resources;
@Path("/outbound")
@Api("/outbound")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class EmailSendingResource {
private final TemplatedEmailSender templatedEmailSender;
public EmailSendingResource(TemplatedEmailSender templatedEmailSender) {
this.templatedEmailSender = templatedEmailSender;
}
@ApiResponses(value = {@ApiResponse(code = 204, message = "Successfully sent"),
@ApiResponse(code = 442, message = "Posted entity is not valid in some way (See message for details)"),
@ApiResponse(code = 500, message = "Email failed to send")})
@POST
@Timed
@ApiOperation("Send an email based on a template")
public void sendEmail(
@ApiParam("Email template and params") @Valid TemplatedEmail templatedEmail) | throws EmailException, TemplatePopulatorParsingException, TemplatePopulatorIOException, |
UKHomeOffice/email-api | src/main/java/uk/gov/homeoffice/emailapi/resources/EmailSendingResource.java | // Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmail.java
// @ApiModel(description = "Enough information to populate and send and email based on a template")
// @JsonDeserialize(as = TemplatedEmailImpl.class)
// @JsonSerialize(as = TemplatedEmailImpl.class)
// public interface TemplatedEmail {
// @ApiModelProperty(value = "Sender of the email in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// String getSender();
//
// @ApiModelProperty(value = "Subject of the email", required = true)
// String getSubject();
//
// @ApiModelProperty(value = "If a recipient uses HTML to view their they will see this template", required = true)
// String getHtmlTemplate();
//
// @ApiModelProperty(value = "If a recipient uses TXT to view their they will see this template", required = true)
// String getTextTemplate();
//
// @ApiModelProperty(value = "Variables to pass to both templates with string keys, and any JSON Number, String, Array, Object as the value ", required = true)
// Map<String, Object> getVariables();
//
// @ApiModelProperty(value = "Array of recipients in an array of strings in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// Collection<String> getRecipients();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/service/TemplatedEmailSender.java
// public interface TemplatedEmailSender {
// void sendEmail(TemplatedEmail templatedEmail)
// throws EmailException, TemplatePopulatorParsingException, TemplatePopulatorIOException,
// InternetAddressParsingException;
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParsingException.java
// public class InternetAddressParsingException extends Exception {
// public InternetAddressParsingException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorIOException.java
// public class TemplatePopulatorIOException extends Exception {
// public TemplatePopulatorIOException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorParsingException.java
// public class TemplatePopulatorParsingException extends Exception {
// public TemplatePopulatorParsingException(Throwable cause) {
// super(cause);
// }
//
// public TemplatePopulatorParsingException(String message) {
// super(message);
// }
// }
| import com.codahale.metrics.annotation.Timed;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
import org.apache.commons.mail.EmailException;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmail;
import uk.gov.homeoffice.emailapi.service.TemplatedEmailSender;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParsingException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorIOException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorParsingException;
import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType; | package uk.gov.homeoffice.emailapi.resources;
@Path("/outbound")
@Api("/outbound")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class EmailSendingResource {
private final TemplatedEmailSender templatedEmailSender;
public EmailSendingResource(TemplatedEmailSender templatedEmailSender) {
this.templatedEmailSender = templatedEmailSender;
}
@ApiResponses(value = {@ApiResponse(code = 204, message = "Successfully sent"),
@ApiResponse(code = 442, message = "Posted entity is not valid in some way (See message for details)"),
@ApiResponse(code = 500, message = "Email failed to send")})
@POST
@Timed
@ApiOperation("Send an email based on a template")
public void sendEmail(
@ApiParam("Email template and params") @Valid TemplatedEmail templatedEmail)
throws EmailException, TemplatePopulatorParsingException, TemplatePopulatorIOException, | // Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmail.java
// @ApiModel(description = "Enough information to populate and send and email based on a template")
// @JsonDeserialize(as = TemplatedEmailImpl.class)
// @JsonSerialize(as = TemplatedEmailImpl.class)
// public interface TemplatedEmail {
// @ApiModelProperty(value = "Sender of the email in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// String getSender();
//
// @ApiModelProperty(value = "Subject of the email", required = true)
// String getSubject();
//
// @ApiModelProperty(value = "If a recipient uses HTML to view their they will see this template", required = true)
// String getHtmlTemplate();
//
// @ApiModelProperty(value = "If a recipient uses TXT to view their they will see this template", required = true)
// String getTextTemplate();
//
// @ApiModelProperty(value = "Variables to pass to both templates with string keys, and any JSON Number, String, Array, Object as the value ", required = true)
// Map<String, Object> getVariables();
//
// @ApiModelProperty(value = "Array of recipients in an array of strings in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// Collection<String> getRecipients();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/service/TemplatedEmailSender.java
// public interface TemplatedEmailSender {
// void sendEmail(TemplatedEmail templatedEmail)
// throws EmailException, TemplatePopulatorParsingException, TemplatePopulatorIOException,
// InternetAddressParsingException;
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParsingException.java
// public class InternetAddressParsingException extends Exception {
// public InternetAddressParsingException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorIOException.java
// public class TemplatePopulatorIOException extends Exception {
// public TemplatePopulatorIOException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulatorParsingException.java
// public class TemplatePopulatorParsingException extends Exception {
// public TemplatePopulatorParsingException(Throwable cause) {
// super(cause);
// }
//
// public TemplatePopulatorParsingException(String message) {
// super(message);
// }
// }
// Path: src/main/java/uk/gov/homeoffice/emailapi/resources/EmailSendingResource.java
import com.codahale.metrics.annotation.Timed;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
import org.apache.commons.mail.EmailException;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmail;
import uk.gov.homeoffice.emailapi.service.TemplatedEmailSender;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParsingException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorIOException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulatorParsingException;
import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
package uk.gov.homeoffice.emailapi.resources;
@Path("/outbound")
@Api("/outbound")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class EmailSendingResource {
private final TemplatedEmailSender templatedEmailSender;
public EmailSendingResource(TemplatedEmailSender templatedEmailSender) {
this.templatedEmailSender = templatedEmailSender;
}
@ApiResponses(value = {@ApiResponse(code = 204, message = "Successfully sent"),
@ApiResponse(code = 442, message = "Posted entity is not valid in some way (See message for details)"),
@ApiResponse(code = 500, message = "Email failed to send")})
@POST
@Timed
@ApiOperation("Send an email based on a template")
public void sendEmail(
@ApiParam("Email template and params") @Valid TemplatedEmail templatedEmail)
throws EmailException, TemplatePopulatorParsingException, TemplatePopulatorIOException, | InternetAddressParsingException { |
UKHomeOffice/email-api | src/test/java/uk/gov/homeoffice/emailapi/templatedemailfactory/TemplatedEmailFactoryImplTest.java | // Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmail.java
// @ApiModel(description = "Enough information to populate and send and email based on a template")
// @JsonDeserialize(as = TemplatedEmailImpl.class)
// @JsonSerialize(as = TemplatedEmailImpl.class)
// public interface TemplatedEmail {
// @ApiModelProperty(value = "Sender of the email in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// String getSender();
//
// @ApiModelProperty(value = "Subject of the email", required = true)
// String getSubject();
//
// @ApiModelProperty(value = "If a recipient uses HTML to view their they will see this template", required = true)
// String getHtmlTemplate();
//
// @ApiModelProperty(value = "If a recipient uses TXT to view their they will see this template", required = true)
// String getTextTemplate();
//
// @ApiModelProperty(value = "Variables to pass to both templates with string keys, and any JSON Number, String, Array, Object as the value ", required = true)
// Map<String, Object> getVariables();
//
// @ApiModelProperty(value = "Array of recipients in an array of strings in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// Collection<String> getRecipients();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmailImpl.java
// public class TemplatedEmailImpl implements TemplatedEmail {
//
// @JsonProperty @NotEmpty private final Collection<String> recipients;
//
// @JsonProperty @Email private final String sender;
//
// @JsonProperty @NotEmpty private final String subject;
//
// @JsonProperty @NotEmpty private final String htmlTemplate;
//
// @JsonProperty private final Map<String, Object> variables;
//
// @JsonProperty @NotEmpty private final String textTemplate;
//
// @JsonCreator
// public TemplatedEmailImpl(@JsonProperty("recipients") Collection<String> recipients,
// @JsonProperty("sender") String sender, @JsonProperty("subject") String subject,
// @JsonProperty("htmlTemplate") String htmlTemplate,
// @JsonProperty("variables") final Map<String, Object> variables,
// @JsonProperty("textTemplate") String textTemplate) {
//
// this.recipients = recipients;
// this.sender = sender;
// this.subject = subject;
// this.htmlTemplate = htmlTemplate;
// this.variables = variables;
// this.textTemplate = textTemplate;
// }
//
// @Override
// public String getSender() {
// return sender;
// }
//
// @Override
// public String getSubject() {
// return subject;
// }
//
// @Override
// public String getHtmlTemplate() {
// return htmlTemplate;
// }
//
// @Override
// public String getTextTemplate() {
// return textTemplate;
// }
//
// @Override
// public Map<String, Object> getVariables() {
// return variables;
// }
//
// @Override
// public Collection<String> getRecipients() {
// return recipients;
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParser.java
// public interface InternetAddressParser {
//
// Collection<InternetAddress> getInternetAddresses(Collection<String> unparsedRecipients)
// throws InternetAddressParsingException;
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParsingException.java
// public class InternetAddressParsingException extends Exception {
// public InternetAddressParsingException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/serverconfig/HtmlEmailFactory.java
// public interface HtmlEmailFactory {
// HtmlEmail getHtmlEmail();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulator.java
// public interface TemplatePopulator {
// String populateTemplate(String template, Map<String, Object> variables)
// throws TemplatePopulatorIOException, TemplatePopulatorParsingException;
// }
| import org.apache.commons.mail.HtmlEmail;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Matchers;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmail;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmailImpl;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParser;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParsingException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.serverconfig.HtmlEmailFactory;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulator;
import javax.mail.internet.InternetAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.mockito.Mockito.*; | package uk.gov.homeoffice.emailapi.templatedemailfactory;
public class TemplatedEmailFactoryImplTest {
public static final String TEMPLATE_CONTENTS = "Template Contents"; | // Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmail.java
// @ApiModel(description = "Enough information to populate and send and email based on a template")
// @JsonDeserialize(as = TemplatedEmailImpl.class)
// @JsonSerialize(as = TemplatedEmailImpl.class)
// public interface TemplatedEmail {
// @ApiModelProperty(value = "Sender of the email in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// String getSender();
//
// @ApiModelProperty(value = "Subject of the email", required = true)
// String getSubject();
//
// @ApiModelProperty(value = "If a recipient uses HTML to view their they will see this template", required = true)
// String getHtmlTemplate();
//
// @ApiModelProperty(value = "If a recipient uses TXT to view their they will see this template", required = true)
// String getTextTemplate();
//
// @ApiModelProperty(value = "Variables to pass to both templates with string keys, and any JSON Number, String, Array, Object as the value ", required = true)
// Map<String, Object> getVariables();
//
// @ApiModelProperty(value = "Array of recipients in an array of strings in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// Collection<String> getRecipients();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmailImpl.java
// public class TemplatedEmailImpl implements TemplatedEmail {
//
// @JsonProperty @NotEmpty private final Collection<String> recipients;
//
// @JsonProperty @Email private final String sender;
//
// @JsonProperty @NotEmpty private final String subject;
//
// @JsonProperty @NotEmpty private final String htmlTemplate;
//
// @JsonProperty private final Map<String, Object> variables;
//
// @JsonProperty @NotEmpty private final String textTemplate;
//
// @JsonCreator
// public TemplatedEmailImpl(@JsonProperty("recipients") Collection<String> recipients,
// @JsonProperty("sender") String sender, @JsonProperty("subject") String subject,
// @JsonProperty("htmlTemplate") String htmlTemplate,
// @JsonProperty("variables") final Map<String, Object> variables,
// @JsonProperty("textTemplate") String textTemplate) {
//
// this.recipients = recipients;
// this.sender = sender;
// this.subject = subject;
// this.htmlTemplate = htmlTemplate;
// this.variables = variables;
// this.textTemplate = textTemplate;
// }
//
// @Override
// public String getSender() {
// return sender;
// }
//
// @Override
// public String getSubject() {
// return subject;
// }
//
// @Override
// public String getHtmlTemplate() {
// return htmlTemplate;
// }
//
// @Override
// public String getTextTemplate() {
// return textTemplate;
// }
//
// @Override
// public Map<String, Object> getVariables() {
// return variables;
// }
//
// @Override
// public Collection<String> getRecipients() {
// return recipients;
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParser.java
// public interface InternetAddressParser {
//
// Collection<InternetAddress> getInternetAddresses(Collection<String> unparsedRecipients)
// throws InternetAddressParsingException;
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParsingException.java
// public class InternetAddressParsingException extends Exception {
// public InternetAddressParsingException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/serverconfig/HtmlEmailFactory.java
// public interface HtmlEmailFactory {
// HtmlEmail getHtmlEmail();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulator.java
// public interface TemplatePopulator {
// String populateTemplate(String template, Map<String, Object> variables)
// throws TemplatePopulatorIOException, TemplatePopulatorParsingException;
// }
// Path: src/test/java/uk/gov/homeoffice/emailapi/templatedemailfactory/TemplatedEmailFactoryImplTest.java
import org.apache.commons.mail.HtmlEmail;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Matchers;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmail;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmailImpl;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParser;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParsingException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.serverconfig.HtmlEmailFactory;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulator;
import javax.mail.internet.InternetAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.mockito.Mockito.*;
package uk.gov.homeoffice.emailapi.templatedemailfactory;
public class TemplatedEmailFactoryImplTest {
public static final String TEMPLATE_CONTENTS = "Template Contents"; | private TemplatePopulator templatePopulator; |
UKHomeOffice/email-api | src/test/java/uk/gov/homeoffice/emailapi/templatedemailfactory/TemplatedEmailFactoryImplTest.java | // Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmail.java
// @ApiModel(description = "Enough information to populate and send and email based on a template")
// @JsonDeserialize(as = TemplatedEmailImpl.class)
// @JsonSerialize(as = TemplatedEmailImpl.class)
// public interface TemplatedEmail {
// @ApiModelProperty(value = "Sender of the email in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// String getSender();
//
// @ApiModelProperty(value = "Subject of the email", required = true)
// String getSubject();
//
// @ApiModelProperty(value = "If a recipient uses HTML to view their they will see this template", required = true)
// String getHtmlTemplate();
//
// @ApiModelProperty(value = "If a recipient uses TXT to view their they will see this template", required = true)
// String getTextTemplate();
//
// @ApiModelProperty(value = "Variables to pass to both templates with string keys, and any JSON Number, String, Array, Object as the value ", required = true)
// Map<String, Object> getVariables();
//
// @ApiModelProperty(value = "Array of recipients in an array of strings in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// Collection<String> getRecipients();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmailImpl.java
// public class TemplatedEmailImpl implements TemplatedEmail {
//
// @JsonProperty @NotEmpty private final Collection<String> recipients;
//
// @JsonProperty @Email private final String sender;
//
// @JsonProperty @NotEmpty private final String subject;
//
// @JsonProperty @NotEmpty private final String htmlTemplate;
//
// @JsonProperty private final Map<String, Object> variables;
//
// @JsonProperty @NotEmpty private final String textTemplate;
//
// @JsonCreator
// public TemplatedEmailImpl(@JsonProperty("recipients") Collection<String> recipients,
// @JsonProperty("sender") String sender, @JsonProperty("subject") String subject,
// @JsonProperty("htmlTemplate") String htmlTemplate,
// @JsonProperty("variables") final Map<String, Object> variables,
// @JsonProperty("textTemplate") String textTemplate) {
//
// this.recipients = recipients;
// this.sender = sender;
// this.subject = subject;
// this.htmlTemplate = htmlTemplate;
// this.variables = variables;
// this.textTemplate = textTemplate;
// }
//
// @Override
// public String getSender() {
// return sender;
// }
//
// @Override
// public String getSubject() {
// return subject;
// }
//
// @Override
// public String getHtmlTemplate() {
// return htmlTemplate;
// }
//
// @Override
// public String getTextTemplate() {
// return textTemplate;
// }
//
// @Override
// public Map<String, Object> getVariables() {
// return variables;
// }
//
// @Override
// public Collection<String> getRecipients() {
// return recipients;
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParser.java
// public interface InternetAddressParser {
//
// Collection<InternetAddress> getInternetAddresses(Collection<String> unparsedRecipients)
// throws InternetAddressParsingException;
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParsingException.java
// public class InternetAddressParsingException extends Exception {
// public InternetAddressParsingException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/serverconfig/HtmlEmailFactory.java
// public interface HtmlEmailFactory {
// HtmlEmail getHtmlEmail();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulator.java
// public interface TemplatePopulator {
// String populateTemplate(String template, Map<String, Object> variables)
// throws TemplatePopulatorIOException, TemplatePopulatorParsingException;
// }
| import org.apache.commons.mail.HtmlEmail;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Matchers;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmail;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmailImpl;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParser;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParsingException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.serverconfig.HtmlEmailFactory;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulator;
import javax.mail.internet.InternetAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.mockito.Mockito.*; | package uk.gov.homeoffice.emailapi.templatedemailfactory;
public class TemplatedEmailFactoryImplTest {
public static final String TEMPLATE_CONTENTS = "Template Contents";
private TemplatePopulator templatePopulator;
private ArrayList<InternetAddress> internetAddresses;
private TemplatedEmailFactoryImpl templatedEmailFactory;
@Before | // Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmail.java
// @ApiModel(description = "Enough information to populate and send and email based on a template")
// @JsonDeserialize(as = TemplatedEmailImpl.class)
// @JsonSerialize(as = TemplatedEmailImpl.class)
// public interface TemplatedEmail {
// @ApiModelProperty(value = "Sender of the email in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// String getSender();
//
// @ApiModelProperty(value = "Subject of the email", required = true)
// String getSubject();
//
// @ApiModelProperty(value = "If a recipient uses HTML to view their they will see this template", required = true)
// String getHtmlTemplate();
//
// @ApiModelProperty(value = "If a recipient uses TXT to view their they will see this template", required = true)
// String getTextTemplate();
//
// @ApiModelProperty(value = "Variables to pass to both templates with string keys, and any JSON Number, String, Array, Object as the value ", required = true)
// Map<String, Object> getVariables();
//
// @ApiModelProperty(value = "Array of recipients in an array of strings in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// Collection<String> getRecipients();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmailImpl.java
// public class TemplatedEmailImpl implements TemplatedEmail {
//
// @JsonProperty @NotEmpty private final Collection<String> recipients;
//
// @JsonProperty @Email private final String sender;
//
// @JsonProperty @NotEmpty private final String subject;
//
// @JsonProperty @NotEmpty private final String htmlTemplate;
//
// @JsonProperty private final Map<String, Object> variables;
//
// @JsonProperty @NotEmpty private final String textTemplate;
//
// @JsonCreator
// public TemplatedEmailImpl(@JsonProperty("recipients") Collection<String> recipients,
// @JsonProperty("sender") String sender, @JsonProperty("subject") String subject,
// @JsonProperty("htmlTemplate") String htmlTemplate,
// @JsonProperty("variables") final Map<String, Object> variables,
// @JsonProperty("textTemplate") String textTemplate) {
//
// this.recipients = recipients;
// this.sender = sender;
// this.subject = subject;
// this.htmlTemplate = htmlTemplate;
// this.variables = variables;
// this.textTemplate = textTemplate;
// }
//
// @Override
// public String getSender() {
// return sender;
// }
//
// @Override
// public String getSubject() {
// return subject;
// }
//
// @Override
// public String getHtmlTemplate() {
// return htmlTemplate;
// }
//
// @Override
// public String getTextTemplate() {
// return textTemplate;
// }
//
// @Override
// public Map<String, Object> getVariables() {
// return variables;
// }
//
// @Override
// public Collection<String> getRecipients() {
// return recipients;
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParser.java
// public interface InternetAddressParser {
//
// Collection<InternetAddress> getInternetAddresses(Collection<String> unparsedRecipients)
// throws InternetAddressParsingException;
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParsingException.java
// public class InternetAddressParsingException extends Exception {
// public InternetAddressParsingException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/serverconfig/HtmlEmailFactory.java
// public interface HtmlEmailFactory {
// HtmlEmail getHtmlEmail();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulator.java
// public interface TemplatePopulator {
// String populateTemplate(String template, Map<String, Object> variables)
// throws TemplatePopulatorIOException, TemplatePopulatorParsingException;
// }
// Path: src/test/java/uk/gov/homeoffice/emailapi/templatedemailfactory/TemplatedEmailFactoryImplTest.java
import org.apache.commons.mail.HtmlEmail;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Matchers;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmail;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmailImpl;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParser;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParsingException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.serverconfig.HtmlEmailFactory;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulator;
import javax.mail.internet.InternetAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.mockito.Mockito.*;
package uk.gov.homeoffice.emailapi.templatedemailfactory;
public class TemplatedEmailFactoryImplTest {
public static final String TEMPLATE_CONTENTS = "Template Contents";
private TemplatePopulator templatePopulator;
private ArrayList<InternetAddress> internetAddresses;
private TemplatedEmailFactoryImpl templatedEmailFactory;
@Before | public void setupSubject() throws InternetAddressParsingException { |
UKHomeOffice/email-api | src/test/java/uk/gov/homeoffice/emailapi/templatedemailfactory/TemplatedEmailFactoryImplTest.java | // Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmail.java
// @ApiModel(description = "Enough information to populate and send and email based on a template")
// @JsonDeserialize(as = TemplatedEmailImpl.class)
// @JsonSerialize(as = TemplatedEmailImpl.class)
// public interface TemplatedEmail {
// @ApiModelProperty(value = "Sender of the email in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// String getSender();
//
// @ApiModelProperty(value = "Subject of the email", required = true)
// String getSubject();
//
// @ApiModelProperty(value = "If a recipient uses HTML to view their they will see this template", required = true)
// String getHtmlTemplate();
//
// @ApiModelProperty(value = "If a recipient uses TXT to view their they will see this template", required = true)
// String getTextTemplate();
//
// @ApiModelProperty(value = "Variables to pass to both templates with string keys, and any JSON Number, String, Array, Object as the value ", required = true)
// Map<String, Object> getVariables();
//
// @ApiModelProperty(value = "Array of recipients in an array of strings in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// Collection<String> getRecipients();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmailImpl.java
// public class TemplatedEmailImpl implements TemplatedEmail {
//
// @JsonProperty @NotEmpty private final Collection<String> recipients;
//
// @JsonProperty @Email private final String sender;
//
// @JsonProperty @NotEmpty private final String subject;
//
// @JsonProperty @NotEmpty private final String htmlTemplate;
//
// @JsonProperty private final Map<String, Object> variables;
//
// @JsonProperty @NotEmpty private final String textTemplate;
//
// @JsonCreator
// public TemplatedEmailImpl(@JsonProperty("recipients") Collection<String> recipients,
// @JsonProperty("sender") String sender, @JsonProperty("subject") String subject,
// @JsonProperty("htmlTemplate") String htmlTemplate,
// @JsonProperty("variables") final Map<String, Object> variables,
// @JsonProperty("textTemplate") String textTemplate) {
//
// this.recipients = recipients;
// this.sender = sender;
// this.subject = subject;
// this.htmlTemplate = htmlTemplate;
// this.variables = variables;
// this.textTemplate = textTemplate;
// }
//
// @Override
// public String getSender() {
// return sender;
// }
//
// @Override
// public String getSubject() {
// return subject;
// }
//
// @Override
// public String getHtmlTemplate() {
// return htmlTemplate;
// }
//
// @Override
// public String getTextTemplate() {
// return textTemplate;
// }
//
// @Override
// public Map<String, Object> getVariables() {
// return variables;
// }
//
// @Override
// public Collection<String> getRecipients() {
// return recipients;
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParser.java
// public interface InternetAddressParser {
//
// Collection<InternetAddress> getInternetAddresses(Collection<String> unparsedRecipients)
// throws InternetAddressParsingException;
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParsingException.java
// public class InternetAddressParsingException extends Exception {
// public InternetAddressParsingException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/serverconfig/HtmlEmailFactory.java
// public interface HtmlEmailFactory {
// HtmlEmail getHtmlEmail();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulator.java
// public interface TemplatePopulator {
// String populateTemplate(String template, Map<String, Object> variables)
// throws TemplatePopulatorIOException, TemplatePopulatorParsingException;
// }
| import org.apache.commons.mail.HtmlEmail;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Matchers;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmail;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmailImpl;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParser;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParsingException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.serverconfig.HtmlEmailFactory;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulator;
import javax.mail.internet.InternetAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.mockito.Mockito.*; | package uk.gov.homeoffice.emailapi.templatedemailfactory;
public class TemplatedEmailFactoryImplTest {
public static final String TEMPLATE_CONTENTS = "Template Contents";
private TemplatePopulator templatePopulator;
private ArrayList<InternetAddress> internetAddresses;
private TemplatedEmailFactoryImpl templatedEmailFactory;
@Before
public void setupSubject() throws InternetAddressParsingException {
templatePopulator = mock(TemplatePopulator.class);
internetAddresses = new ArrayList<>();
| // Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmail.java
// @ApiModel(description = "Enough information to populate and send and email based on a template")
// @JsonDeserialize(as = TemplatedEmailImpl.class)
// @JsonSerialize(as = TemplatedEmailImpl.class)
// public interface TemplatedEmail {
// @ApiModelProperty(value = "Sender of the email in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// String getSender();
//
// @ApiModelProperty(value = "Subject of the email", required = true)
// String getSubject();
//
// @ApiModelProperty(value = "If a recipient uses HTML to view their they will see this template", required = true)
// String getHtmlTemplate();
//
// @ApiModelProperty(value = "If a recipient uses TXT to view their they will see this template", required = true)
// String getTextTemplate();
//
// @ApiModelProperty(value = "Variables to pass to both templates with string keys, and any JSON Number, String, Array, Object as the value ", required = true)
// Map<String, Object> getVariables();
//
// @ApiModelProperty(value = "Array of recipients in an array of strings in format \"example@example.org\" or \"Annie Example <annie@example.com>\"", required = true)
// Collection<String> getRecipients();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/entities/TemplatedEmailImpl.java
// public class TemplatedEmailImpl implements TemplatedEmail {
//
// @JsonProperty @NotEmpty private final Collection<String> recipients;
//
// @JsonProperty @Email private final String sender;
//
// @JsonProperty @NotEmpty private final String subject;
//
// @JsonProperty @NotEmpty private final String htmlTemplate;
//
// @JsonProperty private final Map<String, Object> variables;
//
// @JsonProperty @NotEmpty private final String textTemplate;
//
// @JsonCreator
// public TemplatedEmailImpl(@JsonProperty("recipients") Collection<String> recipients,
// @JsonProperty("sender") String sender, @JsonProperty("subject") String subject,
// @JsonProperty("htmlTemplate") String htmlTemplate,
// @JsonProperty("variables") final Map<String, Object> variables,
// @JsonProperty("textTemplate") String textTemplate) {
//
// this.recipients = recipients;
// this.sender = sender;
// this.subject = subject;
// this.htmlTemplate = htmlTemplate;
// this.variables = variables;
// this.textTemplate = textTemplate;
// }
//
// @Override
// public String getSender() {
// return sender;
// }
//
// @Override
// public String getSubject() {
// return subject;
// }
//
// @Override
// public String getHtmlTemplate() {
// return htmlTemplate;
// }
//
// @Override
// public String getTextTemplate() {
// return textTemplate;
// }
//
// @Override
// public Map<String, Object> getVariables() {
// return variables;
// }
//
// @Override
// public Collection<String> getRecipients() {
// return recipients;
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParser.java
// public interface InternetAddressParser {
//
// Collection<InternetAddress> getInternetAddresses(Collection<String> unparsedRecipients)
// throws InternetAddressParsingException;
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/addressparsing/InternetAddressParsingException.java
// public class InternetAddressParsingException extends Exception {
// public InternetAddressParsingException(final Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/serverconfig/HtmlEmailFactory.java
// public interface HtmlEmailFactory {
// HtmlEmail getHtmlEmail();
// }
//
// Path: src/main/java/uk/gov/homeoffice/emailapi/templatedemailfactory/templating/TemplatePopulator.java
// public interface TemplatePopulator {
// String populateTemplate(String template, Map<String, Object> variables)
// throws TemplatePopulatorIOException, TemplatePopulatorParsingException;
// }
// Path: src/test/java/uk/gov/homeoffice/emailapi/templatedemailfactory/TemplatedEmailFactoryImplTest.java
import org.apache.commons.mail.HtmlEmail;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Matchers;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmail;
import uk.gov.homeoffice.emailapi.entities.TemplatedEmailImpl;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParser;
import uk.gov.homeoffice.emailapi.templatedemailfactory.addressparsing.InternetAddressParsingException;
import uk.gov.homeoffice.emailapi.templatedemailfactory.serverconfig.HtmlEmailFactory;
import uk.gov.homeoffice.emailapi.templatedemailfactory.templating.TemplatePopulator;
import javax.mail.internet.InternetAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.mockito.Mockito.*;
package uk.gov.homeoffice.emailapi.templatedemailfactory;
public class TemplatedEmailFactoryImplTest {
public static final String TEMPLATE_CONTENTS = "Template Contents";
private TemplatePopulator templatePopulator;
private ArrayList<InternetAddress> internetAddresses;
private TemplatedEmailFactoryImpl templatedEmailFactory;
@Before
public void setupSubject() throws InternetAddressParsingException {
templatePopulator = mock(TemplatePopulator.class);
internetAddresses = new ArrayList<>();
| final InternetAddressParser internetAddressParser = mock(InternetAddressParser.class); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.