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
jadler-mocking/jadler
jadler-core/src/main/java/net/jadler/AbstractRequestMatching.java
// Path: jadler-core/src/main/java/net/jadler/matchers/BodyRequestMatcher.java // public static BodyRequestMatcher requestBody(final Matcher<? super String> pred) { // return new BodyRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/HeaderRequestMatcher.java // public static HeaderRequestMatcher requestHeader(final String headerName, // final Matcher<? super List<String>> pred) { // return new HeaderRequestMatcher(pred, headerName); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/MethodRequestMatcher.java // public static MethodRequestMatcher requestMethod(final Matcher<? super String> pred) { // return new MethodRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/ParameterRequestMatcher.java // public static ParameterRequestMatcher requestParameter(final String paramName, // final Matcher<? super List<String>> pred) { // return new ParameterRequestMatcher(pred, paramName); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/PathRequestMatcher.java // public static PathRequestMatcher requestPath(final Matcher<? super String> pred) { // return new PathRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/QueryStringRequestMatcher.java // public static QueryStringRequestMatcher requestQueryString(final Matcher<? super String> pred) { // return new QueryStringRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/RawBodyRequestMatcher.java // public static RawBodyRequestMatcher requestRawBody(final Matcher<byte[]> pred) { // return new RawBodyRequestMatcher(pred); // }
import org.apache.commons.lang.Validate; import org.hamcrest.Matcher; import java.util.ArrayList; import java.util.List; import static net.jadler.matchers.BodyRequestMatcher.requestBody; import static net.jadler.matchers.HeaderRequestMatcher.requestHeader; import static net.jadler.matchers.MethodRequestMatcher.requestMethod; import static net.jadler.matchers.ParameterRequestMatcher.requestParameter; import static net.jadler.matchers.PathRequestMatcher.requestPath; import static net.jadler.matchers.QueryStringRequestMatcher.requestQueryString; import static net.jadler.matchers.RawBodyRequestMatcher.requestRawBody; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalToIgnoringCase; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.notNullValue;
@SuppressWarnings("unchecked") public T havingParameters(final String... names) { for (final String name : names) { havingParameter(name); } return (T) this; } /** * {@inheritDoc} */ @Override public T havingHeaderEqualTo(final String name, final String value) { Validate.notNull(value, "value cannot be null"); return havingHeader(name, hasItem(value)); } /** * {@inheritDoc} */ @Override public T havingHeader(final String name, final Matcher<? super List<String>> predicate) { Validate.notEmpty(name, "name cannot be empty"); Validate.notNull(predicate, "predicate cannot be null");
// Path: jadler-core/src/main/java/net/jadler/matchers/BodyRequestMatcher.java // public static BodyRequestMatcher requestBody(final Matcher<? super String> pred) { // return new BodyRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/HeaderRequestMatcher.java // public static HeaderRequestMatcher requestHeader(final String headerName, // final Matcher<? super List<String>> pred) { // return new HeaderRequestMatcher(pred, headerName); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/MethodRequestMatcher.java // public static MethodRequestMatcher requestMethod(final Matcher<? super String> pred) { // return new MethodRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/ParameterRequestMatcher.java // public static ParameterRequestMatcher requestParameter(final String paramName, // final Matcher<? super List<String>> pred) { // return new ParameterRequestMatcher(pred, paramName); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/PathRequestMatcher.java // public static PathRequestMatcher requestPath(final Matcher<? super String> pred) { // return new PathRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/QueryStringRequestMatcher.java // public static QueryStringRequestMatcher requestQueryString(final Matcher<? super String> pred) { // return new QueryStringRequestMatcher(pred); // } // // Path: jadler-core/src/main/java/net/jadler/matchers/RawBodyRequestMatcher.java // public static RawBodyRequestMatcher requestRawBody(final Matcher<byte[]> pred) { // return new RawBodyRequestMatcher(pred); // } // Path: jadler-core/src/main/java/net/jadler/AbstractRequestMatching.java import org.apache.commons.lang.Validate; import org.hamcrest.Matcher; import java.util.ArrayList; import java.util.List; import static net.jadler.matchers.BodyRequestMatcher.requestBody; import static net.jadler.matchers.HeaderRequestMatcher.requestHeader; import static net.jadler.matchers.MethodRequestMatcher.requestMethod; import static net.jadler.matchers.ParameterRequestMatcher.requestParameter; import static net.jadler.matchers.PathRequestMatcher.requestPath; import static net.jadler.matchers.QueryStringRequestMatcher.requestQueryString; import static net.jadler.matchers.RawBodyRequestMatcher.requestRawBody; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalToIgnoringCase; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.notNullValue; @SuppressWarnings("unchecked") public T havingParameters(final String... names) { for (final String name : names) { havingParameter(name); } return (T) this; } /** * {@inheritDoc} */ @Override public T havingHeaderEqualTo(final String name, final String value) { Validate.notNull(value, "value cannot be null"); return havingHeader(name, hasItem(value)); } /** * {@inheritDoc} */ @Override public T havingHeader(final String name, final Matcher<? super List<String>> predicate) { Validate.notEmpty(name, "name cannot be empty"); Validate.notNull(predicate, "predicate cannot be null");
return that(requestHeader(name, predicate));
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/deprecated/DeprecatedDefaultsConfigurationTest.java
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadler() { // return initInternal(new JadlerMocker(getJettyServer())); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static byte[] rawBodyOf(final HttpResponse response) throws IOException { // return IOUtils.toByteArray(response.getEntity().getContent()); // }
import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.AfterClass; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.verifyThatRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static net.jadler.utils.TestUtils.rawBodyOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.Assert.fail;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.deprecated; /** * Tests that the deprecated way of configuring jadler defaults still works. */ public class DeprecatedDefaultsConfigurationTest { private static final int EXPECTED_STATUS = 409; private static final String EXPECTED_CONTENT_TYPE = "text/html; charset=UTF-8"; private static final Charset EXPECTED_ENCODING = Charset.forName("ISO-8859-2"); private static final String EXPECTED_HEADER_NAME = "default_header"; private static final String EXPECTED_HEADER_VALUE = "value"; private static final String STRING_WITH_DIACRITICS = "\u00e1\u0159\u017e"; private static final byte[] ISO_8859_2_REPRESENTATION = {(byte) 0xE1, (byte) 0xF8, (byte) 0xBE}; @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } /* * Tests that the deprecated way of setting response defaults using the {@code that()} clause still works */ @Test @SuppressWarnings("deprecation") public void ongoingConfiguration() throws IOException {
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadler() { // return initInternal(new JadlerMocker(getJettyServer())); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static byte[] rawBodyOf(final HttpResponse response) throws IOException { // return IOUtils.toByteArray(response.getEntity().getContent()); // } // Path: jadler-all/src/test/java/net/jadler/deprecated/DeprecatedDefaultsConfigurationTest.java import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.AfterClass; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.verifyThatRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static net.jadler.utils.TestUtils.rawBodyOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.Assert.fail; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.deprecated; /** * Tests that the deprecated way of configuring jadler defaults still works. */ public class DeprecatedDefaultsConfigurationTest { private static final int EXPECTED_STATUS = 409; private static final String EXPECTED_CONTENT_TYPE = "text/html; charset=UTF-8"; private static final Charset EXPECTED_ENCODING = Charset.forName("ISO-8859-2"); private static final String EXPECTED_HEADER_NAME = "default_header"; private static final String EXPECTED_HEADER_VALUE = "value"; private static final String STRING_WITH_DIACRITICS = "\u00e1\u0159\u017e"; private static final byte[] ISO_8859_2_REPRESENTATION = {(byte) 0xE1, (byte) 0xF8, (byte) 0xBE}; @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } /* * Tests that the deprecated way of setting response defaults using the {@code that()} clause still works */ @Test @SuppressWarnings("deprecation") public void ongoingConfiguration() throws IOException {
initJadler()
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/deprecated/DeprecatedDefaultsConfigurationTest.java
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadler() { // return initInternal(new JadlerMocker(getJettyServer())); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static byte[] rawBodyOf(final HttpResponse response) throws IOException { // return IOUtils.toByteArray(response.getEntity().getContent()); // }
import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.AfterClass; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.verifyThatRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static net.jadler.utils.TestUtils.rawBodyOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.Assert.fail;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.deprecated; /** * Tests that the deprecated way of configuring jadler defaults still works. */ public class DeprecatedDefaultsConfigurationTest { private static final int EXPECTED_STATUS = 409; private static final String EXPECTED_CONTENT_TYPE = "text/html; charset=UTF-8"; private static final Charset EXPECTED_ENCODING = Charset.forName("ISO-8859-2"); private static final String EXPECTED_HEADER_NAME = "default_header"; private static final String EXPECTED_HEADER_VALUE = "value"; private static final String STRING_WITH_DIACRITICS = "\u00e1\u0159\u017e"; private static final byte[] ISO_8859_2_REPRESENTATION = {(byte) 0xE1, (byte) 0xF8, (byte) 0xBE}; @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } /* * Tests that the deprecated way of setting response defaults using the {@code that()} clause still works */ @Test @SuppressWarnings("deprecation") public void ongoingConfiguration() throws IOException { initJadler() .that() .respondsWithDefaultStatus(EXPECTED_STATUS) .respondsWithDefaultContentType(EXPECTED_CONTENT_TYPE) .respondsWithDefaultEncoding(EXPECTED_ENCODING) .respondsWithDefaultHeader(EXPECTED_HEADER_NAME, EXPECTED_HEADER_VALUE); try {
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadler() { // return initInternal(new JadlerMocker(getJettyServer())); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static byte[] rawBodyOf(final HttpResponse response) throws IOException { // return IOUtils.toByteArray(response.getEntity().getContent()); // } // Path: jadler-all/src/test/java/net/jadler/deprecated/DeprecatedDefaultsConfigurationTest.java import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.AfterClass; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.verifyThatRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static net.jadler.utils.TestUtils.rawBodyOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.Assert.fail; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.deprecated; /** * Tests that the deprecated way of configuring jadler defaults still works. */ public class DeprecatedDefaultsConfigurationTest { private static final int EXPECTED_STATUS = 409; private static final String EXPECTED_CONTENT_TYPE = "text/html; charset=UTF-8"; private static final Charset EXPECTED_ENCODING = Charset.forName("ISO-8859-2"); private static final String EXPECTED_HEADER_NAME = "default_header"; private static final String EXPECTED_HEADER_VALUE = "value"; private static final String STRING_WITH_DIACRITICS = "\u00e1\u0159\u017e"; private static final byte[] ISO_8859_2_REPRESENTATION = {(byte) 0xE1, (byte) 0xF8, (byte) 0xBE}; @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } /* * Tests that the deprecated way of setting response defaults using the {@code that()} clause still works */ @Test @SuppressWarnings("deprecation") public void ongoingConfiguration() throws IOException { initJadler() .that() .respondsWithDefaultStatus(EXPECTED_STATUS) .respondsWithDefaultContentType(EXPECTED_CONTENT_TYPE) .respondsWithDefaultEncoding(EXPECTED_ENCODING) .respondsWithDefaultHeader(EXPECTED_HEADER_NAME, EXPECTED_HEADER_VALUE); try {
onRequest().respond().withBody(STRING_WITH_DIACRITICS);
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/deprecated/DeprecatedDefaultsConfigurationTest.java
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadler() { // return initInternal(new JadlerMocker(getJettyServer())); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static byte[] rawBodyOf(final HttpResponse response) throws IOException { // return IOUtils.toByteArray(response.getEntity().getContent()); // }
import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.AfterClass; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.verifyThatRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static net.jadler.utils.TestUtils.rawBodyOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.Assert.fail;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.deprecated; /** * Tests that the deprecated way of configuring jadler defaults still works. */ public class DeprecatedDefaultsConfigurationTest { private static final int EXPECTED_STATUS = 409; private static final String EXPECTED_CONTENT_TYPE = "text/html; charset=UTF-8"; private static final Charset EXPECTED_ENCODING = Charset.forName("ISO-8859-2"); private static final String EXPECTED_HEADER_NAME = "default_header"; private static final String EXPECTED_HEADER_VALUE = "value"; private static final String STRING_WITH_DIACRITICS = "\u00e1\u0159\u017e"; private static final byte[] ISO_8859_2_REPRESENTATION = {(byte) 0xE1, (byte) 0xF8, (byte) 0xBE}; @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } /* * Tests that the deprecated way of setting response defaults using the {@code that()} clause still works */ @Test @SuppressWarnings("deprecation") public void ongoingConfiguration() throws IOException { initJadler() .that() .respondsWithDefaultStatus(EXPECTED_STATUS) .respondsWithDefaultContentType(EXPECTED_CONTENT_TYPE) .respondsWithDefaultEncoding(EXPECTED_ENCODING) .respondsWithDefaultHeader(EXPECTED_HEADER_NAME, EXPECTED_HEADER_VALUE); try { onRequest().respond().withBody(STRING_WITH_DIACRITICS);
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadler() { // return initInternal(new JadlerMocker(getJettyServer())); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static byte[] rawBodyOf(final HttpResponse response) throws IOException { // return IOUtils.toByteArray(response.getEntity().getContent()); // } // Path: jadler-all/src/test/java/net/jadler/deprecated/DeprecatedDefaultsConfigurationTest.java import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.AfterClass; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.verifyThatRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static net.jadler.utils.TestUtils.rawBodyOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.Assert.fail; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.deprecated; /** * Tests that the deprecated way of configuring jadler defaults still works. */ public class DeprecatedDefaultsConfigurationTest { private static final int EXPECTED_STATUS = 409; private static final String EXPECTED_CONTENT_TYPE = "text/html; charset=UTF-8"; private static final Charset EXPECTED_ENCODING = Charset.forName("ISO-8859-2"); private static final String EXPECTED_HEADER_NAME = "default_header"; private static final String EXPECTED_HEADER_VALUE = "value"; private static final String STRING_WITH_DIACRITICS = "\u00e1\u0159\u017e"; private static final byte[] ISO_8859_2_REPRESENTATION = {(byte) 0xE1, (byte) 0xF8, (byte) 0xBE}; @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } /* * Tests that the deprecated way of setting response defaults using the {@code that()} clause still works */ @Test @SuppressWarnings("deprecation") public void ongoingConfiguration() throws IOException { initJadler() .that() .respondsWithDefaultStatus(EXPECTED_STATUS) .respondsWithDefaultContentType(EXPECTED_CONTENT_TYPE) .respondsWithDefaultEncoding(EXPECTED_ENCODING) .respondsWithDefaultHeader(EXPECTED_HEADER_NAME, EXPECTED_HEADER_VALUE); try { onRequest().respond().withBody(STRING_WITH_DIACRITICS);
final HttpResponse response = Executor.newInstance().execute(Request.Get(jadlerUri())).returnResponse();
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/deprecated/DeprecatedDefaultsConfigurationTest.java
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadler() { // return initInternal(new JadlerMocker(getJettyServer())); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static byte[] rawBodyOf(final HttpResponse response) throws IOException { // return IOUtils.toByteArray(response.getEntity().getContent()); // }
import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.AfterClass; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.verifyThatRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static net.jadler.utils.TestUtils.rawBodyOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.Assert.fail;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.deprecated; /** * Tests that the deprecated way of configuring jadler defaults still works. */ public class DeprecatedDefaultsConfigurationTest { private static final int EXPECTED_STATUS = 409; private static final String EXPECTED_CONTENT_TYPE = "text/html; charset=UTF-8"; private static final Charset EXPECTED_ENCODING = Charset.forName("ISO-8859-2"); private static final String EXPECTED_HEADER_NAME = "default_header"; private static final String EXPECTED_HEADER_VALUE = "value"; private static final String STRING_WITH_DIACRITICS = "\u00e1\u0159\u017e"; private static final byte[] ISO_8859_2_REPRESENTATION = {(byte) 0xE1, (byte) 0xF8, (byte) 0xBE}; @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } /* * Tests that the deprecated way of setting response defaults using the {@code that()} clause still works */ @Test @SuppressWarnings("deprecation") public void ongoingConfiguration() throws IOException { initJadler() .that() .respondsWithDefaultStatus(EXPECTED_STATUS) .respondsWithDefaultContentType(EXPECTED_CONTENT_TYPE) .respondsWithDefaultEncoding(EXPECTED_ENCODING) .respondsWithDefaultHeader(EXPECTED_HEADER_NAME, EXPECTED_HEADER_VALUE); try { onRequest().respond().withBody(STRING_WITH_DIACRITICS); final HttpResponse response = Executor.newInstance().execute(Request.Get(jadlerUri())).returnResponse(); assertThat(response.getStatusLine().getStatusCode(), is(EXPECTED_STATUS)); assertThat(response.getFirstHeader("Content-Type").getValue(), is(EXPECTED_CONTENT_TYPE)); assertThat(response.getFirstHeader(EXPECTED_HEADER_NAME).getValue(), is(EXPECTED_HEADER_VALUE));
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadler() { // return initInternal(new JadlerMocker(getJettyServer())); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static byte[] rawBodyOf(final HttpResponse response) throws IOException { // return IOUtils.toByteArray(response.getEntity().getContent()); // } // Path: jadler-all/src/test/java/net/jadler/deprecated/DeprecatedDefaultsConfigurationTest.java import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.AfterClass; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.verifyThatRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static net.jadler.utils.TestUtils.rawBodyOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.Assert.fail; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.deprecated; /** * Tests that the deprecated way of configuring jadler defaults still works. */ public class DeprecatedDefaultsConfigurationTest { private static final int EXPECTED_STATUS = 409; private static final String EXPECTED_CONTENT_TYPE = "text/html; charset=UTF-8"; private static final Charset EXPECTED_ENCODING = Charset.forName("ISO-8859-2"); private static final String EXPECTED_HEADER_NAME = "default_header"; private static final String EXPECTED_HEADER_VALUE = "value"; private static final String STRING_WITH_DIACRITICS = "\u00e1\u0159\u017e"; private static final byte[] ISO_8859_2_REPRESENTATION = {(byte) 0xE1, (byte) 0xF8, (byte) 0xBE}; @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } /* * Tests that the deprecated way of setting response defaults using the {@code that()} clause still works */ @Test @SuppressWarnings("deprecation") public void ongoingConfiguration() throws IOException { initJadler() .that() .respondsWithDefaultStatus(EXPECTED_STATUS) .respondsWithDefaultContentType(EXPECTED_CONTENT_TYPE) .respondsWithDefaultEncoding(EXPECTED_ENCODING) .respondsWithDefaultHeader(EXPECTED_HEADER_NAME, EXPECTED_HEADER_VALUE); try { onRequest().respond().withBody(STRING_WITH_DIACRITICS); final HttpResponse response = Executor.newInstance().execute(Request.Get(jadlerUri())).returnResponse(); assertThat(response.getStatusLine().getStatusCode(), is(EXPECTED_STATUS)); assertThat(response.getFirstHeader("Content-Type").getValue(), is(EXPECTED_CONTENT_TYPE)); assertThat(response.getFirstHeader(EXPECTED_HEADER_NAME).getValue(), is(EXPECTED_HEADER_VALUE));
assertThat(rawBodyOf(response), is(ISO_8859_2_REPRESENTATION));
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/deprecated/DeprecatedDefaultsConfigurationTest.java
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadler() { // return initInternal(new JadlerMocker(getJettyServer())); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static byte[] rawBodyOf(final HttpResponse response) throws IOException { // return IOUtils.toByteArray(response.getEntity().getContent()); // }
import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.AfterClass; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.verifyThatRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static net.jadler.utils.TestUtils.rawBodyOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.Assert.fail;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.deprecated; /** * Tests that the deprecated way of configuring jadler defaults still works. */ public class DeprecatedDefaultsConfigurationTest { private static final int EXPECTED_STATUS = 409; private static final String EXPECTED_CONTENT_TYPE = "text/html; charset=UTF-8"; private static final Charset EXPECTED_ENCODING = Charset.forName("ISO-8859-2"); private static final String EXPECTED_HEADER_NAME = "default_header"; private static final String EXPECTED_HEADER_VALUE = "value"; private static final String STRING_WITH_DIACRITICS = "\u00e1\u0159\u017e"; private static final byte[] ISO_8859_2_REPRESENTATION = {(byte) 0xE1, (byte) 0xF8, (byte) 0xBE}; @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } /* * Tests that the deprecated way of setting response defaults using the {@code that()} clause still works */ @Test @SuppressWarnings("deprecation") public void ongoingConfiguration() throws IOException { initJadler() .that() .respondsWithDefaultStatus(EXPECTED_STATUS) .respondsWithDefaultContentType(EXPECTED_CONTENT_TYPE) .respondsWithDefaultEncoding(EXPECTED_ENCODING) .respondsWithDefaultHeader(EXPECTED_HEADER_NAME, EXPECTED_HEADER_VALUE); try { onRequest().respond().withBody(STRING_WITH_DIACRITICS); final HttpResponse response = Executor.newInstance().execute(Request.Get(jadlerUri())).returnResponse(); assertThat(response.getStatusLine().getStatusCode(), is(EXPECTED_STATUS)); assertThat(response.getFirstHeader("Content-Type").getValue(), is(EXPECTED_CONTENT_TYPE)); assertThat(response.getFirstHeader(EXPECTED_HEADER_NAME).getValue(), is(EXPECTED_HEADER_VALUE)); assertThat(rawBodyOf(response), is(ISO_8859_2_REPRESENTATION)); } finally {
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadler() { // return initInternal(new JadlerMocker(getJettyServer())); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static byte[] rawBodyOf(final HttpResponse response) throws IOException { // return IOUtils.toByteArray(response.getEntity().getContent()); // } // Path: jadler-all/src/test/java/net/jadler/deprecated/DeprecatedDefaultsConfigurationTest.java import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.AfterClass; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.verifyThatRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static net.jadler.utils.TestUtils.rawBodyOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.Assert.fail; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.deprecated; /** * Tests that the deprecated way of configuring jadler defaults still works. */ public class DeprecatedDefaultsConfigurationTest { private static final int EXPECTED_STATUS = 409; private static final String EXPECTED_CONTENT_TYPE = "text/html; charset=UTF-8"; private static final Charset EXPECTED_ENCODING = Charset.forName("ISO-8859-2"); private static final String EXPECTED_HEADER_NAME = "default_header"; private static final String EXPECTED_HEADER_VALUE = "value"; private static final String STRING_WITH_DIACRITICS = "\u00e1\u0159\u017e"; private static final byte[] ISO_8859_2_REPRESENTATION = {(byte) 0xE1, (byte) 0xF8, (byte) 0xBE}; @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } /* * Tests that the deprecated way of setting response defaults using the {@code that()} clause still works */ @Test @SuppressWarnings("deprecation") public void ongoingConfiguration() throws IOException { initJadler() .that() .respondsWithDefaultStatus(EXPECTED_STATUS) .respondsWithDefaultContentType(EXPECTED_CONTENT_TYPE) .respondsWithDefaultEncoding(EXPECTED_ENCODING) .respondsWithDefaultHeader(EXPECTED_HEADER_NAME, EXPECTED_HEADER_VALUE); try { onRequest().respond().withBody(STRING_WITH_DIACRITICS); final HttpResponse response = Executor.newInstance().execute(Request.Get(jadlerUri())).returnResponse(); assertThat(response.getStatusLine().getStatusCode(), is(EXPECTED_STATUS)); assertThat(response.getFirstHeader("Content-Type").getValue(), is(EXPECTED_CONTENT_TYPE)); assertThat(response.getFirstHeader(EXPECTED_HEADER_NAME).getValue(), is(EXPECTED_HEADER_VALUE)); assertThat(rawBodyOf(response), is(ISO_8859_2_REPRESENTATION)); } finally {
closeJadler();
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/deprecated/DeprecatedDefaultsConfigurationTest.java
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadler() { // return initInternal(new JadlerMocker(getJettyServer())); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static byte[] rawBodyOf(final HttpResponse response) throws IOException { // return IOUtils.toByteArray(response.getEntity().getContent()); // }
import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.AfterClass; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.verifyThatRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static net.jadler.utils.TestUtils.rawBodyOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.Assert.fail;
.that() .respondsWithDefaultStatus(EXPECTED_STATUS) .respondsWithDefaultContentType(EXPECTED_CONTENT_TYPE) .respondsWithDefaultEncoding(EXPECTED_ENCODING) .respondsWithDefaultHeader(EXPECTED_HEADER_NAME, EXPECTED_HEADER_VALUE); try { onRequest().respond().withBody(STRING_WITH_DIACRITICS); final HttpResponse response = Executor.newInstance().execute(Request.Get(jadlerUri())).returnResponse(); assertThat(response.getStatusLine().getStatusCode(), is(EXPECTED_STATUS)); assertThat(response.getFirstHeader("Content-Type").getValue(), is(EXPECTED_CONTENT_TYPE)); assertThat(response.getFirstHeader(EXPECTED_HEADER_NAME).getValue(), is(EXPECTED_HEADER_VALUE)); assertThat(rawBodyOf(response), is(ISO_8859_2_REPRESENTATION)); } finally { closeJadler(); } } /* * Tests that the deprecated way of disabling requests recording using the {@code that()} clause still works */ @Test(expected = IllegalStateException.class) @SuppressWarnings("deprecation") public void ongoingConfiguration_skipsRequestRecording() throws IOException { initJadler().that().skipsRequestsRecording(); try {
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadler() { // return initInternal(new JadlerMocker(getJettyServer())); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static byte[] rawBodyOf(final HttpResponse response) throws IOException { // return IOUtils.toByteArray(response.getEntity().getContent()); // } // Path: jadler-all/src/test/java/net/jadler/deprecated/DeprecatedDefaultsConfigurationTest.java import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.AfterClass; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.verifyThatRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static net.jadler.utils.TestUtils.rawBodyOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.Assert.fail; .that() .respondsWithDefaultStatus(EXPECTED_STATUS) .respondsWithDefaultContentType(EXPECTED_CONTENT_TYPE) .respondsWithDefaultEncoding(EXPECTED_ENCODING) .respondsWithDefaultHeader(EXPECTED_HEADER_NAME, EXPECTED_HEADER_VALUE); try { onRequest().respond().withBody(STRING_WITH_DIACRITICS); final HttpResponse response = Executor.newInstance().execute(Request.Get(jadlerUri())).returnResponse(); assertThat(response.getStatusLine().getStatusCode(), is(EXPECTED_STATUS)); assertThat(response.getFirstHeader("Content-Type").getValue(), is(EXPECTED_CONTENT_TYPE)); assertThat(response.getFirstHeader(EXPECTED_HEADER_NAME).getValue(), is(EXPECTED_HEADER_VALUE)); assertThat(rawBodyOf(response), is(ISO_8859_2_REPRESENTATION)); } finally { closeJadler(); } } /* * Tests that the deprecated way of disabling requests recording using the {@code that()} clause still works */ @Test(expected = IllegalStateException.class) @SuppressWarnings("deprecation") public void ongoingConfiguration_skipsRequestRecording() throws IOException { initJadler().that().skipsRequestsRecording(); try {
verifyThatRequest();
jadler-mocking/jadler
jadler-core/src/test/java/net/jadler/stubbing/MutableStubResponseTest.java
// Path: jadler-core/src/main/java/net/jadler/KeyValues.java // public class KeyValues { // // /** // * An empty instance. // */ // public static final KeyValues EMPTY = new KeyValues(); // private final MultiMap values; // // // /** // * Creates new empty instance. // */ // public KeyValues() { // this.values = new MultiValueMap(); // } // // // /** // * Adds new key-value pair. Supports multi-values for one key (if there has already been added // * some value with this key, additional value is added instead of rewriting). Please note this method // * creates new instance containing all existing values plus the new one rather than modifying this instance. // * // * @param key key (cannot be empty) // * @param value value (cannot be {@code null}, however can be empty for valueless headers) // * @return an exact copy of this instance containing all existing values plus the new one // */ // @SuppressWarnings("unchecked") // public KeyValues add(final String key, final String value) { // Validate.notEmpty(key, "key cannot be empty"); // Validate.notNull(value, "value cannot be null, use an empty string instead"); // // final KeyValues res = new KeyValues(); // res.values.putAll(this.values); // res.values.put(key.toLowerCase(), value); // // return res; // } // // // /** // * Adds all values from the given instance. Supports multi-values for one key (if there has already been added // * some value with this key, additional value is added instead of rewriting). Please note this method // * creates new instance containing all existing values plus the new ones rather than modifying this instance. // * // * @param keyValues values to be added no(cannot be {@code null}) // * @return an exact copy of this instance containing all existing values plus the new ones // */ // @SuppressWarnings("unchecked") // public KeyValues addAll(final KeyValues keyValues) { // Validate.notNull(keyValues, "keyValues cannot be null"); // // final KeyValues res = new KeyValues(); // res.values.putAll(this.values); // res.values.putAll(keyValues.values); // return res; // } // // // /** // * Returns the first value for the given key // * // * @param key key (case insensitive) // * @return single (first) value for the given key or {@code null}, if there is no such a key in this instance // */ // public String getValue(final String key) { // Validate.notEmpty(key, "key cannot be empty"); // // final List<String> allValues = this.getValues(key); // return allValues != null ? allValues.get(0) : null; // } // // // /** // * Returns all values for the given key // * // * @param key key (case insensitive) // * @return all values of the given header or {@code null}, if there is no such a key in this instance // */ // public List<String> getValues(final String key) { // Validate.notEmpty(key, "name cannot be empty"); // // @SuppressWarnings("unchecked") final List<String> result = (List<String>) values.get(key.toLowerCase()); // return result == null || result.isEmpty() ? null : new ArrayList<String>(result); // } // // // /** // * @return all keys (lower-cased) from this instance (never returns {@code null}) // */ // public Set<String> getKeys() { // @SuppressWarnings("unchecked") final Set<String> result = new HashSet<String>(this.values.keySet()); // return result; // } // // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder(); // for (@SuppressWarnings("unchecked") final Iterator<Map.Entry<String, Collection<String>>> it // = this.values.entrySet().iterator(); it.hasNext(); ) { // final Map.Entry<String, Collection<String>> e = it.next(); // // for (final Iterator<String> it2 = e.getValue().iterator(); it2.hasNext(); ) { // sb.append(e.getKey()).append(": ").append(it2.next()); // if (it2.hasNext()) { // sb.append(", "); // } // } // // if (it.hasNext()) { // sb.append(", "); // } // } // // return sb.toString(); // } // // // @Override // public int hashCode() { // int hash = 5; // hash = 43 * hash + (this.values != null ? this.values.hashCode() : 0); // return hash; // } // // // @Override // public boolean equals(final Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final KeyValues other = (KeyValues) obj; // if (this.values != other.values && (this.values == null || !this.values.equals(other.values))) { // return false; // } // return true; // } // }
import net.jadler.KeyValues; import org.apache.commons.collections.MultiMap; import org.apache.commons.collections.map.MultiValueMap; import org.junit.Before; import org.junit.Test; import java.nio.charset.Charset; import java.util.Collection; import java.util.Set; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.stubbing; public class MutableStubResponseTest { private static final int STATUS = 215; private static final long DELAY = 1500; private static final Charset CHARSET = Charset.forName("UTF-8"); private static final String STRING_BODY = "string_body"; private static final byte[] BYTES_BODY = "bytes_body".getBytes(CHARSET); private static final MultiMap HEADERS_MAP;
// Path: jadler-core/src/main/java/net/jadler/KeyValues.java // public class KeyValues { // // /** // * An empty instance. // */ // public static final KeyValues EMPTY = new KeyValues(); // private final MultiMap values; // // // /** // * Creates new empty instance. // */ // public KeyValues() { // this.values = new MultiValueMap(); // } // // // /** // * Adds new key-value pair. Supports multi-values for one key (if there has already been added // * some value with this key, additional value is added instead of rewriting). Please note this method // * creates new instance containing all existing values plus the new one rather than modifying this instance. // * // * @param key key (cannot be empty) // * @param value value (cannot be {@code null}, however can be empty for valueless headers) // * @return an exact copy of this instance containing all existing values plus the new one // */ // @SuppressWarnings("unchecked") // public KeyValues add(final String key, final String value) { // Validate.notEmpty(key, "key cannot be empty"); // Validate.notNull(value, "value cannot be null, use an empty string instead"); // // final KeyValues res = new KeyValues(); // res.values.putAll(this.values); // res.values.put(key.toLowerCase(), value); // // return res; // } // // // /** // * Adds all values from the given instance. Supports multi-values for one key (if there has already been added // * some value with this key, additional value is added instead of rewriting). Please note this method // * creates new instance containing all existing values plus the new ones rather than modifying this instance. // * // * @param keyValues values to be added no(cannot be {@code null}) // * @return an exact copy of this instance containing all existing values plus the new ones // */ // @SuppressWarnings("unchecked") // public KeyValues addAll(final KeyValues keyValues) { // Validate.notNull(keyValues, "keyValues cannot be null"); // // final KeyValues res = new KeyValues(); // res.values.putAll(this.values); // res.values.putAll(keyValues.values); // return res; // } // // // /** // * Returns the first value for the given key // * // * @param key key (case insensitive) // * @return single (first) value for the given key or {@code null}, if there is no such a key in this instance // */ // public String getValue(final String key) { // Validate.notEmpty(key, "key cannot be empty"); // // final List<String> allValues = this.getValues(key); // return allValues != null ? allValues.get(0) : null; // } // // // /** // * Returns all values for the given key // * // * @param key key (case insensitive) // * @return all values of the given header or {@code null}, if there is no such a key in this instance // */ // public List<String> getValues(final String key) { // Validate.notEmpty(key, "name cannot be empty"); // // @SuppressWarnings("unchecked") final List<String> result = (List<String>) values.get(key.toLowerCase()); // return result == null || result.isEmpty() ? null : new ArrayList<String>(result); // } // // // /** // * @return all keys (lower-cased) from this instance (never returns {@code null}) // */ // public Set<String> getKeys() { // @SuppressWarnings("unchecked") final Set<String> result = new HashSet<String>(this.values.keySet()); // return result; // } // // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder(); // for (@SuppressWarnings("unchecked") final Iterator<Map.Entry<String, Collection<String>>> it // = this.values.entrySet().iterator(); it.hasNext(); ) { // final Map.Entry<String, Collection<String>> e = it.next(); // // for (final Iterator<String> it2 = e.getValue().iterator(); it2.hasNext(); ) { // sb.append(e.getKey()).append(": ").append(it2.next()); // if (it2.hasNext()) { // sb.append(", "); // } // } // // if (it.hasNext()) { // sb.append(", "); // } // } // // return sb.toString(); // } // // // @Override // public int hashCode() { // int hash = 5; // hash = 43 * hash + (this.values != null ? this.values.hashCode() : 0); // return hash; // } // // // @Override // public boolean equals(final Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final KeyValues other = (KeyValues) obj; // if (this.values != other.values && (this.values == null || !this.values.equals(other.values))) { // return false; // } // return true; // } // } // Path: jadler-core/src/test/java/net/jadler/stubbing/MutableStubResponseTest.java import net.jadler.KeyValues; import org.apache.commons.collections.MultiMap; import org.apache.commons.collections.map.MultiValueMap; import org.junit.Before; import org.junit.Test; import java.nio.charset.Charset; import java.util.Collection; import java.util.Set; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.stubbing; public class MutableStubResponseTest { private static final int STATUS = 215; private static final long DELAY = 1500; private static final Charset CHARSET = Charset.forName("UTF-8"); private static final String STRING_BODY = "string_body"; private static final byte[] BYTES_BODY = "bytes_body".getBytes(CHARSET); private static final MultiMap HEADERS_MAP;
private static final KeyValues HEADERS = new KeyValues()
jadler-mocking/jadler
jadler-core/src/main/java/net/jadler/stubbing/StubResponse.java
// Path: jadler-core/src/main/java/net/jadler/KeyValues.java // public class KeyValues { // // /** // * An empty instance. // */ // public static final KeyValues EMPTY = new KeyValues(); // private final MultiMap values; // // // /** // * Creates new empty instance. // */ // public KeyValues() { // this.values = new MultiValueMap(); // } // // // /** // * Adds new key-value pair. Supports multi-values for one key (if there has already been added // * some value with this key, additional value is added instead of rewriting). Please note this method // * creates new instance containing all existing values plus the new one rather than modifying this instance. // * // * @param key key (cannot be empty) // * @param value value (cannot be {@code null}, however can be empty for valueless headers) // * @return an exact copy of this instance containing all existing values plus the new one // */ // @SuppressWarnings("unchecked") // public KeyValues add(final String key, final String value) { // Validate.notEmpty(key, "key cannot be empty"); // Validate.notNull(value, "value cannot be null, use an empty string instead"); // // final KeyValues res = new KeyValues(); // res.values.putAll(this.values); // res.values.put(key.toLowerCase(), value); // // return res; // } // // // /** // * Adds all values from the given instance. Supports multi-values for one key (if there has already been added // * some value with this key, additional value is added instead of rewriting). Please note this method // * creates new instance containing all existing values plus the new ones rather than modifying this instance. // * // * @param keyValues values to be added no(cannot be {@code null}) // * @return an exact copy of this instance containing all existing values plus the new ones // */ // @SuppressWarnings("unchecked") // public KeyValues addAll(final KeyValues keyValues) { // Validate.notNull(keyValues, "keyValues cannot be null"); // // final KeyValues res = new KeyValues(); // res.values.putAll(this.values); // res.values.putAll(keyValues.values); // return res; // } // // // /** // * Returns the first value for the given key // * // * @param key key (case insensitive) // * @return single (first) value for the given key or {@code null}, if there is no such a key in this instance // */ // public String getValue(final String key) { // Validate.notEmpty(key, "key cannot be empty"); // // final List<String> allValues = this.getValues(key); // return allValues != null ? allValues.get(0) : null; // } // // // /** // * Returns all values for the given key // * // * @param key key (case insensitive) // * @return all values of the given header or {@code null}, if there is no such a key in this instance // */ // public List<String> getValues(final String key) { // Validate.notEmpty(key, "name cannot be empty"); // // @SuppressWarnings("unchecked") final List<String> result = (List<String>) values.get(key.toLowerCase()); // return result == null || result.isEmpty() ? null : new ArrayList<String>(result); // } // // // /** // * @return all keys (lower-cased) from this instance (never returns {@code null}) // */ // public Set<String> getKeys() { // @SuppressWarnings("unchecked") final Set<String> result = new HashSet<String>(this.values.keySet()); // return result; // } // // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder(); // for (@SuppressWarnings("unchecked") final Iterator<Map.Entry<String, Collection<String>>> it // = this.values.entrySet().iterator(); it.hasNext(); ) { // final Map.Entry<String, Collection<String>> e = it.next(); // // for (final Iterator<String> it2 = e.getValue().iterator(); it2.hasNext(); ) { // sb.append(e.getKey()).append(": ").append(it2.next()); // if (it2.hasNext()) { // sb.append(", "); // } // } // // if (it.hasNext()) { // sb.append(", "); // } // } // // return sb.toString(); // } // // // @Override // public int hashCode() { // int hash = 5; // hash = 43 * hash + (this.values != null ? this.values.hashCode() : 0); // return hash; // } // // // @Override // public boolean equals(final Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final KeyValues other = (KeyValues) obj; // if (this.values != other.values && (this.values == null || !this.values.equals(other.values))) { // return false; // } // return true; // } // }
import net.jadler.KeyValues; import org.apache.commons.lang.Validate; import java.nio.charset.Charset; import java.util.concurrent.TimeUnit; import static org.apache.commons.lang.StringUtils.abbreviate;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.stubbing; /** * Definition of a stub http response. For creating new instances use the {@link #builder()} static method. */ public class StubResponse { /** * An empty stub response containing nothing but defaults (empty body, http status 200, no headers and no delay) */ public static final StubResponse EMPTY = builder().build();
// Path: jadler-core/src/main/java/net/jadler/KeyValues.java // public class KeyValues { // // /** // * An empty instance. // */ // public static final KeyValues EMPTY = new KeyValues(); // private final MultiMap values; // // // /** // * Creates new empty instance. // */ // public KeyValues() { // this.values = new MultiValueMap(); // } // // // /** // * Adds new key-value pair. Supports multi-values for one key (if there has already been added // * some value with this key, additional value is added instead of rewriting). Please note this method // * creates new instance containing all existing values plus the new one rather than modifying this instance. // * // * @param key key (cannot be empty) // * @param value value (cannot be {@code null}, however can be empty for valueless headers) // * @return an exact copy of this instance containing all existing values plus the new one // */ // @SuppressWarnings("unchecked") // public KeyValues add(final String key, final String value) { // Validate.notEmpty(key, "key cannot be empty"); // Validate.notNull(value, "value cannot be null, use an empty string instead"); // // final KeyValues res = new KeyValues(); // res.values.putAll(this.values); // res.values.put(key.toLowerCase(), value); // // return res; // } // // // /** // * Adds all values from the given instance. Supports multi-values for one key (if there has already been added // * some value with this key, additional value is added instead of rewriting). Please note this method // * creates new instance containing all existing values plus the new ones rather than modifying this instance. // * // * @param keyValues values to be added no(cannot be {@code null}) // * @return an exact copy of this instance containing all existing values plus the new ones // */ // @SuppressWarnings("unchecked") // public KeyValues addAll(final KeyValues keyValues) { // Validate.notNull(keyValues, "keyValues cannot be null"); // // final KeyValues res = new KeyValues(); // res.values.putAll(this.values); // res.values.putAll(keyValues.values); // return res; // } // // // /** // * Returns the first value for the given key // * // * @param key key (case insensitive) // * @return single (first) value for the given key or {@code null}, if there is no such a key in this instance // */ // public String getValue(final String key) { // Validate.notEmpty(key, "key cannot be empty"); // // final List<String> allValues = this.getValues(key); // return allValues != null ? allValues.get(0) : null; // } // // // /** // * Returns all values for the given key // * // * @param key key (case insensitive) // * @return all values of the given header or {@code null}, if there is no such a key in this instance // */ // public List<String> getValues(final String key) { // Validate.notEmpty(key, "name cannot be empty"); // // @SuppressWarnings("unchecked") final List<String> result = (List<String>) values.get(key.toLowerCase()); // return result == null || result.isEmpty() ? null : new ArrayList<String>(result); // } // // // /** // * @return all keys (lower-cased) from this instance (never returns {@code null}) // */ // public Set<String> getKeys() { // @SuppressWarnings("unchecked") final Set<String> result = new HashSet<String>(this.values.keySet()); // return result; // } // // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder(); // for (@SuppressWarnings("unchecked") final Iterator<Map.Entry<String, Collection<String>>> it // = this.values.entrySet().iterator(); it.hasNext(); ) { // final Map.Entry<String, Collection<String>> e = it.next(); // // for (final Iterator<String> it2 = e.getValue().iterator(); it2.hasNext(); ) { // sb.append(e.getKey()).append(": ").append(it2.next()); // if (it2.hasNext()) { // sb.append(", "); // } // } // // if (it.hasNext()) { // sb.append(", "); // } // } // // return sb.toString(); // } // // // @Override // public int hashCode() { // int hash = 5; // hash = 43 * hash + (this.values != null ? this.values.hashCode() : 0); // return hash; // } // // // @Override // public boolean equals(final Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final KeyValues other = (KeyValues) obj; // if (this.values != other.values && (this.values == null || !this.values.equals(other.values))) { // return false; // } // return true; // } // } // Path: jadler-core/src/main/java/net/jadler/stubbing/StubResponse.java import net.jadler.KeyValues; import org.apache.commons.lang.Validate; import java.nio.charset.Charset; import java.util.concurrent.TimeUnit; import static org.apache.commons.lang.StringUtils.abbreviate; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.stubbing; /** * Definition of a stub http response. For creating new instances use the {@link #builder()} static method. */ public class StubResponse { /** * An empty stub response containing nothing but defaults (empty body, http status 200, no headers and no delay) */ public static final StubResponse EMPTY = builder().build();
private final KeyValues headers;
jadler-mocking/jadler
jadler-junit/src/test/java/net/jadler/junit/rule/JadlerRuleIntegrationTest.java
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static int port() { // checkInitialized(); // return jadlerMockerContainer.get().getStubHttpServerPort(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // }
import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.junit.AfterClass; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.port; import static net.jadler.Jadler.verifyThatRequest; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.arrayContaining; import static org.hamcrest.Matchers.arrayContainingInAnyOrder; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.is;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.junit.rule; /** * Tests the {@link net.jadler.junit.rule.JadlerRule#JadlerRule()} variant. * * @author Christian Galsterer */ public class JadlerRuleIntegrationTest { private static final String DEFAULT_CONTENT_TYPE = "text/html; charset=UTF-8"; private static final int DEFAULT_STATUS = 201; private static final Charset DEFAULT_ENCODING = Charset.forName("ISO-8859-2"); private static final String HEADER_NAME1 = "name1"; private static final String HEADER_NAME2 = "name2"; private static final String HEADER_VALUE1_1 = "value11"; private static final String HEADER_VALUE1_2 = "value12"; private static final String HEADER_VALUE2 = "value2"; private static final String STRING_WITH_DIACRITICS = "\u00e1\u0159\u017e"; private static final byte[] ISO_8859_2_REPRESENTATION = {(byte) 0xE1, (byte) 0xF8, (byte) 0xBE}; @Rule public JadlerRule defaultJadler = new JadlerRule() .withRequestsRecordingDisabled() .withDefaultResponseContentType(DEFAULT_CONTENT_TYPE) .withDefaultResponseStatus(DEFAULT_STATUS) .withDefaultResponseEncoding(DEFAULT_ENCODING) .withDefaultResponseHeader(HEADER_NAME1, HEADER_VALUE1_1) .withDefaultResponseHeader(HEADER_NAME1, HEADER_VALUE1_2) .withDefaultResponseHeader(HEADER_NAME2, HEADER_VALUE2); @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } private static HeaderMatcher header(final String name, final String value) { return new HeaderMatcher(name, value); } @Before public void setUp() { //send a default response on any request
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static int port() { // checkInitialized(); // return jadlerMockerContainer.get().getStubHttpServerPort(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // } // Path: jadler-junit/src/test/java/net/jadler/junit/rule/JadlerRuleIntegrationTest.java import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.junit.AfterClass; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.port; import static net.jadler.Jadler.verifyThatRequest; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.arrayContaining; import static org.hamcrest.Matchers.arrayContainingInAnyOrder; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.is; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.junit.rule; /** * Tests the {@link net.jadler.junit.rule.JadlerRule#JadlerRule()} variant. * * @author Christian Galsterer */ public class JadlerRuleIntegrationTest { private static final String DEFAULT_CONTENT_TYPE = "text/html; charset=UTF-8"; private static final int DEFAULT_STATUS = 201; private static final Charset DEFAULT_ENCODING = Charset.forName("ISO-8859-2"); private static final String HEADER_NAME1 = "name1"; private static final String HEADER_NAME2 = "name2"; private static final String HEADER_VALUE1_1 = "value11"; private static final String HEADER_VALUE1_2 = "value12"; private static final String HEADER_VALUE2 = "value2"; private static final String STRING_WITH_DIACRITICS = "\u00e1\u0159\u017e"; private static final byte[] ISO_8859_2_REPRESENTATION = {(byte) 0xE1, (byte) 0xF8, (byte) 0xBE}; @Rule public JadlerRule defaultJadler = new JadlerRule() .withRequestsRecordingDisabled() .withDefaultResponseContentType(DEFAULT_CONTENT_TYPE) .withDefaultResponseStatus(DEFAULT_STATUS) .withDefaultResponseEncoding(DEFAULT_ENCODING) .withDefaultResponseHeader(HEADER_NAME1, HEADER_VALUE1_1) .withDefaultResponseHeader(HEADER_NAME1, HEADER_VALUE1_2) .withDefaultResponseHeader(HEADER_NAME2, HEADER_VALUE2); @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } private static HeaderMatcher header(final String name, final String value) { return new HeaderMatcher(name, value); } @Before public void setUp() { //send a default response on any request
onRequest().respond().withBody(STRING_WITH_DIACRITICS);
jadler-mocking/jadler
jadler-junit/src/test/java/net/jadler/junit/rule/JadlerRuleIntegrationTest.java
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static int port() { // checkInitialized(); // return jadlerMockerContainer.get().getStubHttpServerPort(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // }
import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.junit.AfterClass; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.port; import static net.jadler.Jadler.verifyThatRequest; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.arrayContaining; import static org.hamcrest.Matchers.arrayContainingInAnyOrder; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.is;
private static final String STRING_WITH_DIACRITICS = "\u00e1\u0159\u017e"; private static final byte[] ISO_8859_2_REPRESENTATION = {(byte) 0xE1, (byte) 0xF8, (byte) 0xBE}; @Rule public JadlerRule defaultJadler = new JadlerRule() .withRequestsRecordingDisabled() .withDefaultResponseContentType(DEFAULT_CONTENT_TYPE) .withDefaultResponseStatus(DEFAULT_STATUS) .withDefaultResponseEncoding(DEFAULT_ENCODING) .withDefaultResponseHeader(HEADER_NAME1, HEADER_VALUE1_1) .withDefaultResponseHeader(HEADER_NAME1, HEADER_VALUE1_2) .withDefaultResponseHeader(HEADER_NAME2, HEADER_VALUE2); @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } private static HeaderMatcher header(final String name, final String value) { return new HeaderMatcher(name, value); } @Before public void setUp() { //send a default response on any request onRequest().respond().withBody(STRING_WITH_DIACRITICS); } @Test public void testWithDefaultPort() {
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static int port() { // checkInitialized(); // return jadlerMockerContainer.get().getStubHttpServerPort(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // } // Path: jadler-junit/src/test/java/net/jadler/junit/rule/JadlerRuleIntegrationTest.java import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.junit.AfterClass; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.port; import static net.jadler.Jadler.verifyThatRequest; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.arrayContaining; import static org.hamcrest.Matchers.arrayContainingInAnyOrder; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.is; private static final String STRING_WITH_DIACRITICS = "\u00e1\u0159\u017e"; private static final byte[] ISO_8859_2_REPRESENTATION = {(byte) 0xE1, (byte) 0xF8, (byte) 0xBE}; @Rule public JadlerRule defaultJadler = new JadlerRule() .withRequestsRecordingDisabled() .withDefaultResponseContentType(DEFAULT_CONTENT_TYPE) .withDefaultResponseStatus(DEFAULT_STATUS) .withDefaultResponseEncoding(DEFAULT_ENCODING) .withDefaultResponseHeader(HEADER_NAME1, HEADER_VALUE1_1) .withDefaultResponseHeader(HEADER_NAME1, HEADER_VALUE1_2) .withDefaultResponseHeader(HEADER_NAME2, HEADER_VALUE2); @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } private static HeaderMatcher header(final String name, final String value) { return new HeaderMatcher(name, value); } @Before public void setUp() { //send a default response on any request onRequest().respond().withBody(STRING_WITH_DIACRITICS); } @Test public void testWithDefaultPort() {
assertThat(port(), is(greaterThanOrEqualTo(0)));
jadler-mocking/jadler
jadler-junit/src/test/java/net/jadler/junit/rule/JadlerRuleIntegrationTest.java
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static int port() { // checkInitialized(); // return jadlerMockerContainer.get().getStubHttpServerPort(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // }
import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.junit.AfterClass; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.port; import static net.jadler.Jadler.verifyThatRequest; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.arrayContaining; import static org.hamcrest.Matchers.arrayContainingInAnyOrder; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.is;
.withRequestsRecordingDisabled() .withDefaultResponseContentType(DEFAULT_CONTENT_TYPE) .withDefaultResponseStatus(DEFAULT_STATUS) .withDefaultResponseEncoding(DEFAULT_ENCODING) .withDefaultResponseHeader(HEADER_NAME1, HEADER_VALUE1_1) .withDefaultResponseHeader(HEADER_NAME1, HEADER_VALUE1_2) .withDefaultResponseHeader(HEADER_NAME2, HEADER_VALUE2); @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } private static HeaderMatcher header(final String name, final String value) { return new HeaderMatcher(name, value); } @Before public void setUp() { //send a default response on any request onRequest().respond().withBody(STRING_WITH_DIACRITICS); } @Test public void testWithDefaultPort() { assertThat(port(), is(greaterThanOrEqualTo(0))); } @Test(expected = IllegalStateException.class) public void withRequestsRecordingDisabled() {
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static int port() { // checkInitialized(); // return jadlerMockerContainer.get().getStubHttpServerPort(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // } // Path: jadler-junit/src/test/java/net/jadler/junit/rule/JadlerRuleIntegrationTest.java import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.junit.AfterClass; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.port; import static net.jadler.Jadler.verifyThatRequest; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.arrayContaining; import static org.hamcrest.Matchers.arrayContainingInAnyOrder; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.is; .withRequestsRecordingDisabled() .withDefaultResponseContentType(DEFAULT_CONTENT_TYPE) .withDefaultResponseStatus(DEFAULT_STATUS) .withDefaultResponseEncoding(DEFAULT_ENCODING) .withDefaultResponseHeader(HEADER_NAME1, HEADER_VALUE1_1) .withDefaultResponseHeader(HEADER_NAME1, HEADER_VALUE1_2) .withDefaultResponseHeader(HEADER_NAME2, HEADER_VALUE2); @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } private static HeaderMatcher header(final String name, final String value) { return new HeaderMatcher(name, value); } @Before public void setUp() { //send a default response on any request onRequest().respond().withBody(STRING_WITH_DIACRITICS); } @Test public void testWithDefaultPort() { assertThat(port(), is(greaterThanOrEqualTo(0))); } @Test(expected = IllegalStateException.class) public void withRequestsRecordingDisabled() {
verifyThatRequest();
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/ResetJDKIntegrationTest.java
// Path: jadler-jdk/src/main/java/net/jadler/stubbing/server/jdk/JdkStubHttpServer.java // public class JdkStubHttpServer implements StubHttpServer { // // private final HttpServer server; // // public JdkStubHttpServer(final int port) { // isTrue(port >= 0, "port cannot be a negative number"); // // try { // server = HttpServer.create(new InetSocketAddress(port), 0); // } catch (final IOException e) { // throw new JadlerException("Cannot create JDK server", e); // } // } // // public JdkStubHttpServer() { // this(0); // } // // @Override // public void registerRequestManager(final RequestManager ruleProvider) { // notNull(ruleProvider, "ruleProvider cannot be null"); // server.createContext("/", new JdkHandler(ruleProvider)); // } // // @Override // public void start() throws Exception { // server.start(); // } // // @Override // public void stop() throws Exception { // server.stop(0); // } // // @Override // public int getPort() { // return server.getAddress().getPort(); // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // }
import static net.jadler.Jadler.initJadlerUsing; import net.jadler.stubbing.server.jdk.JdkStubHttpServer; import org.junit.BeforeClass;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * Tests that it is possible to reset the {@link JdkStubHttpServer} implementation. */ public class ResetJDKIntegrationTest extends AbstractResetIntegrationTest { @BeforeClass public static void configureMocker() {
// Path: jadler-jdk/src/main/java/net/jadler/stubbing/server/jdk/JdkStubHttpServer.java // public class JdkStubHttpServer implements StubHttpServer { // // private final HttpServer server; // // public JdkStubHttpServer(final int port) { // isTrue(port >= 0, "port cannot be a negative number"); // // try { // server = HttpServer.create(new InetSocketAddress(port), 0); // } catch (final IOException e) { // throw new JadlerException("Cannot create JDK server", e); // } // } // // public JdkStubHttpServer() { // this(0); // } // // @Override // public void registerRequestManager(final RequestManager ruleProvider) { // notNull(ruleProvider, "ruleProvider cannot be null"); // server.createContext("/", new JdkHandler(ruleProvider)); // } // // @Override // public void start() throws Exception { // server.start(); // } // // @Override // public void stop() throws Exception { // server.stop(0); // } // // @Override // public int getPort() { // return server.getAddress().getPort(); // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // } // Path: jadler-all/src/test/java/net/jadler/ResetJDKIntegrationTest.java import static net.jadler.Jadler.initJadlerUsing; import net.jadler.stubbing.server.jdk.JdkStubHttpServer; import org.junit.BeforeClass; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * Tests that it is possible to reset the {@link JdkStubHttpServer} implementation. */ public class ResetJDKIntegrationTest extends AbstractResetIntegrationTest { @BeforeClass public static void configureMocker() {
initJadlerUsing(new JdkStubHttpServer())
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/ResetJDKIntegrationTest.java
// Path: jadler-jdk/src/main/java/net/jadler/stubbing/server/jdk/JdkStubHttpServer.java // public class JdkStubHttpServer implements StubHttpServer { // // private final HttpServer server; // // public JdkStubHttpServer(final int port) { // isTrue(port >= 0, "port cannot be a negative number"); // // try { // server = HttpServer.create(new InetSocketAddress(port), 0); // } catch (final IOException e) { // throw new JadlerException("Cannot create JDK server", e); // } // } // // public JdkStubHttpServer() { // this(0); // } // // @Override // public void registerRequestManager(final RequestManager ruleProvider) { // notNull(ruleProvider, "ruleProvider cannot be null"); // server.createContext("/", new JdkHandler(ruleProvider)); // } // // @Override // public void start() throws Exception { // server.start(); // } // // @Override // public void stop() throws Exception { // server.stop(0); // } // // @Override // public int getPort() { // return server.getAddress().getPort(); // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // }
import static net.jadler.Jadler.initJadlerUsing; import net.jadler.stubbing.server.jdk.JdkStubHttpServer; import org.junit.BeforeClass;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * Tests that it is possible to reset the {@link JdkStubHttpServer} implementation. */ public class ResetJDKIntegrationTest extends AbstractResetIntegrationTest { @BeforeClass public static void configureMocker() {
// Path: jadler-jdk/src/main/java/net/jadler/stubbing/server/jdk/JdkStubHttpServer.java // public class JdkStubHttpServer implements StubHttpServer { // // private final HttpServer server; // // public JdkStubHttpServer(final int port) { // isTrue(port >= 0, "port cannot be a negative number"); // // try { // server = HttpServer.create(new InetSocketAddress(port), 0); // } catch (final IOException e) { // throw new JadlerException("Cannot create JDK server", e); // } // } // // public JdkStubHttpServer() { // this(0); // } // // @Override // public void registerRequestManager(final RequestManager ruleProvider) { // notNull(ruleProvider, "ruleProvider cannot be null"); // server.createContext("/", new JdkHandler(ruleProvider)); // } // // @Override // public void start() throws Exception { // server.start(); // } // // @Override // public void stop() throws Exception { // server.stop(0); // } // // @Override // public int getPort() { // return server.getAddress().getPort(); // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // } // Path: jadler-all/src/test/java/net/jadler/ResetJDKIntegrationTest.java import static net.jadler.Jadler.initJadlerUsing; import net.jadler.stubbing.server.jdk.JdkStubHttpServer; import org.junit.BeforeClass; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * Tests that it is possible to reset the {@link JdkStubHttpServer} implementation. */ public class ResetJDKIntegrationTest extends AbstractResetIntegrationTest { @BeforeClass public static void configureMocker() {
initJadlerUsing(new JdkStubHttpServer())
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/TimeoutIntegrationTest.java
// Path: jadler-all/src/test/java/net/jadler/parameters/TestParameters.java // public class TestParameters { // // /** // * @return parameters for acceptance/integration tests located in this module. The fugly return type // * is required by the jUnit parameters mechanism. It basically returns two stub server factories as // * test parameters. // */ // public Iterable<StubHttpServerFactory[]> provide() { // // return Arrays.asList( // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JettyStubHttpServer(); // } // }), // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JdkStubHttpServer(); // } // }) // ); // } // // private StubHttpServerFactory[] singletonArray(final StubHttpServerFactory server) { // return new StubHttpServerFactory[]{server}; // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static final StatusRetriever STATUS_RETRIEVER = new StatusRetriever(); // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // }
import net.jadler.parameters.StubHttpServerFactory; import net.jadler.parameters.TestParameters; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadlerUsing; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.STATUS_RETRIEVER; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * When a timeout value is defined in a jUnit test, the test is executed in a different thread than the thread * executing the setup and teardown methods thus a separated test for it. */ @RunWith(Parameterized.class) public class TimeoutIntegrationTest { private final StubHttpServerFactory serverFactory; public TimeoutIntegrationTest(final StubHttpServerFactory serverFactory) { this.serverFactory = serverFactory; } @Parameterized.Parameters public static Iterable<StubHttpServerFactory[]> parameters() {
// Path: jadler-all/src/test/java/net/jadler/parameters/TestParameters.java // public class TestParameters { // // /** // * @return parameters for acceptance/integration tests located in this module. The fugly return type // * is required by the jUnit parameters mechanism. It basically returns two stub server factories as // * test parameters. // */ // public Iterable<StubHttpServerFactory[]> provide() { // // return Arrays.asList( // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JettyStubHttpServer(); // } // }), // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JdkStubHttpServer(); // } // }) // ); // } // // private StubHttpServerFactory[] singletonArray(final StubHttpServerFactory server) { // return new StubHttpServerFactory[]{server}; // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static final StatusRetriever STATUS_RETRIEVER = new StatusRetriever(); // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // Path: jadler-all/src/test/java/net/jadler/TimeoutIntegrationTest.java import net.jadler.parameters.StubHttpServerFactory; import net.jadler.parameters.TestParameters; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadlerUsing; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.STATUS_RETRIEVER; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * When a timeout value is defined in a jUnit test, the test is executed in a different thread than the thread * executing the setup and teardown methods thus a separated test for it. */ @RunWith(Parameterized.class) public class TimeoutIntegrationTest { private final StubHttpServerFactory serverFactory; public TimeoutIntegrationTest(final StubHttpServerFactory serverFactory) { this.serverFactory = serverFactory; } @Parameterized.Parameters public static Iterable<StubHttpServerFactory[]> parameters() {
return new TestParameters().provide();
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/TimeoutIntegrationTest.java
// Path: jadler-all/src/test/java/net/jadler/parameters/TestParameters.java // public class TestParameters { // // /** // * @return parameters for acceptance/integration tests located in this module. The fugly return type // * is required by the jUnit parameters mechanism. It basically returns two stub server factories as // * test parameters. // */ // public Iterable<StubHttpServerFactory[]> provide() { // // return Arrays.asList( // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JettyStubHttpServer(); // } // }), // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JdkStubHttpServer(); // } // }) // ); // } // // private StubHttpServerFactory[] singletonArray(final StubHttpServerFactory server) { // return new StubHttpServerFactory[]{server}; // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static final StatusRetriever STATUS_RETRIEVER = new StatusRetriever(); // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // }
import net.jadler.parameters.StubHttpServerFactory; import net.jadler.parameters.TestParameters; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadlerUsing; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.STATUS_RETRIEVER; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * When a timeout value is defined in a jUnit test, the test is executed in a different thread than the thread * executing the setup and teardown methods thus a separated test for it. */ @RunWith(Parameterized.class) public class TimeoutIntegrationTest { private final StubHttpServerFactory serverFactory; public TimeoutIntegrationTest(final StubHttpServerFactory serverFactory) { this.serverFactory = serverFactory; } @Parameterized.Parameters public static Iterable<StubHttpServerFactory[]> parameters() { return new TestParameters().provide(); } @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } @Before public void setUp() {
// Path: jadler-all/src/test/java/net/jadler/parameters/TestParameters.java // public class TestParameters { // // /** // * @return parameters for acceptance/integration tests located in this module. The fugly return type // * is required by the jUnit parameters mechanism. It basically returns two stub server factories as // * test parameters. // */ // public Iterable<StubHttpServerFactory[]> provide() { // // return Arrays.asList( // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JettyStubHttpServer(); // } // }), // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JdkStubHttpServer(); // } // }) // ); // } // // private StubHttpServerFactory[] singletonArray(final StubHttpServerFactory server) { // return new StubHttpServerFactory[]{server}; // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static final StatusRetriever STATUS_RETRIEVER = new StatusRetriever(); // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // Path: jadler-all/src/test/java/net/jadler/TimeoutIntegrationTest.java import net.jadler.parameters.StubHttpServerFactory; import net.jadler.parameters.TestParameters; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadlerUsing; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.STATUS_RETRIEVER; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * When a timeout value is defined in a jUnit test, the test is executed in a different thread than the thread * executing the setup and teardown methods thus a separated test for it. */ @RunWith(Parameterized.class) public class TimeoutIntegrationTest { private final StubHttpServerFactory serverFactory; public TimeoutIntegrationTest(final StubHttpServerFactory serverFactory) { this.serverFactory = serverFactory; } @Parameterized.Parameters public static Iterable<StubHttpServerFactory[]> parameters() { return new TestParameters().provide(); } @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } @Before public void setUp() {
initJadlerUsing(this.serverFactory.createServer());
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/TimeoutIntegrationTest.java
// Path: jadler-all/src/test/java/net/jadler/parameters/TestParameters.java // public class TestParameters { // // /** // * @return parameters for acceptance/integration tests located in this module. The fugly return type // * is required by the jUnit parameters mechanism. It basically returns two stub server factories as // * test parameters. // */ // public Iterable<StubHttpServerFactory[]> provide() { // // return Arrays.asList( // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JettyStubHttpServer(); // } // }), // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JdkStubHttpServer(); // } // }) // ); // } // // private StubHttpServerFactory[] singletonArray(final StubHttpServerFactory server) { // return new StubHttpServerFactory[]{server}; // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static final StatusRetriever STATUS_RETRIEVER = new StatusRetriever(); // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // }
import net.jadler.parameters.StubHttpServerFactory; import net.jadler.parameters.TestParameters; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadlerUsing; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.STATUS_RETRIEVER; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * When a timeout value is defined in a jUnit test, the test is executed in a different thread than the thread * executing the setup and teardown methods thus a separated test for it. */ @RunWith(Parameterized.class) public class TimeoutIntegrationTest { private final StubHttpServerFactory serverFactory; public TimeoutIntegrationTest(final StubHttpServerFactory serverFactory) { this.serverFactory = serverFactory; } @Parameterized.Parameters public static Iterable<StubHttpServerFactory[]> parameters() { return new TestParameters().provide(); } @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } @Before public void setUp() { initJadlerUsing(this.serverFactory.createServer()); } @After public void tearDown() {
// Path: jadler-all/src/test/java/net/jadler/parameters/TestParameters.java // public class TestParameters { // // /** // * @return parameters for acceptance/integration tests located in this module. The fugly return type // * is required by the jUnit parameters mechanism. It basically returns two stub server factories as // * test parameters. // */ // public Iterable<StubHttpServerFactory[]> provide() { // // return Arrays.asList( // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JettyStubHttpServer(); // } // }), // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JdkStubHttpServer(); // } // }) // ); // } // // private StubHttpServerFactory[] singletonArray(final StubHttpServerFactory server) { // return new StubHttpServerFactory[]{server}; // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static final StatusRetriever STATUS_RETRIEVER = new StatusRetriever(); // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // Path: jadler-all/src/test/java/net/jadler/TimeoutIntegrationTest.java import net.jadler.parameters.StubHttpServerFactory; import net.jadler.parameters.TestParameters; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadlerUsing; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.STATUS_RETRIEVER; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * When a timeout value is defined in a jUnit test, the test is executed in a different thread than the thread * executing the setup and teardown methods thus a separated test for it. */ @RunWith(Parameterized.class) public class TimeoutIntegrationTest { private final StubHttpServerFactory serverFactory; public TimeoutIntegrationTest(final StubHttpServerFactory serverFactory) { this.serverFactory = serverFactory; } @Parameterized.Parameters public static Iterable<StubHttpServerFactory[]> parameters() { return new TestParameters().provide(); } @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } @Before public void setUp() { initJadlerUsing(this.serverFactory.createServer()); } @After public void tearDown() {
closeJadler();
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/TimeoutIntegrationTest.java
// Path: jadler-all/src/test/java/net/jadler/parameters/TestParameters.java // public class TestParameters { // // /** // * @return parameters for acceptance/integration tests located in this module. The fugly return type // * is required by the jUnit parameters mechanism. It basically returns two stub server factories as // * test parameters. // */ // public Iterable<StubHttpServerFactory[]> provide() { // // return Arrays.asList( // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JettyStubHttpServer(); // } // }), // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JdkStubHttpServer(); // } // }) // ); // } // // private StubHttpServerFactory[] singletonArray(final StubHttpServerFactory server) { // return new StubHttpServerFactory[]{server}; // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static final StatusRetriever STATUS_RETRIEVER = new StatusRetriever(); // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // }
import net.jadler.parameters.StubHttpServerFactory; import net.jadler.parameters.TestParameters; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadlerUsing; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.STATUS_RETRIEVER; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * When a timeout value is defined in a jUnit test, the test is executed in a different thread than the thread * executing the setup and teardown methods thus a separated test for it. */ @RunWith(Parameterized.class) public class TimeoutIntegrationTest { private final StubHttpServerFactory serverFactory; public TimeoutIntegrationTest(final StubHttpServerFactory serverFactory) { this.serverFactory = serverFactory; } @Parameterized.Parameters public static Iterable<StubHttpServerFactory[]> parameters() { return new TestParameters().provide(); } @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } @Before public void setUp() { initJadlerUsing(this.serverFactory.createServer()); } @After public void tearDown() { closeJadler(); } @Test(timeout = 10000L) public void timeout() throws IOException {
// Path: jadler-all/src/test/java/net/jadler/parameters/TestParameters.java // public class TestParameters { // // /** // * @return parameters for acceptance/integration tests located in this module. The fugly return type // * is required by the jUnit parameters mechanism. It basically returns two stub server factories as // * test parameters. // */ // public Iterable<StubHttpServerFactory[]> provide() { // // return Arrays.asList( // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JettyStubHttpServer(); // } // }), // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JdkStubHttpServer(); // } // }) // ); // } // // private StubHttpServerFactory[] singletonArray(final StubHttpServerFactory server) { // return new StubHttpServerFactory[]{server}; // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static final StatusRetriever STATUS_RETRIEVER = new StatusRetriever(); // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // Path: jadler-all/src/test/java/net/jadler/TimeoutIntegrationTest.java import net.jadler.parameters.StubHttpServerFactory; import net.jadler.parameters.TestParameters; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadlerUsing; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.STATUS_RETRIEVER; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * When a timeout value is defined in a jUnit test, the test is executed in a different thread than the thread * executing the setup and teardown methods thus a separated test for it. */ @RunWith(Parameterized.class) public class TimeoutIntegrationTest { private final StubHttpServerFactory serverFactory; public TimeoutIntegrationTest(final StubHttpServerFactory serverFactory) { this.serverFactory = serverFactory; } @Parameterized.Parameters public static Iterable<StubHttpServerFactory[]> parameters() { return new TestParameters().provide(); } @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } @Before public void setUp() { initJadlerUsing(this.serverFactory.createServer()); } @After public void tearDown() { closeJadler(); } @Test(timeout = 10000L) public void timeout() throws IOException {
onRequest().respond().withStatus(201);
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/TimeoutIntegrationTest.java
// Path: jadler-all/src/test/java/net/jadler/parameters/TestParameters.java // public class TestParameters { // // /** // * @return parameters for acceptance/integration tests located in this module. The fugly return type // * is required by the jUnit parameters mechanism. It basically returns two stub server factories as // * test parameters. // */ // public Iterable<StubHttpServerFactory[]> provide() { // // return Arrays.asList( // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JettyStubHttpServer(); // } // }), // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JdkStubHttpServer(); // } // }) // ); // } // // private StubHttpServerFactory[] singletonArray(final StubHttpServerFactory server) { // return new StubHttpServerFactory[]{server}; // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static final StatusRetriever STATUS_RETRIEVER = new StatusRetriever(); // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // }
import net.jadler.parameters.StubHttpServerFactory; import net.jadler.parameters.TestParameters; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadlerUsing; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.STATUS_RETRIEVER; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * When a timeout value is defined in a jUnit test, the test is executed in a different thread than the thread * executing the setup and teardown methods thus a separated test for it. */ @RunWith(Parameterized.class) public class TimeoutIntegrationTest { private final StubHttpServerFactory serverFactory; public TimeoutIntegrationTest(final StubHttpServerFactory serverFactory) { this.serverFactory = serverFactory; } @Parameterized.Parameters public static Iterable<StubHttpServerFactory[]> parameters() { return new TestParameters().provide(); } @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } @Before public void setUp() { initJadlerUsing(this.serverFactory.createServer()); } @After public void tearDown() { closeJadler(); } @Test(timeout = 10000L) public void timeout() throws IOException { onRequest().respond().withStatus(201);
// Path: jadler-all/src/test/java/net/jadler/parameters/TestParameters.java // public class TestParameters { // // /** // * @return parameters for acceptance/integration tests located in this module. The fugly return type // * is required by the jUnit parameters mechanism. It basically returns two stub server factories as // * test parameters. // */ // public Iterable<StubHttpServerFactory[]> provide() { // // return Arrays.asList( // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JettyStubHttpServer(); // } // }), // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JdkStubHttpServer(); // } // }) // ); // } // // private StubHttpServerFactory[] singletonArray(final StubHttpServerFactory server) { // return new StubHttpServerFactory[]{server}; // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static final StatusRetriever STATUS_RETRIEVER = new StatusRetriever(); // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // Path: jadler-all/src/test/java/net/jadler/TimeoutIntegrationTest.java import net.jadler.parameters.StubHttpServerFactory; import net.jadler.parameters.TestParameters; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadlerUsing; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.STATUS_RETRIEVER; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * When a timeout value is defined in a jUnit test, the test is executed in a different thread than the thread * executing the setup and teardown methods thus a separated test for it. */ @RunWith(Parameterized.class) public class TimeoutIntegrationTest { private final StubHttpServerFactory serverFactory; public TimeoutIntegrationTest(final StubHttpServerFactory serverFactory) { this.serverFactory = serverFactory; } @Parameterized.Parameters public static Iterable<StubHttpServerFactory[]> parameters() { return new TestParameters().provide(); } @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } @Before public void setUp() { initJadlerUsing(this.serverFactory.createServer()); } @After public void tearDown() { closeJadler(); } @Test(timeout = 10000L) public void timeout() throws IOException { onRequest().respond().withStatus(201);
final int status = Executor.newInstance().execute(Request.Get(jadlerUri())).handleResponse(STATUS_RETRIEVER);
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/TimeoutIntegrationTest.java
// Path: jadler-all/src/test/java/net/jadler/parameters/TestParameters.java // public class TestParameters { // // /** // * @return parameters for acceptance/integration tests located in this module. The fugly return type // * is required by the jUnit parameters mechanism. It basically returns two stub server factories as // * test parameters. // */ // public Iterable<StubHttpServerFactory[]> provide() { // // return Arrays.asList( // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JettyStubHttpServer(); // } // }), // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JdkStubHttpServer(); // } // }) // ); // } // // private StubHttpServerFactory[] singletonArray(final StubHttpServerFactory server) { // return new StubHttpServerFactory[]{server}; // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static final StatusRetriever STATUS_RETRIEVER = new StatusRetriever(); // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // }
import net.jadler.parameters.StubHttpServerFactory; import net.jadler.parameters.TestParameters; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadlerUsing; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.STATUS_RETRIEVER; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * When a timeout value is defined in a jUnit test, the test is executed in a different thread than the thread * executing the setup and teardown methods thus a separated test for it. */ @RunWith(Parameterized.class) public class TimeoutIntegrationTest { private final StubHttpServerFactory serverFactory; public TimeoutIntegrationTest(final StubHttpServerFactory serverFactory) { this.serverFactory = serverFactory; } @Parameterized.Parameters public static Iterable<StubHttpServerFactory[]> parameters() { return new TestParameters().provide(); } @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } @Before public void setUp() { initJadlerUsing(this.serverFactory.createServer()); } @After public void tearDown() { closeJadler(); } @Test(timeout = 10000L) public void timeout() throws IOException { onRequest().respond().withStatus(201);
// Path: jadler-all/src/test/java/net/jadler/parameters/TestParameters.java // public class TestParameters { // // /** // * @return parameters for acceptance/integration tests located in this module. The fugly return type // * is required by the jUnit parameters mechanism. It basically returns two stub server factories as // * test parameters. // */ // public Iterable<StubHttpServerFactory[]> provide() { // // return Arrays.asList( // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JettyStubHttpServer(); // } // }), // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JdkStubHttpServer(); // } // }) // ); // } // // private StubHttpServerFactory[] singletonArray(final StubHttpServerFactory server) { // return new StubHttpServerFactory[]{server}; // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static final StatusRetriever STATUS_RETRIEVER = new StatusRetriever(); // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // Path: jadler-all/src/test/java/net/jadler/TimeoutIntegrationTest.java import net.jadler.parameters.StubHttpServerFactory; import net.jadler.parameters.TestParameters; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadlerUsing; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.STATUS_RETRIEVER; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * When a timeout value is defined in a jUnit test, the test is executed in a different thread than the thread * executing the setup and teardown methods thus a separated test for it. */ @RunWith(Parameterized.class) public class TimeoutIntegrationTest { private final StubHttpServerFactory serverFactory; public TimeoutIntegrationTest(final StubHttpServerFactory serverFactory) { this.serverFactory = serverFactory; } @Parameterized.Parameters public static Iterable<StubHttpServerFactory[]> parameters() { return new TestParameters().provide(); } @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } @Before public void setUp() { initJadlerUsing(this.serverFactory.createServer()); } @After public void tearDown() { closeJadler(); } @Test(timeout = 10000L) public void timeout() throws IOException { onRequest().respond().withStatus(201);
final int status = Executor.newInstance().execute(Request.Get(jadlerUri())).handleResponse(STATUS_RETRIEVER);
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/AbstractResetIntegrationTest.java
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void resetJadler() { // final JadlerMocker mocker = jadlerMockerContainer.get(); // if (mocker != null) { // mocker.reset(); // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static final StatusRetriever STATUS_RETRIEVER = new StatusRetriever(); // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // }
import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Test; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.resetJadler; import static net.jadler.Jadler.verifyThatRequest; import static net.jadler.utils.TestUtils.STATUS_RETRIEVER; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * <p>Tests the alternative reset scenario. The stub server is started and stopped only once (before and after the * whole suite) and reset after every test.</p> * * <p>Please note this test class is abstract. The particular extensions must provide their own {@code BeforeClass} * method which initializes Jadler using the desired stub server and instructing it to use {@link #DEFAULT_STATUS} as * a default response status.</p> * * @see JdkResetIntegrationTest * @see JettyResetIntegrationTest */ public abstract class AbstractResetIntegrationTest { protected static final int DEFAULT_STATUS = 409; /** * Shutdown Jadler after the whole test suite */ @AfterClass public static void close() {
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void resetJadler() { // final JadlerMocker mocker = jadlerMockerContainer.get(); // if (mocker != null) { // mocker.reset(); // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static final StatusRetriever STATUS_RETRIEVER = new StatusRetriever(); // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // Path: jadler-all/src/test/java/net/jadler/AbstractResetIntegrationTest.java import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Test; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.resetJadler; import static net.jadler.Jadler.verifyThatRequest; import static net.jadler.utils.TestUtils.STATUS_RETRIEVER; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * <p>Tests the alternative reset scenario. The stub server is started and stopped only once (before and after the * whole suite) and reset after every test.</p> * * <p>Please note this test class is abstract. The particular extensions must provide their own {@code BeforeClass} * method which initializes Jadler using the desired stub server and instructing it to use {@link #DEFAULT_STATUS} as * a default response status.</p> * * @see JdkResetIntegrationTest * @see JettyResetIntegrationTest */ public abstract class AbstractResetIntegrationTest { protected static final int DEFAULT_STATUS = 409; /** * Shutdown Jadler after the whole test suite */ @AfterClass public static void close() {
closeJadler();
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/AbstractResetIntegrationTest.java
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void resetJadler() { // final JadlerMocker mocker = jadlerMockerContainer.get(); // if (mocker != null) { // mocker.reset(); // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static final StatusRetriever STATUS_RETRIEVER = new StatusRetriever(); // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // }
import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Test; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.resetJadler; import static net.jadler.Jadler.verifyThatRequest; import static net.jadler.utils.TestUtils.STATUS_RETRIEVER; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * <p>Tests the alternative reset scenario. The stub server is started and stopped only once (before and after the * whole suite) and reset after every test.</p> * * <p>Please note this test class is abstract. The particular extensions must provide their own {@code BeforeClass} * method which initializes Jadler using the desired stub server and instructing it to use {@link #DEFAULT_STATUS} as * a default response status.</p> * * @see JdkResetIntegrationTest * @see JettyResetIntegrationTest */ public abstract class AbstractResetIntegrationTest { protected static final int DEFAULT_STATUS = 409; /** * Shutdown Jadler after the whole test suite */ @AfterClass public static void close() { closeJadler(); Executor.closeIdleConnections(); } /** * Reset Jadler after each test * * @see Jadler#resetJadler() */ @After public void reset() {
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void resetJadler() { // final JadlerMocker mocker = jadlerMockerContainer.get(); // if (mocker != null) { // mocker.reset(); // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static final StatusRetriever STATUS_RETRIEVER = new StatusRetriever(); // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // Path: jadler-all/src/test/java/net/jadler/AbstractResetIntegrationTest.java import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Test; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.resetJadler; import static net.jadler.Jadler.verifyThatRequest; import static net.jadler.utils.TestUtils.STATUS_RETRIEVER; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * <p>Tests the alternative reset scenario. The stub server is started and stopped only once (before and after the * whole suite) and reset after every test.</p> * * <p>Please note this test class is abstract. The particular extensions must provide their own {@code BeforeClass} * method which initializes Jadler using the desired stub server and instructing it to use {@link #DEFAULT_STATUS} as * a default response status.</p> * * @see JdkResetIntegrationTest * @see JettyResetIntegrationTest */ public abstract class AbstractResetIntegrationTest { protected static final int DEFAULT_STATUS = 409; /** * Shutdown Jadler after the whole test suite */ @AfterClass public static void close() { closeJadler(); Executor.closeIdleConnections(); } /** * Reset Jadler after each test * * @see Jadler#resetJadler() */ @After public void reset() {
resetJadler();
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/AbstractResetIntegrationTest.java
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void resetJadler() { // final JadlerMocker mocker = jadlerMockerContainer.get(); // if (mocker != null) { // mocker.reset(); // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static final StatusRetriever STATUS_RETRIEVER = new StatusRetriever(); // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // }
import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Test; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.resetJadler; import static net.jadler.Jadler.verifyThatRequest; import static net.jadler.utils.TestUtils.STATUS_RETRIEVER; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * <p>Tests the alternative reset scenario. The stub server is started and stopped only once (before and after the * whole suite) and reset after every test.</p> * * <p>Please note this test class is abstract. The particular extensions must provide their own {@code BeforeClass} * method which initializes Jadler using the desired stub server and instructing it to use {@link #DEFAULT_STATUS} as * a default response status.</p> * * @see JdkResetIntegrationTest * @see JettyResetIntegrationTest */ public abstract class AbstractResetIntegrationTest { protected static final int DEFAULT_STATUS = 409; /** * Shutdown Jadler after the whole test suite */ @AfterClass public static void close() { closeJadler(); Executor.closeIdleConnections(); } /** * Reset Jadler after each test * * @see Jadler#resetJadler() */ @After public void reset() { resetJadler(); } /* * Tests this test is independent on the rest of the tests (e.g. Jadler has been correctly reset, * all previously recorded requests have been deleted as well as all previously created stubs) */ @Test public void test200() throws IOException {
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void resetJadler() { // final JadlerMocker mocker = jadlerMockerContainer.get(); // if (mocker != null) { // mocker.reset(); // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static final StatusRetriever STATUS_RETRIEVER = new StatusRetriever(); // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // Path: jadler-all/src/test/java/net/jadler/AbstractResetIntegrationTest.java import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Test; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.resetJadler; import static net.jadler.Jadler.verifyThatRequest; import static net.jadler.utils.TestUtils.STATUS_RETRIEVER; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * <p>Tests the alternative reset scenario. The stub server is started and stopped only once (before and after the * whole suite) and reset after every test.</p> * * <p>Please note this test class is abstract. The particular extensions must provide their own {@code BeforeClass} * method which initializes Jadler using the desired stub server and instructing it to use {@link #DEFAULT_STATUS} as * a default response status.</p> * * @see JdkResetIntegrationTest * @see JettyResetIntegrationTest */ public abstract class AbstractResetIntegrationTest { protected static final int DEFAULT_STATUS = 409; /** * Shutdown Jadler after the whole test suite */ @AfterClass public static void close() { closeJadler(); Executor.closeIdleConnections(); } /** * Reset Jadler after each test * * @see Jadler#resetJadler() */ @After public void reset() { resetJadler(); } /* * Tests this test is independent on the rest of the tests (e.g. Jadler has been correctly reset, * all previously recorded requests have been deleted as well as all previously created stubs) */ @Test public void test200() throws IOException {
onRequest().respond().withStatus(200);
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/AbstractResetIntegrationTest.java
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void resetJadler() { // final JadlerMocker mocker = jadlerMockerContainer.get(); // if (mocker != null) { // mocker.reset(); // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static final StatusRetriever STATUS_RETRIEVER = new StatusRetriever(); // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // }
import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Test; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.resetJadler; import static net.jadler.Jadler.verifyThatRequest; import static net.jadler.utils.TestUtils.STATUS_RETRIEVER; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * <p>Tests the alternative reset scenario. The stub server is started and stopped only once (before and after the * whole suite) and reset after every test.</p> * * <p>Please note this test class is abstract. The particular extensions must provide their own {@code BeforeClass} * method which initializes Jadler using the desired stub server and instructing it to use {@link #DEFAULT_STATUS} as * a default response status.</p> * * @see JdkResetIntegrationTest * @see JettyResetIntegrationTest */ public abstract class AbstractResetIntegrationTest { protected static final int DEFAULT_STATUS = 409; /** * Shutdown Jadler after the whole test suite */ @AfterClass public static void close() { closeJadler(); Executor.closeIdleConnections(); } /** * Reset Jadler after each test * * @see Jadler#resetJadler() */ @After public void reset() { resetJadler(); } /* * Tests this test is independent on the rest of the tests (e.g. Jadler has been correctly reset, * all previously recorded requests have been deleted as well as all previously created stubs) */ @Test public void test200() throws IOException { onRequest().respond().withStatus(200);
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void resetJadler() { // final JadlerMocker mocker = jadlerMockerContainer.get(); // if (mocker != null) { // mocker.reset(); // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static final StatusRetriever STATUS_RETRIEVER = new StatusRetriever(); // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // Path: jadler-all/src/test/java/net/jadler/AbstractResetIntegrationTest.java import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Test; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.resetJadler; import static net.jadler.Jadler.verifyThatRequest; import static net.jadler.utils.TestUtils.STATUS_RETRIEVER; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * <p>Tests the alternative reset scenario. The stub server is started and stopped only once (before and after the * whole suite) and reset after every test.</p> * * <p>Please note this test class is abstract. The particular extensions must provide their own {@code BeforeClass} * method which initializes Jadler using the desired stub server and instructing it to use {@link #DEFAULT_STATUS} as * a default response status.</p> * * @see JdkResetIntegrationTest * @see JettyResetIntegrationTest */ public abstract class AbstractResetIntegrationTest { protected static final int DEFAULT_STATUS = 409; /** * Shutdown Jadler after the whole test suite */ @AfterClass public static void close() { closeJadler(); Executor.closeIdleConnections(); } /** * Reset Jadler after each test * * @see Jadler#resetJadler() */ @After public void reset() { resetJadler(); } /* * Tests this test is independent on the rest of the tests (e.g. Jadler has been correctly reset, * all previously recorded requests have been deleted as well as all previously created stubs) */ @Test public void test200() throws IOException { onRequest().respond().withStatus(200);
final int status = Executor.newInstance().execute(Request.Get(jadlerUri())).handleResponse(STATUS_RETRIEVER);
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/AbstractResetIntegrationTest.java
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void resetJadler() { // final JadlerMocker mocker = jadlerMockerContainer.get(); // if (mocker != null) { // mocker.reset(); // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static final StatusRetriever STATUS_RETRIEVER = new StatusRetriever(); // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // }
import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Test; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.resetJadler; import static net.jadler.Jadler.verifyThatRequest; import static net.jadler.utils.TestUtils.STATUS_RETRIEVER; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * <p>Tests the alternative reset scenario. The stub server is started and stopped only once (before and after the * whole suite) and reset after every test.</p> * * <p>Please note this test class is abstract. The particular extensions must provide their own {@code BeforeClass} * method which initializes Jadler using the desired stub server and instructing it to use {@link #DEFAULT_STATUS} as * a default response status.</p> * * @see JdkResetIntegrationTest * @see JettyResetIntegrationTest */ public abstract class AbstractResetIntegrationTest { protected static final int DEFAULT_STATUS = 409; /** * Shutdown Jadler after the whole test suite */ @AfterClass public static void close() { closeJadler(); Executor.closeIdleConnections(); } /** * Reset Jadler after each test * * @see Jadler#resetJadler() */ @After public void reset() { resetJadler(); } /* * Tests this test is independent on the rest of the tests (e.g. Jadler has been correctly reset, * all previously recorded requests have been deleted as well as all previously created stubs) */ @Test public void test200() throws IOException { onRequest().respond().withStatus(200);
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void resetJadler() { // final JadlerMocker mocker = jadlerMockerContainer.get(); // if (mocker != null) { // mocker.reset(); // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static final StatusRetriever STATUS_RETRIEVER = new StatusRetriever(); // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // Path: jadler-all/src/test/java/net/jadler/AbstractResetIntegrationTest.java import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Test; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.resetJadler; import static net.jadler.Jadler.verifyThatRequest; import static net.jadler.utils.TestUtils.STATUS_RETRIEVER; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * <p>Tests the alternative reset scenario. The stub server is started and stopped only once (before and after the * whole suite) and reset after every test.</p> * * <p>Please note this test class is abstract. The particular extensions must provide their own {@code BeforeClass} * method which initializes Jadler using the desired stub server and instructing it to use {@link #DEFAULT_STATUS} as * a default response status.</p> * * @see JdkResetIntegrationTest * @see JettyResetIntegrationTest */ public abstract class AbstractResetIntegrationTest { protected static final int DEFAULT_STATUS = 409; /** * Shutdown Jadler after the whole test suite */ @AfterClass public static void close() { closeJadler(); Executor.closeIdleConnections(); } /** * Reset Jadler after each test * * @see Jadler#resetJadler() */ @After public void reset() { resetJadler(); } /* * Tests this test is independent on the rest of the tests (e.g. Jadler has been correctly reset, * all previously recorded requests have been deleted as well as all previously created stubs) */ @Test public void test200() throws IOException { onRequest().respond().withStatus(200);
final int status = Executor.newInstance().execute(Request.Get(jadlerUri())).handleResponse(STATUS_RETRIEVER);
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/AbstractResetIntegrationTest.java
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void resetJadler() { // final JadlerMocker mocker = jadlerMockerContainer.get(); // if (mocker != null) { // mocker.reset(); // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static final StatusRetriever STATUS_RETRIEVER = new StatusRetriever(); // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // }
import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Test; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.resetJadler; import static net.jadler.Jadler.verifyThatRequest; import static net.jadler.utils.TestUtils.STATUS_RETRIEVER; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * <p>Tests the alternative reset scenario. The stub server is started and stopped only once (before and after the * whole suite) and reset after every test.</p> * * <p>Please note this test class is abstract. The particular extensions must provide their own {@code BeforeClass} * method which initializes Jadler using the desired stub server and instructing it to use {@link #DEFAULT_STATUS} as * a default response status.</p> * * @see JdkResetIntegrationTest * @see JettyResetIntegrationTest */ public abstract class AbstractResetIntegrationTest { protected static final int DEFAULT_STATUS = 409; /** * Shutdown Jadler after the whole test suite */ @AfterClass public static void close() { closeJadler(); Executor.closeIdleConnections(); } /** * Reset Jadler after each test * * @see Jadler#resetJadler() */ @After public void reset() { resetJadler(); } /* * Tests this test is independent on the rest of the tests (e.g. Jadler has been correctly reset, * all previously recorded requests have been deleted as well as all previously created stubs) */ @Test public void test200() throws IOException { onRequest().respond().withStatus(200); final int status = Executor.newInstance().execute(Request.Get(jadlerUri())).handleResponse(STATUS_RETRIEVER); assertThat(status, is(200));
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void resetJadler() { // final JadlerMocker mocker = jadlerMockerContainer.get(); // if (mocker != null) { // mocker.reset(); // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static Verifying verifyThatRequest() { // checkInitialized(); // return jadlerMockerContainer.get().verifyThatRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static final StatusRetriever STATUS_RETRIEVER = new StatusRetriever(); // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // Path: jadler-all/src/test/java/net/jadler/AbstractResetIntegrationTest.java import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Test; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.Jadler.resetJadler; import static net.jadler.Jadler.verifyThatRequest; import static net.jadler.utils.TestUtils.STATUS_RETRIEVER; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * <p>Tests the alternative reset scenario. The stub server is started and stopped only once (before and after the * whole suite) and reset after every test.</p> * * <p>Please note this test class is abstract. The particular extensions must provide their own {@code BeforeClass} * method which initializes Jadler using the desired stub server and instructing it to use {@link #DEFAULT_STATUS} as * a default response status.</p> * * @see JdkResetIntegrationTest * @see JettyResetIntegrationTest */ public abstract class AbstractResetIntegrationTest { protected static final int DEFAULT_STATUS = 409; /** * Shutdown Jadler after the whole test suite */ @AfterClass public static void close() { closeJadler(); Executor.closeIdleConnections(); } /** * Reset Jadler after each test * * @see Jadler#resetJadler() */ @After public void reset() { resetJadler(); } /* * Tests this test is independent on the rest of the tests (e.g. Jadler has been correctly reset, * all previously recorded requests have been deleted as well as all previously created stubs) */ @Test public void test200() throws IOException { onRequest().respond().withStatus(200); final int status = Executor.newInstance().execute(Request.Get(jadlerUri())).handleResponse(STATUS_RETRIEVER); assertThat(status, is(200));
verifyThatRequest().receivedOnce();
jadler-mocking/jadler
jadler-core/src/test/java/net/jadler/stubbing/StubResponseTest.java
// Path: jadler-core/src/main/java/net/jadler/KeyValues.java // public class KeyValues { // // /** // * An empty instance. // */ // public static final KeyValues EMPTY = new KeyValues(); // private final MultiMap values; // // // /** // * Creates new empty instance. // */ // public KeyValues() { // this.values = new MultiValueMap(); // } // // // /** // * Adds new key-value pair. Supports multi-values for one key (if there has already been added // * some value with this key, additional value is added instead of rewriting). Please note this method // * creates new instance containing all existing values plus the new one rather than modifying this instance. // * // * @param key key (cannot be empty) // * @param value value (cannot be {@code null}, however can be empty for valueless headers) // * @return an exact copy of this instance containing all existing values plus the new one // */ // @SuppressWarnings("unchecked") // public KeyValues add(final String key, final String value) { // Validate.notEmpty(key, "key cannot be empty"); // Validate.notNull(value, "value cannot be null, use an empty string instead"); // // final KeyValues res = new KeyValues(); // res.values.putAll(this.values); // res.values.put(key.toLowerCase(), value); // // return res; // } // // // /** // * Adds all values from the given instance. Supports multi-values for one key (if there has already been added // * some value with this key, additional value is added instead of rewriting). Please note this method // * creates new instance containing all existing values plus the new ones rather than modifying this instance. // * // * @param keyValues values to be added no(cannot be {@code null}) // * @return an exact copy of this instance containing all existing values plus the new ones // */ // @SuppressWarnings("unchecked") // public KeyValues addAll(final KeyValues keyValues) { // Validate.notNull(keyValues, "keyValues cannot be null"); // // final KeyValues res = new KeyValues(); // res.values.putAll(this.values); // res.values.putAll(keyValues.values); // return res; // } // // // /** // * Returns the first value for the given key // * // * @param key key (case insensitive) // * @return single (first) value for the given key or {@code null}, if there is no such a key in this instance // */ // public String getValue(final String key) { // Validate.notEmpty(key, "key cannot be empty"); // // final List<String> allValues = this.getValues(key); // return allValues != null ? allValues.get(0) : null; // } // // // /** // * Returns all values for the given key // * // * @param key key (case insensitive) // * @return all values of the given header or {@code null}, if there is no such a key in this instance // */ // public List<String> getValues(final String key) { // Validate.notEmpty(key, "name cannot be empty"); // // @SuppressWarnings("unchecked") final List<String> result = (List<String>) values.get(key.toLowerCase()); // return result == null || result.isEmpty() ? null : new ArrayList<String>(result); // } // // // /** // * @return all keys (lower-cased) from this instance (never returns {@code null}) // */ // public Set<String> getKeys() { // @SuppressWarnings("unchecked") final Set<String> result = new HashSet<String>(this.values.keySet()); // return result; // } // // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder(); // for (@SuppressWarnings("unchecked") final Iterator<Map.Entry<String, Collection<String>>> it // = this.values.entrySet().iterator(); it.hasNext(); ) { // final Map.Entry<String, Collection<String>> e = it.next(); // // for (final Iterator<String> it2 = e.getValue().iterator(); it2.hasNext(); ) { // sb.append(e.getKey()).append(": ").append(it2.next()); // if (it2.hasNext()) { // sb.append(", "); // } // } // // if (it.hasNext()) { // sb.append(", "); // } // } // // return sb.toString(); // } // // // @Override // public int hashCode() { // int hash = 5; // hash = 43 * hash + (this.values != null ? this.values.hashCode() : 0); // return hash; // } // // // @Override // public boolean equals(final Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final KeyValues other = (KeyValues) obj; // if (this.values != other.values && (this.values == null || !this.values.equals(other.values))) { // return false; // } // return true; // } // }
import net.jadler.KeyValues; import org.junit.Test; import java.nio.charset.Charset; import java.util.concurrent.TimeUnit; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.stubbing; public class StubResponseTest { private static final String STRING_WITH_DIACRITICS = "\u00e1\u0159\u017e"; private static final byte[] UTF_8_REPRESENTATION = {(byte) 0xC3, (byte) 0xA1, (byte) 0xC5, (byte) 0x99, (byte) 0xC5, (byte) 0xBE}; private static final Charset UTF_8_CHARSET = Charset.forName("UTF-8"); private static final String HEADERS_TO_STRING = "headers_to_string";
// Path: jadler-core/src/main/java/net/jadler/KeyValues.java // public class KeyValues { // // /** // * An empty instance. // */ // public static final KeyValues EMPTY = new KeyValues(); // private final MultiMap values; // // // /** // * Creates new empty instance. // */ // public KeyValues() { // this.values = new MultiValueMap(); // } // // // /** // * Adds new key-value pair. Supports multi-values for one key (if there has already been added // * some value with this key, additional value is added instead of rewriting). Please note this method // * creates new instance containing all existing values plus the new one rather than modifying this instance. // * // * @param key key (cannot be empty) // * @param value value (cannot be {@code null}, however can be empty for valueless headers) // * @return an exact copy of this instance containing all existing values plus the new one // */ // @SuppressWarnings("unchecked") // public KeyValues add(final String key, final String value) { // Validate.notEmpty(key, "key cannot be empty"); // Validate.notNull(value, "value cannot be null, use an empty string instead"); // // final KeyValues res = new KeyValues(); // res.values.putAll(this.values); // res.values.put(key.toLowerCase(), value); // // return res; // } // // // /** // * Adds all values from the given instance. Supports multi-values for one key (if there has already been added // * some value with this key, additional value is added instead of rewriting). Please note this method // * creates new instance containing all existing values plus the new ones rather than modifying this instance. // * // * @param keyValues values to be added no(cannot be {@code null}) // * @return an exact copy of this instance containing all existing values plus the new ones // */ // @SuppressWarnings("unchecked") // public KeyValues addAll(final KeyValues keyValues) { // Validate.notNull(keyValues, "keyValues cannot be null"); // // final KeyValues res = new KeyValues(); // res.values.putAll(this.values); // res.values.putAll(keyValues.values); // return res; // } // // // /** // * Returns the first value for the given key // * // * @param key key (case insensitive) // * @return single (first) value for the given key or {@code null}, if there is no such a key in this instance // */ // public String getValue(final String key) { // Validate.notEmpty(key, "key cannot be empty"); // // final List<String> allValues = this.getValues(key); // return allValues != null ? allValues.get(0) : null; // } // // // /** // * Returns all values for the given key // * // * @param key key (case insensitive) // * @return all values of the given header or {@code null}, if there is no such a key in this instance // */ // public List<String> getValues(final String key) { // Validate.notEmpty(key, "name cannot be empty"); // // @SuppressWarnings("unchecked") final List<String> result = (List<String>) values.get(key.toLowerCase()); // return result == null || result.isEmpty() ? null : new ArrayList<String>(result); // } // // // /** // * @return all keys (lower-cased) from this instance (never returns {@code null}) // */ // public Set<String> getKeys() { // @SuppressWarnings("unchecked") final Set<String> result = new HashSet<String>(this.values.keySet()); // return result; // } // // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder(); // for (@SuppressWarnings("unchecked") final Iterator<Map.Entry<String, Collection<String>>> it // = this.values.entrySet().iterator(); it.hasNext(); ) { // final Map.Entry<String, Collection<String>> e = it.next(); // // for (final Iterator<String> it2 = e.getValue().iterator(); it2.hasNext(); ) { // sb.append(e.getKey()).append(": ").append(it2.next()); // if (it2.hasNext()) { // sb.append(", "); // } // } // // if (it.hasNext()) { // sb.append(", "); // } // } // // return sb.toString(); // } // // // @Override // public int hashCode() { // int hash = 5; // hash = 43 * hash + (this.values != null ? this.values.hashCode() : 0); // return hash; // } // // // @Override // public boolean equals(final Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final KeyValues other = (KeyValues) obj; // if (this.values != other.values && (this.values == null || !this.values.equals(other.values))) { // return false; // } // return true; // } // } // Path: jadler-core/src/test/java/net/jadler/stubbing/StubResponseTest.java import net.jadler.KeyValues; import org.junit.Test; import java.nio.charset.Charset; import java.util.concurrent.TimeUnit; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.stubbing; public class StubResponseTest { private static final String STRING_WITH_DIACRITICS = "\u00e1\u0159\u017e"; private static final byte[] UTF_8_REPRESENTATION = {(byte) 0xC3, (byte) 0xA1, (byte) 0xC5, (byte) 0x99, (byte) 0xC5, (byte) 0xBE}; private static final Charset UTF_8_CHARSET = Charset.forName("UTF-8"); private static final String HEADERS_TO_STRING = "headers_to_string";
private static final KeyValues DEFAULT_HEADERS = new KeyValues()
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/StubbingResponseHeadersTest.java
// Path: jadler-all/src/test/java/net/jadler/parameters/TestParameters.java // public class TestParameters { // // /** // * @return parameters for acceptance/integration tests located in this module. The fugly return type // * is required by the jUnit parameters mechanism. It basically returns two stub server factories as // * test parameters. // */ // public Iterable<StubHttpServerFactory[]> provide() { // // return Arrays.asList( // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JettyStubHttpServer(); // } // }), // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JdkStubHttpServer(); // } // }) // ); // } // // private StubHttpServerFactory[] singletonArray(final StubHttpServerFactory server) { // return new StubHttpServerFactory[]{server}; // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // }
import net.jadler.parameters.StubHttpServerFactory; import net.jadler.parameters.TestParameters; import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadlerUsing; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * Integration test for default response headers. */ @RunWith(Parameterized.class) public class StubbingResponseHeadersTest { private final StubHttpServerFactory serverFactory; public StubbingResponseHeadersTest(final StubHttpServerFactory serverFactory) { this.serverFactory = serverFactory; } @Parameterized.Parameters public static Iterable<StubHttpServerFactory[]> parameters() {
// Path: jadler-all/src/test/java/net/jadler/parameters/TestParameters.java // public class TestParameters { // // /** // * @return parameters for acceptance/integration tests located in this module. The fugly return type // * is required by the jUnit parameters mechanism. It basically returns two stub server factories as // * test parameters. // */ // public Iterable<StubHttpServerFactory[]> provide() { // // return Arrays.asList( // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JettyStubHttpServer(); // } // }), // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JdkStubHttpServer(); // } // }) // ); // } // // private StubHttpServerFactory[] singletonArray(final StubHttpServerFactory server) { // return new StubHttpServerFactory[]{server}; // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // Path: jadler-all/src/test/java/net/jadler/StubbingResponseHeadersTest.java import net.jadler.parameters.StubHttpServerFactory; import net.jadler.parameters.TestParameters; import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadlerUsing; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * Integration test for default response headers. */ @RunWith(Parameterized.class) public class StubbingResponseHeadersTest { private final StubHttpServerFactory serverFactory; public StubbingResponseHeadersTest(final StubHttpServerFactory serverFactory) { this.serverFactory = serverFactory; } @Parameterized.Parameters public static Iterable<StubHttpServerFactory[]> parameters() {
return new TestParameters().provide();
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/StubbingResponseHeadersTest.java
// Path: jadler-all/src/test/java/net/jadler/parameters/TestParameters.java // public class TestParameters { // // /** // * @return parameters for acceptance/integration tests located in this module. The fugly return type // * is required by the jUnit parameters mechanism. It basically returns two stub server factories as // * test parameters. // */ // public Iterable<StubHttpServerFactory[]> provide() { // // return Arrays.asList( // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JettyStubHttpServer(); // } // }), // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JdkStubHttpServer(); // } // }) // ); // } // // private StubHttpServerFactory[] singletonArray(final StubHttpServerFactory server) { // return new StubHttpServerFactory[]{server}; // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // }
import net.jadler.parameters.StubHttpServerFactory; import net.jadler.parameters.TestParameters; import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadlerUsing; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * Integration test for default response headers. */ @RunWith(Parameterized.class) public class StubbingResponseHeadersTest { private final StubHttpServerFactory serverFactory; public StubbingResponseHeadersTest(final StubHttpServerFactory serverFactory) { this.serverFactory = serverFactory; } @Parameterized.Parameters public static Iterable<StubHttpServerFactory[]> parameters() { return new TestParameters().provide(); } @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } @Before public void setUp() {
// Path: jadler-all/src/test/java/net/jadler/parameters/TestParameters.java // public class TestParameters { // // /** // * @return parameters for acceptance/integration tests located in this module. The fugly return type // * is required by the jUnit parameters mechanism. It basically returns two stub server factories as // * test parameters. // */ // public Iterable<StubHttpServerFactory[]> provide() { // // return Arrays.asList( // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JettyStubHttpServer(); // } // }), // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JdkStubHttpServer(); // } // }) // ); // } // // private StubHttpServerFactory[] singletonArray(final StubHttpServerFactory server) { // return new StubHttpServerFactory[]{server}; // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // Path: jadler-all/src/test/java/net/jadler/StubbingResponseHeadersTest.java import net.jadler.parameters.StubHttpServerFactory; import net.jadler.parameters.TestParameters; import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadlerUsing; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * Integration test for default response headers. */ @RunWith(Parameterized.class) public class StubbingResponseHeadersTest { private final StubHttpServerFactory serverFactory; public StubbingResponseHeadersTest(final StubHttpServerFactory serverFactory) { this.serverFactory = serverFactory; } @Parameterized.Parameters public static Iterable<StubHttpServerFactory[]> parameters() { return new TestParameters().provide(); } @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } @Before public void setUp() {
initJadlerUsing(serverFactory.createServer());
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/StubbingResponseHeadersTest.java
// Path: jadler-all/src/test/java/net/jadler/parameters/TestParameters.java // public class TestParameters { // // /** // * @return parameters for acceptance/integration tests located in this module. The fugly return type // * is required by the jUnit parameters mechanism. It basically returns two stub server factories as // * test parameters. // */ // public Iterable<StubHttpServerFactory[]> provide() { // // return Arrays.asList( // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JettyStubHttpServer(); // } // }), // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JdkStubHttpServer(); // } // }) // ); // } // // private StubHttpServerFactory[] singletonArray(final StubHttpServerFactory server) { // return new StubHttpServerFactory[]{server}; // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // }
import net.jadler.parameters.StubHttpServerFactory; import net.jadler.parameters.TestParameters; import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadlerUsing; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * Integration test for default response headers. */ @RunWith(Parameterized.class) public class StubbingResponseHeadersTest { private final StubHttpServerFactory serverFactory; public StubbingResponseHeadersTest(final StubHttpServerFactory serverFactory) { this.serverFactory = serverFactory; } @Parameterized.Parameters public static Iterable<StubHttpServerFactory[]> parameters() { return new TestParameters().provide(); } @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } @Before public void setUp() { initJadlerUsing(serverFactory.createServer()); } @After public void tearDown() {
// Path: jadler-all/src/test/java/net/jadler/parameters/TestParameters.java // public class TestParameters { // // /** // * @return parameters for acceptance/integration tests located in this module. The fugly return type // * is required by the jUnit parameters mechanism. It basically returns two stub server factories as // * test parameters. // */ // public Iterable<StubHttpServerFactory[]> provide() { // // return Arrays.asList( // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JettyStubHttpServer(); // } // }), // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JdkStubHttpServer(); // } // }) // ); // } // // private StubHttpServerFactory[] singletonArray(final StubHttpServerFactory server) { // return new StubHttpServerFactory[]{server}; // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // Path: jadler-all/src/test/java/net/jadler/StubbingResponseHeadersTest.java import net.jadler.parameters.StubHttpServerFactory; import net.jadler.parameters.TestParameters; import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadlerUsing; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * Integration test for default response headers. */ @RunWith(Parameterized.class) public class StubbingResponseHeadersTest { private final StubHttpServerFactory serverFactory; public StubbingResponseHeadersTest(final StubHttpServerFactory serverFactory) { this.serverFactory = serverFactory; } @Parameterized.Parameters public static Iterable<StubHttpServerFactory[]> parameters() { return new TestParameters().provide(); } @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } @Before public void setUp() { initJadlerUsing(serverFactory.createServer()); } @After public void tearDown() {
closeJadler();
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/StubbingResponseHeadersTest.java
// Path: jadler-all/src/test/java/net/jadler/parameters/TestParameters.java // public class TestParameters { // // /** // * @return parameters for acceptance/integration tests located in this module. The fugly return type // * is required by the jUnit parameters mechanism. It basically returns two stub server factories as // * test parameters. // */ // public Iterable<StubHttpServerFactory[]> provide() { // // return Arrays.asList( // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JettyStubHttpServer(); // } // }), // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JdkStubHttpServer(); // } // }) // ); // } // // private StubHttpServerFactory[] singletonArray(final StubHttpServerFactory server) { // return new StubHttpServerFactory[]{server}; // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // }
import net.jadler.parameters.StubHttpServerFactory; import net.jadler.parameters.TestParameters; import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadlerUsing; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * Integration test for default response headers. */ @RunWith(Parameterized.class) public class StubbingResponseHeadersTest { private final StubHttpServerFactory serverFactory; public StubbingResponseHeadersTest(final StubHttpServerFactory serverFactory) { this.serverFactory = serverFactory; } @Parameterized.Parameters public static Iterable<StubHttpServerFactory[]> parameters() { return new TestParameters().provide(); } @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } @Before public void setUp() { initJadlerUsing(serverFactory.createServer()); } @After public void tearDown() { closeJadler(); } /* * Checks that exactly two default headers (Date and Content-Lenght) are sent in a stub response. */ @Test public void allHeaders() throws IOException {
// Path: jadler-all/src/test/java/net/jadler/parameters/TestParameters.java // public class TestParameters { // // /** // * @return parameters for acceptance/integration tests located in this module. The fugly return type // * is required by the jUnit parameters mechanism. It basically returns two stub server factories as // * test parameters. // */ // public Iterable<StubHttpServerFactory[]> provide() { // // return Arrays.asList( // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JettyStubHttpServer(); // } // }), // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JdkStubHttpServer(); // } // }) // ); // } // // private StubHttpServerFactory[] singletonArray(final StubHttpServerFactory server) { // return new StubHttpServerFactory[]{server}; // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // Path: jadler-all/src/test/java/net/jadler/StubbingResponseHeadersTest.java import net.jadler.parameters.StubHttpServerFactory; import net.jadler.parameters.TestParameters; import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadlerUsing; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * Integration test for default response headers. */ @RunWith(Parameterized.class) public class StubbingResponseHeadersTest { private final StubHttpServerFactory serverFactory; public StubbingResponseHeadersTest(final StubHttpServerFactory serverFactory) { this.serverFactory = serverFactory; } @Parameterized.Parameters public static Iterable<StubHttpServerFactory[]> parameters() { return new TestParameters().provide(); } @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } @Before public void setUp() { initJadlerUsing(serverFactory.createServer()); } @After public void tearDown() { closeJadler(); } /* * Checks that exactly two default headers (Date and Content-Lenght) are sent in a stub response. */ @Test public void allHeaders() throws IOException {
onRequest().respond().withBody("13 chars long");
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/StubbingResponseHeadersTest.java
// Path: jadler-all/src/test/java/net/jadler/parameters/TestParameters.java // public class TestParameters { // // /** // * @return parameters for acceptance/integration tests located in this module. The fugly return type // * is required by the jUnit parameters mechanism. It basically returns two stub server factories as // * test parameters. // */ // public Iterable<StubHttpServerFactory[]> provide() { // // return Arrays.asList( // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JettyStubHttpServer(); // } // }), // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JdkStubHttpServer(); // } // }) // ); // } // // private StubHttpServerFactory[] singletonArray(final StubHttpServerFactory server) { // return new StubHttpServerFactory[]{server}; // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // }
import net.jadler.parameters.StubHttpServerFactory; import net.jadler.parameters.TestParameters; import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadlerUsing; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * Integration test for default response headers. */ @RunWith(Parameterized.class) public class StubbingResponseHeadersTest { private final StubHttpServerFactory serverFactory; public StubbingResponseHeadersTest(final StubHttpServerFactory serverFactory) { this.serverFactory = serverFactory; } @Parameterized.Parameters public static Iterable<StubHttpServerFactory[]> parameters() { return new TestParameters().provide(); } @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } @Before public void setUp() { initJadlerUsing(serverFactory.createServer()); } @After public void tearDown() { closeJadler(); } /* * Checks that exactly two default headers (Date and Content-Lenght) are sent in a stub response. */ @Test public void allHeaders() throws IOException { onRequest().respond().withBody("13 chars long");
// Path: jadler-all/src/test/java/net/jadler/parameters/TestParameters.java // public class TestParameters { // // /** // * @return parameters for acceptance/integration tests located in this module. The fugly return type // * is required by the jUnit parameters mechanism. It basically returns two stub server factories as // * test parameters. // */ // public Iterable<StubHttpServerFactory[]> provide() { // // return Arrays.asList( // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JettyStubHttpServer(); // } // }), // singletonArray(new StubHttpServerFactory() { // @Override // public StubHttpServer createServer() { // return new JdkStubHttpServer(); // } // }) // ); // } // // private StubHttpServerFactory[] singletonArray(final StubHttpServerFactory server) { // return new StubHttpServerFactory[]{server}; // } // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadlerUsing(final StubHttpServer server) { // return initInternal(new JadlerMocker(server)); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // Path: jadler-all/src/test/java/net/jadler/StubbingResponseHeadersTest.java import net.jadler.parameters.StubHttpServerFactory; import net.jadler.parameters.TestParameters; import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadlerUsing; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * Integration test for default response headers. */ @RunWith(Parameterized.class) public class StubbingResponseHeadersTest { private final StubHttpServerFactory serverFactory; public StubbingResponseHeadersTest(final StubHttpServerFactory serverFactory) { this.serverFactory = serverFactory; } @Parameterized.Parameters public static Iterable<StubHttpServerFactory[]> parameters() { return new TestParameters().provide(); } @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } @Before public void setUp() { initJadlerUsing(serverFactory.createServer()); } @After public void tearDown() { closeJadler(); } /* * Checks that exactly two default headers (Date and Content-Lenght) are sent in a stub response. */ @Test public void allHeaders() throws IOException { onRequest().respond().withBody("13 chars long");
final HttpResponse resp = Executor.newInstance().execute(Request.Get(jadlerUri())).returnResponse();
jadler-mocking/jadler
jadler-core/src/main/java/net/jadler/stubbing/MutableStubResponse.java
// Path: jadler-core/src/main/java/net/jadler/KeyValues.java // public class KeyValues { // // /** // * An empty instance. // */ // public static final KeyValues EMPTY = new KeyValues(); // private final MultiMap values; // // // /** // * Creates new empty instance. // */ // public KeyValues() { // this.values = new MultiValueMap(); // } // // // /** // * Adds new key-value pair. Supports multi-values for one key (if there has already been added // * some value with this key, additional value is added instead of rewriting). Please note this method // * creates new instance containing all existing values plus the new one rather than modifying this instance. // * // * @param key key (cannot be empty) // * @param value value (cannot be {@code null}, however can be empty for valueless headers) // * @return an exact copy of this instance containing all existing values plus the new one // */ // @SuppressWarnings("unchecked") // public KeyValues add(final String key, final String value) { // Validate.notEmpty(key, "key cannot be empty"); // Validate.notNull(value, "value cannot be null, use an empty string instead"); // // final KeyValues res = new KeyValues(); // res.values.putAll(this.values); // res.values.put(key.toLowerCase(), value); // // return res; // } // // // /** // * Adds all values from the given instance. Supports multi-values for one key (if there has already been added // * some value with this key, additional value is added instead of rewriting). Please note this method // * creates new instance containing all existing values plus the new ones rather than modifying this instance. // * // * @param keyValues values to be added no(cannot be {@code null}) // * @return an exact copy of this instance containing all existing values plus the new ones // */ // @SuppressWarnings("unchecked") // public KeyValues addAll(final KeyValues keyValues) { // Validate.notNull(keyValues, "keyValues cannot be null"); // // final KeyValues res = new KeyValues(); // res.values.putAll(this.values); // res.values.putAll(keyValues.values); // return res; // } // // // /** // * Returns the first value for the given key // * // * @param key key (case insensitive) // * @return single (first) value for the given key or {@code null}, if there is no such a key in this instance // */ // public String getValue(final String key) { // Validate.notEmpty(key, "key cannot be empty"); // // final List<String> allValues = this.getValues(key); // return allValues != null ? allValues.get(0) : null; // } // // // /** // * Returns all values for the given key // * // * @param key key (case insensitive) // * @return all values of the given header or {@code null}, if there is no such a key in this instance // */ // public List<String> getValues(final String key) { // Validate.notEmpty(key, "name cannot be empty"); // // @SuppressWarnings("unchecked") final List<String> result = (List<String>) values.get(key.toLowerCase()); // return result == null || result.isEmpty() ? null : new ArrayList<String>(result); // } // // // /** // * @return all keys (lower-cased) from this instance (never returns {@code null}) // */ // public Set<String> getKeys() { // @SuppressWarnings("unchecked") final Set<String> result = new HashSet<String>(this.values.keySet()); // return result; // } // // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder(); // for (@SuppressWarnings("unchecked") final Iterator<Map.Entry<String, Collection<String>>> it // = this.values.entrySet().iterator(); it.hasNext(); ) { // final Map.Entry<String, Collection<String>> e = it.next(); // // for (final Iterator<String> it2 = e.getValue().iterator(); it2.hasNext(); ) { // sb.append(e.getKey()).append(": ").append(it2.next()); // if (it2.hasNext()) { // sb.append(", "); // } // } // // if (it.hasNext()) { // sb.append(", "); // } // } // // return sb.toString(); // } // // // @Override // public int hashCode() { // int hash = 5; // hash = 43 * hash + (this.values != null ? this.values.hashCode() : 0); // return hash; // } // // // @Override // public boolean equals(final Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final KeyValues other = (KeyValues) obj; // if (this.values != other.values && (this.values == null || !this.values.equals(other.values))) { // return false; // } // return true; // } // }
import net.jadler.KeyValues; import org.apache.commons.collections.MultiMap; import org.apache.commons.collections.map.MultiValueMap; import java.nio.charset.Charset; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.TimeUnit;
} /** * @return a {@link StubResponse} instance created from data stored in this object */ StubResponse toStubResponse() { final StubResponse.Builder builder = StubResponse.builder() .status(status) .delay(delay, TimeUnit.MILLISECONDS) .headers(this.createHeaders()); if (this.stringBody != null) { if (this.encoding == null) { throw new IllegalStateException("The response body encoding has not been set yet, " + "cannot generate a StubResponse instance."); } else { builder.body(this.stringBody, this.encoding); } } else if (this.rawBody != null) { builder.body(rawBody); } else { throw new IllegalStateException("The response body has not been set yet, " + "cannot generate a StubResponse instance."); } return builder.build(); }
// Path: jadler-core/src/main/java/net/jadler/KeyValues.java // public class KeyValues { // // /** // * An empty instance. // */ // public static final KeyValues EMPTY = new KeyValues(); // private final MultiMap values; // // // /** // * Creates new empty instance. // */ // public KeyValues() { // this.values = new MultiValueMap(); // } // // // /** // * Adds new key-value pair. Supports multi-values for one key (if there has already been added // * some value with this key, additional value is added instead of rewriting). Please note this method // * creates new instance containing all existing values plus the new one rather than modifying this instance. // * // * @param key key (cannot be empty) // * @param value value (cannot be {@code null}, however can be empty for valueless headers) // * @return an exact copy of this instance containing all existing values plus the new one // */ // @SuppressWarnings("unchecked") // public KeyValues add(final String key, final String value) { // Validate.notEmpty(key, "key cannot be empty"); // Validate.notNull(value, "value cannot be null, use an empty string instead"); // // final KeyValues res = new KeyValues(); // res.values.putAll(this.values); // res.values.put(key.toLowerCase(), value); // // return res; // } // // // /** // * Adds all values from the given instance. Supports multi-values for one key (if there has already been added // * some value with this key, additional value is added instead of rewriting). Please note this method // * creates new instance containing all existing values plus the new ones rather than modifying this instance. // * // * @param keyValues values to be added no(cannot be {@code null}) // * @return an exact copy of this instance containing all existing values plus the new ones // */ // @SuppressWarnings("unchecked") // public KeyValues addAll(final KeyValues keyValues) { // Validate.notNull(keyValues, "keyValues cannot be null"); // // final KeyValues res = new KeyValues(); // res.values.putAll(this.values); // res.values.putAll(keyValues.values); // return res; // } // // // /** // * Returns the first value for the given key // * // * @param key key (case insensitive) // * @return single (first) value for the given key or {@code null}, if there is no such a key in this instance // */ // public String getValue(final String key) { // Validate.notEmpty(key, "key cannot be empty"); // // final List<String> allValues = this.getValues(key); // return allValues != null ? allValues.get(0) : null; // } // // // /** // * Returns all values for the given key // * // * @param key key (case insensitive) // * @return all values of the given header or {@code null}, if there is no such a key in this instance // */ // public List<String> getValues(final String key) { // Validate.notEmpty(key, "name cannot be empty"); // // @SuppressWarnings("unchecked") final List<String> result = (List<String>) values.get(key.toLowerCase()); // return result == null || result.isEmpty() ? null : new ArrayList<String>(result); // } // // // /** // * @return all keys (lower-cased) from this instance (never returns {@code null}) // */ // public Set<String> getKeys() { // @SuppressWarnings("unchecked") final Set<String> result = new HashSet<String>(this.values.keySet()); // return result; // } // // // @Override // public String toString() { // final StringBuilder sb = new StringBuilder(); // for (@SuppressWarnings("unchecked") final Iterator<Map.Entry<String, Collection<String>>> it // = this.values.entrySet().iterator(); it.hasNext(); ) { // final Map.Entry<String, Collection<String>> e = it.next(); // // for (final Iterator<String> it2 = e.getValue().iterator(); it2.hasNext(); ) { // sb.append(e.getKey()).append(": ").append(it2.next()); // if (it2.hasNext()) { // sb.append(", "); // } // } // // if (it.hasNext()) { // sb.append(", "); // } // } // // return sb.toString(); // } // // // @Override // public int hashCode() { // int hash = 5; // hash = 43 * hash + (this.values != null ? this.values.hashCode() : 0); // return hash; // } // // // @Override // public boolean equals(final Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final KeyValues other = (KeyValues) obj; // if (this.values != other.values && (this.values == null || !this.values.equals(other.values))) { // return false; // } // return true; // } // } // Path: jadler-core/src/main/java/net/jadler/stubbing/MutableStubResponse.java import net.jadler.KeyValues; import org.apache.commons.collections.MultiMap; import org.apache.commons.collections.map.MultiValueMap; import java.nio.charset.Charset; import java.util.Collection; import java.util.Iterator; import java.util.concurrent.TimeUnit; } /** * @return a {@link StubResponse} instance created from data stored in this object */ StubResponse toStubResponse() { final StubResponse.Builder builder = StubResponse.builder() .status(status) .delay(delay, TimeUnit.MILLISECONDS) .headers(this.createHeaders()); if (this.stringBody != null) { if (this.encoding == null) { throw new IllegalStateException("The response body encoding has not been set yet, " + "cannot generate a StubResponse instance."); } else { builder.body(this.stringBody, this.encoding); } } else if (this.rawBody != null) { builder.body(rawBody); } else { throw new IllegalStateException("The response body has not been set yet, " + "cannot generate a StubResponse instance."); } return builder.build(); }
private KeyValues createHeaders() {
jadler-mocking/jadler
jadler-jetty/src/main/java/net/jadler/stubbing/server/jetty/JettyStubHttpServer.java
// Path: jadler-core/src/main/java/net/jadler/RequestManager.java // public interface RequestManager { // // /** // * Returns a stub response for the given request. The request is recorded for further mocking (verifying). // * // * @param req http request to return a stub response for // * @return definition of a stub response to be returned by the stub http server (never returns {@code null}) // */ // StubResponse provideStubResponseFor(Request req); // // // /** // * Verifies whether the number of received http requests fitting the given predicates is as expected. Basically // * at first this operation computes the exact number of http requests received so far fitting the given predicates // * and then verifies whether the number is as expected. If not a {@link net.jadler.mocking.VerificationException} // * is thrown and the exact reason is logged on the {@code INFO} level. // * // * @param requestPredicates predicates about the http requests received so far (cannot be {@code null}, can be // * empty however) // * @param nrRequestsPredicate a predicate about the number of http requests received so far which fit the given // * request predicates (cannot be {@code null}) // * @throws net.jadler.mocking.VerificationException if the verification fails // */ // void evaluateVerification(Collection<Matcher<? super Request>> requestPredicates, // Matcher<Integer> nrRequestsPredicate); // // // /** // * @param predicates predicates to be applied on all incoming http requests // * @return number of requests recorded by {@link #provideStubResponseFor(net.jadler.Request)} matching the // * given matchers // * @deprecated this (rather internal) method has been deprecated. Please use // * {@link #evaluateVerification(java.util.Collection, org.hamcrest.Matcher)} instead // */ // @Deprecated // int numberOfRequestsMatching(Collection<Matcher<? super Request>> predicates); // } // // Path: jadler-core/src/main/java/net/jadler/stubbing/server/StubHttpServer.java // public interface StubHttpServer { // // /** // * Registers a response provider. This component provides a response prescription (in form // * of a {@link net.jadler.stubbing.StubResponse} instance) for a given http request. // * // * @param requestManager response provider to use to retrieve response prescriptions. // */ // void registerRequestManager(RequestManager requestManager); // // // /** // * Starts the underlying http server. From now, the server must be able to respond // * according to prescriptions returned from the registered {@link StubHttpServerManager} instance. // * // * @throws Exception when ugh... something went wrong // */ // void start() throws Exception; // // // /** // * Stops the underlying http server. // * // * @throws Exception when an error occurred while stopping the server // */ // void stop() throws Exception; // // // /** // * @return HTTP server port // */ // int getPort(); // }
import net.jadler.RequestManager; import net.jadler.stubbing.server.StubHttpServer; import org.apache.commons.lang.Validate; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.stubbing.server.jetty; /** * Default stub http server implementation using Jetty as an http server. */ public class JettyStubHttpServer implements StubHttpServer { private static final Logger logger = LoggerFactory.getLogger(JettyStubHttpServer.class); private final Server server; private final Connector httpConnector; public JettyStubHttpServer() { this(0); } public JettyStubHttpServer(final int port) { this.server = new Server(); this.server.setSendServerVersion(false); this.server.setSendDateHeader(true); this.httpConnector = new SelectChannelConnector(); this.httpConnector.setPort(port); server.addConnector(this.httpConnector); } /** * {@inheritDoc} */ @Override
// Path: jadler-core/src/main/java/net/jadler/RequestManager.java // public interface RequestManager { // // /** // * Returns a stub response for the given request. The request is recorded for further mocking (verifying). // * // * @param req http request to return a stub response for // * @return definition of a stub response to be returned by the stub http server (never returns {@code null}) // */ // StubResponse provideStubResponseFor(Request req); // // // /** // * Verifies whether the number of received http requests fitting the given predicates is as expected. Basically // * at first this operation computes the exact number of http requests received so far fitting the given predicates // * and then verifies whether the number is as expected. If not a {@link net.jadler.mocking.VerificationException} // * is thrown and the exact reason is logged on the {@code INFO} level. // * // * @param requestPredicates predicates about the http requests received so far (cannot be {@code null}, can be // * empty however) // * @param nrRequestsPredicate a predicate about the number of http requests received so far which fit the given // * request predicates (cannot be {@code null}) // * @throws net.jadler.mocking.VerificationException if the verification fails // */ // void evaluateVerification(Collection<Matcher<? super Request>> requestPredicates, // Matcher<Integer> nrRequestsPredicate); // // // /** // * @param predicates predicates to be applied on all incoming http requests // * @return number of requests recorded by {@link #provideStubResponseFor(net.jadler.Request)} matching the // * given matchers // * @deprecated this (rather internal) method has been deprecated. Please use // * {@link #evaluateVerification(java.util.Collection, org.hamcrest.Matcher)} instead // */ // @Deprecated // int numberOfRequestsMatching(Collection<Matcher<? super Request>> predicates); // } // // Path: jadler-core/src/main/java/net/jadler/stubbing/server/StubHttpServer.java // public interface StubHttpServer { // // /** // * Registers a response provider. This component provides a response prescription (in form // * of a {@link net.jadler.stubbing.StubResponse} instance) for a given http request. // * // * @param requestManager response provider to use to retrieve response prescriptions. // */ // void registerRequestManager(RequestManager requestManager); // // // /** // * Starts the underlying http server. From now, the server must be able to respond // * according to prescriptions returned from the registered {@link StubHttpServerManager} instance. // * // * @throws Exception when ugh... something went wrong // */ // void start() throws Exception; // // // /** // * Stops the underlying http server. // * // * @throws Exception when an error occurred while stopping the server // */ // void stop() throws Exception; // // // /** // * @return HTTP server port // */ // int getPort(); // } // Path: jadler-jetty/src/main/java/net/jadler/stubbing/server/jetty/JettyStubHttpServer.java import net.jadler.RequestManager; import net.jadler.stubbing.server.StubHttpServer; import org.apache.commons.lang.Validate; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.stubbing.server.jetty; /** * Default stub http server implementation using Jetty as an http server. */ public class JettyStubHttpServer implements StubHttpServer { private static final Logger logger = LoggerFactory.getLogger(JettyStubHttpServer.class); private final Server server; private final Connector httpConnector; public JettyStubHttpServer() { this(0); } public JettyStubHttpServer(final int port) { this.server = new Server(); this.server.setSendServerVersion(false); this.server.setSendDateHeader(true); this.httpConnector = new SelectChannelConnector(); this.httpConnector.setPort(port); server.addConnector(this.httpConnector); } /** * {@inheritDoc} */ @Override
public void registerRequestManager(final RequestManager ruleProvider) {
jadler-mocking/jadler
jadler-jdk/src/main/java/net/jadler/stubbing/server/jdk/JdkStubHttpServer.java
// Path: jadler-core/src/main/java/net/jadler/RequestManager.java // public interface RequestManager { // // /** // * Returns a stub response for the given request. The request is recorded for further mocking (verifying). // * // * @param req http request to return a stub response for // * @return definition of a stub response to be returned by the stub http server (never returns {@code null}) // */ // StubResponse provideStubResponseFor(Request req); // // // /** // * Verifies whether the number of received http requests fitting the given predicates is as expected. Basically // * at first this operation computes the exact number of http requests received so far fitting the given predicates // * and then verifies whether the number is as expected. If not a {@link net.jadler.mocking.VerificationException} // * is thrown and the exact reason is logged on the {@code INFO} level. // * // * @param requestPredicates predicates about the http requests received so far (cannot be {@code null}, can be // * empty however) // * @param nrRequestsPredicate a predicate about the number of http requests received so far which fit the given // * request predicates (cannot be {@code null}) // * @throws net.jadler.mocking.VerificationException if the verification fails // */ // void evaluateVerification(Collection<Matcher<? super Request>> requestPredicates, // Matcher<Integer> nrRequestsPredicate); // // // /** // * @param predicates predicates to be applied on all incoming http requests // * @return number of requests recorded by {@link #provideStubResponseFor(net.jadler.Request)} matching the // * given matchers // * @deprecated this (rather internal) method has been deprecated. Please use // * {@link #evaluateVerification(java.util.Collection, org.hamcrest.Matcher)} instead // */ // @Deprecated // int numberOfRequestsMatching(Collection<Matcher<? super Request>> predicates); // } // // Path: jadler-core/src/main/java/net/jadler/exception/JadlerException.java // public class JadlerException extends RuntimeException { // // /** // * @param cause the cause of this exception // * @see RuntimeException#RuntimeException(java.lang.Throwable) // */ // public JadlerException(final Throwable cause) { // super(cause); // } // // /** // * @param message the detail message // * @param cause the cause of this exception // * @see RuntimeException#RuntimeException(java.lang.String, java.lang.Throwable) // */ // public JadlerException(final String message, final Throwable cause) { // super(message, cause); // } // // /** // * @param message the detail message // * @see RuntimeException#RuntimeException(java.lang.String) // */ // public JadlerException(final String message) { // super(message); // } // // /** // * @see RuntimeException#RuntimeException() // */ // public JadlerException() { // } // } // // Path: jadler-core/src/main/java/net/jadler/stubbing/server/StubHttpServer.java // public interface StubHttpServer { // // /** // * Registers a response provider. This component provides a response prescription (in form // * of a {@link net.jadler.stubbing.StubResponse} instance) for a given http request. // * // * @param requestManager response provider to use to retrieve response prescriptions. // */ // void registerRequestManager(RequestManager requestManager); // // // /** // * Starts the underlying http server. From now, the server must be able to respond // * according to prescriptions returned from the registered {@link StubHttpServerManager} instance. // * // * @throws Exception when ugh... something went wrong // */ // void start() throws Exception; // // // /** // * Stops the underlying http server. // * // * @throws Exception when an error occurred while stopping the server // */ // void stop() throws Exception; // // // /** // * @return HTTP server port // */ // int getPort(); // }
import com.sun.net.httpserver.HttpServer; import net.jadler.RequestManager; import net.jadler.exception.JadlerException; import net.jadler.stubbing.server.StubHttpServer; import java.io.IOException; import java.net.InetSocketAddress; import static org.apache.commons.lang.Validate.isTrue; import static org.apache.commons.lang.Validate.notNull;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.stubbing.server.jdk; /** * Stub server implementation based on {@link HttpServer} which is part of JDK. */ public class JdkStubHttpServer implements StubHttpServer { private final HttpServer server; public JdkStubHttpServer(final int port) { isTrue(port >= 0, "port cannot be a negative number"); try { server = HttpServer.create(new InetSocketAddress(port), 0); } catch (final IOException e) {
// Path: jadler-core/src/main/java/net/jadler/RequestManager.java // public interface RequestManager { // // /** // * Returns a stub response for the given request. The request is recorded for further mocking (verifying). // * // * @param req http request to return a stub response for // * @return definition of a stub response to be returned by the stub http server (never returns {@code null}) // */ // StubResponse provideStubResponseFor(Request req); // // // /** // * Verifies whether the number of received http requests fitting the given predicates is as expected. Basically // * at first this operation computes the exact number of http requests received so far fitting the given predicates // * and then verifies whether the number is as expected. If not a {@link net.jadler.mocking.VerificationException} // * is thrown and the exact reason is logged on the {@code INFO} level. // * // * @param requestPredicates predicates about the http requests received so far (cannot be {@code null}, can be // * empty however) // * @param nrRequestsPredicate a predicate about the number of http requests received so far which fit the given // * request predicates (cannot be {@code null}) // * @throws net.jadler.mocking.VerificationException if the verification fails // */ // void evaluateVerification(Collection<Matcher<? super Request>> requestPredicates, // Matcher<Integer> nrRequestsPredicate); // // // /** // * @param predicates predicates to be applied on all incoming http requests // * @return number of requests recorded by {@link #provideStubResponseFor(net.jadler.Request)} matching the // * given matchers // * @deprecated this (rather internal) method has been deprecated. Please use // * {@link #evaluateVerification(java.util.Collection, org.hamcrest.Matcher)} instead // */ // @Deprecated // int numberOfRequestsMatching(Collection<Matcher<? super Request>> predicates); // } // // Path: jadler-core/src/main/java/net/jadler/exception/JadlerException.java // public class JadlerException extends RuntimeException { // // /** // * @param cause the cause of this exception // * @see RuntimeException#RuntimeException(java.lang.Throwable) // */ // public JadlerException(final Throwable cause) { // super(cause); // } // // /** // * @param message the detail message // * @param cause the cause of this exception // * @see RuntimeException#RuntimeException(java.lang.String, java.lang.Throwable) // */ // public JadlerException(final String message, final Throwable cause) { // super(message, cause); // } // // /** // * @param message the detail message // * @see RuntimeException#RuntimeException(java.lang.String) // */ // public JadlerException(final String message) { // super(message); // } // // /** // * @see RuntimeException#RuntimeException() // */ // public JadlerException() { // } // } // // Path: jadler-core/src/main/java/net/jadler/stubbing/server/StubHttpServer.java // public interface StubHttpServer { // // /** // * Registers a response provider. This component provides a response prescription (in form // * of a {@link net.jadler.stubbing.StubResponse} instance) for a given http request. // * // * @param requestManager response provider to use to retrieve response prescriptions. // */ // void registerRequestManager(RequestManager requestManager); // // // /** // * Starts the underlying http server. From now, the server must be able to respond // * according to prescriptions returned from the registered {@link StubHttpServerManager} instance. // * // * @throws Exception when ugh... something went wrong // */ // void start() throws Exception; // // // /** // * Stops the underlying http server. // * // * @throws Exception when an error occurred while stopping the server // */ // void stop() throws Exception; // // // /** // * @return HTTP server port // */ // int getPort(); // } // Path: jadler-jdk/src/main/java/net/jadler/stubbing/server/jdk/JdkStubHttpServer.java import com.sun.net.httpserver.HttpServer; import net.jadler.RequestManager; import net.jadler.exception.JadlerException; import net.jadler.stubbing.server.StubHttpServer; import java.io.IOException; import java.net.InetSocketAddress; import static org.apache.commons.lang.Validate.isTrue; import static org.apache.commons.lang.Validate.notNull; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.stubbing.server.jdk; /** * Stub server implementation based on {@link HttpServer} which is part of JDK. */ public class JdkStubHttpServer implements StubHttpServer { private final HttpServer server; public JdkStubHttpServer(final int port) { isTrue(port >= 0, "port cannot be a negative number"); try { server = HttpServer.create(new InetSocketAddress(port), 0); } catch (final IOException e) {
throw new JadlerException("Cannot create JDK server", e);
jadler-mocking/jadler
jadler-jdk/src/main/java/net/jadler/stubbing/server/jdk/JdkStubHttpServer.java
// Path: jadler-core/src/main/java/net/jadler/RequestManager.java // public interface RequestManager { // // /** // * Returns a stub response for the given request. The request is recorded for further mocking (verifying). // * // * @param req http request to return a stub response for // * @return definition of a stub response to be returned by the stub http server (never returns {@code null}) // */ // StubResponse provideStubResponseFor(Request req); // // // /** // * Verifies whether the number of received http requests fitting the given predicates is as expected. Basically // * at first this operation computes the exact number of http requests received so far fitting the given predicates // * and then verifies whether the number is as expected. If not a {@link net.jadler.mocking.VerificationException} // * is thrown and the exact reason is logged on the {@code INFO} level. // * // * @param requestPredicates predicates about the http requests received so far (cannot be {@code null}, can be // * empty however) // * @param nrRequestsPredicate a predicate about the number of http requests received so far which fit the given // * request predicates (cannot be {@code null}) // * @throws net.jadler.mocking.VerificationException if the verification fails // */ // void evaluateVerification(Collection<Matcher<? super Request>> requestPredicates, // Matcher<Integer> nrRequestsPredicate); // // // /** // * @param predicates predicates to be applied on all incoming http requests // * @return number of requests recorded by {@link #provideStubResponseFor(net.jadler.Request)} matching the // * given matchers // * @deprecated this (rather internal) method has been deprecated. Please use // * {@link #evaluateVerification(java.util.Collection, org.hamcrest.Matcher)} instead // */ // @Deprecated // int numberOfRequestsMatching(Collection<Matcher<? super Request>> predicates); // } // // Path: jadler-core/src/main/java/net/jadler/exception/JadlerException.java // public class JadlerException extends RuntimeException { // // /** // * @param cause the cause of this exception // * @see RuntimeException#RuntimeException(java.lang.Throwable) // */ // public JadlerException(final Throwable cause) { // super(cause); // } // // /** // * @param message the detail message // * @param cause the cause of this exception // * @see RuntimeException#RuntimeException(java.lang.String, java.lang.Throwable) // */ // public JadlerException(final String message, final Throwable cause) { // super(message, cause); // } // // /** // * @param message the detail message // * @see RuntimeException#RuntimeException(java.lang.String) // */ // public JadlerException(final String message) { // super(message); // } // // /** // * @see RuntimeException#RuntimeException() // */ // public JadlerException() { // } // } // // Path: jadler-core/src/main/java/net/jadler/stubbing/server/StubHttpServer.java // public interface StubHttpServer { // // /** // * Registers a response provider. This component provides a response prescription (in form // * of a {@link net.jadler.stubbing.StubResponse} instance) for a given http request. // * // * @param requestManager response provider to use to retrieve response prescriptions. // */ // void registerRequestManager(RequestManager requestManager); // // // /** // * Starts the underlying http server. From now, the server must be able to respond // * according to prescriptions returned from the registered {@link StubHttpServerManager} instance. // * // * @throws Exception when ugh... something went wrong // */ // void start() throws Exception; // // // /** // * Stops the underlying http server. // * // * @throws Exception when an error occurred while stopping the server // */ // void stop() throws Exception; // // // /** // * @return HTTP server port // */ // int getPort(); // }
import com.sun.net.httpserver.HttpServer; import net.jadler.RequestManager; import net.jadler.exception.JadlerException; import net.jadler.stubbing.server.StubHttpServer; import java.io.IOException; import java.net.InetSocketAddress; import static org.apache.commons.lang.Validate.isTrue; import static org.apache.commons.lang.Validate.notNull;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.stubbing.server.jdk; /** * Stub server implementation based on {@link HttpServer} which is part of JDK. */ public class JdkStubHttpServer implements StubHttpServer { private final HttpServer server; public JdkStubHttpServer(final int port) { isTrue(port >= 0, "port cannot be a negative number"); try { server = HttpServer.create(new InetSocketAddress(port), 0); } catch (final IOException e) { throw new JadlerException("Cannot create JDK server", e); } } public JdkStubHttpServer() { this(0); } @Override
// Path: jadler-core/src/main/java/net/jadler/RequestManager.java // public interface RequestManager { // // /** // * Returns a stub response for the given request. The request is recorded for further mocking (verifying). // * // * @param req http request to return a stub response for // * @return definition of a stub response to be returned by the stub http server (never returns {@code null}) // */ // StubResponse provideStubResponseFor(Request req); // // // /** // * Verifies whether the number of received http requests fitting the given predicates is as expected. Basically // * at first this operation computes the exact number of http requests received so far fitting the given predicates // * and then verifies whether the number is as expected. If not a {@link net.jadler.mocking.VerificationException} // * is thrown and the exact reason is logged on the {@code INFO} level. // * // * @param requestPredicates predicates about the http requests received so far (cannot be {@code null}, can be // * empty however) // * @param nrRequestsPredicate a predicate about the number of http requests received so far which fit the given // * request predicates (cannot be {@code null}) // * @throws net.jadler.mocking.VerificationException if the verification fails // */ // void evaluateVerification(Collection<Matcher<? super Request>> requestPredicates, // Matcher<Integer> nrRequestsPredicate); // // // /** // * @param predicates predicates to be applied on all incoming http requests // * @return number of requests recorded by {@link #provideStubResponseFor(net.jadler.Request)} matching the // * given matchers // * @deprecated this (rather internal) method has been deprecated. Please use // * {@link #evaluateVerification(java.util.Collection, org.hamcrest.Matcher)} instead // */ // @Deprecated // int numberOfRequestsMatching(Collection<Matcher<? super Request>> predicates); // } // // Path: jadler-core/src/main/java/net/jadler/exception/JadlerException.java // public class JadlerException extends RuntimeException { // // /** // * @param cause the cause of this exception // * @see RuntimeException#RuntimeException(java.lang.Throwable) // */ // public JadlerException(final Throwable cause) { // super(cause); // } // // /** // * @param message the detail message // * @param cause the cause of this exception // * @see RuntimeException#RuntimeException(java.lang.String, java.lang.Throwable) // */ // public JadlerException(final String message, final Throwable cause) { // super(message, cause); // } // // /** // * @param message the detail message // * @see RuntimeException#RuntimeException(java.lang.String) // */ // public JadlerException(final String message) { // super(message); // } // // /** // * @see RuntimeException#RuntimeException() // */ // public JadlerException() { // } // } // // Path: jadler-core/src/main/java/net/jadler/stubbing/server/StubHttpServer.java // public interface StubHttpServer { // // /** // * Registers a response provider. This component provides a response prescription (in form // * of a {@link net.jadler.stubbing.StubResponse} instance) for a given http request. // * // * @param requestManager response provider to use to retrieve response prescriptions. // */ // void registerRequestManager(RequestManager requestManager); // // // /** // * Starts the underlying http server. From now, the server must be able to respond // * according to prescriptions returned from the registered {@link StubHttpServerManager} instance. // * // * @throws Exception when ugh... something went wrong // */ // void start() throws Exception; // // // /** // * Stops the underlying http server. // * // * @throws Exception when an error occurred while stopping the server // */ // void stop() throws Exception; // // // /** // * @return HTTP server port // */ // int getPort(); // } // Path: jadler-jdk/src/main/java/net/jadler/stubbing/server/jdk/JdkStubHttpServer.java import com.sun.net.httpserver.HttpServer; import net.jadler.RequestManager; import net.jadler.exception.JadlerException; import net.jadler.stubbing.server.StubHttpServer; import java.io.IOException; import java.net.InetSocketAddress; import static org.apache.commons.lang.Validate.isTrue; import static org.apache.commons.lang.Validate.notNull; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.stubbing.server.jdk; /** * Stub server implementation based on {@link HttpServer} which is part of JDK. */ public class JdkStubHttpServer implements StubHttpServer { private final HttpServer server; public JdkStubHttpServer(final int port) { isTrue(port >= 0, "port cannot be a negative number"); try { server = HttpServer.create(new InetSocketAddress(port), 0); } catch (final IOException e) { throw new JadlerException("Cannot create JDK server", e); } } public JdkStubHttpServer() { this(0); } @Override
public void registerRequestManager(final RequestManager ruleProvider) {
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/SuperDefaultsIntegrationTest.java
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadler() { // return initInternal(new JadlerMocker(getJettyServer())); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static byte[] rawBodyOf(final HttpResponse response) throws IOException { // return IOUtils.toByteArray(response.getEntity().getContent()); // }
import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static net.jadler.utils.TestUtils.rawBodyOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * Test suite for response super defaults (default response status and encoding values used when not defined at all). */ public class SuperDefaultsIntegrationTest { private static final String STRING_WITH_DIACRITICS = "\u00e1\u0159\u017e"; @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } @Before public void setUp() {
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadler() { // return initInternal(new JadlerMocker(getJettyServer())); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static byte[] rawBodyOf(final HttpResponse response) throws IOException { // return IOUtils.toByteArray(response.getEntity().getContent()); // } // Path: jadler-all/src/test/java/net/jadler/SuperDefaultsIntegrationTest.java import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static net.jadler.utils.TestUtils.rawBodyOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * Test suite for response super defaults (default response status and encoding values used when not defined at all). */ public class SuperDefaultsIntegrationTest { private static final String STRING_WITH_DIACRITICS = "\u00e1\u0159\u017e"; @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } @Before public void setUp() {
initJadler(); //no defaults for the response status nor encoding set here
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/SuperDefaultsIntegrationTest.java
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadler() { // return initInternal(new JadlerMocker(getJettyServer())); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static byte[] rawBodyOf(final HttpResponse response) throws IOException { // return IOUtils.toByteArray(response.getEntity().getContent()); // }
import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static net.jadler.utils.TestUtils.rawBodyOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * Test suite for response super defaults (default response status and encoding values used when not defined at all). */ public class SuperDefaultsIntegrationTest { private static final String STRING_WITH_DIACRITICS = "\u00e1\u0159\u017e"; @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } @Before public void setUp() { initJadler(); //no defaults for the response status nor encoding set here } @After public void tearDown() {
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadler() { // return initInternal(new JadlerMocker(getJettyServer())); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static byte[] rawBodyOf(final HttpResponse response) throws IOException { // return IOUtils.toByteArray(response.getEntity().getContent()); // } // Path: jadler-all/src/test/java/net/jadler/SuperDefaultsIntegrationTest.java import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static net.jadler.utils.TestUtils.rawBodyOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * Test suite for response super defaults (default response status and encoding values used when not defined at all). */ public class SuperDefaultsIntegrationTest { private static final String STRING_WITH_DIACRITICS = "\u00e1\u0159\u017e"; @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } @Before public void setUp() { initJadler(); //no defaults for the response status nor encoding set here } @After public void tearDown() {
closeJadler();
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/SuperDefaultsIntegrationTest.java
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadler() { // return initInternal(new JadlerMocker(getJettyServer())); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static byte[] rawBodyOf(final HttpResponse response) throws IOException { // return IOUtils.toByteArray(response.getEntity().getContent()); // }
import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static net.jadler.utils.TestUtils.rawBodyOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * Test suite for response super defaults (default response status and encoding values used when not defined at all). */ public class SuperDefaultsIntegrationTest { private static final String STRING_WITH_DIACRITICS = "\u00e1\u0159\u017e"; @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } @Before public void setUp() { initJadler(); //no defaults for the response status nor encoding set here } @After public void tearDown() { closeJadler(); } /* * When no defaults (response status and encoding) are set during Jadler initialization nor the status and encoding * values are provided during stubbing super-defaults (200, UTF-8) are used. */ @Test public void superDefaults() throws IOException { //no values for the response status nor encoding set here
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadler() { // return initInternal(new JadlerMocker(getJettyServer())); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static byte[] rawBodyOf(final HttpResponse response) throws IOException { // return IOUtils.toByteArray(response.getEntity().getContent()); // } // Path: jadler-all/src/test/java/net/jadler/SuperDefaultsIntegrationTest.java import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static net.jadler.utils.TestUtils.rawBodyOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * Test suite for response super defaults (default response status and encoding values used when not defined at all). */ public class SuperDefaultsIntegrationTest { private static final String STRING_WITH_DIACRITICS = "\u00e1\u0159\u017e"; @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } @Before public void setUp() { initJadler(); //no defaults for the response status nor encoding set here } @After public void tearDown() { closeJadler(); } /* * When no defaults (response status and encoding) are set during Jadler initialization nor the status and encoding * values are provided during stubbing super-defaults (200, UTF-8) are used. */ @Test public void superDefaults() throws IOException { //no values for the response status nor encoding set here
onRequest().respond().withBody(STRING_WITH_DIACRITICS);
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/SuperDefaultsIntegrationTest.java
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadler() { // return initInternal(new JadlerMocker(getJettyServer())); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static byte[] rawBodyOf(final HttpResponse response) throws IOException { // return IOUtils.toByteArray(response.getEntity().getContent()); // }
import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static net.jadler.utils.TestUtils.rawBodyOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * Test suite for response super defaults (default response status and encoding values used when not defined at all). */ public class SuperDefaultsIntegrationTest { private static final String STRING_WITH_DIACRITICS = "\u00e1\u0159\u017e"; @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } @Before public void setUp() { initJadler(); //no defaults for the response status nor encoding set here } @After public void tearDown() { closeJadler(); } /* * When no defaults (response status and encoding) are set during Jadler initialization nor the status and encoding * values are provided during stubbing super-defaults (200, UTF-8) are used. */ @Test public void superDefaults() throws IOException { //no values for the response status nor encoding set here onRequest().respond().withBody(STRING_WITH_DIACRITICS); final HttpResponse response = Executor.newInstance()
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadler() { // return initInternal(new JadlerMocker(getJettyServer())); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static byte[] rawBodyOf(final HttpResponse response) throws IOException { // return IOUtils.toByteArray(response.getEntity().getContent()); // } // Path: jadler-all/src/test/java/net/jadler/SuperDefaultsIntegrationTest.java import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static net.jadler.utils.TestUtils.rawBodyOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * Test suite for response super defaults (default response status and encoding values used when not defined at all). */ public class SuperDefaultsIntegrationTest { private static final String STRING_WITH_DIACRITICS = "\u00e1\u0159\u017e"; @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } @Before public void setUp() { initJadler(); //no defaults for the response status nor encoding set here } @After public void tearDown() { closeJadler(); } /* * When no defaults (response status and encoding) are set during Jadler initialization nor the status and encoding * values are provided during stubbing super-defaults (200, UTF-8) are used. */ @Test public void superDefaults() throws IOException { //no values for the response status nor encoding set here onRequest().respond().withBody(STRING_WITH_DIACRITICS); final HttpResponse response = Executor.newInstance()
.execute(Request.Post(jadlerUri()).bodyString("postbody", null)).returnResponse();
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/SuperDefaultsIntegrationTest.java
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadler() { // return initInternal(new JadlerMocker(getJettyServer())); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static byte[] rawBodyOf(final HttpResponse response) throws IOException { // return IOUtils.toByteArray(response.getEntity().getContent()); // }
import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static net.jadler.utils.TestUtils.rawBodyOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * Test suite for response super defaults (default response status and encoding values used when not defined at all). */ public class SuperDefaultsIntegrationTest { private static final String STRING_WITH_DIACRITICS = "\u00e1\u0159\u017e"; @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } @Before public void setUp() { initJadler(); //no defaults for the response status nor encoding set here } @After public void tearDown() { closeJadler(); } /* * When no defaults (response status and encoding) are set during Jadler initialization nor the status and encoding * values are provided during stubbing super-defaults (200, UTF-8) are used. */ @Test public void superDefaults() throws IOException { //no values for the response status nor encoding set here onRequest().respond().withBody(STRING_WITH_DIACRITICS); final HttpResponse response = Executor.newInstance() .execute(Request.Post(jadlerUri()).bodyString("postbody", null)).returnResponse(); assertThat(response.getStatusLine().getStatusCode(), is(200)); //the response body is decodable correctly using UTF-8
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static void closeJadler() { // final StubHttpServerManager serverManager = jadlerMockerContainer.get(); // if (serverManager != null && serverManager.isStarted()) { // serverManager.close(); // } // // jadlerMockerContainer.set(null); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static OngoingConfiguration initJadler() { // return initInternal(new JadlerMocker(getJettyServer())); // } // // Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static RequestStubbing onRequest() { // checkInitialized(); // return jadlerMockerContainer.get().onRequest(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static String jadlerUri() { // return "http://localhost:" + port(); // } // // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java // public static byte[] rawBodyOf(final HttpResponse response) throws IOException { // return IOUtils.toByteArray(response.getEntity().getContent()); // } // Path: jadler-all/src/test/java/net/jadler/SuperDefaultsIntegrationTest.java import org.apache.http.HttpResponse; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import static net.jadler.Jadler.closeJadler; import static net.jadler.Jadler.initJadler; import static net.jadler.Jadler.onRequest; import static net.jadler.utils.TestUtils.jadlerUri; import static net.jadler.utils.TestUtils.rawBodyOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler; /** * Test suite for response super defaults (default response status and encoding values used when not defined at all). */ public class SuperDefaultsIntegrationTest { private static final String STRING_WITH_DIACRITICS = "\u00e1\u0159\u017e"; @AfterClass public static void cleanup() { Executor.closeIdleConnections(); } @Before public void setUp() { initJadler(); //no defaults for the response status nor encoding set here } @After public void tearDown() { closeJadler(); } /* * When no defaults (response status and encoding) are set during Jadler initialization nor the status and encoding * values are provided during stubbing super-defaults (200, UTF-8) are used. */ @Test public void superDefaults() throws IOException { //no values for the response status nor encoding set here onRequest().respond().withBody(STRING_WITH_DIACRITICS); final HttpResponse response = Executor.newInstance() .execute(Request.Post(jadlerUri()).bodyString("postbody", null)).returnResponse(); assertThat(response.getStatusLine().getStatusCode(), is(200)); //the response body is decodable correctly using UTF-8
assertThat(rawBodyOf(response), is(STRING_WITH_DIACRITICS.getBytes(Charset.forName("UTF-8"))));
jadler-mocking/jadler
jadler-all/src/test/java/net/jadler/utils/TestUtils.java
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static int port() { // checkInitialized(); // return jadlerMockerContainer.get().getStubHttpServerPort(); // }
import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ResponseHandler; import java.io.IOException; import static net.jadler.Jadler.port;
/* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.utils; /** * Various handy functions and classes useful for testing. */ public class TestUtils { /** * An http response handler which retrieves just the response status code value. */ public static final StatusRetriever STATUS_RETRIEVER = new StatusRetriever(); /** * @return URI of the Jadler stub server */ public static String jadlerUri() {
// Path: jadler-core/src/main/java/net/jadler/Jadler.java // public static int port() { // checkInitialized(); // return jadlerMockerContainer.get().getStubHttpServerPort(); // } // Path: jadler-all/src/test/java/net/jadler/utils/TestUtils.java import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ResponseHandler; import java.io.IOException; import static net.jadler.Jadler.port; /* * Copyright (c) 2012 - 2016 Jadler contributors * This program is made available under the terms of the MIT License. */ package net.jadler.utils; /** * Various handy functions and classes useful for testing. */ public class TestUtils { /** * An http response handler which retrieves just the response status code value. */ public static final StatusRetriever STATUS_RETRIEVER = new StatusRetriever(); /** * @return URI of the Jadler stub server */ public static String jadlerUri() {
return "http://localhost:" + port();
JorenSix/Panako
src/be/panako/cli/Resolve.java
// Path: src/be/panako/strategy/Strategy.java // public abstract class Strategy { // // // /** // * Store an audio file in the data store. The name of the resource is used to extract a // * numerical identifier. The description is arbitrary. // * @param resource The audio resource. // * @param description An arbitrary description. // * @return The number of seconds of processed audio. // */ // public abstract double store(String resource, String description); // // public abstract void query(String query, int maxNumberOfResults,Set<Integer> avoid, QueryResultHandler handler); // // public abstract void monitor(String query,int maxNumberOfReqults,Set<Integer> avoid,QueryResultHandler handler); // // /** // * Are there fingerprints for this resource already stored in the database? // * @param resource The name of the resource. // * @return True if the resource is already treated. False otherwise. // */ // public abstract boolean hasResource(String resource); // // /** // * // * @return True if the storage is available, false otherwise. // */ // public abstract boolean isStorageAvailable(); // // /** // * Print some storage statistics. // */ // public abstract void printStorageStatistics(); // // /** // * Checks the configuration and returns a strategy. // * @return An instance of the strategy. // */ // private static Strategy strategy; // public static Strategy getInstance(){ // if(strategy == null){ // Reflections reflections = new Reflections("be.panako.strategy"); // Set<Class<? extends Strategy>> modules = reflections.getSubTypesOf(be.panako.strategy.Strategy.class); // String configuredStrategyName = Config.get(Key.STRATEGY); // // for(Class<? extends Strategy> module : modules) { // try { // if(configuredStrategyName.equalsIgnoreCase(Strategy.classToName(module))) { // strategy = ((Strategy) module.getDeclaredConstructor().newInstance()); // break; // } // } catch (Exception e) { // //should not happen, instantiation should not be a problem // e.printStackTrace(); // } // } // } // return strategy; // } // // public static String classToName(Class<? extends Strategy> c){ // //fully qualified name // String name = c.getCanonicalName(); // //unqualified name // name = name.substring(name.lastIndexOf('.')+1); // //lower case first letter // name = name.substring(0,1).toLowerCase() + name.substring(1); // // return name.replace("Strategy", ""); // } // // /** // * Returns an internal identifier, probably an integer, for a given filename. // * @param filename the name of the file to resolve. // * @return An internal identifier, probably an integer, for a given filename. // */ // public abstract String resolve(String filename); // // // public void print(String path, boolean sonicVisualizerOutput) { // } // // /** // * Clear al information from the key value store // */ // public abstract void clear(); // }
import java.io.File; import java.util.List; import be.panako.strategy.Strategy;
/*************************************************************************** * * * Panako - acoustic fingerprinting * * Copyright (C) 2014 - 2021 - Joren Six / IPEM * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of the * * License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Affero General Public License for more details. * * * * You should have received a copy of the GNU Affero General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/> * * * **************************************************************************** * ______ ________ ___ __ ________ ___ ___ ______ * * /_____/\ /_______/\ /__/\ /__/\ /_______/\ /___/\/__/\ /_____/\ * * \:::_ \ \\::: _ \ \\::\_\\ \ \\::: _ \ \\::.\ \\ \ \\:::_ \ \ * * \:(_) \ \\::(_) \ \\:. `-\ \ \\::(_) \ \\:: \/_) \ \\:\ \ \ \ * * \: ___\/ \:: __ \ \\:. _ \ \\:: __ \ \\:. __ ( ( \:\ \ \ \ * * \ \ \ \:.\ \ \ \\. \`-\ \ \\:.\ \ \ \\: \ ) \ \ \:\_\ \ \ * * \_\/ \__\/\__\/ \__\/ \__\/ \__\/\__\/ \__\/\__\/ \_____\/ * * * **************************************************************************** * * * Panako * * Acoustic Fingerprinting * * * ****************************************************************************/ package be.panako.cli; public class Resolve extends Application { @Override public void run(String... args) {
// Path: src/be/panako/strategy/Strategy.java // public abstract class Strategy { // // // /** // * Store an audio file in the data store. The name of the resource is used to extract a // * numerical identifier. The description is arbitrary. // * @param resource The audio resource. // * @param description An arbitrary description. // * @return The number of seconds of processed audio. // */ // public abstract double store(String resource, String description); // // public abstract void query(String query, int maxNumberOfResults,Set<Integer> avoid, QueryResultHandler handler); // // public abstract void monitor(String query,int maxNumberOfReqults,Set<Integer> avoid,QueryResultHandler handler); // // /** // * Are there fingerprints for this resource already stored in the database? // * @param resource The name of the resource. // * @return True if the resource is already treated. False otherwise. // */ // public abstract boolean hasResource(String resource); // // /** // * // * @return True if the storage is available, false otherwise. // */ // public abstract boolean isStorageAvailable(); // // /** // * Print some storage statistics. // */ // public abstract void printStorageStatistics(); // // /** // * Checks the configuration and returns a strategy. // * @return An instance of the strategy. // */ // private static Strategy strategy; // public static Strategy getInstance(){ // if(strategy == null){ // Reflections reflections = new Reflections("be.panako.strategy"); // Set<Class<? extends Strategy>> modules = reflections.getSubTypesOf(be.panako.strategy.Strategy.class); // String configuredStrategyName = Config.get(Key.STRATEGY); // // for(Class<? extends Strategy> module : modules) { // try { // if(configuredStrategyName.equalsIgnoreCase(Strategy.classToName(module))) { // strategy = ((Strategy) module.getDeclaredConstructor().newInstance()); // break; // } // } catch (Exception e) { // //should not happen, instantiation should not be a problem // e.printStackTrace(); // } // } // } // return strategy; // } // // public static String classToName(Class<? extends Strategy> c){ // //fully qualified name // String name = c.getCanonicalName(); // //unqualified name // name = name.substring(name.lastIndexOf('.')+1); // //lower case first letter // name = name.substring(0,1).toLowerCase() + name.substring(1); // // return name.replace("Strategy", ""); // } // // /** // * Returns an internal identifier, probably an integer, for a given filename. // * @param filename the name of the file to resolve. // * @return An internal identifier, probably an integer, for a given filename. // */ // public abstract String resolve(String filename); // // // public void print(String path, boolean sonicVisualizerOutput) { // } // // /** // * Clear al information from the key value store // */ // public abstract void clear(); // } // Path: src/be/panako/cli/Resolve.java import java.io.File; import java.util.List; import be.panako.strategy.Strategy; /*************************************************************************** * * * Panako - acoustic fingerprinting * * Copyright (C) 2014 - 2021 - Joren Six / IPEM * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of the * * License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Affero General Public License for more details. * * * * You should have received a copy of the GNU Affero General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/> * * * **************************************************************************** * ______ ________ ___ __ ________ ___ ___ ______ * * /_____/\ /_______/\ /__/\ /__/\ /_______/\ /___/\/__/\ /_____/\ * * \:::_ \ \\::: _ \ \\::\_\\ \ \\::: _ \ \\::.\ \\ \ \\:::_ \ \ * * \:(_) \ \\::(_) \ \\:. `-\ \ \\::(_) \ \\:: \/_) \ \\:\ \ \ \ * * \: ___\/ \:: __ \ \\:. _ \ \\:: __ \ \\:. __ ( ( \:\ \ \ \ * * \ \ \ \:.\ \ \ \\. \`-\ \ \\:.\ \ \ \\: \ ) \ \ \:\_\ \ \ * * \_\/ \__\/\__\/ \__\/ \__\/ \__\/\__\/ \__\/\__\/ \_____\/ * * * **************************************************************************** * * * Panako * * Acoustic Fingerprinting * * * ****************************************************************************/ package be.panako.cli; public class Resolve extends Application { @Override public void run(String... args) {
Strategy strat = Strategy.getInstance();
JorenSix/Panako
src/be/panako/cli/Stats.java
// Path: src/be/panako/strategy/Strategy.java // public abstract class Strategy { // // // /** // * Store an audio file in the data store. The name of the resource is used to extract a // * numerical identifier. The description is arbitrary. // * @param resource The audio resource. // * @param description An arbitrary description. // * @return The number of seconds of processed audio. // */ // public abstract double store(String resource, String description); // // public abstract void query(String query, int maxNumberOfResults,Set<Integer> avoid, QueryResultHandler handler); // // public abstract void monitor(String query,int maxNumberOfReqults,Set<Integer> avoid,QueryResultHandler handler); // // /** // * Are there fingerprints for this resource already stored in the database? // * @param resource The name of the resource. // * @return True if the resource is already treated. False otherwise. // */ // public abstract boolean hasResource(String resource); // // /** // * // * @return True if the storage is available, false otherwise. // */ // public abstract boolean isStorageAvailable(); // // /** // * Print some storage statistics. // */ // public abstract void printStorageStatistics(); // // /** // * Checks the configuration and returns a strategy. // * @return An instance of the strategy. // */ // private static Strategy strategy; // public static Strategy getInstance(){ // if(strategy == null){ // Reflections reflections = new Reflections("be.panako.strategy"); // Set<Class<? extends Strategy>> modules = reflections.getSubTypesOf(be.panako.strategy.Strategy.class); // String configuredStrategyName = Config.get(Key.STRATEGY); // // for(Class<? extends Strategy> module : modules) { // try { // if(configuredStrategyName.equalsIgnoreCase(Strategy.classToName(module))) { // strategy = ((Strategy) module.getDeclaredConstructor().newInstance()); // break; // } // } catch (Exception e) { // //should not happen, instantiation should not be a problem // e.printStackTrace(); // } // } // } // return strategy; // } // // public static String classToName(Class<? extends Strategy> c){ // //fully qualified name // String name = c.getCanonicalName(); // //unqualified name // name = name.substring(name.lastIndexOf('.')+1); // //lower case first letter // name = name.substring(0,1).toLowerCase() + name.substring(1); // // return name.replace("Strategy", ""); // } // // /** // * Returns an internal identifier, probably an integer, for a given filename. // * @param filename the name of the file to resolve. // * @return An internal identifier, probably an integer, for a given filename. // */ // public abstract String resolve(String filename); // // // public void print(String path, boolean sonicVisualizerOutput) { // } // // /** // * Clear al information from the key value store // */ // public abstract void clear(); // }
import be.panako.strategy.Strategy;
/*************************************************************************** * * * Panako - acoustic fingerprinting * * Copyright (C) 2014 - 2021 - Joren Six / IPEM * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of the * * License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Affero General Public License for more details. * * * * You should have received a copy of the GNU Affero General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/> * * * **************************************************************************** * ______ ________ ___ __ ________ ___ ___ ______ * * /_____/\ /_______/\ /__/\ /__/\ /_______/\ /___/\/__/\ /_____/\ * * \:::_ \ \\::: _ \ \\::\_\\ \ \\::: _ \ \\::.\ \\ \ \\:::_ \ \ * * \:(_) \ \\::(_) \ \\:. `-\ \ \\::(_) \ \\:: \/_) \ \\:\ \ \ \ * * \: ___\/ \:: __ \ \\:. _ \ \\:: __ \ \\:. __ ( ( \:\ \ \ \ * * \ \ \ \:.\ \ \ \\. \`-\ \ \\:.\ \ \ \\: \ ) \ \ \:\_\ \ \ * * \_\/ \__\/\__\/ \__\/ \__\/ \__\/\__\/ \__\/\__\/ \_____\/ * * * **************************************************************************** * * * Panako * * Acoustic Fingerprinting * * * ****************************************************************************/ package be.panako.cli; /** * Shows some statistics about the storage. * @author Joren Six */ public class Stats extends Application { @Override public void run(String... args) {
// Path: src/be/panako/strategy/Strategy.java // public abstract class Strategy { // // // /** // * Store an audio file in the data store. The name of the resource is used to extract a // * numerical identifier. The description is arbitrary. // * @param resource The audio resource. // * @param description An arbitrary description. // * @return The number of seconds of processed audio. // */ // public abstract double store(String resource, String description); // // public abstract void query(String query, int maxNumberOfResults,Set<Integer> avoid, QueryResultHandler handler); // // public abstract void monitor(String query,int maxNumberOfReqults,Set<Integer> avoid,QueryResultHandler handler); // // /** // * Are there fingerprints for this resource already stored in the database? // * @param resource The name of the resource. // * @return True if the resource is already treated. False otherwise. // */ // public abstract boolean hasResource(String resource); // // /** // * // * @return True if the storage is available, false otherwise. // */ // public abstract boolean isStorageAvailable(); // // /** // * Print some storage statistics. // */ // public abstract void printStorageStatistics(); // // /** // * Checks the configuration and returns a strategy. // * @return An instance of the strategy. // */ // private static Strategy strategy; // public static Strategy getInstance(){ // if(strategy == null){ // Reflections reflections = new Reflections("be.panako.strategy"); // Set<Class<? extends Strategy>> modules = reflections.getSubTypesOf(be.panako.strategy.Strategy.class); // String configuredStrategyName = Config.get(Key.STRATEGY); // // for(Class<? extends Strategy> module : modules) { // try { // if(configuredStrategyName.equalsIgnoreCase(Strategy.classToName(module))) { // strategy = ((Strategy) module.getDeclaredConstructor().newInstance()); // break; // } // } catch (Exception e) { // //should not happen, instantiation should not be a problem // e.printStackTrace(); // } // } // } // return strategy; // } // // public static String classToName(Class<? extends Strategy> c){ // //fully qualified name // String name = c.getCanonicalName(); // //unqualified name // name = name.substring(name.lastIndexOf('.')+1); // //lower case first letter // name = name.substring(0,1).toLowerCase() + name.substring(1); // // return name.replace("Strategy", ""); // } // // /** // * Returns an internal identifier, probably an integer, for a given filename. // * @param filename the name of the file to resolve. // * @return An internal identifier, probably an integer, for a given filename. // */ // public abstract String resolve(String filename); // // // public void print(String path, boolean sonicVisualizerOutput) { // } // // /** // * Clear al information from the key value store // */ // public abstract void clear(); // } // Path: src/be/panako/cli/Stats.java import be.panako.strategy.Strategy; /*************************************************************************** * * * Panako - acoustic fingerprinting * * Copyright (C) 2014 - 2021 - Joren Six / IPEM * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of the * * License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Affero General Public License for more details. * * * * You should have received a copy of the GNU Affero General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/> * * * **************************************************************************** * ______ ________ ___ __ ________ ___ ___ ______ * * /_____/\ /_______/\ /__/\ /__/\ /_______/\ /___/\/__/\ /_____/\ * * \:::_ \ \\::: _ \ \\::\_\\ \ \\::: _ \ \\::.\ \\ \ \\:::_ \ \ * * \:(_) \ \\::(_) \ \\:. `-\ \ \\::(_) \ \\:: \/_) \ \\:\ \ \ \ * * \: ___\/ \:: __ \ \\:. _ \ \\:: __ \ \\:. __ ( ( \:\ \ \ \ * * \ \ \ \:.\ \ \ \\. \`-\ \ \\:.\ \ \ \\: \ ) \ \ \:\_\ \ \ * * \_\/ \__\/\__\/ \__\/ \__\/ \__\/\__\/ \__\/\__\/ \_____\/ * * * **************************************************************************** * * * Panako * * Acoustic Fingerprinting * * * ****************************************************************************/ package be.panako.cli; /** * Shows some statistics about the storage. * @author Joren Six */ public class Stats extends Application { @Override public void run(String... args) {
Strategy strategy = Strategy.getInstance();
JorenSix/Panako
src/be/panako/cli/Print.java
// Path: src/be/panako/strategy/Strategy.java // public abstract class Strategy { // // // /** // * Store an audio file in the data store. The name of the resource is used to extract a // * numerical identifier. The description is arbitrary. // * @param resource The audio resource. // * @param description An arbitrary description. // * @return The number of seconds of processed audio. // */ // public abstract double store(String resource, String description); // // public abstract void query(String query, int maxNumberOfResults,Set<Integer> avoid, QueryResultHandler handler); // // public abstract void monitor(String query,int maxNumberOfReqults,Set<Integer> avoid,QueryResultHandler handler); // // /** // * Are there fingerprints for this resource already stored in the database? // * @param resource The name of the resource. // * @return True if the resource is already treated. False otherwise. // */ // public abstract boolean hasResource(String resource); // // /** // * // * @return True if the storage is available, false otherwise. // */ // public abstract boolean isStorageAvailable(); // // /** // * Print some storage statistics. // */ // public abstract void printStorageStatistics(); // // /** // * Checks the configuration and returns a strategy. // * @return An instance of the strategy. // */ // private static Strategy strategy; // public static Strategy getInstance(){ // if(strategy == null){ // Reflections reflections = new Reflections("be.panako.strategy"); // Set<Class<? extends Strategy>> modules = reflections.getSubTypesOf(be.panako.strategy.Strategy.class); // String configuredStrategyName = Config.get(Key.STRATEGY); // // for(Class<? extends Strategy> module : modules) { // try { // if(configuredStrategyName.equalsIgnoreCase(Strategy.classToName(module))) { // strategy = ((Strategy) module.getDeclaredConstructor().newInstance()); // break; // } // } catch (Exception e) { // //should not happen, instantiation should not be a problem // e.printStackTrace(); // } // } // } // return strategy; // } // // public static String classToName(Class<? extends Strategy> c){ // //fully qualified name // String name = c.getCanonicalName(); // //unqualified name // name = name.substring(name.lastIndexOf('.')+1); // //lower case first letter // name = name.substring(0,1).toLowerCase() + name.substring(1); // // return name.replace("Strategy", ""); // } // // /** // * Returns an internal identifier, probably an integer, for a given filename. // * @param filename the name of the file to resolve. // * @return An internal identifier, probably an integer, for a given filename. // */ // public abstract String resolve(String filename); // // // public void print(String path, boolean sonicVisualizerOutput) { // } // // /** // * Clear al information from the key value store // */ // public abstract void clear(); // }
import be.panako.strategy.Strategy; import java.io.File; import java.util.List;
/*************************************************************************** * * * Panako - acoustic fingerprinting * * Copyright (C) 2014 - 2021 - Joren Six / IPEM * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of the * * License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Affero General Public License for more details. * * * * You should have received a copy of the GNU Affero General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/> * * * **************************************************************************** * ______ ________ ___ __ ________ ___ ___ ______ * * /_____/\ /_______/\ /__/\ /__/\ /_______/\ /___/\/__/\ /_____/\ * * \:::_ \ \\::: _ \ \\::\_\\ \ \\::: _ \ \\::.\ \\ \ \\:::_ \ \ * * \:(_) \ \\::(_) \ \\:. `-\ \ \\::(_) \ \\:: \/_) \ \\:\ \ \ \ * * \: ___\/ \:: __ \ \\:. _ \ \\:: __ \ \\:. __ ( ( \:\ \ \ \ * * \ \ \ \:.\ \ \ \\. \`-\ \ \\:.\ \ \ \\: \ ) \ \ \:\_\ \ \ * * \_\/ \__\/\__\/ \__\/ \__\/ \__\/\__\/ \__\/\__\/ \_____\/ * * * **************************************************************************** * * * Panako * * Acoustic Fingerprinting * * * ****************************************************************************/ package be.panako.cli; /** * Query the storage for audio fragments. * @author Joren Six */ public class Print extends Application{ @Override public void run(String... args) { List<File> files = this.getFilesFromArguments(args); boolean sonicVisualizerOutput = hasArgument("-sv", args);
// Path: src/be/panako/strategy/Strategy.java // public abstract class Strategy { // // // /** // * Store an audio file in the data store. The name of the resource is used to extract a // * numerical identifier. The description is arbitrary. // * @param resource The audio resource. // * @param description An arbitrary description. // * @return The number of seconds of processed audio. // */ // public abstract double store(String resource, String description); // // public abstract void query(String query, int maxNumberOfResults,Set<Integer> avoid, QueryResultHandler handler); // // public abstract void monitor(String query,int maxNumberOfReqults,Set<Integer> avoid,QueryResultHandler handler); // // /** // * Are there fingerprints for this resource already stored in the database? // * @param resource The name of the resource. // * @return True if the resource is already treated. False otherwise. // */ // public abstract boolean hasResource(String resource); // // /** // * // * @return True if the storage is available, false otherwise. // */ // public abstract boolean isStorageAvailable(); // // /** // * Print some storage statistics. // */ // public abstract void printStorageStatistics(); // // /** // * Checks the configuration and returns a strategy. // * @return An instance of the strategy. // */ // private static Strategy strategy; // public static Strategy getInstance(){ // if(strategy == null){ // Reflections reflections = new Reflections("be.panako.strategy"); // Set<Class<? extends Strategy>> modules = reflections.getSubTypesOf(be.panako.strategy.Strategy.class); // String configuredStrategyName = Config.get(Key.STRATEGY); // // for(Class<? extends Strategy> module : modules) { // try { // if(configuredStrategyName.equalsIgnoreCase(Strategy.classToName(module))) { // strategy = ((Strategy) module.getDeclaredConstructor().newInstance()); // break; // } // } catch (Exception e) { // //should not happen, instantiation should not be a problem // e.printStackTrace(); // } // } // } // return strategy; // } // // public static String classToName(Class<? extends Strategy> c){ // //fully qualified name // String name = c.getCanonicalName(); // //unqualified name // name = name.substring(name.lastIndexOf('.')+1); // //lower case first letter // name = name.substring(0,1).toLowerCase() + name.substring(1); // // return name.replace("Strategy", ""); // } // // /** // * Returns an internal identifier, probably an integer, for a given filename. // * @param filename the name of the file to resolve. // * @return An internal identifier, probably an integer, for a given filename. // */ // public abstract String resolve(String filename); // // // public void print(String path, boolean sonicVisualizerOutput) { // } // // /** // * Clear al information from the key value store // */ // public abstract void clear(); // } // Path: src/be/panako/cli/Print.java import be.panako.strategy.Strategy; import java.io.File; import java.util.List; /*************************************************************************** * * * Panako - acoustic fingerprinting * * Copyright (C) 2014 - 2021 - Joren Six / IPEM * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of the * * License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Affero General Public License for more details. * * * * You should have received a copy of the GNU Affero General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/> * * * **************************************************************************** * ______ ________ ___ __ ________ ___ ___ ______ * * /_____/\ /_______/\ /__/\ /__/\ /_______/\ /___/\/__/\ /_____/\ * * \:::_ \ \\::: _ \ \\::\_\\ \ \\::: _ \ \\::.\ \\ \ \\:::_ \ \ * * \:(_) \ \\::(_) \ \\:. `-\ \ \\::(_) \ \\:: \/_) \ \\:\ \ \ \ * * \: ___\/ \:: __ \ \\:. _ \ \\:: __ \ \\:. __ ( ( \:\ \ \ \ * * \ \ \ \:.\ \ \ \\. \`-\ \ \\:.\ \ \ \\: \ ) \ \ \:\_\ \ \ * * \_\/ \__\/\__\/ \__\/ \__\/ \__\/\__\/ \__\/\__\/ \_____\/ * * * **************************************************************************** * * * Panako * * Acoustic Fingerprinting * * * ****************************************************************************/ package be.panako.cli; /** * Query the storage for audio fragments. * @author Joren Six */ public class Print extends Application{ @Override public void run(String... args) { List<File> files = this.getFilesFromArguments(args); boolean sonicVisualizerOutput = hasArgument("-sv", args);
Strategy strategy = Strategy.getInstance();
JorenSix/Panako
src/be/panako/cli/Clear.java
// Path: src/be/panako/strategy/Strategy.java // public abstract class Strategy { // // // /** // * Store an audio file in the data store. The name of the resource is used to extract a // * numerical identifier. The description is arbitrary. // * @param resource The audio resource. // * @param description An arbitrary description. // * @return The number of seconds of processed audio. // */ // public abstract double store(String resource, String description); // // public abstract void query(String query, int maxNumberOfResults,Set<Integer> avoid, QueryResultHandler handler); // // public abstract void monitor(String query,int maxNumberOfReqults,Set<Integer> avoid,QueryResultHandler handler); // // /** // * Are there fingerprints for this resource already stored in the database? // * @param resource The name of the resource. // * @return True if the resource is already treated. False otherwise. // */ // public abstract boolean hasResource(String resource); // // /** // * // * @return True if the storage is available, false otherwise. // */ // public abstract boolean isStorageAvailable(); // // /** // * Print some storage statistics. // */ // public abstract void printStorageStatistics(); // // /** // * Checks the configuration and returns a strategy. // * @return An instance of the strategy. // */ // private static Strategy strategy; // public static Strategy getInstance(){ // if(strategy == null){ // Reflections reflections = new Reflections("be.panako.strategy"); // Set<Class<? extends Strategy>> modules = reflections.getSubTypesOf(be.panako.strategy.Strategy.class); // String configuredStrategyName = Config.get(Key.STRATEGY); // // for(Class<? extends Strategy> module : modules) { // try { // if(configuredStrategyName.equalsIgnoreCase(Strategy.classToName(module))) { // strategy = ((Strategy) module.getDeclaredConstructor().newInstance()); // break; // } // } catch (Exception e) { // //should not happen, instantiation should not be a problem // e.printStackTrace(); // } // } // } // return strategy; // } // // public static String classToName(Class<? extends Strategy> c){ // //fully qualified name // String name = c.getCanonicalName(); // //unqualified name // name = name.substring(name.lastIndexOf('.')+1); // //lower case first letter // name = name.substring(0,1).toLowerCase() + name.substring(1); // // return name.replace("Strategy", ""); // } // // /** // * Returns an internal identifier, probably an integer, for a given filename. // * @param filename the name of the file to resolve. // * @return An internal identifier, probably an integer, for a given filename. // */ // public abstract String resolve(String filename); // // // public void print(String path, boolean sonicVisualizerOutput) { // } // // /** // * Clear al information from the key value store // */ // public abstract void clear(); // }
import be.panako.strategy.Strategy;
/*************************************************************************** * * * Panako - acoustic fingerprinting * * Copyright (C) 2014 - 2021 - Joren Six / IPEM * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of the * * License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Affero General Public License for more details. * * * * You should have received a copy of the GNU Affero General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/> * * * **************************************************************************** * ______ ________ ___ __ ________ ___ ___ ______ * * /_____/\ /_______/\ /__/\ /__/\ /_______/\ /___/\/__/\ /_____/\ * * \:::_ \ \\::: _ \ \\::\_\\ \ \\::: _ \ \\::.\ \\ \ \\:::_ \ \ * * \:(_) \ \\::(_) \ \\:. `-\ \ \\::(_) \ \\:: \/_) \ \\:\ \ \ \ * * \: ___\/ \:: __ \ \\:. _ \ \\:: __ \ \\:. __ ( ( \:\ \ \ \ * * \ \ \ \:.\ \ \ \\. \`-\ \ \\:.\ \ \ \\: \ ) \ \ \:\_\ \ \ * * \_\/ \__\/\__\/ \__\/ \__\/ \__\/\__\/ \__\/\__\/ \_____\/ * * * **************************************************************************** * * * Panako * * Acoustic Fingerprinting * * * ****************************************************************************/ package be.panako.cli; public class Clear extends Application { @Override public void run(String... args) {
// Path: src/be/panako/strategy/Strategy.java // public abstract class Strategy { // // // /** // * Store an audio file in the data store. The name of the resource is used to extract a // * numerical identifier. The description is arbitrary. // * @param resource The audio resource. // * @param description An arbitrary description. // * @return The number of seconds of processed audio. // */ // public abstract double store(String resource, String description); // // public abstract void query(String query, int maxNumberOfResults,Set<Integer> avoid, QueryResultHandler handler); // // public abstract void monitor(String query,int maxNumberOfReqults,Set<Integer> avoid,QueryResultHandler handler); // // /** // * Are there fingerprints for this resource already stored in the database? // * @param resource The name of the resource. // * @return True if the resource is already treated. False otherwise. // */ // public abstract boolean hasResource(String resource); // // /** // * // * @return True if the storage is available, false otherwise. // */ // public abstract boolean isStorageAvailable(); // // /** // * Print some storage statistics. // */ // public abstract void printStorageStatistics(); // // /** // * Checks the configuration and returns a strategy. // * @return An instance of the strategy. // */ // private static Strategy strategy; // public static Strategy getInstance(){ // if(strategy == null){ // Reflections reflections = new Reflections("be.panako.strategy"); // Set<Class<? extends Strategy>> modules = reflections.getSubTypesOf(be.panako.strategy.Strategy.class); // String configuredStrategyName = Config.get(Key.STRATEGY); // // for(Class<? extends Strategy> module : modules) { // try { // if(configuredStrategyName.equalsIgnoreCase(Strategy.classToName(module))) { // strategy = ((Strategy) module.getDeclaredConstructor().newInstance()); // break; // } // } catch (Exception e) { // //should not happen, instantiation should not be a problem // e.printStackTrace(); // } // } // } // return strategy; // } // // public static String classToName(Class<? extends Strategy> c){ // //fully qualified name // String name = c.getCanonicalName(); // //unqualified name // name = name.substring(name.lastIndexOf('.')+1); // //lower case first letter // name = name.substring(0,1).toLowerCase() + name.substring(1); // // return name.replace("Strategy", ""); // } // // /** // * Returns an internal identifier, probably an integer, for a given filename. // * @param filename the name of the file to resolve. // * @return An internal identifier, probably an integer, for a given filename. // */ // public abstract String resolve(String filename); // // // public void print(String path, boolean sonicVisualizerOutput) { // } // // /** // * Clear al information from the key value store // */ // public abstract void clear(); // } // Path: src/be/panako/cli/Clear.java import be.panako.strategy.Strategy; /*************************************************************************** * * * Panako - acoustic fingerprinting * * Copyright (C) 2014 - 2021 - Joren Six / IPEM * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of the * * License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Affero General Public License for more details. * * * * You should have received a copy of the GNU Affero General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/> * * * **************************************************************************** * ______ ________ ___ __ ________ ___ ___ ______ * * /_____/\ /_______/\ /__/\ /__/\ /_______/\ /___/\/__/\ /_____/\ * * \:::_ \ \\::: _ \ \\::\_\\ \ \\::: _ \ \\::.\ \\ \ \\:::_ \ \ * * \:(_) \ \\::(_) \ \\:. `-\ \ \\::(_) \ \\:: \/_) \ \\:\ \ \ \ * * \: ___\/ \:: __ \ \\:. _ \ \\:: __ \ \\:. __ ( ( \:\ \ \ \ * * \ \ \ \:.\ \ \ \\. \`-\ \ \\:.\ \ \ \\: \ ) \ \ \:\_\ \ \ * * \_\/ \__\/\__\/ \__\/ \__\/ \__\/\__\/ \__\/\__\/ \_____\/ * * * **************************************************************************** * * * Panako * * Acoustic Fingerprinting * * * ****************************************************************************/ package be.panako.cli; public class Clear extends Application { @Override public void run(String... args) {
Strategy strat = Strategy.getInstance();
optimizely/android-sdk
user-profile/src/androidTest/java/com/optimizely/ab/android/user_profile/LegacyDiskCacheTest.java
// Path: shared/src/main/java/com/optimizely/ab/android/shared/Cache.java // public class Cache { // // @NonNull private final Context context; // @NonNull private final Logger logger; // // /** // * Create new instance of {@link Cache}. // * // * @param context any {@link Context instance} // * @param logger a {@link Logger} instances // */ // public Cache(@NonNull Context context, @NonNull Logger logger) { // this.context = context; // this.logger = logger; // } // // /** // * Delete the cache file. // * // * @param filename the path to the file // * @return true if the file was deleted or false otherwise // */ // public boolean delete(String filename) { // return context.deleteFile(filename); // } // // /** // * Check if the cache file exists. // * // * @param filename the path to the file // * @return true if the file exists or false otherwise // */ // public boolean exists(String filename) { // String[] files = context.fileList(); // return files != null && Arrays.asList(files).contains(filename); // } // // /** // * Load data from the cache file. // * // * @param filename the path to the file // * @return the loaded cache file as String or null if the file cannot be loaded // */ // @Nullable // public String load(String filename) { // FileInputStream fileInputStream = null; // try { // fileInputStream = context.openFileInput(filename); // InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); // BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // StringBuilder sb = new StringBuilder(); // String line; // while ((line = bufferedReader.readLine()) != null) { // sb.append(line); // } // return sb.toString(); // } catch (Exception e) { // logger.warn("Unable to load file {}.", filename); // return null; // } finally { // try { // if (fileInputStream != null) { // fileInputStream.close(); // } // } catch (Exception e) { // logger.warn("Unable to close file {}.", filename, e); // } // } // } // // /** // * Save data to the cache file and overwrite any existing data. // * // * @param filename the path to the file // * @param data the String data to write to the file // * @return true if the file was saved // */ // public boolean save(String filename, String data) { // FileOutputStream fileOutputStream = null; // try { // fileOutputStream = context.openFileOutput(filename, Context.MODE_PRIVATE); // fileOutputStream.write(data.getBytes()); // return true; // } catch (Exception e) { // logger.error("Error saving file {}.", filename); // return false; // } finally { // if (fileOutputStream != null) { // try { // fileOutputStream.close(); // } catch (Exception e) { // logger.warn("Unable to close file {}.", filename, e); // // } // } // } // } // }
import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; import com.optimizely.ab.android.shared.Cache; import org.json.JSONException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
/**************************************************************************** * Copyright 2021, Optimizely, Inc. and contributors * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES 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.optimizely.ab.android.user_profile; /** * Tests for {@link UserProfileCache.LegacyDiskCache} */ @RunWith(AndroidJUnit4.class) public class LegacyDiskCacheTest { // Runs tasks serially on the calling thread private ExecutorService executor = Executors.newSingleThreadExecutor();
// Path: shared/src/main/java/com/optimizely/ab/android/shared/Cache.java // public class Cache { // // @NonNull private final Context context; // @NonNull private final Logger logger; // // /** // * Create new instance of {@link Cache}. // * // * @param context any {@link Context instance} // * @param logger a {@link Logger} instances // */ // public Cache(@NonNull Context context, @NonNull Logger logger) { // this.context = context; // this.logger = logger; // } // // /** // * Delete the cache file. // * // * @param filename the path to the file // * @return true if the file was deleted or false otherwise // */ // public boolean delete(String filename) { // return context.deleteFile(filename); // } // // /** // * Check if the cache file exists. // * // * @param filename the path to the file // * @return true if the file exists or false otherwise // */ // public boolean exists(String filename) { // String[] files = context.fileList(); // return files != null && Arrays.asList(files).contains(filename); // } // // /** // * Load data from the cache file. // * // * @param filename the path to the file // * @return the loaded cache file as String or null if the file cannot be loaded // */ // @Nullable // public String load(String filename) { // FileInputStream fileInputStream = null; // try { // fileInputStream = context.openFileInput(filename); // InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); // BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // StringBuilder sb = new StringBuilder(); // String line; // while ((line = bufferedReader.readLine()) != null) { // sb.append(line); // } // return sb.toString(); // } catch (Exception e) { // logger.warn("Unable to load file {}.", filename); // return null; // } finally { // try { // if (fileInputStream != null) { // fileInputStream.close(); // } // } catch (Exception e) { // logger.warn("Unable to close file {}.", filename, e); // } // } // } // // /** // * Save data to the cache file and overwrite any existing data. // * // * @param filename the path to the file // * @param data the String data to write to the file // * @return true if the file was saved // */ // public boolean save(String filename, String data) { // FileOutputStream fileOutputStream = null; // try { // fileOutputStream = context.openFileOutput(filename, Context.MODE_PRIVATE); // fileOutputStream.write(data.getBytes()); // return true; // } catch (Exception e) { // logger.error("Error saving file {}.", filename); // return false; // } finally { // if (fileOutputStream != null) { // try { // fileOutputStream.close(); // } catch (Exception e) { // logger.warn("Unable to close file {}.", filename, e); // // } // } // } // } // } // Path: user-profile/src/androidTest/java/com/optimizely/ab/android/user_profile/LegacyDiskCacheTest.java import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; import com.optimizely.ab.android.shared.Cache; import org.json.JSONException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /**************************************************************************** * Copyright 2021, Optimizely, Inc. and contributors * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES 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.optimizely.ab.android.user_profile; /** * Tests for {@link UserProfileCache.LegacyDiskCache} */ @RunWith(AndroidJUnit4.class) public class LegacyDiskCacheTest { // Runs tasks serially on the calling thread private ExecutorService executor = Executors.newSingleThreadExecutor();
private Cache cache;
optimizely/android-sdk
user-profile/src/androidTest/java/com/optimizely/ab/android/user_profile/DiskCacheTest.java
// Path: shared/src/main/java/com/optimizely/ab/android/shared/Cache.java // public class Cache { // // @NonNull private final Context context; // @NonNull private final Logger logger; // // /** // * Create new instance of {@link Cache}. // * // * @param context any {@link Context instance} // * @param logger a {@link Logger} instances // */ // public Cache(@NonNull Context context, @NonNull Logger logger) { // this.context = context; // this.logger = logger; // } // // /** // * Delete the cache file. // * // * @param filename the path to the file // * @return true if the file was deleted or false otherwise // */ // public boolean delete(String filename) { // return context.deleteFile(filename); // } // // /** // * Check if the cache file exists. // * // * @param filename the path to the file // * @return true if the file exists or false otherwise // */ // public boolean exists(String filename) { // String[] files = context.fileList(); // return files != null && Arrays.asList(files).contains(filename); // } // // /** // * Load data from the cache file. // * // * @param filename the path to the file // * @return the loaded cache file as String or null if the file cannot be loaded // */ // @Nullable // public String load(String filename) { // FileInputStream fileInputStream = null; // try { // fileInputStream = context.openFileInput(filename); // InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); // BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // StringBuilder sb = new StringBuilder(); // String line; // while ((line = bufferedReader.readLine()) != null) { // sb.append(line); // } // return sb.toString(); // } catch (Exception e) { // logger.warn("Unable to load file {}.", filename); // return null; // } finally { // try { // if (fileInputStream != null) { // fileInputStream.close(); // } // } catch (Exception e) { // logger.warn("Unable to close file {}.", filename, e); // } // } // } // // /** // * Save data to the cache file and overwrite any existing data. // * // * @param filename the path to the file // * @param data the String data to write to the file // * @return true if the file was saved // */ // public boolean save(String filename, String data) { // FileOutputStream fileOutputStream = null; // try { // fileOutputStream = context.openFileOutput(filename, Context.MODE_PRIVATE); // fileOutputStream.write(data.getBytes()); // return true; // } catch (Exception e) { // logger.error("Error saving file {}.", filename); // return false; // } finally { // if (fileOutputStream != null) { // try { // fileOutputStream.close(); // } catch (Exception e) { // logger.warn("Unable to close file {}.", filename, e); // // } // } // } // } // }
import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; import com.optimizely.ab.android.shared.Cache; import org.json.JSONException; import org.json.JSONObject; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
/**************************************************************************** * Copyright 2017, Optimizely, Inc. and contributors * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES 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.optimizely.ab.android.user_profile; /** * Tests for {@link UserProfileCache.DiskCache} */ @RunWith(AndroidJUnit4.class) public class DiskCacheTest { // Runs tasks serially on the calling thread private ExecutorService executor = Executors.newSingleThreadExecutor();
// Path: shared/src/main/java/com/optimizely/ab/android/shared/Cache.java // public class Cache { // // @NonNull private final Context context; // @NonNull private final Logger logger; // // /** // * Create new instance of {@link Cache}. // * // * @param context any {@link Context instance} // * @param logger a {@link Logger} instances // */ // public Cache(@NonNull Context context, @NonNull Logger logger) { // this.context = context; // this.logger = logger; // } // // /** // * Delete the cache file. // * // * @param filename the path to the file // * @return true if the file was deleted or false otherwise // */ // public boolean delete(String filename) { // return context.deleteFile(filename); // } // // /** // * Check if the cache file exists. // * // * @param filename the path to the file // * @return true if the file exists or false otherwise // */ // public boolean exists(String filename) { // String[] files = context.fileList(); // return files != null && Arrays.asList(files).contains(filename); // } // // /** // * Load data from the cache file. // * // * @param filename the path to the file // * @return the loaded cache file as String or null if the file cannot be loaded // */ // @Nullable // public String load(String filename) { // FileInputStream fileInputStream = null; // try { // fileInputStream = context.openFileInput(filename); // InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); // BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // StringBuilder sb = new StringBuilder(); // String line; // while ((line = bufferedReader.readLine()) != null) { // sb.append(line); // } // return sb.toString(); // } catch (Exception e) { // logger.warn("Unable to load file {}.", filename); // return null; // } finally { // try { // if (fileInputStream != null) { // fileInputStream.close(); // } // } catch (Exception e) { // logger.warn("Unable to close file {}.", filename, e); // } // } // } // // /** // * Save data to the cache file and overwrite any existing data. // * // * @param filename the path to the file // * @param data the String data to write to the file // * @return true if the file was saved // */ // public boolean save(String filename, String data) { // FileOutputStream fileOutputStream = null; // try { // fileOutputStream = context.openFileOutput(filename, Context.MODE_PRIVATE); // fileOutputStream.write(data.getBytes()); // return true; // } catch (Exception e) { // logger.error("Error saving file {}.", filename); // return false; // } finally { // if (fileOutputStream != null) { // try { // fileOutputStream.close(); // } catch (Exception e) { // logger.warn("Unable to close file {}.", filename, e); // // } // } // } // } // } // Path: user-profile/src/androidTest/java/com/optimizely/ab/android/user_profile/DiskCacheTest.java import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; import com.optimizely.ab.android.shared.Cache; import org.json.JSONException; import org.json.JSONObject; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /**************************************************************************** * Copyright 2017, Optimizely, Inc. and contributors * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES 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.optimizely.ab.android.user_profile; /** * Tests for {@link UserProfileCache.DiskCache} */ @RunWith(AndroidJUnit4.class) public class DiskCacheTest { // Runs tasks serially on the calling thread private ExecutorService executor = Executors.newSingleThreadExecutor();
private Cache cache;
optimizely/android-sdk
user-profile/src/main/java/com/optimizely/ab/android/user_profile/DefaultUserProfileService.java
// Path: shared/src/main/java/com/optimizely/ab/android/shared/Cache.java // public class Cache { // // @NonNull private final Context context; // @NonNull private final Logger logger; // // /** // * Create new instance of {@link Cache}. // * // * @param context any {@link Context instance} // * @param logger a {@link Logger} instances // */ // public Cache(@NonNull Context context, @NonNull Logger logger) { // this.context = context; // this.logger = logger; // } // // /** // * Delete the cache file. // * // * @param filename the path to the file // * @return true if the file was deleted or false otherwise // */ // public boolean delete(String filename) { // return context.deleteFile(filename); // } // // /** // * Check if the cache file exists. // * // * @param filename the path to the file // * @return true if the file exists or false otherwise // */ // public boolean exists(String filename) { // String[] files = context.fileList(); // return files != null && Arrays.asList(files).contains(filename); // } // // /** // * Load data from the cache file. // * // * @param filename the path to the file // * @return the loaded cache file as String or null if the file cannot be loaded // */ // @Nullable // public String load(String filename) { // FileInputStream fileInputStream = null; // try { // fileInputStream = context.openFileInput(filename); // InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); // BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // StringBuilder sb = new StringBuilder(); // String line; // while ((line = bufferedReader.readLine()) != null) { // sb.append(line); // } // return sb.toString(); // } catch (Exception e) { // logger.warn("Unable to load file {}.", filename); // return null; // } finally { // try { // if (fileInputStream != null) { // fileInputStream.close(); // } // } catch (Exception e) { // logger.warn("Unable to close file {}.", filename, e); // } // } // } // // /** // * Save data to the cache file and overwrite any existing data. // * // * @param filename the path to the file // * @param data the String data to write to the file // * @return true if the file was saved // */ // public boolean save(String filename, String data) { // FileOutputStream fileOutputStream = null; // try { // fileOutputStream = context.openFileOutput(filename, Context.MODE_PRIVATE); // fileOutputStream.write(data.getBytes()); // return true; // } catch (Exception e) { // logger.error("Error saving file {}.", filename); // return false; // } finally { // if (fileOutputStream != null) { // try { // fileOutputStream.close(); // } catch (Exception e) { // logger.warn("Unable to close file {}.", filename, e); // // } // } // } // } // }
import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import android.os.Build; import android.content.Context; import android.os.AsyncTask; import android.annotation.TargetApi; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.optimizely.ab.android.shared.Cache; import com.optimizely.ab.bucketing.UserProfileService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map;
/**************************************************************************** * Copyright 2017,2021, Optimizely, Inc. and contributors * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES 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.optimizely.ab.android.user_profile; /** * Android implementation of {@link UserProfileService} * <p> * Makes bucketing sticky. This module is what allows the SDK * to know if a user has already been bucketed for an experiment. * Once a user is bucketed they will stay bucketed unless the device's * storage is cleared. Bucketing information is stored in a simple file. */ public class DefaultUserProfileService implements UserProfileService { @NonNull private final UserProfileCache userProfileCache; @NonNull private final Logger logger; DefaultUserProfileService(@NonNull UserProfileCache userProfileCache, @NonNull Logger logger) { this.userProfileCache = userProfileCache; this.logger = logger; } /** * Gets a new instance of {@link DefaultUserProfileService}. * * @param projectId your project's id * @param context an instance of {@link Context} * @return the instance as {@link UserProfileService} */ public static UserProfileService newInstance(@NonNull String projectId, @NonNull Context context) { UserProfileCache userProfileCache = new UserProfileCache(
// Path: shared/src/main/java/com/optimizely/ab/android/shared/Cache.java // public class Cache { // // @NonNull private final Context context; // @NonNull private final Logger logger; // // /** // * Create new instance of {@link Cache}. // * // * @param context any {@link Context instance} // * @param logger a {@link Logger} instances // */ // public Cache(@NonNull Context context, @NonNull Logger logger) { // this.context = context; // this.logger = logger; // } // // /** // * Delete the cache file. // * // * @param filename the path to the file // * @return true if the file was deleted or false otherwise // */ // public boolean delete(String filename) { // return context.deleteFile(filename); // } // // /** // * Check if the cache file exists. // * // * @param filename the path to the file // * @return true if the file exists or false otherwise // */ // public boolean exists(String filename) { // String[] files = context.fileList(); // return files != null && Arrays.asList(files).contains(filename); // } // // /** // * Load data from the cache file. // * // * @param filename the path to the file // * @return the loaded cache file as String or null if the file cannot be loaded // */ // @Nullable // public String load(String filename) { // FileInputStream fileInputStream = null; // try { // fileInputStream = context.openFileInput(filename); // InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); // BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // StringBuilder sb = new StringBuilder(); // String line; // while ((line = bufferedReader.readLine()) != null) { // sb.append(line); // } // return sb.toString(); // } catch (Exception e) { // logger.warn("Unable to load file {}.", filename); // return null; // } finally { // try { // if (fileInputStream != null) { // fileInputStream.close(); // } // } catch (Exception e) { // logger.warn("Unable to close file {}.", filename, e); // } // } // } // // /** // * Save data to the cache file and overwrite any existing data. // * // * @param filename the path to the file // * @param data the String data to write to the file // * @return true if the file was saved // */ // public boolean save(String filename, String data) { // FileOutputStream fileOutputStream = null; // try { // fileOutputStream = context.openFileOutput(filename, Context.MODE_PRIVATE); // fileOutputStream.write(data.getBytes()); // return true; // } catch (Exception e) { // logger.error("Error saving file {}.", filename); // return false; // } finally { // if (fileOutputStream != null) { // try { // fileOutputStream.close(); // } catch (Exception e) { // logger.warn("Unable to close file {}.", filename, e); // // } // } // } // } // } // Path: user-profile/src/main/java/com/optimizely/ab/android/user_profile/DefaultUserProfileService.java import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import android.os.Build; import android.content.Context; import android.os.AsyncTask; import android.annotation.TargetApi; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.optimizely.ab.android.shared.Cache; import com.optimizely.ab.bucketing.UserProfileService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; /**************************************************************************** * Copyright 2017,2021, Optimizely, Inc. and contributors * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES 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.optimizely.ab.android.user_profile; /** * Android implementation of {@link UserProfileService} * <p> * Makes bucketing sticky. This module is what allows the SDK * to know if a user has already been bucketed for an experiment. * Once a user is bucketed they will stay bucketed unless the device's * storage is cleared. Bucketing information is stored in a simple file. */ public class DefaultUserProfileService implements UserProfileService { @NonNull private final UserProfileCache userProfileCache; @NonNull private final Logger logger; DefaultUserProfileService(@NonNull UserProfileCache userProfileCache, @NonNull Logger logger) { this.userProfileCache = userProfileCache; this.logger = logger; } /** * Gets a new instance of {@link DefaultUserProfileService}. * * @param projectId your project's id * @param context an instance of {@link Context} * @return the instance as {@link UserProfileService} */ public static UserProfileService newInstance(@NonNull String projectId, @NonNull Context context) { UserProfileCache userProfileCache = new UserProfileCache(
new UserProfileCache.DiskCache(new Cache(context, LoggerFactory.getLogger(Cache.class)),
optimizely/android-sdk
datafile-handler/src/androidTest/java/com/optimizely/ab/android/datafile_handler/DatafileCacheTest.java
// Path: shared/src/main/java/com/optimizely/ab/android/shared/Cache.java // public class Cache { // // @NonNull private final Context context; // @NonNull private final Logger logger; // // /** // * Create new instance of {@link Cache}. // * // * @param context any {@link Context instance} // * @param logger a {@link Logger} instances // */ // public Cache(@NonNull Context context, @NonNull Logger logger) { // this.context = context; // this.logger = logger; // } // // /** // * Delete the cache file. // * // * @param filename the path to the file // * @return true if the file was deleted or false otherwise // */ // public boolean delete(String filename) { // return context.deleteFile(filename); // } // // /** // * Check if the cache file exists. // * // * @param filename the path to the file // * @return true if the file exists or false otherwise // */ // public boolean exists(String filename) { // String[] files = context.fileList(); // return files != null && Arrays.asList(files).contains(filename); // } // // /** // * Load data from the cache file. // * // * @param filename the path to the file // * @return the loaded cache file as String or null if the file cannot be loaded // */ // @Nullable // public String load(String filename) { // FileInputStream fileInputStream = null; // try { // fileInputStream = context.openFileInput(filename); // InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); // BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // StringBuilder sb = new StringBuilder(); // String line; // while ((line = bufferedReader.readLine()) != null) { // sb.append(line); // } // return sb.toString(); // } catch (Exception e) { // logger.warn("Unable to load file {}.", filename); // return null; // } finally { // try { // if (fileInputStream != null) { // fileInputStream.close(); // } // } catch (Exception e) { // logger.warn("Unable to close file {}.", filename, e); // } // } // } // // /** // * Save data to the cache file and overwrite any existing data. // * // * @param filename the path to the file // * @param data the String data to write to the file // * @return true if the file was saved // */ // public boolean save(String filename, String data) { // FileOutputStream fileOutputStream = null; // try { // fileOutputStream = context.openFileOutput(filename, Context.MODE_PRIVATE); // fileOutputStream.write(data.getBytes()); // return true; // } catch (Exception e) { // logger.error("Error saving file {}.", filename); // return false; // } finally { // if (fileOutputStream != null) { // try { // fileOutputStream.close(); // } catch (Exception e) { // logger.warn("Unable to close file {}.", filename, e); // // } // } // } // } // }
import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; import com.optimizely.ab.android.shared.Cache; import org.json.JSONException; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import java.io.IOException; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.Matchers.any; import static org.mockito.Matchers.contains;
/**************************************************************************** * Copyright 2016, Optimizely, Inc. and contributors * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES 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.optimizely.ab.android.datafile_handler; /** * Tests for {@link DatafileCache} */ @RunWith(AndroidJUnit4.class) public class DatafileCacheTest { private DatafileCache datafileCache; private Logger logger; @Before public void setup() { logger = mock(Logger.class);
// Path: shared/src/main/java/com/optimizely/ab/android/shared/Cache.java // public class Cache { // // @NonNull private final Context context; // @NonNull private final Logger logger; // // /** // * Create new instance of {@link Cache}. // * // * @param context any {@link Context instance} // * @param logger a {@link Logger} instances // */ // public Cache(@NonNull Context context, @NonNull Logger logger) { // this.context = context; // this.logger = logger; // } // // /** // * Delete the cache file. // * // * @param filename the path to the file // * @return true if the file was deleted or false otherwise // */ // public boolean delete(String filename) { // return context.deleteFile(filename); // } // // /** // * Check if the cache file exists. // * // * @param filename the path to the file // * @return true if the file exists or false otherwise // */ // public boolean exists(String filename) { // String[] files = context.fileList(); // return files != null && Arrays.asList(files).contains(filename); // } // // /** // * Load data from the cache file. // * // * @param filename the path to the file // * @return the loaded cache file as String or null if the file cannot be loaded // */ // @Nullable // public String load(String filename) { // FileInputStream fileInputStream = null; // try { // fileInputStream = context.openFileInput(filename); // InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); // BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // StringBuilder sb = new StringBuilder(); // String line; // while ((line = bufferedReader.readLine()) != null) { // sb.append(line); // } // return sb.toString(); // } catch (Exception e) { // logger.warn("Unable to load file {}.", filename); // return null; // } finally { // try { // if (fileInputStream != null) { // fileInputStream.close(); // } // } catch (Exception e) { // logger.warn("Unable to close file {}.", filename, e); // } // } // } // // /** // * Save data to the cache file and overwrite any existing data. // * // * @param filename the path to the file // * @param data the String data to write to the file // * @return true if the file was saved // */ // public boolean save(String filename, String data) { // FileOutputStream fileOutputStream = null; // try { // fileOutputStream = context.openFileOutput(filename, Context.MODE_PRIVATE); // fileOutputStream.write(data.getBytes()); // return true; // } catch (Exception e) { // logger.error("Error saving file {}.", filename); // return false; // } finally { // if (fileOutputStream != null) { // try { // fileOutputStream.close(); // } catch (Exception e) { // logger.warn("Unable to close file {}.", filename, e); // // } // } // } // } // } // Path: datafile-handler/src/androidTest/java/com/optimizely/ab/android/datafile_handler/DatafileCacheTest.java import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; import com.optimizely.ab.android.shared.Cache; import org.json.JSONException; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import java.io.IOException; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.Matchers.any; import static org.mockito.Matchers.contains; /**************************************************************************** * Copyright 2016, Optimizely, Inc. and contributors * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES 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.optimizely.ab.android.datafile_handler; /** * Tests for {@link DatafileCache} */ @RunWith(AndroidJUnit4.class) public class DatafileCacheTest { private DatafileCache datafileCache; private Logger logger; @Before public void setup() { logger = mock(Logger.class);
Cache cache = new Cache(InstrumentationRegistry.getInstrumentation().getTargetContext(), logger);
optimizely/android-sdk
user-profile/src/androidTest/java/com/optimizely/ab/android/user_profile/DefaultUserProfileServiceTest.java
// Path: shared/src/main/java/com/optimizely/ab/android/shared/Cache.java // public class Cache { // // @NonNull private final Context context; // @NonNull private final Logger logger; // // /** // * Create new instance of {@link Cache}. // * // * @param context any {@link Context instance} // * @param logger a {@link Logger} instances // */ // public Cache(@NonNull Context context, @NonNull Logger logger) { // this.context = context; // this.logger = logger; // } // // /** // * Delete the cache file. // * // * @param filename the path to the file // * @return true if the file was deleted or false otherwise // */ // public boolean delete(String filename) { // return context.deleteFile(filename); // } // // /** // * Check if the cache file exists. // * // * @param filename the path to the file // * @return true if the file exists or false otherwise // */ // public boolean exists(String filename) { // String[] files = context.fileList(); // return files != null && Arrays.asList(files).contains(filename); // } // // /** // * Load data from the cache file. // * // * @param filename the path to the file // * @return the loaded cache file as String or null if the file cannot be loaded // */ // @Nullable // public String load(String filename) { // FileInputStream fileInputStream = null; // try { // fileInputStream = context.openFileInput(filename); // InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); // BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // StringBuilder sb = new StringBuilder(); // String line; // while ((line = bufferedReader.readLine()) != null) { // sb.append(line); // } // return sb.toString(); // } catch (Exception e) { // logger.warn("Unable to load file {}.", filename); // return null; // } finally { // try { // if (fileInputStream != null) { // fileInputStream.close(); // } // } catch (Exception e) { // logger.warn("Unable to close file {}.", filename, e); // } // } // } // // /** // * Save data to the cache file and overwrite any existing data. // * // * @param filename the path to the file // * @param data the String data to write to the file // * @return true if the file was saved // */ // public boolean save(String filename, String data) { // FileOutputStream fileOutputStream = null; // try { // fileOutputStream = context.openFileOutput(filename, Context.MODE_PRIVATE); // fileOutputStream.write(data.getBytes()); // return true; // } catch (Exception e) { // logger.error("Error saving file {}.", filename); // return false; // } finally { // if (fileOutputStream != null) { // try { // fileOutputStream.close(); // } catch (Exception e) { // logger.warn("Unable to close file {}.", filename, e); // // } // } // } // } // }
import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; import com.optimizely.ab.android.shared.Cache; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import static org.mockito.Mockito.mock;
/**************************************************************************** * Copyright 2017, Optimizely, Inc. and contributors * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES 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.optimizely.ab.android.user_profile; /** * Tests for {@link DefaultUserProfileService} */ @RunWith(AndroidJUnit4.class) public class DefaultUserProfileServiceTest { private DefaultUserProfileService userProfileService;
// Path: shared/src/main/java/com/optimizely/ab/android/shared/Cache.java // public class Cache { // // @NonNull private final Context context; // @NonNull private final Logger logger; // // /** // * Create new instance of {@link Cache}. // * // * @param context any {@link Context instance} // * @param logger a {@link Logger} instances // */ // public Cache(@NonNull Context context, @NonNull Logger logger) { // this.context = context; // this.logger = logger; // } // // /** // * Delete the cache file. // * // * @param filename the path to the file // * @return true if the file was deleted or false otherwise // */ // public boolean delete(String filename) { // return context.deleteFile(filename); // } // // /** // * Check if the cache file exists. // * // * @param filename the path to the file // * @return true if the file exists or false otherwise // */ // public boolean exists(String filename) { // String[] files = context.fileList(); // return files != null && Arrays.asList(files).contains(filename); // } // // /** // * Load data from the cache file. // * // * @param filename the path to the file // * @return the loaded cache file as String or null if the file cannot be loaded // */ // @Nullable // public String load(String filename) { // FileInputStream fileInputStream = null; // try { // fileInputStream = context.openFileInput(filename); // InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); // BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // StringBuilder sb = new StringBuilder(); // String line; // while ((line = bufferedReader.readLine()) != null) { // sb.append(line); // } // return sb.toString(); // } catch (Exception e) { // logger.warn("Unable to load file {}.", filename); // return null; // } finally { // try { // if (fileInputStream != null) { // fileInputStream.close(); // } // } catch (Exception e) { // logger.warn("Unable to close file {}.", filename, e); // } // } // } // // /** // * Save data to the cache file and overwrite any existing data. // * // * @param filename the path to the file // * @param data the String data to write to the file // * @return true if the file was saved // */ // public boolean save(String filename, String data) { // FileOutputStream fileOutputStream = null; // try { // fileOutputStream = context.openFileOutput(filename, Context.MODE_PRIVATE); // fileOutputStream.write(data.getBytes()); // return true; // } catch (Exception e) { // logger.error("Error saving file {}.", filename); // return false; // } finally { // if (fileOutputStream != null) { // try { // fileOutputStream.close(); // } catch (Exception e) { // logger.warn("Unable to close file {}.", filename, e); // // } // } // } // } // } // Path: user-profile/src/androidTest/java/com/optimizely/ab/android/user_profile/DefaultUserProfileServiceTest.java import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; import com.optimizely.ab.android.shared.Cache; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import static org.mockito.Mockito.mock; /**************************************************************************** * Copyright 2017, Optimizely, Inc. and contributors * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES 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.optimizely.ab.android.user_profile; /** * Tests for {@link DefaultUserProfileService} */ @RunWith(AndroidJUnit4.class) public class DefaultUserProfileServiceTest { private DefaultUserProfileService userProfileService;
private Cache cache;
optimizely/android-sdk
datafile-handler/src/main/java/com/optimizely/ab/android/datafile_handler/DatafileLoader.java
// Path: shared/src/main/java/com/optimizely/ab/android/shared/OptlyStorage.java // public class OptlyStorage { // // private static final String PREFS_NAME = "optly"; // // @NonNull private Context context; // // /** // * Creates a new instance of {@link OptlyStorage} // * // * @param context any instance of {@link Context} // * @hide // */ // public OptlyStorage(@NonNull Context context) { // this.context = context; // } // // /** // * Save a long value // * // * @param key a String key // * @param value a long value // * @hide // */ // public void saveLong(String key, long value) { // getWritablePrefs().putLong(key, value ).apply(); // } // // /** // * Get a long value // * @param key a String key // * @param defaultValue the value to return if the key isn't stored // * @return the long value // * @hide // */ // public long getLong(String key, long defaultValue) { // return getReadablePrefs().getLong(key, defaultValue); // } // // private SharedPreferences.Editor getWritablePrefs() { // return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit(); // } // // private SharedPreferences getReadablePrefs() { // return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); // } // }
import java.util.concurrent.Executors; import android.content.Context; import android.os.Build; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import com.optimizely.ab.android.shared.OptlyStorage; import org.json.JSONObject; import org.slf4j.Logger; import java.util.Date; import java.util.concurrent.ExecutorService;
/**************************************************************************** * Copyright 2016-2021, Optimizely, Inc. and contributors * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES 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.optimizely.ab.android.datafile_handler; /** * Handles intents and bindings in {@link DatafileService} */ public class DatafileLoader { private static final String datafileDownloadTime = "optlyDatafileDownloadTime"; private static Long minTimeBetweenDownloadsMilli = 60 * 1000L; @Nullable private DatafileCache datafileCache; @NonNull private final DatafileClient datafileClient; @NonNull private final Logger logger;
// Path: shared/src/main/java/com/optimizely/ab/android/shared/OptlyStorage.java // public class OptlyStorage { // // private static final String PREFS_NAME = "optly"; // // @NonNull private Context context; // // /** // * Creates a new instance of {@link OptlyStorage} // * // * @param context any instance of {@link Context} // * @hide // */ // public OptlyStorage(@NonNull Context context) { // this.context = context; // } // // /** // * Save a long value // * // * @param key a String key // * @param value a long value // * @hide // */ // public void saveLong(String key, long value) { // getWritablePrefs().putLong(key, value ).apply(); // } // // /** // * Get a long value // * @param key a String key // * @param defaultValue the value to return if the key isn't stored // * @return the long value // * @hide // */ // public long getLong(String key, long defaultValue) { // return getReadablePrefs().getLong(key, defaultValue); // } // // private SharedPreferences.Editor getWritablePrefs() { // return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE).edit(); // } // // private SharedPreferences getReadablePrefs() { // return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); // } // } // Path: datafile-handler/src/main/java/com/optimizely/ab/android/datafile_handler/DatafileLoader.java import java.util.concurrent.Executors; import android.content.Context; import android.os.Build; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import com.optimizely.ab.android.shared.OptlyStorage; import org.json.JSONObject; import org.slf4j.Logger; import java.util.Date; import java.util.concurrent.ExecutorService; /**************************************************************************** * Copyright 2016-2021, Optimizely, Inc. and contributors * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES 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.optimizely.ab.android.datafile_handler; /** * Handles intents and bindings in {@link DatafileService} */ public class DatafileLoader { private static final String datafileDownloadTime = "optlyDatafileDownloadTime"; private static Long minTimeBetweenDownloadsMilli = 60 * 1000L; @Nullable private DatafileCache datafileCache; @NonNull private final DatafileClient datafileClient; @NonNull private final Logger logger;
@NonNull private final OptlyStorage storage;
optimizely/android-sdk
datafile-handler/src/main/java/com/optimizely/ab/android/datafile_handler/DatafileHandler.java
// Path: shared/src/main/java/com/optimizely/ab/android/shared/DatafileConfig.java // public class DatafileConfig { // public static String defaultHost = "https://cdn.optimizely.com"; // public static String projectUrlSuffix = "/json/%s.json"; // public static String environmentUrlSuffix = "/datafiles/%s.json"; // public static String delimiter = "::::"; // // private final String projectId; // private final String sdkKey; // private final String host; // private final String datafileUrlString; // // /** // * Constructor used to construct a DatafileConfig to get cache key, url, // * for the appropriate environment. One or the other can be null. But, not both. // * @param projectId project id string. // * @param sdkKey the environment url. // * @param host used to override the DatafileConfig.defaultHost used for datafile synchronization. // */ // public DatafileConfig(String projectId, String sdkKey, String host) { // assert(projectId != null || sdkKey != null); // this.projectId = projectId; // this.sdkKey = sdkKey; // this.host = host; // // if (sdkKey != null) { // this.datafileUrlString = String.format((this.host + environmentUrlSuffix), sdkKey); // } // else { // this.datafileUrlString = String.format((this.host + projectUrlSuffix), projectId); // } // } // // /** // * Constructor used to construct a DatafileConfig to get cache key, url, // * for the appropriate environment. One or the other can be null. But, not both. // * @param projectId project id string. // * @param sdkKey the environment url. // */ // public DatafileConfig(String projectId, String sdkKey) { // this(projectId, sdkKey, defaultHost); // } // // /** // * This returns the current datafile key string. // * @return datafile key string. // */ // public String getKey() { // return sdkKey != null ? sdkKey : projectId; // } // // /** // * Get the url associated with this project. If there is an environment, // * that url is returned. // * @return url of current project configuration. // */ // public String getUrl() { // return datafileUrlString; // } // // public String toJSONString() { // JSONObject jsonObject = new JSONObject(); // try { // jsonObject.put("projectId", projectId); // jsonObject.put("sdkKey", sdkKey); // return jsonObject.toString(); // } catch (JSONException e) { // e.printStackTrace(); // } // // return null; // } // // public static DatafileConfig fromJSONString(String jsonString) { // try { // JSONObject jsonObject = new JSONObject(jsonString); // String projectId = null; // if (jsonObject.has("projectId")) { // projectId = jsonObject.getString("projectId"); // } // String environmentKey = null; // if (jsonObject.has("sdkKey")) { // environmentKey = jsonObject.getString("sdkKey"); // } // return new DatafileConfig(projectId, environmentKey); // } catch (JSONException e) { // e.printStackTrace(); // } // // return null; // } // /** // * To string either returns the proejct id as string or a concatenated string of project id // * delimiter and environment key. // * @return the string identification for the DatafileConfig // */ // @Override // public String toString() { // return projectId != null ? projectId : "null" + delimiter + (sdkKey != null? sdkKey : "null"); // } // // public boolean equals(Object o) { // if (o == this) { // return true; // } // if (!(o instanceof DatafileConfig)) { // return false; // } // DatafileConfig p = (DatafileConfig) o; // return this.projectId != null ? (p.projectId != null ? this.projectId.equals(p.projectId) : this.projectId == p.projectId) : p.projectId == null // && // this.sdkKey != null ? (p.sdkKey != null ? this.sdkKey.equals(p.sdkKey) : this.sdkKey == p.sdkKey) : p.sdkKey == null; // // } // // public int hashCode() { // int result = 17; // result = 31 * result + (projectId == null ? 0 : projectId.hashCode()) + (sdkKey == null ? 0 : sdkKey.hashCode()); // return result; // } // // }
import android.content.Context; import com.optimizely.ab.config.ProjectConfig; import com.optimizely.ab.config.ProjectConfigManager; import com.optimizely.ab.android.shared.DatafileConfig; import java.util.function.Function;
/**************************************************************************** * Copyright 2017-2018, Optimizely, Inc. and contributors * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES 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.optimizely.ab.android.datafile_handler; /** * DatafileHandler * @deprecated * This interface will be replaced by the ProjectConfigManager. If you are implementing this interface moving forward, * you will also need to implement the {@link ProjectConfigManager} . * class that is used to interact with the datafile_handler module. This interface can be * overridden so that the sdk user can provide a override for the default DatafileHandler. */ @Deprecated public interface DatafileHandler { /** * Synchronous call to download the datafile. * * @param context application context for download * @param datafileConfig DatafileConfig for the datafile * @return a valid datafile or null */
// Path: shared/src/main/java/com/optimizely/ab/android/shared/DatafileConfig.java // public class DatafileConfig { // public static String defaultHost = "https://cdn.optimizely.com"; // public static String projectUrlSuffix = "/json/%s.json"; // public static String environmentUrlSuffix = "/datafiles/%s.json"; // public static String delimiter = "::::"; // // private final String projectId; // private final String sdkKey; // private final String host; // private final String datafileUrlString; // // /** // * Constructor used to construct a DatafileConfig to get cache key, url, // * for the appropriate environment. One or the other can be null. But, not both. // * @param projectId project id string. // * @param sdkKey the environment url. // * @param host used to override the DatafileConfig.defaultHost used for datafile synchronization. // */ // public DatafileConfig(String projectId, String sdkKey, String host) { // assert(projectId != null || sdkKey != null); // this.projectId = projectId; // this.sdkKey = sdkKey; // this.host = host; // // if (sdkKey != null) { // this.datafileUrlString = String.format((this.host + environmentUrlSuffix), sdkKey); // } // else { // this.datafileUrlString = String.format((this.host + projectUrlSuffix), projectId); // } // } // // /** // * Constructor used to construct a DatafileConfig to get cache key, url, // * for the appropriate environment. One or the other can be null. But, not both. // * @param projectId project id string. // * @param sdkKey the environment url. // */ // public DatafileConfig(String projectId, String sdkKey) { // this(projectId, sdkKey, defaultHost); // } // // /** // * This returns the current datafile key string. // * @return datafile key string. // */ // public String getKey() { // return sdkKey != null ? sdkKey : projectId; // } // // /** // * Get the url associated with this project. If there is an environment, // * that url is returned. // * @return url of current project configuration. // */ // public String getUrl() { // return datafileUrlString; // } // // public String toJSONString() { // JSONObject jsonObject = new JSONObject(); // try { // jsonObject.put("projectId", projectId); // jsonObject.put("sdkKey", sdkKey); // return jsonObject.toString(); // } catch (JSONException e) { // e.printStackTrace(); // } // // return null; // } // // public static DatafileConfig fromJSONString(String jsonString) { // try { // JSONObject jsonObject = new JSONObject(jsonString); // String projectId = null; // if (jsonObject.has("projectId")) { // projectId = jsonObject.getString("projectId"); // } // String environmentKey = null; // if (jsonObject.has("sdkKey")) { // environmentKey = jsonObject.getString("sdkKey"); // } // return new DatafileConfig(projectId, environmentKey); // } catch (JSONException e) { // e.printStackTrace(); // } // // return null; // } // /** // * To string either returns the proejct id as string or a concatenated string of project id // * delimiter and environment key. // * @return the string identification for the DatafileConfig // */ // @Override // public String toString() { // return projectId != null ? projectId : "null" + delimiter + (sdkKey != null? sdkKey : "null"); // } // // public boolean equals(Object o) { // if (o == this) { // return true; // } // if (!(o instanceof DatafileConfig)) { // return false; // } // DatafileConfig p = (DatafileConfig) o; // return this.projectId != null ? (p.projectId != null ? this.projectId.equals(p.projectId) : this.projectId == p.projectId) : p.projectId == null // && // this.sdkKey != null ? (p.sdkKey != null ? this.sdkKey.equals(p.sdkKey) : this.sdkKey == p.sdkKey) : p.sdkKey == null; // // } // // public int hashCode() { // int result = 17; // result = 31 * result + (projectId == null ? 0 : projectId.hashCode()) + (sdkKey == null ? 0 : sdkKey.hashCode()); // return result; // } // // } // Path: datafile-handler/src/main/java/com/optimizely/ab/android/datafile_handler/DatafileHandler.java import android.content.Context; import com.optimizely.ab.config.ProjectConfig; import com.optimizely.ab.config.ProjectConfigManager; import com.optimizely.ab.android.shared.DatafileConfig; import java.util.function.Function; /**************************************************************************** * Copyright 2017-2018, Optimizely, Inc. and contributors * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES 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.optimizely.ab.android.datafile_handler; /** * DatafileHandler * @deprecated * This interface will be replaced by the ProjectConfigManager. If you are implementing this interface moving forward, * you will also need to implement the {@link ProjectConfigManager} . * class that is used to interact with the datafile_handler module. This interface can be * overridden so that the sdk user can provide a override for the default DatafileHandler. */ @Deprecated public interface DatafileHandler { /** * Synchronous call to download the datafile. * * @param context application context for download * @param datafileConfig DatafileConfig for the datafile * @return a valid datafile or null */
String downloadDatafile(Context context, DatafileConfig datafileConfig);
optimizely/android-sdk
user-profile/src/main/java/com/optimizely/ab/android/user_profile/UserProfileCache.java
// Path: shared/src/main/java/com/optimizely/ab/android/shared/Cache.java // public class Cache { // // @NonNull private final Context context; // @NonNull private final Logger logger; // // /** // * Create new instance of {@link Cache}. // * // * @param context any {@link Context instance} // * @param logger a {@link Logger} instances // */ // public Cache(@NonNull Context context, @NonNull Logger logger) { // this.context = context; // this.logger = logger; // } // // /** // * Delete the cache file. // * // * @param filename the path to the file // * @return true if the file was deleted or false otherwise // */ // public boolean delete(String filename) { // return context.deleteFile(filename); // } // // /** // * Check if the cache file exists. // * // * @param filename the path to the file // * @return true if the file exists or false otherwise // */ // public boolean exists(String filename) { // String[] files = context.fileList(); // return files != null && Arrays.asList(files).contains(filename); // } // // /** // * Load data from the cache file. // * // * @param filename the path to the file // * @return the loaded cache file as String or null if the file cannot be loaded // */ // @Nullable // public String load(String filename) { // FileInputStream fileInputStream = null; // try { // fileInputStream = context.openFileInput(filename); // InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); // BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // StringBuilder sb = new StringBuilder(); // String line; // while ((line = bufferedReader.readLine()) != null) { // sb.append(line); // } // return sb.toString(); // } catch (Exception e) { // logger.warn("Unable to load file {}.", filename); // return null; // } finally { // try { // if (fileInputStream != null) { // fileInputStream.close(); // } // } catch (Exception e) { // logger.warn("Unable to close file {}.", filename, e); // } // } // } // // /** // * Save data to the cache file and overwrite any existing data. // * // * @param filename the path to the file // * @param data the String data to write to the file // * @return true if the file was saved // */ // public boolean save(String filename, String data) { // FileOutputStream fileOutputStream = null; // try { // fileOutputStream = context.openFileOutput(filename, Context.MODE_PRIVATE); // fileOutputStream.write(data.getBytes()); // return true; // } catch (Exception e) { // logger.error("Error saving file {}.", filename); // return false; // } finally { // if (fileOutputStream != null) { // try { // fileOutputStream.close(); // } catch (Exception e) { // logger.warn("Unable to close file {}.", filename, e); // // } // } // } // } // }
import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import static com.optimizely.ab.bucketing.UserProfileService.experimentBucketMapKey; import static com.optimizely.ab.bucketing.UserProfileService.userIdKey; import static com.optimizely.ab.bucketing.UserProfileService.variationIdKey; import android.annotation.TargetApi; import android.os.AsyncTask; import android.os.Build; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import com.optimizely.ab.android.shared.Cache; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import java.util.Iterator;
logger.info("Saved user profile for {}.", userId); } } /** * Load the cache from disk to memory. */ void start() { // Migrate legacy user profiles if found. migrateLegacyUserProfiles(); try { JSONObject userProfilesJson = diskCache.load(); Map<String, Map<String, Object>> userProfilesMap = UserProfileCacheUtils.convertJSONObjectToMap (userProfilesJson); memoryCache.clear(); memoryCache.putAll(userProfilesMap); logger.info("Loaded user profile cache from disk."); } catch (Exception e) { clear(); logger.error("Unable to parse user profile cache from disk.", e); } } /** * Write-through cache persisted on disk. */ static class DiskCache { private static final String FILE_NAME = "optly-user-profile-service-%s.json";
// Path: shared/src/main/java/com/optimizely/ab/android/shared/Cache.java // public class Cache { // // @NonNull private final Context context; // @NonNull private final Logger logger; // // /** // * Create new instance of {@link Cache}. // * // * @param context any {@link Context instance} // * @param logger a {@link Logger} instances // */ // public Cache(@NonNull Context context, @NonNull Logger logger) { // this.context = context; // this.logger = logger; // } // // /** // * Delete the cache file. // * // * @param filename the path to the file // * @return true if the file was deleted or false otherwise // */ // public boolean delete(String filename) { // return context.deleteFile(filename); // } // // /** // * Check if the cache file exists. // * // * @param filename the path to the file // * @return true if the file exists or false otherwise // */ // public boolean exists(String filename) { // String[] files = context.fileList(); // return files != null && Arrays.asList(files).contains(filename); // } // // /** // * Load data from the cache file. // * // * @param filename the path to the file // * @return the loaded cache file as String or null if the file cannot be loaded // */ // @Nullable // public String load(String filename) { // FileInputStream fileInputStream = null; // try { // fileInputStream = context.openFileInput(filename); // InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); // BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // StringBuilder sb = new StringBuilder(); // String line; // while ((line = bufferedReader.readLine()) != null) { // sb.append(line); // } // return sb.toString(); // } catch (Exception e) { // logger.warn("Unable to load file {}.", filename); // return null; // } finally { // try { // if (fileInputStream != null) { // fileInputStream.close(); // } // } catch (Exception e) { // logger.warn("Unable to close file {}.", filename, e); // } // } // } // // /** // * Save data to the cache file and overwrite any existing data. // * // * @param filename the path to the file // * @param data the String data to write to the file // * @return true if the file was saved // */ // public boolean save(String filename, String data) { // FileOutputStream fileOutputStream = null; // try { // fileOutputStream = context.openFileOutput(filename, Context.MODE_PRIVATE); // fileOutputStream.write(data.getBytes()); // return true; // } catch (Exception e) { // logger.error("Error saving file {}.", filename); // return false; // } finally { // if (fileOutputStream != null) { // try { // fileOutputStream.close(); // } catch (Exception e) { // logger.warn("Unable to close file {}.", filename, e); // // } // } // } // } // } // Path: user-profile/src/main/java/com/optimizely/ab/android/user_profile/UserProfileCache.java import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import static com.optimizely.ab.bucketing.UserProfileService.experimentBucketMapKey; import static com.optimizely.ab.bucketing.UserProfileService.userIdKey; import static com.optimizely.ab.bucketing.UserProfileService.variationIdKey; import android.annotation.TargetApi; import android.os.AsyncTask; import android.os.Build; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import com.optimizely.ab.android.shared.Cache; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import java.util.Iterator; logger.info("Saved user profile for {}.", userId); } } /** * Load the cache from disk to memory. */ void start() { // Migrate legacy user profiles if found. migrateLegacyUserProfiles(); try { JSONObject userProfilesJson = diskCache.load(); Map<String, Map<String, Object>> userProfilesMap = UserProfileCacheUtils.convertJSONObjectToMap (userProfilesJson); memoryCache.clear(); memoryCache.putAll(userProfilesMap); logger.info("Loaded user profile cache from disk."); } catch (Exception e) { clear(); logger.error("Unable to parse user profile cache from disk.", e); } } /** * Write-through cache persisted on disk. */ static class DiskCache { private static final String FILE_NAME = "optly-user-profile-service-%s.json";
@NonNull private final Cache cache;
optimizely/android-sdk
datafile-handler/src/test/java/com/optimizely/ab/android/datafile_handler/DefaultDatafileHandlerUnitTest.java
// Path: shared/src/main/java/com/optimizely/ab/android/shared/DatafileConfig.java // public class DatafileConfig { // public static String defaultHost = "https://cdn.optimizely.com"; // public static String projectUrlSuffix = "/json/%s.json"; // public static String environmentUrlSuffix = "/datafiles/%s.json"; // public static String delimiter = "::::"; // // private final String projectId; // private final String sdkKey; // private final String host; // private final String datafileUrlString; // // /** // * Constructor used to construct a DatafileConfig to get cache key, url, // * for the appropriate environment. One or the other can be null. But, not both. // * @param projectId project id string. // * @param sdkKey the environment url. // * @param host used to override the DatafileConfig.defaultHost used for datafile synchronization. // */ // public DatafileConfig(String projectId, String sdkKey, String host) { // assert(projectId != null || sdkKey != null); // this.projectId = projectId; // this.sdkKey = sdkKey; // this.host = host; // // if (sdkKey != null) { // this.datafileUrlString = String.format((this.host + environmentUrlSuffix), sdkKey); // } // else { // this.datafileUrlString = String.format((this.host + projectUrlSuffix), projectId); // } // } // // /** // * Constructor used to construct a DatafileConfig to get cache key, url, // * for the appropriate environment. One or the other can be null. But, not both. // * @param projectId project id string. // * @param sdkKey the environment url. // */ // public DatafileConfig(String projectId, String sdkKey) { // this(projectId, sdkKey, defaultHost); // } // // /** // * This returns the current datafile key string. // * @return datafile key string. // */ // public String getKey() { // return sdkKey != null ? sdkKey : projectId; // } // // /** // * Get the url associated with this project. If there is an environment, // * that url is returned. // * @return url of current project configuration. // */ // public String getUrl() { // return datafileUrlString; // } // // public String toJSONString() { // JSONObject jsonObject = new JSONObject(); // try { // jsonObject.put("projectId", projectId); // jsonObject.put("sdkKey", sdkKey); // return jsonObject.toString(); // } catch (JSONException e) { // e.printStackTrace(); // } // // return null; // } // // public static DatafileConfig fromJSONString(String jsonString) { // try { // JSONObject jsonObject = new JSONObject(jsonString); // String projectId = null; // if (jsonObject.has("projectId")) { // projectId = jsonObject.getString("projectId"); // } // String environmentKey = null; // if (jsonObject.has("sdkKey")) { // environmentKey = jsonObject.getString("sdkKey"); // } // return new DatafileConfig(projectId, environmentKey); // } catch (JSONException e) { // e.printStackTrace(); // } // // return null; // } // /** // * To string either returns the proejct id as string or a concatenated string of project id // * delimiter and environment key. // * @return the string identification for the DatafileConfig // */ // @Override // public String toString() { // return projectId != null ? projectId : "null" + delimiter + (sdkKey != null? sdkKey : "null"); // } // // public boolean equals(Object o) { // if (o == this) { // return true; // } // if (!(o instanceof DatafileConfig)) { // return false; // } // DatafileConfig p = (DatafileConfig) o; // return this.projectId != null ? (p.projectId != null ? this.projectId.equals(p.projectId) : this.projectId == p.projectId) : p.projectId == null // && // this.sdkKey != null ? (p.sdkKey != null ? this.sdkKey.equals(p.sdkKey) : this.sdkKey == p.sdkKey) : p.sdkKey == null; // // } // // public int hashCode() { // int result = 17; // result = 31 * result + (projectId == null ? 0 : projectId.hashCode()) + (sdkKey == null ? 0 : sdkKey.hashCode()); // return result; // } // // }
import android.content.Context; import com.optimizely.ab.android.shared.DatafileConfig; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package com.optimizely.ab.android.datafile_handler; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class DefaultDatafileHandlerUnitTest { DatafileHandler handler = mock(DefaultDatafileHandler.class); @Test public void testHandler() throws Exception { handler = new DefaultDatafileHandler(); Context context = mock(Context.class); when(context.getApplicationContext()).thenReturn(context);
// Path: shared/src/main/java/com/optimizely/ab/android/shared/DatafileConfig.java // public class DatafileConfig { // public static String defaultHost = "https://cdn.optimizely.com"; // public static String projectUrlSuffix = "/json/%s.json"; // public static String environmentUrlSuffix = "/datafiles/%s.json"; // public static String delimiter = "::::"; // // private final String projectId; // private final String sdkKey; // private final String host; // private final String datafileUrlString; // // /** // * Constructor used to construct a DatafileConfig to get cache key, url, // * for the appropriate environment. One or the other can be null. But, not both. // * @param projectId project id string. // * @param sdkKey the environment url. // * @param host used to override the DatafileConfig.defaultHost used for datafile synchronization. // */ // public DatafileConfig(String projectId, String sdkKey, String host) { // assert(projectId != null || sdkKey != null); // this.projectId = projectId; // this.sdkKey = sdkKey; // this.host = host; // // if (sdkKey != null) { // this.datafileUrlString = String.format((this.host + environmentUrlSuffix), sdkKey); // } // else { // this.datafileUrlString = String.format((this.host + projectUrlSuffix), projectId); // } // } // // /** // * Constructor used to construct a DatafileConfig to get cache key, url, // * for the appropriate environment. One or the other can be null. But, not both. // * @param projectId project id string. // * @param sdkKey the environment url. // */ // public DatafileConfig(String projectId, String sdkKey) { // this(projectId, sdkKey, defaultHost); // } // // /** // * This returns the current datafile key string. // * @return datafile key string. // */ // public String getKey() { // return sdkKey != null ? sdkKey : projectId; // } // // /** // * Get the url associated with this project. If there is an environment, // * that url is returned. // * @return url of current project configuration. // */ // public String getUrl() { // return datafileUrlString; // } // // public String toJSONString() { // JSONObject jsonObject = new JSONObject(); // try { // jsonObject.put("projectId", projectId); // jsonObject.put("sdkKey", sdkKey); // return jsonObject.toString(); // } catch (JSONException e) { // e.printStackTrace(); // } // // return null; // } // // public static DatafileConfig fromJSONString(String jsonString) { // try { // JSONObject jsonObject = new JSONObject(jsonString); // String projectId = null; // if (jsonObject.has("projectId")) { // projectId = jsonObject.getString("projectId"); // } // String environmentKey = null; // if (jsonObject.has("sdkKey")) { // environmentKey = jsonObject.getString("sdkKey"); // } // return new DatafileConfig(projectId, environmentKey); // } catch (JSONException e) { // e.printStackTrace(); // } // // return null; // } // /** // * To string either returns the proejct id as string or a concatenated string of project id // * delimiter and environment key. // * @return the string identification for the DatafileConfig // */ // @Override // public String toString() { // return projectId != null ? projectId : "null" + delimiter + (sdkKey != null? sdkKey : "null"); // } // // public boolean equals(Object o) { // if (o == this) { // return true; // } // if (!(o instanceof DatafileConfig)) { // return false; // } // DatafileConfig p = (DatafileConfig) o; // return this.projectId != null ? (p.projectId != null ? this.projectId.equals(p.projectId) : this.projectId == p.projectId) : p.projectId == null // && // this.sdkKey != null ? (p.sdkKey != null ? this.sdkKey.equals(p.sdkKey) : this.sdkKey == p.sdkKey) : p.sdkKey == null; // // } // // public int hashCode() { // int result = 17; // result = 31 * result + (projectId == null ? 0 : projectId.hashCode()) + (sdkKey == null ? 0 : sdkKey.hashCode()); // return result; // } // // } // Path: datafile-handler/src/test/java/com/optimizely/ab/android/datafile_handler/DefaultDatafileHandlerUnitTest.java import android.content.Context; import com.optimizely.ab.android.shared.DatafileConfig; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package com.optimizely.ab.android.datafile_handler; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class DefaultDatafileHandlerUnitTest { DatafileHandler handler = mock(DefaultDatafileHandler.class); @Test public void testHandler() throws Exception { handler = new DefaultDatafileHandler(); Context context = mock(Context.class); when(context.getApplicationContext()).thenReturn(context);
assertFalse(handler.isDatafileSaved(context, new DatafileConfig("1", null)));
optimizely/android-sdk
datafile-handler/src/androidTest/java/com/optimizely/ab/android/datafile_handler/DefaultDatafileHandlerTest.java
// Path: shared/src/main/java/com/optimizely/ab/android/shared/DatafileConfig.java // public class DatafileConfig { // public static String defaultHost = "https://cdn.optimizely.com"; // public static String projectUrlSuffix = "/json/%s.json"; // public static String environmentUrlSuffix = "/datafiles/%s.json"; // public static String delimiter = "::::"; // // private final String projectId; // private final String sdkKey; // private final String host; // private final String datafileUrlString; // // /** // * Constructor used to construct a DatafileConfig to get cache key, url, // * for the appropriate environment. One or the other can be null. But, not both. // * @param projectId project id string. // * @param sdkKey the environment url. // * @param host used to override the DatafileConfig.defaultHost used for datafile synchronization. // */ // public DatafileConfig(String projectId, String sdkKey, String host) { // assert(projectId != null || sdkKey != null); // this.projectId = projectId; // this.sdkKey = sdkKey; // this.host = host; // // if (sdkKey != null) { // this.datafileUrlString = String.format((this.host + environmentUrlSuffix), sdkKey); // } // else { // this.datafileUrlString = String.format((this.host + projectUrlSuffix), projectId); // } // } // // /** // * Constructor used to construct a DatafileConfig to get cache key, url, // * for the appropriate environment. One or the other can be null. But, not both. // * @param projectId project id string. // * @param sdkKey the environment url. // */ // public DatafileConfig(String projectId, String sdkKey) { // this(projectId, sdkKey, defaultHost); // } // // /** // * This returns the current datafile key string. // * @return datafile key string. // */ // public String getKey() { // return sdkKey != null ? sdkKey : projectId; // } // // /** // * Get the url associated with this project. If there is an environment, // * that url is returned. // * @return url of current project configuration. // */ // public String getUrl() { // return datafileUrlString; // } // // public String toJSONString() { // JSONObject jsonObject = new JSONObject(); // try { // jsonObject.put("projectId", projectId); // jsonObject.put("sdkKey", sdkKey); // return jsonObject.toString(); // } catch (JSONException e) { // e.printStackTrace(); // } // // return null; // } // // public static DatafileConfig fromJSONString(String jsonString) { // try { // JSONObject jsonObject = new JSONObject(jsonString); // String projectId = null; // if (jsonObject.has("projectId")) { // projectId = jsonObject.getString("projectId"); // } // String environmentKey = null; // if (jsonObject.has("sdkKey")) { // environmentKey = jsonObject.getString("sdkKey"); // } // return new DatafileConfig(projectId, environmentKey); // } catch (JSONException e) { // e.printStackTrace(); // } // // return null; // } // /** // * To string either returns the proejct id as string or a concatenated string of project id // * delimiter and environment key. // * @return the string identification for the DatafileConfig // */ // @Override // public String toString() { // return projectId != null ? projectId : "null" + delimiter + (sdkKey != null? sdkKey : "null"); // } // // public boolean equals(Object o) { // if (o == this) { // return true; // } // if (!(o instanceof DatafileConfig)) { // return false; // } // DatafileConfig p = (DatafileConfig) o; // return this.projectId != null ? (p.projectId != null ? this.projectId.equals(p.projectId) : this.projectId == p.projectId) : p.projectId == null // && // this.sdkKey != null ? (p.sdkKey != null ? this.sdkKey.equals(p.sdkKey) : this.sdkKey == p.sdkKey) : p.sdkKey == null; // // } // // public int hashCode() { // int result = 17; // result = 31 * result + (projectId == null ? 0 : projectId.hashCode()) + (sdkKey == null ? 0 : sdkKey.hashCode()); // return result; // } // // }
import android.content.Context; import androidx.annotation.Nullable; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; import com.optimizely.ab.android.shared.DatafileConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock;
package com.optimizely.ab.android.datafile_handler; /** * Tests for {@link DefaultDatafileHandler} */ @RunWith(AndroidJUnit4.class) public class DefaultDatafileHandlerTest { DatafileHandler datafileHandler = mock(DefaultDatafileHandler.class); @Before public void setup() { datafileHandler = new DefaultDatafileHandler(); } @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); assertEquals("com.optimizely.ab.android.datafile_handler.test", appContext.getPackageName()); } @Test public void testSaveExistsRemoveWithoutEnvironment() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
// Path: shared/src/main/java/com/optimizely/ab/android/shared/DatafileConfig.java // public class DatafileConfig { // public static String defaultHost = "https://cdn.optimizely.com"; // public static String projectUrlSuffix = "/json/%s.json"; // public static String environmentUrlSuffix = "/datafiles/%s.json"; // public static String delimiter = "::::"; // // private final String projectId; // private final String sdkKey; // private final String host; // private final String datafileUrlString; // // /** // * Constructor used to construct a DatafileConfig to get cache key, url, // * for the appropriate environment. One or the other can be null. But, not both. // * @param projectId project id string. // * @param sdkKey the environment url. // * @param host used to override the DatafileConfig.defaultHost used for datafile synchronization. // */ // public DatafileConfig(String projectId, String sdkKey, String host) { // assert(projectId != null || sdkKey != null); // this.projectId = projectId; // this.sdkKey = sdkKey; // this.host = host; // // if (sdkKey != null) { // this.datafileUrlString = String.format((this.host + environmentUrlSuffix), sdkKey); // } // else { // this.datafileUrlString = String.format((this.host + projectUrlSuffix), projectId); // } // } // // /** // * Constructor used to construct a DatafileConfig to get cache key, url, // * for the appropriate environment. One or the other can be null. But, not both. // * @param projectId project id string. // * @param sdkKey the environment url. // */ // public DatafileConfig(String projectId, String sdkKey) { // this(projectId, sdkKey, defaultHost); // } // // /** // * This returns the current datafile key string. // * @return datafile key string. // */ // public String getKey() { // return sdkKey != null ? sdkKey : projectId; // } // // /** // * Get the url associated with this project. If there is an environment, // * that url is returned. // * @return url of current project configuration. // */ // public String getUrl() { // return datafileUrlString; // } // // public String toJSONString() { // JSONObject jsonObject = new JSONObject(); // try { // jsonObject.put("projectId", projectId); // jsonObject.put("sdkKey", sdkKey); // return jsonObject.toString(); // } catch (JSONException e) { // e.printStackTrace(); // } // // return null; // } // // public static DatafileConfig fromJSONString(String jsonString) { // try { // JSONObject jsonObject = new JSONObject(jsonString); // String projectId = null; // if (jsonObject.has("projectId")) { // projectId = jsonObject.getString("projectId"); // } // String environmentKey = null; // if (jsonObject.has("sdkKey")) { // environmentKey = jsonObject.getString("sdkKey"); // } // return new DatafileConfig(projectId, environmentKey); // } catch (JSONException e) { // e.printStackTrace(); // } // // return null; // } // /** // * To string either returns the proejct id as string or a concatenated string of project id // * delimiter and environment key. // * @return the string identification for the DatafileConfig // */ // @Override // public String toString() { // return projectId != null ? projectId : "null" + delimiter + (sdkKey != null? sdkKey : "null"); // } // // public boolean equals(Object o) { // if (o == this) { // return true; // } // if (!(o instanceof DatafileConfig)) { // return false; // } // DatafileConfig p = (DatafileConfig) o; // return this.projectId != null ? (p.projectId != null ? this.projectId.equals(p.projectId) : this.projectId == p.projectId) : p.projectId == null // && // this.sdkKey != null ? (p.sdkKey != null ? this.sdkKey.equals(p.sdkKey) : this.sdkKey == p.sdkKey) : p.sdkKey == null; // // } // // public int hashCode() { // int result = 17; // result = 31 * result + (projectId == null ? 0 : projectId.hashCode()) + (sdkKey == null ? 0 : sdkKey.hashCode()); // return result; // } // // } // Path: datafile-handler/src/androidTest/java/com/optimizely/ab/android/datafile_handler/DefaultDatafileHandlerTest.java import android.content.Context; import androidx.annotation.Nullable; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; import com.optimizely.ab.android.shared.DatafileConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; package com.optimizely.ab.android.datafile_handler; /** * Tests for {@link DefaultDatafileHandler} */ @RunWith(AndroidJUnit4.class) public class DefaultDatafileHandlerTest { DatafileHandler datafileHandler = mock(DefaultDatafileHandler.class); @Before public void setup() { datafileHandler = new DefaultDatafileHandler(); } @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); assertEquals("com.optimizely.ab.android.datafile_handler.test", appContext.getPackageName()); } @Test public void testSaveExistsRemoveWithoutEnvironment() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
DatafileConfig projectId = new DatafileConfig("1", null);
optimizely/android-sdk
event-handler/src/main/java/com/optimizely/ab/android/event_handler/DefaultEventHandler.java
// Path: shared/src/main/java/com/optimizely/ab/android/shared/WorkerScheduler.java // public class WorkerScheduler { // // when true, work requested only when connection is available. // public static boolean requestOnlyWhenConnected = true; // // /** // * Unschedule a scheduled service for a given worker id // * @param context current application context // * @param workerId work id to cancel // */ // public static void unscheduleService(Context context, String workerId) { // WorkManager.getInstance(context).cancelAllWorkByTag(workerId); // } // // /** // * Schedule a repeated service using the work scheduler from androidx. // * @param context current application context // * @param workerId worker id // * @param clazz class based on ListenableWorker // * @param data androidx.work.Data // * @param interval the interval for the repeated service // * @return An (WorkRequest, Operation) that can be used for tracing work state // */ // public static AbstractMap.SimpleEntry<WorkRequest, Operation> scheduleService(Context context, String workerId, Class clazz, Data data, long interval) { // unscheduleService(context, workerId); // // long minutes = interval < 15 ? 15 : interval; // // WorkRequest.Builder workRequestBuilder = new PeriodicWorkRequest.Builder(clazz, minutes, TimeUnit.MINUTES) // .addTag(workerId) // .setInputData(data) // .setInitialDelay(minutes, TimeUnit.MINUTES); // // if (requestOnlyWhenConnected) { // // requests only when connection is available (to control network connection failures) // Constraints constraints = new Constraints.Builder() // .setRequiredNetworkType(NetworkType.CONNECTED) // .build(); // workRequestBuilder.setConstraints(constraints); // } // // WorkRequest workRequest = workRequestBuilder.build(); // Operation operation = WorkManager.getInstance(context).enqueue(workRequest); // // return new AbstractMap.SimpleEntry<>(workRequest, operation); // } // // /** // * This method should be pulled out to a worker helper class. This method uses the // * WorkManagerRequest // * @param context - application context // * @param workerId - the tag as well as unique identifier // * @param clazz - worker class // * @param data - input data for the worker // * @param retryInterval - the dispatch retry interval in milli-seconds // * @return An (WorkRequest, Operation) that can be used for tracing work state // */ // public static AbstractMap.SimpleEntry<WorkRequest, Operation> startService(Context context, String workerId, Class clazz, Data data, Long retryInterval) { // // Create a WorkRequest for your Worker and sending it input // WorkRequest.Builder workRequestBuilder = new OneTimeWorkRequest.Builder(clazz) // .setInputData(data) // .addTag(workerId); // // if (requestOnlyWhenConnected) { // // requests only when connection is available (to control network connection failures) // Constraints constraints = new Constraints.Builder() // .setRequiredNetworkType(NetworkType.CONNECTED) // .build(); // workRequestBuilder.setConstraints(constraints); // } // // if (retryInterval > 0) { // // NOTE: retry still enabled by default (LINEAR, 30secs) even when setBackoffCriteria is not called. // workRequestBuilder.setBackoffCriteria( // BackoffPolicy.LINEAR, // retryInterval, // TimeUnit.MILLISECONDS); // } // // WorkRequest workRequest = workRequestBuilder.build(); // Operation operation = WorkManager.getInstance(context).enqueue(workRequest); // // return new AbstractMap.SimpleEntry<>(workRequest, operation); // } // // }
import android.content.Context; import androidx.annotation.NonNull; import androidx.work.Data; import com.optimizely.ab.android.shared.WorkerScheduler; import com.optimizely.ab.event.EventHandler; import com.optimizely.ab.event.LogEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
*/ public void setDispatchInterval(long dispatchInterval) { if (dispatchInterval <= 0) { this.dispatchInterval = -1; } else { this.dispatchInterval = dispatchInterval; } } /** * @see EventHandler#dispatchEvent(LogEvent) */ @Override public void dispatchEvent(@NonNull LogEvent logEvent) { if (logEvent.getEndpointUrl() == null) { logger.error("Event dispatcher received a null url"); return; } if (logEvent.getBody() == null) { logger.error("Event dispatcher received a null request body"); return; } if (logEvent.getEndpointUrl().isEmpty()) { logger.error("Event dispatcher received an empty url"); } // NOTE: retryInterval (dispatchInterval) is passed to WorkManager: // - in InputData to enable/disable retries // - in BackOffCriteria to change retry interval Data inputData = EventWorker.getData(logEvent, dispatchInterval);
// Path: shared/src/main/java/com/optimizely/ab/android/shared/WorkerScheduler.java // public class WorkerScheduler { // // when true, work requested only when connection is available. // public static boolean requestOnlyWhenConnected = true; // // /** // * Unschedule a scheduled service for a given worker id // * @param context current application context // * @param workerId work id to cancel // */ // public static void unscheduleService(Context context, String workerId) { // WorkManager.getInstance(context).cancelAllWorkByTag(workerId); // } // // /** // * Schedule a repeated service using the work scheduler from androidx. // * @param context current application context // * @param workerId worker id // * @param clazz class based on ListenableWorker // * @param data androidx.work.Data // * @param interval the interval for the repeated service // * @return An (WorkRequest, Operation) that can be used for tracing work state // */ // public static AbstractMap.SimpleEntry<WorkRequest, Operation> scheduleService(Context context, String workerId, Class clazz, Data data, long interval) { // unscheduleService(context, workerId); // // long minutes = interval < 15 ? 15 : interval; // // WorkRequest.Builder workRequestBuilder = new PeriodicWorkRequest.Builder(clazz, minutes, TimeUnit.MINUTES) // .addTag(workerId) // .setInputData(data) // .setInitialDelay(minutes, TimeUnit.MINUTES); // // if (requestOnlyWhenConnected) { // // requests only when connection is available (to control network connection failures) // Constraints constraints = new Constraints.Builder() // .setRequiredNetworkType(NetworkType.CONNECTED) // .build(); // workRequestBuilder.setConstraints(constraints); // } // // WorkRequest workRequest = workRequestBuilder.build(); // Operation operation = WorkManager.getInstance(context).enqueue(workRequest); // // return new AbstractMap.SimpleEntry<>(workRequest, operation); // } // // /** // * This method should be pulled out to a worker helper class. This method uses the // * WorkManagerRequest // * @param context - application context // * @param workerId - the tag as well as unique identifier // * @param clazz - worker class // * @param data - input data for the worker // * @param retryInterval - the dispatch retry interval in milli-seconds // * @return An (WorkRequest, Operation) that can be used for tracing work state // */ // public static AbstractMap.SimpleEntry<WorkRequest, Operation> startService(Context context, String workerId, Class clazz, Data data, Long retryInterval) { // // Create a WorkRequest for your Worker and sending it input // WorkRequest.Builder workRequestBuilder = new OneTimeWorkRequest.Builder(clazz) // .setInputData(data) // .addTag(workerId); // // if (requestOnlyWhenConnected) { // // requests only when connection is available (to control network connection failures) // Constraints constraints = new Constraints.Builder() // .setRequiredNetworkType(NetworkType.CONNECTED) // .build(); // workRequestBuilder.setConstraints(constraints); // } // // if (retryInterval > 0) { // // NOTE: retry still enabled by default (LINEAR, 30secs) even when setBackoffCriteria is not called. // workRequestBuilder.setBackoffCriteria( // BackoffPolicy.LINEAR, // retryInterval, // TimeUnit.MILLISECONDS); // } // // WorkRequest workRequest = workRequestBuilder.build(); // Operation operation = WorkManager.getInstance(context).enqueue(workRequest); // // return new AbstractMap.SimpleEntry<>(workRequest, operation); // } // // } // Path: event-handler/src/main/java/com/optimizely/ab/android/event_handler/DefaultEventHandler.java import android.content.Context; import androidx.annotation.NonNull; import androidx.work.Data; import com.optimizely.ab.android.shared.WorkerScheduler; import com.optimizely.ab.event.EventHandler; import com.optimizely.ab.event.LogEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; */ public void setDispatchInterval(long dispatchInterval) { if (dispatchInterval <= 0) { this.dispatchInterval = -1; } else { this.dispatchInterval = dispatchInterval; } } /** * @see EventHandler#dispatchEvent(LogEvent) */ @Override public void dispatchEvent(@NonNull LogEvent logEvent) { if (logEvent.getEndpointUrl() == null) { logger.error("Event dispatcher received a null url"); return; } if (logEvent.getBody() == null) { logger.error("Event dispatcher received a null request body"); return; } if (logEvent.getEndpointUrl().isEmpty()) { logger.error("Event dispatcher received an empty url"); } // NOTE: retryInterval (dispatchInterval) is passed to WorkManager: // - in InputData to enable/disable retries // - in BackOffCriteria to change retry interval Data inputData = EventWorker.getData(logEvent, dispatchInterval);
WorkerScheduler.startService(context, EventWorker.workerId, EventWorker.class, inputData, dispatchInterval);
optimizely/android-sdk
user-profile/src/androidTest/java/com/optimizely/ab/android/user_profile/UserProfileCacheTest.java
// Path: shared/src/main/java/com/optimizely/ab/android/shared/Cache.java // public class Cache { // // @NonNull private final Context context; // @NonNull private final Logger logger; // // /** // * Create new instance of {@link Cache}. // * // * @param context any {@link Context instance} // * @param logger a {@link Logger} instances // */ // public Cache(@NonNull Context context, @NonNull Logger logger) { // this.context = context; // this.logger = logger; // } // // /** // * Delete the cache file. // * // * @param filename the path to the file // * @return true if the file was deleted or false otherwise // */ // public boolean delete(String filename) { // return context.deleteFile(filename); // } // // /** // * Check if the cache file exists. // * // * @param filename the path to the file // * @return true if the file exists or false otherwise // */ // public boolean exists(String filename) { // String[] files = context.fileList(); // return files != null && Arrays.asList(files).contains(filename); // } // // /** // * Load data from the cache file. // * // * @param filename the path to the file // * @return the loaded cache file as String or null if the file cannot be loaded // */ // @Nullable // public String load(String filename) { // FileInputStream fileInputStream = null; // try { // fileInputStream = context.openFileInput(filename); // InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); // BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // StringBuilder sb = new StringBuilder(); // String line; // while ((line = bufferedReader.readLine()) != null) { // sb.append(line); // } // return sb.toString(); // } catch (Exception e) { // logger.warn("Unable to load file {}.", filename); // return null; // } finally { // try { // if (fileInputStream != null) { // fileInputStream.close(); // } // } catch (Exception e) { // logger.warn("Unable to close file {}.", filename, e); // } // } // } // // /** // * Save data to the cache file and overwrite any existing data. // * // * @param filename the path to the file // * @param data the String data to write to the file // * @return true if the file was saved // */ // public boolean save(String filename, String data) { // FileOutputStream fileOutputStream = null; // try { // fileOutputStream = context.openFileOutput(filename, Context.MODE_PRIVATE); // fileOutputStream.write(data.getBytes()); // return true; // } catch (Exception e) { // logger.error("Error saving file {}.", filename); // return false; // } finally { // if (fileOutputStream != null) { // try { // fileOutputStream.close(); // } catch (Exception e) { // logger.warn("Unable to close file {}.", filename, e); // // } // } // } // } // }
import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; import com.optimizely.ab.android.shared.Cache; import org.json.JSONException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
/**************************************************************************** * Copyright 2021, Optimizely, Inc. and contributors * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES 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.optimizely.ab.android.user_profile; /** * Tests for {@link UserProfileCache} */ @RunWith(AndroidJUnit4.class) public class UserProfileCacheTest { // Runs tasks serially on the calling thread private ExecutorService executor = Executors.newSingleThreadExecutor(); private Logger logger;
// Path: shared/src/main/java/com/optimizely/ab/android/shared/Cache.java // public class Cache { // // @NonNull private final Context context; // @NonNull private final Logger logger; // // /** // * Create new instance of {@link Cache}. // * // * @param context any {@link Context instance} // * @param logger a {@link Logger} instances // */ // public Cache(@NonNull Context context, @NonNull Logger logger) { // this.context = context; // this.logger = logger; // } // // /** // * Delete the cache file. // * // * @param filename the path to the file // * @return true if the file was deleted or false otherwise // */ // public boolean delete(String filename) { // return context.deleteFile(filename); // } // // /** // * Check if the cache file exists. // * // * @param filename the path to the file // * @return true if the file exists or false otherwise // */ // public boolean exists(String filename) { // String[] files = context.fileList(); // return files != null && Arrays.asList(files).contains(filename); // } // // /** // * Load data from the cache file. // * // * @param filename the path to the file // * @return the loaded cache file as String or null if the file cannot be loaded // */ // @Nullable // public String load(String filename) { // FileInputStream fileInputStream = null; // try { // fileInputStream = context.openFileInput(filename); // InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); // BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // StringBuilder sb = new StringBuilder(); // String line; // while ((line = bufferedReader.readLine()) != null) { // sb.append(line); // } // return sb.toString(); // } catch (Exception e) { // logger.warn("Unable to load file {}.", filename); // return null; // } finally { // try { // if (fileInputStream != null) { // fileInputStream.close(); // } // } catch (Exception e) { // logger.warn("Unable to close file {}.", filename, e); // } // } // } // // /** // * Save data to the cache file and overwrite any existing data. // * // * @param filename the path to the file // * @param data the String data to write to the file // * @return true if the file was saved // */ // public boolean save(String filename, String data) { // FileOutputStream fileOutputStream = null; // try { // fileOutputStream = context.openFileOutput(filename, Context.MODE_PRIVATE); // fileOutputStream.write(data.getBytes()); // return true; // } catch (Exception e) { // logger.error("Error saving file {}.", filename); // return false; // } finally { // if (fileOutputStream != null) { // try { // fileOutputStream.close(); // } catch (Exception e) { // logger.warn("Unable to close file {}.", filename, e); // // } // } // } // } // } // Path: user-profile/src/androidTest/java/com/optimizely/ab/android/user_profile/UserProfileCacheTest.java import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; import com.optimizely.ab.android.shared.Cache; import org.json.JSONException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /**************************************************************************** * Copyright 2021, Optimizely, Inc. and contributors * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES 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.optimizely.ab.android.user_profile; /** * Tests for {@link UserProfileCache} */ @RunWith(AndroidJUnit4.class) public class UserProfileCacheTest { // Runs tasks serially on the calling thread private ExecutorService executor = Executors.newSingleThreadExecutor(); private Logger logger;
private Cache cache;
JoshuaKissoon/DOSNA
src/dosna/dhtAbstraction/DataManager.java
// Path: src/dosna/content/DOSNAContent.java // public abstract class DOSNAContent implements KadContent, ActorRelatedContent, Serializable // { // // public static final String TYPE = "DOSNAContent"; // // public final long createTs; // public long updateTs; // // /* Set of actors related to this content */ // Map<String, String> relatedActors; // // // { // this.createTs = this.updateTs = System.currentTimeMillis() / 1000L; // relatedActors = new HashMap<>(); // } // // public DOSNAContent() // { // // } // // @Override // public long getCreatedTimestamp() // { // return this.createTs; // } // // @Override // public long getLastUpdatedTimestamp() // { // return this.updateTs; // } // // @Override // public byte[] toSerializedForm() // { // Gson gson = new Gson(); // // try ( // // ByteArrayOutputStream bout = new ByteArrayOutputStream(); // // ObjectOutputStream out = new ObjectOutputStream(bout)) // // { // // out.writeObject(this); // // out.close(); // // return bout.toByteArray(); // // } // // catch (IOException ex) // // { // // ex.printStackTrace(); // // } // // return gson.toJson(this).getBytes(); // } // // @Override // public DOSNAContent fromSerializedForm(byte[] data) // { // // try (ByteArrayInputStream bin = new ByteArrayInputStream(data); // // ObjectInputStream oin = new ObjectInputStream(bin)) // // { // // DOSNAContent val = (DOSNAContent) oin.readObject(); // // oin.close(); // // System.out.println("Deserialized: " + val); // // return val; // // } // // catch (IOException | ClassNotFoundException ex) // // { // // ex.printStackTrace(); // // } // Gson gson = new Gson(); // DOSNAContent val = gson.fromJson(new String(data), this.getClass()); // return val; // } // // /** // * When some updates have been made to a content, // * this method can be called to update the lastUpdated timestamp. // */ // public void setUpdated() // { // this.updateTs = System.currentTimeMillis() / 1000L; // } // // /** // * When adding an actor we store the actor's ID and the actor's relationship to this content // */ // @Override // public void addActor(String userId, String relationship) // { // this.relatedActors.put(userId, relationship); // } // // @Override // public void addActor(Actor a, String relationship) // { // addActor(a.getId(), relationship); // } // // @Override // public List<String> getRelatedActors() // { // return new ArrayList<>(this.relatedActors.keySet()); // } // // @Override // public String toString() // { // StringBuilder sb = new StringBuilder(this.getType()); // // sb.append(": "); // // sb.append("[Actors: "); // // for (String a : this.relatedActors.keySet()) // { // sb.append(a); // sb.append("; "); // } // // sb.append("]"); // // return sb.toString(); // } // }
import dosna.content.DOSNAContent; import java.io.IOException; import java.util.NoSuchElementException; import kademlia.JKademliaNode; import kademlia.dht.GetParameter; import kademlia.dht.KademliaStorageEntry; import kademlia.exceptions.ContentNotFoundException; import kademlia.node.KademliaId;
package dosna.dhtAbstraction; /** * An abstraction that handles routing data on the network and storing data. * This class is an abstraction of the DHT and routing protocol for our system. * * @author Joshua Kissoon * @since 20140326 */ public interface DataManager { /** * Put data onto the network. * This will put the data onto the network based on the routing protocol. * It may or may not store data locally. * * @param content The content to be stored on the network * * @return How many nodes was this content stored on * * @throws java.io.IOException */
// Path: src/dosna/content/DOSNAContent.java // public abstract class DOSNAContent implements KadContent, ActorRelatedContent, Serializable // { // // public static final String TYPE = "DOSNAContent"; // // public final long createTs; // public long updateTs; // // /* Set of actors related to this content */ // Map<String, String> relatedActors; // // // { // this.createTs = this.updateTs = System.currentTimeMillis() / 1000L; // relatedActors = new HashMap<>(); // } // // public DOSNAContent() // { // // } // // @Override // public long getCreatedTimestamp() // { // return this.createTs; // } // // @Override // public long getLastUpdatedTimestamp() // { // return this.updateTs; // } // // @Override // public byte[] toSerializedForm() // { // Gson gson = new Gson(); // // try ( // // ByteArrayOutputStream bout = new ByteArrayOutputStream(); // // ObjectOutputStream out = new ObjectOutputStream(bout)) // // { // // out.writeObject(this); // // out.close(); // // return bout.toByteArray(); // // } // // catch (IOException ex) // // { // // ex.printStackTrace(); // // } // // return gson.toJson(this).getBytes(); // } // // @Override // public DOSNAContent fromSerializedForm(byte[] data) // { // // try (ByteArrayInputStream bin = new ByteArrayInputStream(data); // // ObjectInputStream oin = new ObjectInputStream(bin)) // // { // // DOSNAContent val = (DOSNAContent) oin.readObject(); // // oin.close(); // // System.out.println("Deserialized: " + val); // // return val; // // } // // catch (IOException | ClassNotFoundException ex) // // { // // ex.printStackTrace(); // // } // Gson gson = new Gson(); // DOSNAContent val = gson.fromJson(new String(data), this.getClass()); // return val; // } // // /** // * When some updates have been made to a content, // * this method can be called to update the lastUpdated timestamp. // */ // public void setUpdated() // { // this.updateTs = System.currentTimeMillis() / 1000L; // } // // /** // * When adding an actor we store the actor's ID and the actor's relationship to this content // */ // @Override // public void addActor(String userId, String relationship) // { // this.relatedActors.put(userId, relationship); // } // // @Override // public void addActor(Actor a, String relationship) // { // addActor(a.getId(), relationship); // } // // @Override // public List<String> getRelatedActors() // { // return new ArrayList<>(this.relatedActors.keySet()); // } // // @Override // public String toString() // { // StringBuilder sb = new StringBuilder(this.getType()); // // sb.append(": "); // // sb.append("[Actors: "); // // for (String a : this.relatedActors.keySet()) // { // sb.append(a); // sb.append("; "); // } // // sb.append("]"); // // return sb.toString(); // } // } // Path: src/dosna/dhtAbstraction/DataManager.java import dosna.content.DOSNAContent; import java.io.IOException; import java.util.NoSuchElementException; import kademlia.JKademliaNode; import kademlia.dht.GetParameter; import kademlia.dht.KademliaStorageEntry; import kademlia.exceptions.ContentNotFoundException; import kademlia.node.KademliaId; package dosna.dhtAbstraction; /** * An abstraction that handles routing data on the network and storing data. * This class is an abstraction of the DHT and routing protocol for our system. * * @author Joshua Kissoon * @since 20140326 */ public interface DataManager { /** * Put data onto the network. * This will put the data onto the network based on the routing protocol. * It may or may not store data locally. * * @param content The content to be stored on the network * * @return How many nodes was this content stored on * * @throws java.io.IOException */
public int put(final DOSNAContent content) throws IOException;
JoshuaKissoon/DOSNA
src/dosna/core/ContentMetadata.java
// Path: src/dosna/content/DOSNAContent.java // public abstract class DOSNAContent implements KadContent, ActorRelatedContent, Serializable // { // // public static final String TYPE = "DOSNAContent"; // // public final long createTs; // public long updateTs; // // /* Set of actors related to this content */ // Map<String, String> relatedActors; // // // { // this.createTs = this.updateTs = System.currentTimeMillis() / 1000L; // relatedActors = new HashMap<>(); // } // // public DOSNAContent() // { // // } // // @Override // public long getCreatedTimestamp() // { // return this.createTs; // } // // @Override // public long getLastUpdatedTimestamp() // { // return this.updateTs; // } // // @Override // public byte[] toSerializedForm() // { // Gson gson = new Gson(); // // try ( // // ByteArrayOutputStream bout = new ByteArrayOutputStream(); // // ObjectOutputStream out = new ObjectOutputStream(bout)) // // { // // out.writeObject(this); // // out.close(); // // return bout.toByteArray(); // // } // // catch (IOException ex) // // { // // ex.printStackTrace(); // // } // // return gson.toJson(this).getBytes(); // } // // @Override // public DOSNAContent fromSerializedForm(byte[] data) // { // // try (ByteArrayInputStream bin = new ByteArrayInputStream(data); // // ObjectInputStream oin = new ObjectInputStream(bin)) // // { // // DOSNAContent val = (DOSNAContent) oin.readObject(); // // oin.close(); // // System.out.println("Deserialized: " + val); // // return val; // // } // // catch (IOException | ClassNotFoundException ex) // // { // // ex.printStackTrace(); // // } // Gson gson = new Gson(); // DOSNAContent val = gson.fromJson(new String(data), this.getClass()); // return val; // } // // /** // * When some updates have been made to a content, // * this method can be called to update the lastUpdated timestamp. // */ // public void setUpdated() // { // this.updateTs = System.currentTimeMillis() / 1000L; // } // // /** // * When adding an actor we store the actor's ID and the actor's relationship to this content // */ // @Override // public void addActor(String userId, String relationship) // { // this.relatedActors.put(userId, relationship); // } // // @Override // public void addActor(Actor a, String relationship) // { // addActor(a.getId(), relationship); // } // // @Override // public List<String> getRelatedActors() // { // return new ArrayList<>(this.relatedActors.keySet()); // } // // @Override // public String toString() // { // StringBuilder sb = new StringBuilder(this.getType()); // // sb.append(": "); // // sb.append("[Actors: "); // // for (String a : this.relatedActors.keySet()) // { // sb.append(a); // sb.append("; "); // } // // sb.append("]"); // // return sb.toString(); // } // }
import dosna.content.DOSNAContent; import java.io.Serializable; import kademlia.node.KademliaId;
package dosna.core; /** * Class used by the content manager to store metadata of a content. * It will be used to keep track of content in Sorted order by timestamp. * * This class should be kept as small as possible and should never contain the actual content. * * * @author Joshua Kissoon * @since 20140406 */ public final class ContentMetadata implements Comparable<ContentMetadata>, Serializable { private KademliaId key; private long updateTs; private String ownerId; private String type; /** * Blank constructor used mainly by serializers. */ public ContentMetadata() { } /** * Create a new ContentMetadata object for the given content * * @param content */
// Path: src/dosna/content/DOSNAContent.java // public abstract class DOSNAContent implements KadContent, ActorRelatedContent, Serializable // { // // public static final String TYPE = "DOSNAContent"; // // public final long createTs; // public long updateTs; // // /* Set of actors related to this content */ // Map<String, String> relatedActors; // // // { // this.createTs = this.updateTs = System.currentTimeMillis() / 1000L; // relatedActors = new HashMap<>(); // } // // public DOSNAContent() // { // // } // // @Override // public long getCreatedTimestamp() // { // return this.createTs; // } // // @Override // public long getLastUpdatedTimestamp() // { // return this.updateTs; // } // // @Override // public byte[] toSerializedForm() // { // Gson gson = new Gson(); // // try ( // // ByteArrayOutputStream bout = new ByteArrayOutputStream(); // // ObjectOutputStream out = new ObjectOutputStream(bout)) // // { // // out.writeObject(this); // // out.close(); // // return bout.toByteArray(); // // } // // catch (IOException ex) // // { // // ex.printStackTrace(); // // } // // return gson.toJson(this).getBytes(); // } // // @Override // public DOSNAContent fromSerializedForm(byte[] data) // { // // try (ByteArrayInputStream bin = new ByteArrayInputStream(data); // // ObjectInputStream oin = new ObjectInputStream(bin)) // // { // // DOSNAContent val = (DOSNAContent) oin.readObject(); // // oin.close(); // // System.out.println("Deserialized: " + val); // // return val; // // } // // catch (IOException | ClassNotFoundException ex) // // { // // ex.printStackTrace(); // // } // Gson gson = new Gson(); // DOSNAContent val = gson.fromJson(new String(data), this.getClass()); // return val; // } // // /** // * When some updates have been made to a content, // * this method can be called to update the lastUpdated timestamp. // */ // public void setUpdated() // { // this.updateTs = System.currentTimeMillis() / 1000L; // } // // /** // * When adding an actor we store the actor's ID and the actor's relationship to this content // */ // @Override // public void addActor(String userId, String relationship) // { // this.relatedActors.put(userId, relationship); // } // // @Override // public void addActor(Actor a, String relationship) // { // addActor(a.getId(), relationship); // } // // @Override // public List<String> getRelatedActors() // { // return new ArrayList<>(this.relatedActors.keySet()); // } // // @Override // public String toString() // { // StringBuilder sb = new StringBuilder(this.getType()); // // sb.append(": "); // // sb.append("[Actors: "); // // for (String a : this.relatedActors.keySet()) // { // sb.append(a); // sb.append("; "); // } // // sb.append("]"); // // return sb.toString(); // } // } // Path: src/dosna/core/ContentMetadata.java import dosna.content.DOSNAContent; import java.io.Serializable; import kademlia.node.KademliaId; package dosna.core; /** * Class used by the content manager to store metadata of a content. * It will be used to keep track of content in Sorted order by timestamp. * * This class should be kept as small as possible and should never contain the actual content. * * * @author Joshua Kissoon * @since 20140406 */ public final class ContentMetadata implements Comparable<ContentMetadata>, Serializable { private KademliaId key; private long updateTs; private String ownerId; private String type; /** * Blank constructor used mainly by serializers. */ public ContentMetadata() { } /** * Create a new ContentMetadata object for the given content * * @param content */
public ContentMetadata(final DOSNAContent content)
JoshuaKissoon/DOSNA
src/dosna/dhtAbstraction/DosnaDataManager.java
// Path: src/dosna/content/DOSNAContent.java // public abstract class DOSNAContent implements KadContent, ActorRelatedContent, Serializable // { // // public static final String TYPE = "DOSNAContent"; // // public final long createTs; // public long updateTs; // // /* Set of actors related to this content */ // Map<String, String> relatedActors; // // // { // this.createTs = this.updateTs = System.currentTimeMillis() / 1000L; // relatedActors = new HashMap<>(); // } // // public DOSNAContent() // { // // } // // @Override // public long getCreatedTimestamp() // { // return this.createTs; // } // // @Override // public long getLastUpdatedTimestamp() // { // return this.updateTs; // } // // @Override // public byte[] toSerializedForm() // { // Gson gson = new Gson(); // // try ( // // ByteArrayOutputStream bout = new ByteArrayOutputStream(); // // ObjectOutputStream out = new ObjectOutputStream(bout)) // // { // // out.writeObject(this); // // out.close(); // // return bout.toByteArray(); // // } // // catch (IOException ex) // // { // // ex.printStackTrace(); // // } // // return gson.toJson(this).getBytes(); // } // // @Override // public DOSNAContent fromSerializedForm(byte[] data) // { // // try (ByteArrayInputStream bin = new ByteArrayInputStream(data); // // ObjectInputStream oin = new ObjectInputStream(bin)) // // { // // DOSNAContent val = (DOSNAContent) oin.readObject(); // // oin.close(); // // System.out.println("Deserialized: " + val); // // return val; // // } // // catch (IOException | ClassNotFoundException ex) // // { // // ex.printStackTrace(); // // } // Gson gson = new Gson(); // DOSNAContent val = gson.fromJson(new String(data), this.getClass()); // return val; // } // // /** // * When some updates have been made to a content, // * this method can be called to update the lastUpdated timestamp. // */ // public void setUpdated() // { // this.updateTs = System.currentTimeMillis() / 1000L; // } // // /** // * When adding an actor we store the actor's ID and the actor's relationship to this content // */ // @Override // public void addActor(String userId, String relationship) // { // this.relatedActors.put(userId, relationship); // } // // @Override // public void addActor(Actor a, String relationship) // { // addActor(a.getId(), relationship); // } // // @Override // public List<String> getRelatedActors() // { // return new ArrayList<>(this.relatedActors.keySet()); // } // // @Override // public String toString() // { // StringBuilder sb = new StringBuilder(this.getType()); // // sb.append(": "); // // sb.append("[Actors: "); // // for (String a : this.relatedActors.keySet()) // { // sb.append(a); // sb.append("; "); // } // // sb.append("]"); // // return sb.toString(); // } // } // // Path: src/dosna/DOSNAConfig.java // public class DOSNAConfig // { // // /** // * @return The Kademlia node that serves as the bootstrap node for the network // * // * @throws java.net.UnknownHostException // */ // public Node getBootstrapNode() throws UnknownHostException // { // return new Node(new KademliaId("BOOTSTRAPBOOTSTRAPBO"), InetAddress.getLocalHost(), 15049); // } // }
import dosna.content.DOSNAContent; import dosna.DOSNAConfig; import java.io.IOException; import java.net.UnknownHostException; import java.util.NoSuchElementException; import kademlia.dht.GetParameter; import kademlia.JKademliaNode; import kademlia.dht.KademliaStorageEntry; import kademlia.exceptions.ContentNotFoundException; import kademlia.node.KademliaId;
package dosna.dhtAbstraction; /** * An implementation of the DataManager for this Application. * We use the Kademlia routing protocol here. * * @author Joshua Kissoon * @since 20140326 */ public final class DosnaDataManager implements DataManager { /** * The Kademlia instance to be used. * We use composition rather than inheritance. */ private final JKademliaNode kad; /** * Initialize Kademlia * * @param ownerId * @param nodeId The NodeId to be used for this Kademlia instance * @param port * * @throws java.io.IOException * @throws java.net.UnknownHostException * @todo Try loading data from file, if no file exist, then create a new Kademlia instance */ public DosnaDataManager(final String ownerId, final KademliaId nodeId, final int port) throws IOException, UnknownHostException { kad = new JKademliaNode(ownerId, nodeId, port);
// Path: src/dosna/content/DOSNAContent.java // public abstract class DOSNAContent implements KadContent, ActorRelatedContent, Serializable // { // // public static final String TYPE = "DOSNAContent"; // // public final long createTs; // public long updateTs; // // /* Set of actors related to this content */ // Map<String, String> relatedActors; // // // { // this.createTs = this.updateTs = System.currentTimeMillis() / 1000L; // relatedActors = new HashMap<>(); // } // // public DOSNAContent() // { // // } // // @Override // public long getCreatedTimestamp() // { // return this.createTs; // } // // @Override // public long getLastUpdatedTimestamp() // { // return this.updateTs; // } // // @Override // public byte[] toSerializedForm() // { // Gson gson = new Gson(); // // try ( // // ByteArrayOutputStream bout = new ByteArrayOutputStream(); // // ObjectOutputStream out = new ObjectOutputStream(bout)) // // { // // out.writeObject(this); // // out.close(); // // return bout.toByteArray(); // // } // // catch (IOException ex) // // { // // ex.printStackTrace(); // // } // // return gson.toJson(this).getBytes(); // } // // @Override // public DOSNAContent fromSerializedForm(byte[] data) // { // // try (ByteArrayInputStream bin = new ByteArrayInputStream(data); // // ObjectInputStream oin = new ObjectInputStream(bin)) // // { // // DOSNAContent val = (DOSNAContent) oin.readObject(); // // oin.close(); // // System.out.println("Deserialized: " + val); // // return val; // // } // // catch (IOException | ClassNotFoundException ex) // // { // // ex.printStackTrace(); // // } // Gson gson = new Gson(); // DOSNAContent val = gson.fromJson(new String(data), this.getClass()); // return val; // } // // /** // * When some updates have been made to a content, // * this method can be called to update the lastUpdated timestamp. // */ // public void setUpdated() // { // this.updateTs = System.currentTimeMillis() / 1000L; // } // // /** // * When adding an actor we store the actor's ID and the actor's relationship to this content // */ // @Override // public void addActor(String userId, String relationship) // { // this.relatedActors.put(userId, relationship); // } // // @Override // public void addActor(Actor a, String relationship) // { // addActor(a.getId(), relationship); // } // // @Override // public List<String> getRelatedActors() // { // return new ArrayList<>(this.relatedActors.keySet()); // } // // @Override // public String toString() // { // StringBuilder sb = new StringBuilder(this.getType()); // // sb.append(": "); // // sb.append("[Actors: "); // // for (String a : this.relatedActors.keySet()) // { // sb.append(a); // sb.append("; "); // } // // sb.append("]"); // // return sb.toString(); // } // } // // Path: src/dosna/DOSNAConfig.java // public class DOSNAConfig // { // // /** // * @return The Kademlia node that serves as the bootstrap node for the network // * // * @throws java.net.UnknownHostException // */ // public Node getBootstrapNode() throws UnknownHostException // { // return new Node(new KademliaId("BOOTSTRAPBOOTSTRAPBO"), InetAddress.getLocalHost(), 15049); // } // } // Path: src/dosna/dhtAbstraction/DosnaDataManager.java import dosna.content.DOSNAContent; import dosna.DOSNAConfig; import java.io.IOException; import java.net.UnknownHostException; import java.util.NoSuchElementException; import kademlia.dht.GetParameter; import kademlia.JKademliaNode; import kademlia.dht.KademliaStorageEntry; import kademlia.exceptions.ContentNotFoundException; import kademlia.node.KademliaId; package dosna.dhtAbstraction; /** * An implementation of the DataManager for this Application. * We use the Kademlia routing protocol here. * * @author Joshua Kissoon * @since 20140326 */ public final class DosnaDataManager implements DataManager { /** * The Kademlia instance to be used. * We use composition rather than inheritance. */ private final JKademliaNode kad; /** * Initialize Kademlia * * @param ownerId * @param nodeId The NodeId to be used for this Kademlia instance * @param port * * @throws java.io.IOException * @throws java.net.UnknownHostException * @todo Try loading data from file, if no file exist, then create a new Kademlia instance */ public DosnaDataManager(final String ownerId, final KademliaId nodeId, final int port) throws IOException, UnknownHostException { kad = new JKademliaNode(ownerId, nodeId, port);
kad.bootstrap(new DOSNAConfig().getBootstrapNode());
JoshuaKissoon/DOSNA
src/dosna/dhtAbstraction/DosnaDataManager.java
// Path: src/dosna/content/DOSNAContent.java // public abstract class DOSNAContent implements KadContent, ActorRelatedContent, Serializable // { // // public static final String TYPE = "DOSNAContent"; // // public final long createTs; // public long updateTs; // // /* Set of actors related to this content */ // Map<String, String> relatedActors; // // // { // this.createTs = this.updateTs = System.currentTimeMillis() / 1000L; // relatedActors = new HashMap<>(); // } // // public DOSNAContent() // { // // } // // @Override // public long getCreatedTimestamp() // { // return this.createTs; // } // // @Override // public long getLastUpdatedTimestamp() // { // return this.updateTs; // } // // @Override // public byte[] toSerializedForm() // { // Gson gson = new Gson(); // // try ( // // ByteArrayOutputStream bout = new ByteArrayOutputStream(); // // ObjectOutputStream out = new ObjectOutputStream(bout)) // // { // // out.writeObject(this); // // out.close(); // // return bout.toByteArray(); // // } // // catch (IOException ex) // // { // // ex.printStackTrace(); // // } // // return gson.toJson(this).getBytes(); // } // // @Override // public DOSNAContent fromSerializedForm(byte[] data) // { // // try (ByteArrayInputStream bin = new ByteArrayInputStream(data); // // ObjectInputStream oin = new ObjectInputStream(bin)) // // { // // DOSNAContent val = (DOSNAContent) oin.readObject(); // // oin.close(); // // System.out.println("Deserialized: " + val); // // return val; // // } // // catch (IOException | ClassNotFoundException ex) // // { // // ex.printStackTrace(); // // } // Gson gson = new Gson(); // DOSNAContent val = gson.fromJson(new String(data), this.getClass()); // return val; // } // // /** // * When some updates have been made to a content, // * this method can be called to update the lastUpdated timestamp. // */ // public void setUpdated() // { // this.updateTs = System.currentTimeMillis() / 1000L; // } // // /** // * When adding an actor we store the actor's ID and the actor's relationship to this content // */ // @Override // public void addActor(String userId, String relationship) // { // this.relatedActors.put(userId, relationship); // } // // @Override // public void addActor(Actor a, String relationship) // { // addActor(a.getId(), relationship); // } // // @Override // public List<String> getRelatedActors() // { // return new ArrayList<>(this.relatedActors.keySet()); // } // // @Override // public String toString() // { // StringBuilder sb = new StringBuilder(this.getType()); // // sb.append(": "); // // sb.append("[Actors: "); // // for (String a : this.relatedActors.keySet()) // { // sb.append(a); // sb.append("; "); // } // // sb.append("]"); // // return sb.toString(); // } // } // // Path: src/dosna/DOSNAConfig.java // public class DOSNAConfig // { // // /** // * @return The Kademlia node that serves as the bootstrap node for the network // * // * @throws java.net.UnknownHostException // */ // public Node getBootstrapNode() throws UnknownHostException // { // return new Node(new KademliaId("BOOTSTRAPBOOTSTRAPBO"), InetAddress.getLocalHost(), 15049); // } // }
import dosna.content.DOSNAContent; import dosna.DOSNAConfig; import java.io.IOException; import java.net.UnknownHostException; import java.util.NoSuchElementException; import kademlia.dht.GetParameter; import kademlia.JKademliaNode; import kademlia.dht.KademliaStorageEntry; import kademlia.exceptions.ContentNotFoundException; import kademlia.node.KademliaId;
package dosna.dhtAbstraction; /** * An implementation of the DataManager for this Application. * We use the Kademlia routing protocol here. * * @author Joshua Kissoon * @since 20140326 */ public final class DosnaDataManager implements DataManager { /** * The Kademlia instance to be used. * We use composition rather than inheritance. */ private final JKademliaNode kad; /** * Initialize Kademlia * * @param ownerId * @param nodeId The NodeId to be used for this Kademlia instance * @param port * * @throws java.io.IOException * @throws java.net.UnknownHostException * @todo Try loading data from file, if no file exist, then create a new Kademlia instance */ public DosnaDataManager(final String ownerId, final KademliaId nodeId, final int port) throws IOException, UnknownHostException { kad = new JKademliaNode(ownerId, nodeId, port); kad.bootstrap(new DOSNAConfig().getBootstrapNode()); } /** * Initialize Kademlia with a random port number * * @param ownerId * @param nodeId * * @throws java.io.IOException */ public DosnaDataManager(final String ownerId, final KademliaId nodeId) throws IOException { this(ownerId, nodeId, (int) ((Math.random() * 20000) + 5000)); } /** * Put data onto the network. * This will put the data onto the network based on the routing protocol. * It may or may not store data locally. */ @Override
// Path: src/dosna/content/DOSNAContent.java // public abstract class DOSNAContent implements KadContent, ActorRelatedContent, Serializable // { // // public static final String TYPE = "DOSNAContent"; // // public final long createTs; // public long updateTs; // // /* Set of actors related to this content */ // Map<String, String> relatedActors; // // // { // this.createTs = this.updateTs = System.currentTimeMillis() / 1000L; // relatedActors = new HashMap<>(); // } // // public DOSNAContent() // { // // } // // @Override // public long getCreatedTimestamp() // { // return this.createTs; // } // // @Override // public long getLastUpdatedTimestamp() // { // return this.updateTs; // } // // @Override // public byte[] toSerializedForm() // { // Gson gson = new Gson(); // // try ( // // ByteArrayOutputStream bout = new ByteArrayOutputStream(); // // ObjectOutputStream out = new ObjectOutputStream(bout)) // // { // // out.writeObject(this); // // out.close(); // // return bout.toByteArray(); // // } // // catch (IOException ex) // // { // // ex.printStackTrace(); // // } // // return gson.toJson(this).getBytes(); // } // // @Override // public DOSNAContent fromSerializedForm(byte[] data) // { // // try (ByteArrayInputStream bin = new ByteArrayInputStream(data); // // ObjectInputStream oin = new ObjectInputStream(bin)) // // { // // DOSNAContent val = (DOSNAContent) oin.readObject(); // // oin.close(); // // System.out.println("Deserialized: " + val); // // return val; // // } // // catch (IOException | ClassNotFoundException ex) // // { // // ex.printStackTrace(); // // } // Gson gson = new Gson(); // DOSNAContent val = gson.fromJson(new String(data), this.getClass()); // return val; // } // // /** // * When some updates have been made to a content, // * this method can be called to update the lastUpdated timestamp. // */ // public void setUpdated() // { // this.updateTs = System.currentTimeMillis() / 1000L; // } // // /** // * When adding an actor we store the actor's ID and the actor's relationship to this content // */ // @Override // public void addActor(String userId, String relationship) // { // this.relatedActors.put(userId, relationship); // } // // @Override // public void addActor(Actor a, String relationship) // { // addActor(a.getId(), relationship); // } // // @Override // public List<String> getRelatedActors() // { // return new ArrayList<>(this.relatedActors.keySet()); // } // // @Override // public String toString() // { // StringBuilder sb = new StringBuilder(this.getType()); // // sb.append(": "); // // sb.append("[Actors: "); // // for (String a : this.relatedActors.keySet()) // { // sb.append(a); // sb.append("; "); // } // // sb.append("]"); // // return sb.toString(); // } // } // // Path: src/dosna/DOSNAConfig.java // public class DOSNAConfig // { // // /** // * @return The Kademlia node that serves as the bootstrap node for the network // * // * @throws java.net.UnknownHostException // */ // public Node getBootstrapNode() throws UnknownHostException // { // return new Node(new KademliaId("BOOTSTRAPBOOTSTRAPBO"), InetAddress.getLocalHost(), 15049); // } // } // Path: src/dosna/dhtAbstraction/DosnaDataManager.java import dosna.content.DOSNAContent; import dosna.DOSNAConfig; import java.io.IOException; import java.net.UnknownHostException; import java.util.NoSuchElementException; import kademlia.dht.GetParameter; import kademlia.JKademliaNode; import kademlia.dht.KademliaStorageEntry; import kademlia.exceptions.ContentNotFoundException; import kademlia.node.KademliaId; package dosna.dhtAbstraction; /** * An implementation of the DataManager for this Application. * We use the Kademlia routing protocol here. * * @author Joshua Kissoon * @since 20140326 */ public final class DosnaDataManager implements DataManager { /** * The Kademlia instance to be used. * We use composition rather than inheritance. */ private final JKademliaNode kad; /** * Initialize Kademlia * * @param ownerId * @param nodeId The NodeId to be used for this Kademlia instance * @param port * * @throws java.io.IOException * @throws java.net.UnknownHostException * @todo Try loading data from file, if no file exist, then create a new Kademlia instance */ public DosnaDataManager(final String ownerId, final KademliaId nodeId, final int port) throws IOException, UnknownHostException { kad = new JKademliaNode(ownerId, nodeId, port); kad.bootstrap(new DOSNAConfig().getBootstrapNode()); } /** * Initialize Kademlia with a random port number * * @param ownerId * @param nodeId * * @throws java.io.IOException */ public DosnaDataManager(final String ownerId, final KademliaId nodeId) throws IOException { this(ownerId, nodeId, (int) ((Math.random() * 20000) + 5000)); } /** * Put data onto the network. * This will put the data onto the network based on the routing protocol. * It may or may not store data locally. */ @Override
public synchronized int put(final DOSNAContent content) throws IOException
JoshuaKissoon/DOSNA
src/dosna/osn/activitystream/ActivityStreamContentSelector.java
// Path: src/dosna/core/ContentMetadata.java // public final class ContentMetadata implements Comparable<ContentMetadata>, Serializable // { // // private KademliaId key; // private long updateTs; // private String ownerId; // private String type; // // /** // * Blank constructor used mainly by serializers. // */ // public ContentMetadata() // { // // } // // /** // * Create a new ContentMetadata object for the given content // * // * @param content // */ // public ContentMetadata(final DOSNAContent content) // { // this.key = content.getKey(); // this.updateTs = content.getLastUpdatedTimestamp(); // this.ownerId = content.getOwnerId(); // this.type = content.getType(); // } // // public KademliaId getKey() // { // return this.key; // } // // public long getLastUpdatedTimestamp() // { // return this.updateTs; // } // // public String getOwnerId() // { // return this.ownerId; // } // // public String getType() // { // return this.type; // } // // /** // * We compare content Metadata based on timestamp // */ // @Override // public int compareTo(final ContentMetadata o) // { // if (this.getKey().equals(o.getKey())) // { // return 0; // } // // return this.getLastUpdatedTimestamp() > o.getLastUpdatedTimestamp() ? 1 : -1; // } // // @Override // public String toString() // { // StringBuilder sb = new StringBuilder("ContentMetadata: "); // // sb.append("[Type: "); // sb.append(this.getType()); // sb.append("]"); // // sb.append("[Owner: "); // sb.append(this.getOwnerId()); // sb.append("]"); // // sb.append(""); // // return sb.toString(); // } // }
import dosna.core.ContentMetadata; import java.util.ArrayList; import java.util.Collection; import java.util.TreeSet;
package dosna.osn.activitystream; /** * An algorithm that selects which content to display on the user's home stream * * @author Joshua Kissoon * @since 20140505 */ public class ActivityStreamContentSelector { private final static int NUM_CONTENT_ON_HOME_STREAM = 35;
// Path: src/dosna/core/ContentMetadata.java // public final class ContentMetadata implements Comparable<ContentMetadata>, Serializable // { // // private KademliaId key; // private long updateTs; // private String ownerId; // private String type; // // /** // * Blank constructor used mainly by serializers. // */ // public ContentMetadata() // { // // } // // /** // * Create a new ContentMetadata object for the given content // * // * @param content // */ // public ContentMetadata(final DOSNAContent content) // { // this.key = content.getKey(); // this.updateTs = content.getLastUpdatedTimestamp(); // this.ownerId = content.getOwnerId(); // this.type = content.getType(); // } // // public KademliaId getKey() // { // return this.key; // } // // public long getLastUpdatedTimestamp() // { // return this.updateTs; // } // // public String getOwnerId() // { // return this.ownerId; // } // // public String getType() // { // return this.type; // } // // /** // * We compare content Metadata based on timestamp // */ // @Override // public int compareTo(final ContentMetadata o) // { // if (this.getKey().equals(o.getKey())) // { // return 0; // } // // return this.getLastUpdatedTimestamp() > o.getLastUpdatedTimestamp() ? 1 : -1; // } // // @Override // public String toString() // { // StringBuilder sb = new StringBuilder("ContentMetadata: "); // // sb.append("[Type: "); // sb.append(this.getType()); // sb.append("]"); // // sb.append("[Owner: "); // sb.append(this.getOwnerId()); // sb.append("]"); // // sb.append(""); // // return sb.toString(); // } // } // Path: src/dosna/osn/activitystream/ActivityStreamContentSelector.java import dosna.core.ContentMetadata; import java.util.ArrayList; import java.util.Collection; import java.util.TreeSet; package dosna.osn.activitystream; /** * An algorithm that selects which content to display on the user's home stream * * @author Joshua Kissoon * @since 20140505 */ public class ActivityStreamContentSelector { private final static int NUM_CONTENT_ON_HOME_STREAM = 35;
public TreeSet<ContentMetadata> contentMD;
JoshuaKissoon/DOSNA
src/dosna/osn/actor/ActorConnectionsManager.java
// Path: src/dosna/dhtAbstraction/DataManager.java // public interface DataManager // { // // /** // * Put data onto the network. // * This will put the data onto the network based on the routing protocol. // * It may or may not store data locally. // * // * @param content The content to be stored on the network // * // * @return How many nodes was this content stored on // * // * @throws java.io.IOException // */ // public int put(final DOSNAContent content) throws IOException; // // /** // * Get entries for the required data from the network // * // * @param gp // * // * @return A single data entry // * // * @throws java.io.IOException // * @throws kademlia.exceptions.ContentNotFoundException // */ // public KademliaStorageEntry get(final GetParameter gp) throws IOException, NoSuchElementException, ContentNotFoundException; // // /** // * Get entries for the required data from the network // * // * @param key // * @param type // * // * @return A single data entry // * // * @throws java.io.IOException // * @throws kademlia.exceptions.ContentNotFoundException // */ // public KademliaStorageEntry get(final KademliaId key, final String type) throws IOException, NoSuchElementException, ContentNotFoundException; // // /** // * Get entries for the required data from the network // * // * @param key // * @param type // * @param ownerId // * // * @return A single data entry // * // * @throws java.io.IOException // * @throws kademlia.exceptions.ContentNotFoundException // */ // public KademliaStorageEntry get(final KademliaId key, final String type, final String ownerId) throws IOException, NoSuchElementException, ContentNotFoundException; // // /** // * Run an update call to update the data stored locally on this computer. // * This may involve deleting some data and adding some other data. // */ // public void updateStorage(); // // /** // * Save the state of the DataManager and shutdown // * // * @param saveState Whether to save the state of the application or not // * // * @throws java.io.IOException // */ // public void shutdown(final boolean saveState) throws IOException; // // /** // * @return The JKademliaNode used by this DataManager // */ // public JKademliaNode getKademliaNode(); // }
import dosna.dhtAbstraction.DataManager; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.TreeSet; import kademlia.exceptions.ContentNotFoundException;
* @return Whether the connection exist */ public boolean hasConnection(final Actor conn) { for (Relationship r : this.connections) { if (r.getConnectionUid().equals(conn.getId())) { return true; } } return false; } /** * @return The set of all relationships that this actor has */ public Collection<Relationship> getRelationships() { return this.connections; } /** * Here we load all Actors that are connected with this actor. * * @param dataManager DataManager to be used to load the connections * * @return The set of Actors connected to this actor */
// Path: src/dosna/dhtAbstraction/DataManager.java // public interface DataManager // { // // /** // * Put data onto the network. // * This will put the data onto the network based on the routing protocol. // * It may or may not store data locally. // * // * @param content The content to be stored on the network // * // * @return How many nodes was this content stored on // * // * @throws java.io.IOException // */ // public int put(final DOSNAContent content) throws IOException; // // /** // * Get entries for the required data from the network // * // * @param gp // * // * @return A single data entry // * // * @throws java.io.IOException // * @throws kademlia.exceptions.ContentNotFoundException // */ // public KademliaStorageEntry get(final GetParameter gp) throws IOException, NoSuchElementException, ContentNotFoundException; // // /** // * Get entries for the required data from the network // * // * @param key // * @param type // * // * @return A single data entry // * // * @throws java.io.IOException // * @throws kademlia.exceptions.ContentNotFoundException // */ // public KademliaStorageEntry get(final KademliaId key, final String type) throws IOException, NoSuchElementException, ContentNotFoundException; // // /** // * Get entries for the required data from the network // * // * @param key // * @param type // * @param ownerId // * // * @return A single data entry // * // * @throws java.io.IOException // * @throws kademlia.exceptions.ContentNotFoundException // */ // public KademliaStorageEntry get(final KademliaId key, final String type, final String ownerId) throws IOException, NoSuchElementException, ContentNotFoundException; // // /** // * Run an update call to update the data stored locally on this computer. // * This may involve deleting some data and adding some other data. // */ // public void updateStorage(); // // /** // * Save the state of the DataManager and shutdown // * // * @param saveState Whether to save the state of the application or not // * // * @throws java.io.IOException // */ // public void shutdown(final boolean saveState) throws IOException; // // /** // * @return The JKademliaNode used by this DataManager // */ // public JKademliaNode getKademliaNode(); // } // Path: src/dosna/osn/actor/ActorConnectionsManager.java import dosna.dhtAbstraction.DataManager; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.TreeSet; import kademlia.exceptions.ContentNotFoundException; * @return Whether the connection exist */ public boolean hasConnection(final Actor conn) { for (Relationship r : this.connections) { if (r.getConnectionUid().equals(conn.getId())) { return true; } } return false; } /** * @return The set of all relationships that this actor has */ public Collection<Relationship> getRelationships() { return this.connections; } /** * Here we load all Actors that are connected with this actor. * * @param dataManager DataManager to be used to load the connections * * @return The set of Actors connected to this actor */
public Collection<Actor> loadConnections(final DataManager dataManager)
JoshuaKissoon/DOSNA
src/dosna/osn/actor/ActorManager.java
// Path: src/dosna/dhtAbstraction/DataManager.java // public interface DataManager // { // // /** // * Put data onto the network. // * This will put the data onto the network based on the routing protocol. // * It may or may not store data locally. // * // * @param content The content to be stored on the network // * // * @return How many nodes was this content stored on // * // * @throws java.io.IOException // */ // public int put(final DOSNAContent content) throws IOException; // // /** // * Get entries for the required data from the network // * // * @param gp // * // * @return A single data entry // * // * @throws java.io.IOException // * @throws kademlia.exceptions.ContentNotFoundException // */ // public KademliaStorageEntry get(final GetParameter gp) throws IOException, NoSuchElementException, ContentNotFoundException; // // /** // * Get entries for the required data from the network // * // * @param key // * @param type // * // * @return A single data entry // * // * @throws java.io.IOException // * @throws kademlia.exceptions.ContentNotFoundException // */ // public KademliaStorageEntry get(final KademliaId key, final String type) throws IOException, NoSuchElementException, ContentNotFoundException; // // /** // * Get entries for the required data from the network // * // * @param key // * @param type // * @param ownerId // * // * @return A single data entry // * // * @throws java.io.IOException // * @throws kademlia.exceptions.ContentNotFoundException // */ // public KademliaStorageEntry get(final KademliaId key, final String type, final String ownerId) throws IOException, NoSuchElementException, ContentNotFoundException; // // /** // * Run an update call to update the data stored locally on this computer. // * This may involve deleting some data and adding some other data. // */ // public void updateStorage(); // // /** // * Save the state of the DataManager and shutdown // * // * @param saveState Whether to save the state of the application or not // * // * @throws java.io.IOException // */ // public void shutdown(final boolean saveState) throws IOException; // // /** // * @return The JKademliaNode used by this DataManager // */ // public JKademliaNode getKademliaNode(); // } // // Path: src/dosna/notification/NotificationBox.java // public class NotificationBox extends DOSNAContent // { // // public final static String TYPE = "NotificationBox"; // // private List<Notification> notifications; // private String ownerId; // // private KademliaId key; // // // { // notifications = new ArrayList<>(); // } // // public NotificationBox() // { // // } // // /** // * Setup the Notification Box // * // * @param owner The owner of this notification box // */ // public NotificationBox(final Actor owner) // { // this(owner.getId()); // } // // /** // * Setup the Notification Box // * // * @param ownerId The ID of the owner of this notification box // */ // public NotificationBox(final String ownerId) // { // this.ownerId = ownerId; // this.generateNodeId(); // } // // private void generateNodeId() // { // byte[] keyData = null; // try // { // keyData = HashCalculator.sha1Hash(this.ownerId + "NotificationBox"); // } // catch (NoSuchAlgorithmException ex) // { // /*@todo try some other hash here */ // System.err.println("SHA-1 Hash algorithm isn't existent."); // } // this.key = new KademliaId(keyData); // } // // /** // * Adds a new notification to the notification box // * // * @param n the notification to add // */ // public void addNotification(Notification n) // { // this.notifications.add(n); // this.setUpdated(); // } // // /** // * @return All notifications in this notifications box // */ // public List<Notification> getNotifications() // { // return this.notifications; // } // // /** // * Deletes all notifications from the notification box. // */ // public void emptyBox() // { // this.notifications = new ArrayList<>(); // this.setUpdated(); // } // // /** // * Check whether this box has any notifications. // * // * @return // */ // public boolean hasNotifications() // { // return !this.notifications.isEmpty(); // } // // @Override // public KademliaId getKey() // { // return this.key; // } // // @Override // public String getType() // { // return TYPE; // } // // @Override // public String getOwnerId() // { // return this.ownerId; // } // // @Override // public String toString() // { // StringBuilder sb = new StringBuilder("NotificationBox: "); // // sb.append("[Owner: "); // sb.append(ownerId); // sb.append(""); // // for (Notification n : this.notifications) // { // sb.append(n); // sb.append(" ; "); // } // // sb.append("]"); // // return sb.toString(); // } // // }
import dosna.dhtAbstraction.DataManager; import dosna.notification.NotificationBox; import java.io.IOException; import kademlia.dht.GetParameter; import kademlia.dht.KademliaStorageEntry; import kademlia.exceptions.ContentNotFoundException;
package dosna.osn.actor; /** * A class that handles actors on the DOSN. * * @author Joshua Kissoon * @since 20140501 */ public class ActorManager {
// Path: src/dosna/dhtAbstraction/DataManager.java // public interface DataManager // { // // /** // * Put data onto the network. // * This will put the data onto the network based on the routing protocol. // * It may or may not store data locally. // * // * @param content The content to be stored on the network // * // * @return How many nodes was this content stored on // * // * @throws java.io.IOException // */ // public int put(final DOSNAContent content) throws IOException; // // /** // * Get entries for the required data from the network // * // * @param gp // * // * @return A single data entry // * // * @throws java.io.IOException // * @throws kademlia.exceptions.ContentNotFoundException // */ // public KademliaStorageEntry get(final GetParameter gp) throws IOException, NoSuchElementException, ContentNotFoundException; // // /** // * Get entries for the required data from the network // * // * @param key // * @param type // * // * @return A single data entry // * // * @throws java.io.IOException // * @throws kademlia.exceptions.ContentNotFoundException // */ // public KademliaStorageEntry get(final KademliaId key, final String type) throws IOException, NoSuchElementException, ContentNotFoundException; // // /** // * Get entries for the required data from the network // * // * @param key // * @param type // * @param ownerId // * // * @return A single data entry // * // * @throws java.io.IOException // * @throws kademlia.exceptions.ContentNotFoundException // */ // public KademliaStorageEntry get(final KademliaId key, final String type, final String ownerId) throws IOException, NoSuchElementException, ContentNotFoundException; // // /** // * Run an update call to update the data stored locally on this computer. // * This may involve deleting some data and adding some other data. // */ // public void updateStorage(); // // /** // * Save the state of the DataManager and shutdown // * // * @param saveState Whether to save the state of the application or not // * // * @throws java.io.IOException // */ // public void shutdown(final boolean saveState) throws IOException; // // /** // * @return The JKademliaNode used by this DataManager // */ // public JKademliaNode getKademliaNode(); // } // // Path: src/dosna/notification/NotificationBox.java // public class NotificationBox extends DOSNAContent // { // // public final static String TYPE = "NotificationBox"; // // private List<Notification> notifications; // private String ownerId; // // private KademliaId key; // // // { // notifications = new ArrayList<>(); // } // // public NotificationBox() // { // // } // // /** // * Setup the Notification Box // * // * @param owner The owner of this notification box // */ // public NotificationBox(final Actor owner) // { // this(owner.getId()); // } // // /** // * Setup the Notification Box // * // * @param ownerId The ID of the owner of this notification box // */ // public NotificationBox(final String ownerId) // { // this.ownerId = ownerId; // this.generateNodeId(); // } // // private void generateNodeId() // { // byte[] keyData = null; // try // { // keyData = HashCalculator.sha1Hash(this.ownerId + "NotificationBox"); // } // catch (NoSuchAlgorithmException ex) // { // /*@todo try some other hash here */ // System.err.println("SHA-1 Hash algorithm isn't existent."); // } // this.key = new KademliaId(keyData); // } // // /** // * Adds a new notification to the notification box // * // * @param n the notification to add // */ // public void addNotification(Notification n) // { // this.notifications.add(n); // this.setUpdated(); // } // // /** // * @return All notifications in this notifications box // */ // public List<Notification> getNotifications() // { // return this.notifications; // } // // /** // * Deletes all notifications from the notification box. // */ // public void emptyBox() // { // this.notifications = new ArrayList<>(); // this.setUpdated(); // } // // /** // * Check whether this box has any notifications. // * // * @return // */ // public boolean hasNotifications() // { // return !this.notifications.isEmpty(); // } // // @Override // public KademliaId getKey() // { // return this.key; // } // // @Override // public String getType() // { // return TYPE; // } // // @Override // public String getOwnerId() // { // return this.ownerId; // } // // @Override // public String toString() // { // StringBuilder sb = new StringBuilder("NotificationBox: "); // // sb.append("[Owner: "); // sb.append(ownerId); // sb.append(""); // // for (Notification n : this.notifications) // { // sb.append(n); // sb.append(" ; "); // } // // sb.append("]"); // // return sb.toString(); // } // // } // Path: src/dosna/osn/actor/ActorManager.java import dosna.dhtAbstraction.DataManager; import dosna.notification.NotificationBox; import java.io.IOException; import kademlia.dht.GetParameter; import kademlia.dht.KademliaStorageEntry; import kademlia.exceptions.ContentNotFoundException; package dosna.osn.actor; /** * A class that handles actors on the DOSN. * * @author Joshua Kissoon * @since 20140501 */ public class ActorManager {
private final DataManager dataManager;
JoshuaKissoon/DOSNA
src/dosna/simulations/NotificationBoxSimulation.java
// Path: src/dosna/notification/Notification.java // public class Notification // { // // private final KademliaId key; // private final String notification; // // /** // * Create a new notification // * // * @param key The key of the content this notification is for // * @param notification The Notification itself. // */ // public Notification(KademliaId key, String notification) // { // this.key = key; // this.notification = notification; // } // // public KademliaId getContentKey() // { // return this.key; // } // // public String getNotification() // { // return this.notification; // } // // @Override // public String toString() // { // StringBuilder sb = new StringBuilder("Notification: "); // // sb.append("[Text: "); // sb.append(notification); // sb.append("]"); // // return sb.toString(); // } // } // // Path: src/dosna/notification/NotificationBox.java // public class NotificationBox extends DOSNAContent // { // // public final static String TYPE = "NotificationBox"; // // private List<Notification> notifications; // private String ownerId; // // private KademliaId key; // // // { // notifications = new ArrayList<>(); // } // // public NotificationBox() // { // // } // // /** // * Setup the Notification Box // * // * @param owner The owner of this notification box // */ // public NotificationBox(final Actor owner) // { // this(owner.getId()); // } // // /** // * Setup the Notification Box // * // * @param ownerId The ID of the owner of this notification box // */ // public NotificationBox(final String ownerId) // { // this.ownerId = ownerId; // this.generateNodeId(); // } // // private void generateNodeId() // { // byte[] keyData = null; // try // { // keyData = HashCalculator.sha1Hash(this.ownerId + "NotificationBox"); // } // catch (NoSuchAlgorithmException ex) // { // /*@todo try some other hash here */ // System.err.println("SHA-1 Hash algorithm isn't existent."); // } // this.key = new KademliaId(keyData); // } // // /** // * Adds a new notification to the notification box // * // * @param n the notification to add // */ // public void addNotification(Notification n) // { // this.notifications.add(n); // this.setUpdated(); // } // // /** // * @return All notifications in this notifications box // */ // public List<Notification> getNotifications() // { // return this.notifications; // } // // /** // * Deletes all notifications from the notification box. // */ // public void emptyBox() // { // this.notifications = new ArrayList<>(); // this.setUpdated(); // } // // /** // * Check whether this box has any notifications. // * // * @return // */ // public boolean hasNotifications() // { // return !this.notifications.isEmpty(); // } // // @Override // public KademliaId getKey() // { // return this.key; // } // // @Override // public String getType() // { // return TYPE; // } // // @Override // public String getOwnerId() // { // return this.ownerId; // } // // @Override // public String toString() // { // StringBuilder sb = new StringBuilder("NotificationBox: "); // // sb.append("[Owner: "); // sb.append(ownerId); // sb.append(""); // // for (Notification n : this.notifications) // { // sb.append(n); // sb.append(" ; "); // } // // sb.append("]"); // // return sb.toString(); // } // // }
import dosna.notification.Notification; import dosna.notification.NotificationBox; import java.io.IOException; import kademlia.JKademliaNode; import kademlia.dht.GetParameter; import kademlia.dht.KademliaStorageEntry; import kademlia.exceptions.ContentNotFoundException; import kademlia.node.KademliaId;
package dosna.simulations; /** * Just testing notification box handling. * * @author Joshua Kissoon * @since 20140504 */ public class NotificationBoxSimulation { public NotificationBoxSimulation() { try { JKademliaNode kad = new JKademliaNode("Joshua", new KademliaId("JOSHUAJOSHUAJOSHUAJO"), 3445); JKademliaNode kad2 = new JKademliaNode("Joshua2", new KademliaId("JOSHUAJOSHUAJOSHUAJK"), 3446); kad.bootstrap(kad2.getNode());
// Path: src/dosna/notification/Notification.java // public class Notification // { // // private final KademliaId key; // private final String notification; // // /** // * Create a new notification // * // * @param key The key of the content this notification is for // * @param notification The Notification itself. // */ // public Notification(KademliaId key, String notification) // { // this.key = key; // this.notification = notification; // } // // public KademliaId getContentKey() // { // return this.key; // } // // public String getNotification() // { // return this.notification; // } // // @Override // public String toString() // { // StringBuilder sb = new StringBuilder("Notification: "); // // sb.append("[Text: "); // sb.append(notification); // sb.append("]"); // // return sb.toString(); // } // } // // Path: src/dosna/notification/NotificationBox.java // public class NotificationBox extends DOSNAContent // { // // public final static String TYPE = "NotificationBox"; // // private List<Notification> notifications; // private String ownerId; // // private KademliaId key; // // // { // notifications = new ArrayList<>(); // } // // public NotificationBox() // { // // } // // /** // * Setup the Notification Box // * // * @param owner The owner of this notification box // */ // public NotificationBox(final Actor owner) // { // this(owner.getId()); // } // // /** // * Setup the Notification Box // * // * @param ownerId The ID of the owner of this notification box // */ // public NotificationBox(final String ownerId) // { // this.ownerId = ownerId; // this.generateNodeId(); // } // // private void generateNodeId() // { // byte[] keyData = null; // try // { // keyData = HashCalculator.sha1Hash(this.ownerId + "NotificationBox"); // } // catch (NoSuchAlgorithmException ex) // { // /*@todo try some other hash here */ // System.err.println("SHA-1 Hash algorithm isn't existent."); // } // this.key = new KademliaId(keyData); // } // // /** // * Adds a new notification to the notification box // * // * @param n the notification to add // */ // public void addNotification(Notification n) // { // this.notifications.add(n); // this.setUpdated(); // } // // /** // * @return All notifications in this notifications box // */ // public List<Notification> getNotifications() // { // return this.notifications; // } // // /** // * Deletes all notifications from the notification box. // */ // public void emptyBox() // { // this.notifications = new ArrayList<>(); // this.setUpdated(); // } // // /** // * Check whether this box has any notifications. // * // * @return // */ // public boolean hasNotifications() // { // return !this.notifications.isEmpty(); // } // // @Override // public KademliaId getKey() // { // return this.key; // } // // @Override // public String getType() // { // return TYPE; // } // // @Override // public String getOwnerId() // { // return this.ownerId; // } // // @Override // public String toString() // { // StringBuilder sb = new StringBuilder("NotificationBox: "); // // sb.append("[Owner: "); // sb.append(ownerId); // sb.append(""); // // for (Notification n : this.notifications) // { // sb.append(n); // sb.append(" ; "); // } // // sb.append("]"); // // return sb.toString(); // } // // } // Path: src/dosna/simulations/NotificationBoxSimulation.java import dosna.notification.Notification; import dosna.notification.NotificationBox; import java.io.IOException; import kademlia.JKademliaNode; import kademlia.dht.GetParameter; import kademlia.dht.KademliaStorageEntry; import kademlia.exceptions.ContentNotFoundException; import kademlia.node.KademliaId; package dosna.simulations; /** * Just testing notification box handling. * * @author Joshua Kissoon * @since 20140504 */ public class NotificationBoxSimulation { public NotificationBoxSimulation() { try { JKademliaNode kad = new JKademliaNode("Joshua", new KademliaId("JOSHUAJOSHUAJOSHUAJO"), 3445); JKademliaNode kad2 = new JKademliaNode("Joshua2", new KademliaId("JOSHUAJOSHUAJOSHUAJK"), 3446); kad.bootstrap(kad2.getNode());
NotificationBox nb = new NotificationBox("Joshua");
JoshuaKissoon/DOSNA
src/dosna/simulations/NotificationBoxSimulation.java
// Path: src/dosna/notification/Notification.java // public class Notification // { // // private final KademliaId key; // private final String notification; // // /** // * Create a new notification // * // * @param key The key of the content this notification is for // * @param notification The Notification itself. // */ // public Notification(KademliaId key, String notification) // { // this.key = key; // this.notification = notification; // } // // public KademliaId getContentKey() // { // return this.key; // } // // public String getNotification() // { // return this.notification; // } // // @Override // public String toString() // { // StringBuilder sb = new StringBuilder("Notification: "); // // sb.append("[Text: "); // sb.append(notification); // sb.append("]"); // // return sb.toString(); // } // } // // Path: src/dosna/notification/NotificationBox.java // public class NotificationBox extends DOSNAContent // { // // public final static String TYPE = "NotificationBox"; // // private List<Notification> notifications; // private String ownerId; // // private KademliaId key; // // // { // notifications = new ArrayList<>(); // } // // public NotificationBox() // { // // } // // /** // * Setup the Notification Box // * // * @param owner The owner of this notification box // */ // public NotificationBox(final Actor owner) // { // this(owner.getId()); // } // // /** // * Setup the Notification Box // * // * @param ownerId The ID of the owner of this notification box // */ // public NotificationBox(final String ownerId) // { // this.ownerId = ownerId; // this.generateNodeId(); // } // // private void generateNodeId() // { // byte[] keyData = null; // try // { // keyData = HashCalculator.sha1Hash(this.ownerId + "NotificationBox"); // } // catch (NoSuchAlgorithmException ex) // { // /*@todo try some other hash here */ // System.err.println("SHA-1 Hash algorithm isn't existent."); // } // this.key = new KademliaId(keyData); // } // // /** // * Adds a new notification to the notification box // * // * @param n the notification to add // */ // public void addNotification(Notification n) // { // this.notifications.add(n); // this.setUpdated(); // } // // /** // * @return All notifications in this notifications box // */ // public List<Notification> getNotifications() // { // return this.notifications; // } // // /** // * Deletes all notifications from the notification box. // */ // public void emptyBox() // { // this.notifications = new ArrayList<>(); // this.setUpdated(); // } // // /** // * Check whether this box has any notifications. // * // * @return // */ // public boolean hasNotifications() // { // return !this.notifications.isEmpty(); // } // // @Override // public KademliaId getKey() // { // return this.key; // } // // @Override // public String getType() // { // return TYPE; // } // // @Override // public String getOwnerId() // { // return this.ownerId; // } // // @Override // public String toString() // { // StringBuilder sb = new StringBuilder("NotificationBox: "); // // sb.append("[Owner: "); // sb.append(ownerId); // sb.append(""); // // for (Notification n : this.notifications) // { // sb.append(n); // sb.append(" ; "); // } // // sb.append("]"); // // return sb.toString(); // } // // }
import dosna.notification.Notification; import dosna.notification.NotificationBox; import java.io.IOException; import kademlia.JKademliaNode; import kademlia.dht.GetParameter; import kademlia.dht.KademliaStorageEntry; import kademlia.exceptions.ContentNotFoundException; import kademlia.node.KademliaId;
package dosna.simulations; /** * Just testing notification box handling. * * @author Joshua Kissoon * @since 20140504 */ public class NotificationBoxSimulation { public NotificationBoxSimulation() { try { JKademliaNode kad = new JKademliaNode("Joshua", new KademliaId("JOSHUAJOSHUAJOSHUAJO"), 3445); JKademliaNode kad2 = new JKademliaNode("Joshua2", new KademliaId("JOSHUAJOSHUAJOSHUAJK"), 3446); kad.bootstrap(kad2.getNode()); NotificationBox nb = new NotificationBox("Joshua");
// Path: src/dosna/notification/Notification.java // public class Notification // { // // private final KademliaId key; // private final String notification; // // /** // * Create a new notification // * // * @param key The key of the content this notification is for // * @param notification The Notification itself. // */ // public Notification(KademliaId key, String notification) // { // this.key = key; // this.notification = notification; // } // // public KademliaId getContentKey() // { // return this.key; // } // // public String getNotification() // { // return this.notification; // } // // @Override // public String toString() // { // StringBuilder sb = new StringBuilder("Notification: "); // // sb.append("[Text: "); // sb.append(notification); // sb.append("]"); // // return sb.toString(); // } // } // // Path: src/dosna/notification/NotificationBox.java // public class NotificationBox extends DOSNAContent // { // // public final static String TYPE = "NotificationBox"; // // private List<Notification> notifications; // private String ownerId; // // private KademliaId key; // // // { // notifications = new ArrayList<>(); // } // // public NotificationBox() // { // // } // // /** // * Setup the Notification Box // * // * @param owner The owner of this notification box // */ // public NotificationBox(final Actor owner) // { // this(owner.getId()); // } // // /** // * Setup the Notification Box // * // * @param ownerId The ID of the owner of this notification box // */ // public NotificationBox(final String ownerId) // { // this.ownerId = ownerId; // this.generateNodeId(); // } // // private void generateNodeId() // { // byte[] keyData = null; // try // { // keyData = HashCalculator.sha1Hash(this.ownerId + "NotificationBox"); // } // catch (NoSuchAlgorithmException ex) // { // /*@todo try some other hash here */ // System.err.println("SHA-1 Hash algorithm isn't existent."); // } // this.key = new KademliaId(keyData); // } // // /** // * Adds a new notification to the notification box // * // * @param n the notification to add // */ // public void addNotification(Notification n) // { // this.notifications.add(n); // this.setUpdated(); // } // // /** // * @return All notifications in this notifications box // */ // public List<Notification> getNotifications() // { // return this.notifications; // } // // /** // * Deletes all notifications from the notification box. // */ // public void emptyBox() // { // this.notifications = new ArrayList<>(); // this.setUpdated(); // } // // /** // * Check whether this box has any notifications. // * // * @return // */ // public boolean hasNotifications() // { // return !this.notifications.isEmpty(); // } // // @Override // public KademliaId getKey() // { // return this.key; // } // // @Override // public String getType() // { // return TYPE; // } // // @Override // public String getOwnerId() // { // return this.ownerId; // } // // @Override // public String toString() // { // StringBuilder sb = new StringBuilder("NotificationBox: "); // // sb.append("[Owner: "); // sb.append(ownerId); // sb.append(""); // // for (Notification n : this.notifications) // { // sb.append(n); // sb.append(" ; "); // } // // sb.append("]"); // // return sb.toString(); // } // // } // Path: src/dosna/simulations/NotificationBoxSimulation.java import dosna.notification.Notification; import dosna.notification.NotificationBox; import java.io.IOException; import kademlia.JKademliaNode; import kademlia.dht.GetParameter; import kademlia.dht.KademliaStorageEntry; import kademlia.exceptions.ContentNotFoundException; import kademlia.node.KademliaId; package dosna.simulations; /** * Just testing notification box handling. * * @author Joshua Kissoon * @since 20140504 */ public class NotificationBoxSimulation { public NotificationBoxSimulation() { try { JKademliaNode kad = new JKademliaNode("Joshua", new KademliaId("JOSHUAJOSHUAJOSHUAJO"), 3445); JKademliaNode kad2 = new JKademliaNode("Joshua2", new KademliaId("JOSHUAJOSHUAJOSHUAJK"), 3446); kad.bootstrap(kad2.getNode()); NotificationBox nb = new NotificationBox("Joshua");
nb.addNotification(new Notification(new KademliaId(), "Some Notification 1"));
rsgoncalves/ecco
src/main/java/uk/ac/manchester/cs/diff/concept/change/ConceptChange.java
// Path: src/main/java/uk/ac/manchester/cs/diff/concept/witnesses/WitnessAxioms.java // public class WitnessAxioms { // private Set<OWLAxiom> direct, indirect; // // /** // * Constructor // * @param direct Set of direct witness axioms // * @param indirect Set of indirect witness axioms // */ // public WitnessAxioms(Set<OWLAxiom> direct, Set<OWLAxiom> indirect) { // this.direct = direct; // this.indirect = indirect; // } // // // /** // * Get the set of direct witness axioms // * @return Set of direct witness axioms // */ // public Set<OWLAxiom> getDirectWitnesses() { // return direct; // } // // // /** // * Get the set of indirect witness axioms // * @return Set of indirect witness axioms // */ // public Set<OWLAxiom> getIndirectWitnesses() { // return indirect; // } // // // /** // * Check if there are any witness axioms (direct or otherwise) // * @return true if this contains any witness axioms // */ // public boolean isEmpty() { // if((direct == null || direct.isEmpty()) && (indirect == null || indirect.isEmpty())) // return true; // else // return false; // } // }
import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.semanticweb.owlapi.model.OWLAxiom; import org.semanticweb.owlapi.model.OWLClass; import uk.ac.manchester.cs.diff.concept.witnesses.WitnessAxioms;
/******************************************************************************* * This file is part of ecco. * * ecco is distributed under the terms of the GNU Lesser General Public License (LGPL), Version 3.0. * * Copyright 2011-2014, The University of Manchester * * ecco is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser * General Public License as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * ecco 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 Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ecco. * If not, see http://www.gnu.org/licenses/. ******************************************************************************/ package uk.ac.manchester.cs.diff.concept.change; /** * @author Rafael S. Goncalves <br> * Information Management Group (IMG) <br> * School of Computer Science <br> * University of Manchester <br> */ public class ConceptChange { private OWLClass c; private Set<OWLAxiom> dirSpecWit, indirSpecWit, dirGenWit, indirGenWit, allWit; private Map<OWLAxiom,Set<OWLAxiom>> dirSpecWitsOfAx, dirGenWitsOfAx, indirSpecWitsOfAx, indirGenWitsOfAx; /** * Constructor * @param c Concept * @param specWits Witnesses for a specialisation * @param genWits Witnesses for a generalisation */
// Path: src/main/java/uk/ac/manchester/cs/diff/concept/witnesses/WitnessAxioms.java // public class WitnessAxioms { // private Set<OWLAxiom> direct, indirect; // // /** // * Constructor // * @param direct Set of direct witness axioms // * @param indirect Set of indirect witness axioms // */ // public WitnessAxioms(Set<OWLAxiom> direct, Set<OWLAxiom> indirect) { // this.direct = direct; // this.indirect = indirect; // } // // // /** // * Get the set of direct witness axioms // * @return Set of direct witness axioms // */ // public Set<OWLAxiom> getDirectWitnesses() { // return direct; // } // // // /** // * Get the set of indirect witness axioms // * @return Set of indirect witness axioms // */ // public Set<OWLAxiom> getIndirectWitnesses() { // return indirect; // } // // // /** // * Check if there are any witness axioms (direct or otherwise) // * @return true if this contains any witness axioms // */ // public boolean isEmpty() { // if((direct == null || direct.isEmpty()) && (indirect == null || indirect.isEmpty())) // return true; // else // return false; // } // } // Path: src/main/java/uk/ac/manchester/cs/diff/concept/change/ConceptChange.java import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.semanticweb.owlapi.model.OWLAxiom; import org.semanticweb.owlapi.model.OWLClass; import uk.ac.manchester.cs.diff.concept.witnesses.WitnessAxioms; /******************************************************************************* * This file is part of ecco. * * ecco is distributed under the terms of the GNU Lesser General Public License (LGPL), Version 3.0. * * Copyright 2011-2014, The University of Manchester * * ecco is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser * General Public License as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * ecco 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 Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ecco. * If not, see http://www.gnu.org/licenses/. ******************************************************************************/ package uk.ac.manchester.cs.diff.concept.change; /** * @author Rafael S. Goncalves <br> * Information Management Group (IMG) <br> * School of Computer Science <br> * University of Manchester <br> */ public class ConceptChange { private OWLClass c; private Set<OWLAxiom> dirSpecWit, indirSpecWit, dirGenWit, indirGenWit, allWit; private Map<OWLAxiom,Set<OWLAxiom>> dirSpecWitsOfAx, dirGenWitsOfAx, indirSpecWitsOfAx, indirGenWitsOfAx; /** * Constructor * @param c Concept * @param specWits Witnesses for a specialisation * @param genWits Witnesses for a generalisation */
public ConceptChange(OWLClass c, WitnessAxioms specWits, WitnessAxioms genWits) {
rsgoncalves/ecco
src/main/java/uk/ac/manchester/cs/diff/output/xml/XMLDiffReport.java
// Path: src/main/java/uk/ac/manchester/cs/diff/unity/changeset/ChangeSet.java // public interface ChangeSet { // // /** // * Check if change set is empty // * @return true if change set is empty, false otherwise // */ // public boolean isEmpty(); // // // /** // * Get the operation time // * @return Operation time // */ // public double getOperationTime(); // // }
import org.w3c.dom.Document; import uk.ac.manchester.cs.diff.unity.changeset.ChangeSet;
/******************************************************************************* * This file is part of ecco. * * ecco is distributed under the terms of the GNU Lesser General Public License (LGPL), Version 3.0. * * Copyright 2011-2014, The University of Manchester * * ecco is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser * General Public License as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * ecco 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 Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ecco. * If not, see http://www.gnu.org/licenses/. ******************************************************************************/ package uk.ac.manchester.cs.diff.output.xml; /** * @author Rafael S. Goncalves <br> * Information Management Group (IMG) <br> * School of Computer Science <br> * University of Manchester <br> */ public interface XMLDiffReport { /** * Get XML document using term names * @return Term name based XML document */ public Document getXMLDocumentUsingTermNames(); /** * Get XML document using term labels * @return Label based XML document */ public Document getXMLDocumentUsingLabels(); /** * Get XML document using automatically generated symbols * @return Gensym based XML document */ public Document getXMLDocumentUsingGenSyms(); /** * Get a specified XML document as a string * @param doc XML document * @return String containing the given XML document */ public String getReportAsString(Document doc); /** * Get a transformation of the given document, according to the specified XSLT file, into HTML * @param doc XML document * @param xsltPath File path to XSLT file * @return String containing the HTML code resulting from the transformation */ public String getReportAsHTML(Document doc, String xsltPath); /** * Get the change set associated with this report * @return Change set */
// Path: src/main/java/uk/ac/manchester/cs/diff/unity/changeset/ChangeSet.java // public interface ChangeSet { // // /** // * Check if change set is empty // * @return true if change set is empty, false otherwise // */ // public boolean isEmpty(); // // // /** // * Get the operation time // * @return Operation time // */ // public double getOperationTime(); // // } // Path: src/main/java/uk/ac/manchester/cs/diff/output/xml/XMLDiffReport.java import org.w3c.dom.Document; import uk.ac.manchester.cs.diff.unity.changeset.ChangeSet; /******************************************************************************* * This file is part of ecco. * * ecco is distributed under the terms of the GNU Lesser General Public License (LGPL), Version 3.0. * * Copyright 2011-2014, The University of Manchester * * ecco is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser * General Public License as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * ecco 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 Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ecco. * If not, see http://www.gnu.org/licenses/. ******************************************************************************/ package uk.ac.manchester.cs.diff.output.xml; /** * @author Rafael S. Goncalves <br> * Information Management Group (IMG) <br> * School of Computer Science <br> * University of Manchester <br> */ public interface XMLDiffReport { /** * Get XML document using term names * @return Term name based XML document */ public Document getXMLDocumentUsingTermNames(); /** * Get XML document using term labels * @return Label based XML document */ public Document getXMLDocumentUsingLabels(); /** * Get XML document using automatically generated symbols * @return Gensym based XML document */ public Document getXMLDocumentUsingGenSyms(); /** * Get a specified XML document as a string * @param doc XML document * @return String containing the given XML document */ public String getReportAsString(Document doc); /** * Get a transformation of the given document, according to the specified XSLT file, into HTML * @param doc XML document * @param xsltPath File path to XSLT file * @return String containing the HTML code resulting from the transformation */ public String getReportAsHTML(Document doc, String xsltPath); /** * Get the change set associated with this report * @return Change set */
public ChangeSet getChangeSet();
rsgoncalves/ecco
src/main/java/uk/ac/manchester/cs/diff/unity/changeset/AlignedChangeSet.java
// Path: src/main/java/uk/ac/manchester/cs/diff/exception/NotImplementedException.java // public class NotImplementedException extends RuntimeException { // private static final long serialVersionUID = 1L; // // // /** // * Constructor // * @see RuntimeException#RuntimeException() // */ // public NotImplementedException() { // super(); // } // // // /** // * Constructor // * @param s Message // * @see RuntimeException#RuntimeException(String s) // */ // public NotImplementedException(String s) { // super(s); // } // // // /** // * Constructor // * @param s Message // * @param throwable Throwable // * @see RuntimeException#RuntimeException(String s, Throwable throwable) // */ // public NotImplementedException(String s, Throwable throwable) { // super(s, throwable); // } // // // /** // * Constructor // * @param throwable Throwable // * @see RuntimeException#RuntimeException(Throwable throwable) // */ // public NotImplementedException(Throwable throwable) { // super(throwable); // } // }
import uk.ac.manchester.cs.diff.exception.NotImplementedException;
package uk.ac.manchester.cs.diff.unity.changeset; /** * @author Rafael S. Goncalves <br> * Stanford Center for Biomedical Informatics Research (BMIR) <br> * School of Medicine, Stanford University <br> */ public class AlignedChangeSet implements AlignedChangeSetInt { private AlignedDirectChangeSet directChangeSet; private AlignedIndirectChangeSet indirectChangeSet; /** * Constructor * @param directChangeSet Direct change set * @param indirectChangeSet Indirect change set */ public AlignedChangeSet(AlignedDirectChangeSet directChangeSet, AlignedIndirectChangeSet indirectChangeSet) { this.directChangeSet = directChangeSet; this.indirectChangeSet = indirectChangeSet; } @Override public AlignedDirectChangeSet getDirectChangeSet() { return directChangeSet; } @Override public AlignedIndirectChangeSet getIndirectChangeSet() { return indirectChangeSet; } @Override public boolean isEmpty() { if(directChangeSet.isEmpty() && indirectChangeSet.isEmpty()) return true; else return false; } @Override public double getOperationTime() { // TODO: not implemented
// Path: src/main/java/uk/ac/manchester/cs/diff/exception/NotImplementedException.java // public class NotImplementedException extends RuntimeException { // private static final long serialVersionUID = 1L; // // // /** // * Constructor // * @see RuntimeException#RuntimeException() // */ // public NotImplementedException() { // super(); // } // // // /** // * Constructor // * @param s Message // * @see RuntimeException#RuntimeException(String s) // */ // public NotImplementedException(String s) { // super(s); // } // // // /** // * Constructor // * @param s Message // * @param throwable Throwable // * @see RuntimeException#RuntimeException(String s, Throwable throwable) // */ // public NotImplementedException(String s, Throwable throwable) { // super(s, throwable); // } // // // /** // * Constructor // * @param throwable Throwable // * @see RuntimeException#RuntimeException(Throwable throwable) // */ // public NotImplementedException(Throwable throwable) { // super(throwable); // } // } // Path: src/main/java/uk/ac/manchester/cs/diff/unity/changeset/AlignedChangeSet.java import uk.ac.manchester.cs.diff.exception.NotImplementedException; package uk.ac.manchester.cs.diff.unity.changeset; /** * @author Rafael S. Goncalves <br> * Stanford Center for Biomedical Informatics Research (BMIR) <br> * School of Medicine, Stanford University <br> */ public class AlignedChangeSet implements AlignedChangeSetInt { private AlignedDirectChangeSet directChangeSet; private AlignedIndirectChangeSet indirectChangeSet; /** * Constructor * @param directChangeSet Direct change set * @param indirectChangeSet Indirect change set */ public AlignedChangeSet(AlignedDirectChangeSet directChangeSet, AlignedIndirectChangeSet indirectChangeSet) { this.directChangeSet = directChangeSet; this.indirectChangeSet = indirectChangeSet; } @Override public AlignedDirectChangeSet getDirectChangeSet() { return directChangeSet; } @Override public AlignedIndirectChangeSet getIndirectChangeSet() { return indirectChangeSet; } @Override public boolean isEmpty() { if(directChangeSet.isEmpty() && indirectChangeSet.isEmpty()) return true; else return false; } @Override public double getOperationTime() { // TODO: not implemented
throw new NotImplementedException("not implemented".toUpperCase());
rsgoncalves/ecco
src/main/java/uk/ac/manchester/cs/diff/axiom/changeset/StructuralChangeSet.java
// Path: src/main/java/uk/ac/manchester/cs/diff/axiom/change/StructuralAddition.java // public class StructuralAddition extends StructuralChange { // /** // * Constructor // * @param axiom Added axiom // */ // public StructuralAddition(OWLAxiom axiom) { // super(axiom); // } // } // // Path: src/main/java/uk/ac/manchester/cs/diff/axiom/change/StructuralRemoval.java // public class StructuralRemoval extends StructuralChange { // /** // * Constructor // * @param axiom Removed axiom // */ // public StructuralRemoval(OWLAxiom axiom) { // super(axiom); // } // }
import java.util.HashSet; import java.util.Set; import org.semanticweb.owlapi.model.OWLAxiom; import uk.ac.manchester.cs.diff.axiom.change.StructuralAddition; import uk.ac.manchester.cs.diff.axiom.change.StructuralRemoval;
/******************************************************************************* * This file is part of ecco. * * ecco is distributed under the terms of the GNU Lesser General Public License (LGPL), Version 3.0. * * Copyright 2011-2014, The University of Manchester * * ecco is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser * General Public License as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * ecco 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 Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ecco. * If not, see http://www.gnu.org/licenses/. ******************************************************************************/ package uk.ac.manchester.cs.diff.axiom.changeset; /** * @author Rafael S. Goncalves <br> * Information Management Group (IMG) <br> * School of Computer Science <br> * University of Manchester <br> */ public class StructuralChangeSet implements AxiomChangeSet { private Set<OWLAxiom> additions, removals, shared; private String ont1name, ont2name; private double diffTime; /** * Constructor * @param additions Set of added axioms * @param removals Set of removed axioms * @param shared Set of shared axioms */ public StructuralChangeSet(Set<OWLAxiom> additions, Set<OWLAxiom> removals, Set<OWLAxiom> shared) { this.additions = additions; this.removals = removals; this.shared = shared; } /** * Set file name of specified ontology (1 or 2) * @param ontNr Ontology number * @param name Ontology file name * @deprecated */ public void setOntologyName(int ontNr, String name) { if(ontNr == 1) ont1name = name; else if(ontNr == 2) ont2name = name; } /** * Set diff time * @param time Diff time * @deprecated */ public void setDiffTime(double time) { diffTime = time; } /** * Get the CPU time (in seconds) spent in structural diff * @return CPU time (in seconds) spent in structural diff */ public double getOperationTime() { return diffTime; } /** * Get file name of ontology 1 * @return File name of ontology 1 */ public String getOntology1FileName() { return ont1name; } /** * Get file name of ontology 2 * @return File name of ontology 2 */ public String getOntology2FileName() { return ont2name; } /** * Get the set of structural additions * @return Set of structural additions */
// Path: src/main/java/uk/ac/manchester/cs/diff/axiom/change/StructuralAddition.java // public class StructuralAddition extends StructuralChange { // /** // * Constructor // * @param axiom Added axiom // */ // public StructuralAddition(OWLAxiom axiom) { // super(axiom); // } // } // // Path: src/main/java/uk/ac/manchester/cs/diff/axiom/change/StructuralRemoval.java // public class StructuralRemoval extends StructuralChange { // /** // * Constructor // * @param axiom Removed axiom // */ // public StructuralRemoval(OWLAxiom axiom) { // super(axiom); // } // } // Path: src/main/java/uk/ac/manchester/cs/diff/axiom/changeset/StructuralChangeSet.java import java.util.HashSet; import java.util.Set; import org.semanticweb.owlapi.model.OWLAxiom; import uk.ac.manchester.cs.diff.axiom.change.StructuralAddition; import uk.ac.manchester.cs.diff.axiom.change.StructuralRemoval; /******************************************************************************* * This file is part of ecco. * * ecco is distributed under the terms of the GNU Lesser General Public License (LGPL), Version 3.0. * * Copyright 2011-2014, The University of Manchester * * ecco is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser * General Public License as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * ecco 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 Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ecco. * If not, see http://www.gnu.org/licenses/. ******************************************************************************/ package uk.ac.manchester.cs.diff.axiom.changeset; /** * @author Rafael S. Goncalves <br> * Information Management Group (IMG) <br> * School of Computer Science <br> * University of Manchester <br> */ public class StructuralChangeSet implements AxiomChangeSet { private Set<OWLAxiom> additions, removals, shared; private String ont1name, ont2name; private double diffTime; /** * Constructor * @param additions Set of added axioms * @param removals Set of removed axioms * @param shared Set of shared axioms */ public StructuralChangeSet(Set<OWLAxiom> additions, Set<OWLAxiom> removals, Set<OWLAxiom> shared) { this.additions = additions; this.removals = removals; this.shared = shared; } /** * Set file name of specified ontology (1 or 2) * @param ontNr Ontology number * @param name Ontology file name * @deprecated */ public void setOntologyName(int ontNr, String name) { if(ontNr == 1) ont1name = name; else if(ontNr == 2) ont2name = name; } /** * Set diff time * @param time Diff time * @deprecated */ public void setDiffTime(double time) { diffTime = time; } /** * Get the CPU time (in seconds) spent in structural diff * @return CPU time (in seconds) spent in structural diff */ public double getOperationTime() { return diffTime; } /** * Get file name of ontology 1 * @return File name of ontology 1 */ public String getOntology1FileName() { return ont1name; } /** * Get file name of ontology 2 * @return File name of ontology 2 */ public String getOntology2FileName() { return ont2name; } /** * Get the set of structural additions * @return Set of structural additions */
public Set<StructuralAddition> getAdditions() {
rsgoncalves/ecco
src/main/java/uk/ac/manchester/cs/diff/axiom/changeset/StructuralChangeSet.java
// Path: src/main/java/uk/ac/manchester/cs/diff/axiom/change/StructuralAddition.java // public class StructuralAddition extends StructuralChange { // /** // * Constructor // * @param axiom Added axiom // */ // public StructuralAddition(OWLAxiom axiom) { // super(axiom); // } // } // // Path: src/main/java/uk/ac/manchester/cs/diff/axiom/change/StructuralRemoval.java // public class StructuralRemoval extends StructuralChange { // /** // * Constructor // * @param axiom Removed axiom // */ // public StructuralRemoval(OWLAxiom axiom) { // super(axiom); // } // }
import java.util.HashSet; import java.util.Set; import org.semanticweb.owlapi.model.OWLAxiom; import uk.ac.manchester.cs.diff.axiom.change.StructuralAddition; import uk.ac.manchester.cs.diff.axiom.change.StructuralRemoval;
public String getOntology1FileName() { return ont1name; } /** * Get file name of ontology 2 * @return File name of ontology 2 */ public String getOntology2FileName() { return ont2name; } /** * Get the set of structural additions * @return Set of structural additions */ public Set<StructuralAddition> getAdditions() { Set<StructuralAddition> additionSet = new HashSet<StructuralAddition>(); for(OWLAxiom ax : additions) additionSet.add(new StructuralAddition(ax)); return additionSet; } /** * Get the set of structural removals * @return Set of structural removals */
// Path: src/main/java/uk/ac/manchester/cs/diff/axiom/change/StructuralAddition.java // public class StructuralAddition extends StructuralChange { // /** // * Constructor // * @param axiom Added axiom // */ // public StructuralAddition(OWLAxiom axiom) { // super(axiom); // } // } // // Path: src/main/java/uk/ac/manchester/cs/diff/axiom/change/StructuralRemoval.java // public class StructuralRemoval extends StructuralChange { // /** // * Constructor // * @param axiom Removed axiom // */ // public StructuralRemoval(OWLAxiom axiom) { // super(axiom); // } // } // Path: src/main/java/uk/ac/manchester/cs/diff/axiom/changeset/StructuralChangeSet.java import java.util.HashSet; import java.util.Set; import org.semanticweb.owlapi.model.OWLAxiom; import uk.ac.manchester.cs.diff.axiom.change.StructuralAddition; import uk.ac.manchester.cs.diff.axiom.change.StructuralRemoval; public String getOntology1FileName() { return ont1name; } /** * Get file name of ontology 2 * @return File name of ontology 2 */ public String getOntology2FileName() { return ont2name; } /** * Get the set of structural additions * @return Set of structural additions */ public Set<StructuralAddition> getAdditions() { Set<StructuralAddition> additionSet = new HashSet<StructuralAddition>(); for(OWLAxiom ax : additions) additionSet.add(new StructuralAddition(ax)); return additionSet; } /** * Get the set of structural removals * @return Set of structural removals */
public Set<StructuralRemoval> getRemovals() {
rsgoncalves/ecco
src/main/java/uk/ac/manchester/cs/diff/axiom/changeset/LogicalChangeSet.java
// Path: src/main/java/uk/ac/manchester/cs/diff/axiom/change/LogicalAddition.java // public class LogicalAddition extends LogicalChange { // /** // * Constructor // * @param axiom Axiom change // * @param isEffectual true if change is logically effectual, false otherwise // */ // public LogicalAddition(OWLAxiom axiom, boolean isEffectual) { // super(axiom, isEffectual); // } // } // // Path: src/main/java/uk/ac/manchester/cs/diff/axiom/change/LogicalRemoval.java // public class LogicalRemoval extends LogicalChange { // /** // * Constructor // * @param axiom Axiom change // * @param isEffectual true if change is logically effectual, false otherwise // */ // public LogicalRemoval(OWLAxiom axiom, boolean isEffectual) { // super(axiom, isEffectual); // } // }
import java.util.HashSet; import java.util.Set; import org.semanticweb.owlapi.model.OWLAxiom; import uk.ac.manchester.cs.diff.axiom.change.LogicalAddition; import uk.ac.manchester.cs.diff.axiom.change.LogicalRemoval;
/******************************************************************************* * This file is part of ecco. * * ecco is distributed under the terms of the GNU Lesser General Public License (LGPL), Version 3.0. * * Copyright 2011-2014, The University of Manchester * * ecco is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser * General Public License as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * ecco 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 Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ecco. * If not, see http://www.gnu.org/licenses/. ******************************************************************************/ package uk.ac.manchester.cs.diff.axiom.changeset; /** * @author Rafael S. Goncalves <br> * Information Management Group (IMG) <br> * School of Computer Science <br> * University of Manchester <br> */ public class LogicalChangeSet implements AxiomChangeSet { private Set<OWLAxiom> effectualAdditions, ineffectualAdditions, effectualRemovals, ineffectualRemovals; private StructuralChangeSet structuralChangeSet; private double diffTime; /** * Constructor * @param effectualAdditions Effectual additions * @param ineffectualAdditions Ineffectual additions * @param effectualRemovals Effectual removals * @param ineffectualRemovals Ineffectual removals * @param structuralChangeSet Structural change set */ public LogicalChangeSet(Set<OWLAxiom> effectualAdditions, Set<OWLAxiom> ineffectualAdditions, Set<OWLAxiom> effectualRemovals, Set<OWLAxiom> ineffectualRemovals, StructuralChangeSet structuralChangeSet) { this.effectualAdditions = effectualAdditions; this.ineffectualAdditions = ineffectualAdditions; this.effectualRemovals = effectualRemovals; this.ineffectualRemovals = ineffectualRemovals; this.structuralChangeSet = structuralChangeSet; } /** * Get the structural change set between ontologies * @return Structural change set */ public StructuralChangeSet getStructuralChangeSet() { return structuralChangeSet; } /** * Set diff time * @param time Diff time * @deprecated */ public void setDiffTime(double time) { diffTime = time; } /** * Get the CPU time (in seconds) spent in structural diff * @return CPU time (in seconds) spent in structural diff */ public double getOperationTime() { return diffTime; } /** * Get the set of effectual and ineffectual additions * @return Set of effectual and ineffectual additions */
// Path: src/main/java/uk/ac/manchester/cs/diff/axiom/change/LogicalAddition.java // public class LogicalAddition extends LogicalChange { // /** // * Constructor // * @param axiom Axiom change // * @param isEffectual true if change is logically effectual, false otherwise // */ // public LogicalAddition(OWLAxiom axiom, boolean isEffectual) { // super(axiom, isEffectual); // } // } // // Path: src/main/java/uk/ac/manchester/cs/diff/axiom/change/LogicalRemoval.java // public class LogicalRemoval extends LogicalChange { // /** // * Constructor // * @param axiom Axiom change // * @param isEffectual true if change is logically effectual, false otherwise // */ // public LogicalRemoval(OWLAxiom axiom, boolean isEffectual) { // super(axiom, isEffectual); // } // } // Path: src/main/java/uk/ac/manchester/cs/diff/axiom/changeset/LogicalChangeSet.java import java.util.HashSet; import java.util.Set; import org.semanticweb.owlapi.model.OWLAxiom; import uk.ac.manchester.cs.diff.axiom.change.LogicalAddition; import uk.ac.manchester.cs.diff.axiom.change.LogicalRemoval; /******************************************************************************* * This file is part of ecco. * * ecco is distributed under the terms of the GNU Lesser General Public License (LGPL), Version 3.0. * * Copyright 2011-2014, The University of Manchester * * ecco is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser * General Public License as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * ecco 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 Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ecco. * If not, see http://www.gnu.org/licenses/. ******************************************************************************/ package uk.ac.manchester.cs.diff.axiom.changeset; /** * @author Rafael S. Goncalves <br> * Information Management Group (IMG) <br> * School of Computer Science <br> * University of Manchester <br> */ public class LogicalChangeSet implements AxiomChangeSet { private Set<OWLAxiom> effectualAdditions, ineffectualAdditions, effectualRemovals, ineffectualRemovals; private StructuralChangeSet structuralChangeSet; private double diffTime; /** * Constructor * @param effectualAdditions Effectual additions * @param ineffectualAdditions Ineffectual additions * @param effectualRemovals Effectual removals * @param ineffectualRemovals Ineffectual removals * @param structuralChangeSet Structural change set */ public LogicalChangeSet(Set<OWLAxiom> effectualAdditions, Set<OWLAxiom> ineffectualAdditions, Set<OWLAxiom> effectualRemovals, Set<OWLAxiom> ineffectualRemovals, StructuralChangeSet structuralChangeSet) { this.effectualAdditions = effectualAdditions; this.ineffectualAdditions = ineffectualAdditions; this.effectualRemovals = effectualRemovals; this.ineffectualRemovals = ineffectualRemovals; this.structuralChangeSet = structuralChangeSet; } /** * Get the structural change set between ontologies * @return Structural change set */ public StructuralChangeSet getStructuralChangeSet() { return structuralChangeSet; } /** * Set diff time * @param time Diff time * @deprecated */ public void setDiffTime(double time) { diffTime = time; } /** * Get the CPU time (in seconds) spent in structural diff * @return CPU time (in seconds) spent in structural diff */ public double getOperationTime() { return diffTime; } /** * Get the set of effectual and ineffectual additions * @return Set of effectual and ineffectual additions */
public Set<LogicalAddition> getAdditions() {
rsgoncalves/ecco
src/main/java/uk/ac/manchester/cs/diff/axiom/changeset/LogicalChangeSet.java
// Path: src/main/java/uk/ac/manchester/cs/diff/axiom/change/LogicalAddition.java // public class LogicalAddition extends LogicalChange { // /** // * Constructor // * @param axiom Axiom change // * @param isEffectual true if change is logically effectual, false otherwise // */ // public LogicalAddition(OWLAxiom axiom, boolean isEffectual) { // super(axiom, isEffectual); // } // } // // Path: src/main/java/uk/ac/manchester/cs/diff/axiom/change/LogicalRemoval.java // public class LogicalRemoval extends LogicalChange { // /** // * Constructor // * @param axiom Axiom change // * @param isEffectual true if change is logically effectual, false otherwise // */ // public LogicalRemoval(OWLAxiom axiom, boolean isEffectual) { // super(axiom, isEffectual); // } // }
import java.util.HashSet; import java.util.Set; import org.semanticweb.owlapi.model.OWLAxiom; import uk.ac.manchester.cs.diff.axiom.change.LogicalAddition; import uk.ac.manchester.cs.diff.axiom.change.LogicalRemoval;
/******************************************************************************* * This file is part of ecco. * * ecco is distributed under the terms of the GNU Lesser General Public License (LGPL), Version 3.0. * * Copyright 2011-2014, The University of Manchester * * ecco is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser * General Public License as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * ecco 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 Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ecco. * If not, see http://www.gnu.org/licenses/. ******************************************************************************/ package uk.ac.manchester.cs.diff.axiom.changeset; /** * @author Rafael S. Goncalves <br> * Information Management Group (IMG) <br> * School of Computer Science <br> * University of Manchester <br> */ public class LogicalChangeSet implements AxiomChangeSet { private Set<OWLAxiom> effectualAdditions, ineffectualAdditions, effectualRemovals, ineffectualRemovals; private StructuralChangeSet structuralChangeSet; private double diffTime; /** * Constructor * @param effectualAdditions Effectual additions * @param ineffectualAdditions Ineffectual additions * @param effectualRemovals Effectual removals * @param ineffectualRemovals Ineffectual removals * @param structuralChangeSet Structural change set */ public LogicalChangeSet(Set<OWLAxiom> effectualAdditions, Set<OWLAxiom> ineffectualAdditions, Set<OWLAxiom> effectualRemovals, Set<OWLAxiom> ineffectualRemovals, StructuralChangeSet structuralChangeSet) { this.effectualAdditions = effectualAdditions; this.ineffectualAdditions = ineffectualAdditions; this.effectualRemovals = effectualRemovals; this.ineffectualRemovals = ineffectualRemovals; this.structuralChangeSet = structuralChangeSet; } /** * Get the structural change set between ontologies * @return Structural change set */ public StructuralChangeSet getStructuralChangeSet() { return structuralChangeSet; } /** * Set diff time * @param time Diff time * @deprecated */ public void setDiffTime(double time) { diffTime = time; } /** * Get the CPU time (in seconds) spent in structural diff * @return CPU time (in seconds) spent in structural diff */ public double getOperationTime() { return diffTime; } /** * Get the set of effectual and ineffectual additions * @return Set of effectual and ineffectual additions */ public Set<LogicalAddition> getAdditions() { Set<LogicalAddition> additionSet = new HashSet<LogicalAddition>(); for(OWLAxiom ax : effectualAdditions) additionSet.add(new LogicalAddition(ax, true)); for(OWLAxiom ax : ineffectualAdditions) additionSet.add(new LogicalAddition(ax, false)); return additionSet; } /** * Get the set of effectual and ineffectual removals * @return Set of effectual and ineffectual removals */
// Path: src/main/java/uk/ac/manchester/cs/diff/axiom/change/LogicalAddition.java // public class LogicalAddition extends LogicalChange { // /** // * Constructor // * @param axiom Axiom change // * @param isEffectual true if change is logically effectual, false otherwise // */ // public LogicalAddition(OWLAxiom axiom, boolean isEffectual) { // super(axiom, isEffectual); // } // } // // Path: src/main/java/uk/ac/manchester/cs/diff/axiom/change/LogicalRemoval.java // public class LogicalRemoval extends LogicalChange { // /** // * Constructor // * @param axiom Axiom change // * @param isEffectual true if change is logically effectual, false otherwise // */ // public LogicalRemoval(OWLAxiom axiom, boolean isEffectual) { // super(axiom, isEffectual); // } // } // Path: src/main/java/uk/ac/manchester/cs/diff/axiom/changeset/LogicalChangeSet.java import java.util.HashSet; import java.util.Set; import org.semanticweb.owlapi.model.OWLAxiom; import uk.ac.manchester.cs.diff.axiom.change.LogicalAddition; import uk.ac.manchester.cs.diff.axiom.change.LogicalRemoval; /******************************************************************************* * This file is part of ecco. * * ecco is distributed under the terms of the GNU Lesser General Public License (LGPL), Version 3.0. * * Copyright 2011-2014, The University of Manchester * * ecco is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser * General Public License as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * ecco 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 Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ecco. * If not, see http://www.gnu.org/licenses/. ******************************************************************************/ package uk.ac.manchester.cs.diff.axiom.changeset; /** * @author Rafael S. Goncalves <br> * Information Management Group (IMG) <br> * School of Computer Science <br> * University of Manchester <br> */ public class LogicalChangeSet implements AxiomChangeSet { private Set<OWLAxiom> effectualAdditions, ineffectualAdditions, effectualRemovals, ineffectualRemovals; private StructuralChangeSet structuralChangeSet; private double diffTime; /** * Constructor * @param effectualAdditions Effectual additions * @param ineffectualAdditions Ineffectual additions * @param effectualRemovals Effectual removals * @param ineffectualRemovals Ineffectual removals * @param structuralChangeSet Structural change set */ public LogicalChangeSet(Set<OWLAxiom> effectualAdditions, Set<OWLAxiom> ineffectualAdditions, Set<OWLAxiom> effectualRemovals, Set<OWLAxiom> ineffectualRemovals, StructuralChangeSet structuralChangeSet) { this.effectualAdditions = effectualAdditions; this.ineffectualAdditions = ineffectualAdditions; this.effectualRemovals = effectualRemovals; this.ineffectualRemovals = ineffectualRemovals; this.structuralChangeSet = structuralChangeSet; } /** * Get the structural change set between ontologies * @return Structural change set */ public StructuralChangeSet getStructuralChangeSet() { return structuralChangeSet; } /** * Set diff time * @param time Diff time * @deprecated */ public void setDiffTime(double time) { diffTime = time; } /** * Get the CPU time (in seconds) spent in structural diff * @return CPU time (in seconds) spent in structural diff */ public double getOperationTime() { return diffTime; } /** * Get the set of effectual and ineffectual additions * @return Set of effectual and ineffectual additions */ public Set<LogicalAddition> getAdditions() { Set<LogicalAddition> additionSet = new HashSet<LogicalAddition>(); for(OWLAxiom ax : effectualAdditions) additionSet.add(new LogicalAddition(ax, true)); for(OWLAxiom ax : ineffectualAdditions) additionSet.add(new LogicalAddition(ax, false)); return additionSet; } /** * Get the set of effectual and ineffectual removals * @return Set of effectual and ineffectual removals */
public Set<LogicalRemoval> getRemovals() {
Freelander/ting
app/src/main/java/com/music/ting/ui/activity/BaseActivity.java
// Path: app/src/main/java/com/music/ting/ui/fragment/DownLoadFragment.java // public class DownLoadFragment extends Fragment { // // private View view; // // private ImageView downLoadControl, cancelDownLoad; // private NumberProgressBar progressBar; // private TextView songTitle; // public static boolean isDownLoad = false; // private boolean isPause = true; // private FileInfo mFileInfo; // private ProgressReceiver mReceiver; // // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, // @Nullable Bundle savedInstanceState) { // // if (isDownLoad) { // view = inflater.inflate(R.layout.fragment_download, container, false); // registerReceiver(); // // downLoadControl = (ImageView) view.findViewById(R.id.download_control); // cancelDownLoad = (ImageView) view.findViewById(R.id.delete_download); // progressBar = (NumberProgressBar) view.findViewById(R.id.progressBar); // songTitle = (TextView) view.findViewById(R.id.song_title); // // ViewOnClickListener viewOnClickListener = new ViewOnClickListener(); // downLoadControl.setOnClickListener(viewOnClickListener); // cancelDownLoad.setOnClickListener(viewOnClickListener); // // } else { // view = inflater.inflate(R.layout.fragment_not_download, container, false); // } // // // // // // return view; // } // // /** // * 注册广播 // */ // public void registerReceiver(){ // // mReceiver = new ProgressReceiver(); // IntentFilter filter = new IntentFilter(); // filter.addAction(DownloadService.ACTION_UPDATE); // filter.addAction(DownloadService.ACTION_DELETE); // filter.addAction(DownloadService.ACTION_FILEINFO); // filter.addAction(DownloadService.ACTION_OK); // getActivity().registerReceiver(mReceiver, filter); // } // // // /** // * 广播接收器 // */ // public class ProgressReceiver extends BroadcastReceiver{ // // @Override // public void onReceive(Context context, Intent intent) { // String action = intent.getAction(); // if (DownloadService.ACTION_UPDATE.equals(action)) { // int finished = intent.getIntExtra("finished", 0); // progressBar.setProgress(finished); // mFileInfo = (FileInfo) intent.getSerializableExtra("fileInfo"); // songTitle.setText(mFileInfo.getfileName()); // } else if (DownloadService.ACTION_DELETE.equals(action)) { // isDownLoad = false; // stopService(); // DownLoadFragment loadFragment = new DownLoadFragment(); // getFragmentManager().beginTransaction().replace(R.id.container,loadFragment). // show(loadFragment).commit(); // }else if(DownloadService.ACTION_OK.equals(action)){ // isDownLoad = false; // stopService(); // DownLoadFragment loadFragment = new DownLoadFragment(); // getFragmentManager().beginTransaction().replace(R.id.container,loadFragment). // show(loadFragment).commit(); // // } // } // } // // /** // * 暂停服务 // */ // public void stopService(){ // Intent intent = new Intent(view.getContext(),DownloadService.class); // view.getContext().stopService(intent); // // } // // class ViewOnClickListener implements View.OnClickListener { // // @Override // public void onClick(View v) { // Intent intent = new Intent(view.getContext(), DownloadService.class); // switch (v.getId()) { // case R.id.download_control: // if (isPause) { // downLoadControl.setImageResource(R.drawable.ic_fa_arrow_down); // intent.setAction(DownloadService.ACTION_STOP); // intent.putExtra("fileInfo", mFileInfo); // getActivity().startService(intent); // isPause = false; // } else { // downLoadControl.setImageResource(R.drawable.ic_fa_pause); // intent.setAction(DownloadService.ACTION_START); // intent.putExtra("fileInfo", mFileInfo); // getActivity().startService(intent); // isPause = true; // } // break; // case R.id.delete_download: // stopService(); // intent.setAction(DownloadService.ACTION_DELETE); // intent.putExtra("fileInfo", mFileInfo); // getActivity().startService(intent); // break; // // } // } // } // // // }
import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.widget.Toast; import com.music.ting.R; import com.music.ting.ui.fragment.DownLoadFragment;
package com.music.ting.ui.activity; /** * Created by Jun on 2015/5/15. */ public class BaseActivity extends ActionBarActivity { private Toolbar toolbar; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } public void initToolbar(){ toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setHomeButtonEnabled(true);//设置返回键可用 getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.action_setting: Toast.makeText(this,"设置",Toast.LENGTH_SHORT).show(); break; case R.id.action_download_setting:
// Path: app/src/main/java/com/music/ting/ui/fragment/DownLoadFragment.java // public class DownLoadFragment extends Fragment { // // private View view; // // private ImageView downLoadControl, cancelDownLoad; // private NumberProgressBar progressBar; // private TextView songTitle; // public static boolean isDownLoad = false; // private boolean isPause = true; // private FileInfo mFileInfo; // private ProgressReceiver mReceiver; // // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, // @Nullable Bundle savedInstanceState) { // // if (isDownLoad) { // view = inflater.inflate(R.layout.fragment_download, container, false); // registerReceiver(); // // downLoadControl = (ImageView) view.findViewById(R.id.download_control); // cancelDownLoad = (ImageView) view.findViewById(R.id.delete_download); // progressBar = (NumberProgressBar) view.findViewById(R.id.progressBar); // songTitle = (TextView) view.findViewById(R.id.song_title); // // ViewOnClickListener viewOnClickListener = new ViewOnClickListener(); // downLoadControl.setOnClickListener(viewOnClickListener); // cancelDownLoad.setOnClickListener(viewOnClickListener); // // } else { // view = inflater.inflate(R.layout.fragment_not_download, container, false); // } // // // // // // return view; // } // // /** // * 注册广播 // */ // public void registerReceiver(){ // // mReceiver = new ProgressReceiver(); // IntentFilter filter = new IntentFilter(); // filter.addAction(DownloadService.ACTION_UPDATE); // filter.addAction(DownloadService.ACTION_DELETE); // filter.addAction(DownloadService.ACTION_FILEINFO); // filter.addAction(DownloadService.ACTION_OK); // getActivity().registerReceiver(mReceiver, filter); // } // // // /** // * 广播接收器 // */ // public class ProgressReceiver extends BroadcastReceiver{ // // @Override // public void onReceive(Context context, Intent intent) { // String action = intent.getAction(); // if (DownloadService.ACTION_UPDATE.equals(action)) { // int finished = intent.getIntExtra("finished", 0); // progressBar.setProgress(finished); // mFileInfo = (FileInfo) intent.getSerializableExtra("fileInfo"); // songTitle.setText(mFileInfo.getfileName()); // } else if (DownloadService.ACTION_DELETE.equals(action)) { // isDownLoad = false; // stopService(); // DownLoadFragment loadFragment = new DownLoadFragment(); // getFragmentManager().beginTransaction().replace(R.id.container,loadFragment). // show(loadFragment).commit(); // }else if(DownloadService.ACTION_OK.equals(action)){ // isDownLoad = false; // stopService(); // DownLoadFragment loadFragment = new DownLoadFragment(); // getFragmentManager().beginTransaction().replace(R.id.container,loadFragment). // show(loadFragment).commit(); // // } // } // } // // /** // * 暂停服务 // */ // public void stopService(){ // Intent intent = new Intent(view.getContext(),DownloadService.class); // view.getContext().stopService(intent); // // } // // class ViewOnClickListener implements View.OnClickListener { // // @Override // public void onClick(View v) { // Intent intent = new Intent(view.getContext(), DownloadService.class); // switch (v.getId()) { // case R.id.download_control: // if (isPause) { // downLoadControl.setImageResource(R.drawable.ic_fa_arrow_down); // intent.setAction(DownloadService.ACTION_STOP); // intent.putExtra("fileInfo", mFileInfo); // getActivity().startService(intent); // isPause = false; // } else { // downLoadControl.setImageResource(R.drawable.ic_fa_pause); // intent.setAction(DownloadService.ACTION_START); // intent.putExtra("fileInfo", mFileInfo); // getActivity().startService(intent); // isPause = true; // } // break; // case R.id.delete_download: // stopService(); // intent.setAction(DownloadService.ACTION_DELETE); // intent.putExtra("fileInfo", mFileInfo); // getActivity().startService(intent); // break; // // } // } // } // // // } // Path: app/src/main/java/com/music/ting/ui/activity/BaseActivity.java import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.widget.Toast; import com.music.ting.R; import com.music.ting.ui.fragment.DownLoadFragment; package com.music.ting.ui.activity; /** * Created by Jun on 2015/5/15. */ public class BaseActivity extends ActionBarActivity { private Toolbar toolbar; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } public void initToolbar(){ toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setHomeButtonEnabled(true);//设置返回键可用 getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.action_setting: Toast.makeText(this,"设置",Toast.LENGTH_SHORT).show(); break; case R.id.action_download_setting:
DownLoadFragment downLoad = new DownLoadFragment();
Freelander/ting
app/src/main/java/com/music/ting/ui/activity/MainActivity.java
// Path: app/src/main/java/com/music/ting/model/DrawerListBean.java // public class DrawerListBean { // // private String title; // private int titleImageId; // // public DrawerListBean(String title, int titleImageId){ // this.title = title; // this.titleImageId = titleImageId; // } // public void setTitle(String title) { // this.title = title; // } // // public String getTitle() { // return title; // } // // public void setTitleImageId(int titleImageId){ // this.titleImageId = titleImageId; // } // public int getTitleImageId(){ // return titleImageId; // } // } // // Path: app/src/main/java/com/music/ting/ui/fragment/SongsListFragment.java // public class SongsListFragment extends Fragment { // // private ListView songListView; // private SwipeRefreshLayout songSwipe; // private View view; // private List<Songs> songsList = new ArrayList<Songs>(); // // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // view = inflater.inflate(R.layout.fragment_songs_list,container,false); // // songListView = (ListView) view.findViewById(R.id.songs_list); // songSwipe = (SwipeRefreshLayout) view.findViewById(R.id.song_swipe); // // //给刷新控件一个颜色 // songSwipe.setColorSchemeColors(R.color.colorPrimary, R.color.colorPrimary, // R.color.colorPrimary,R.color.colorPrimary); // //刚进入到界面设置刷新控件正在刷新 // songSwipe.post(new Runnable() { // @Override // public void run() { // songSwipe.setRefreshing(true); // } // }); // //加载数据 // initData(20); // /** // * 刷新控件监听事件 // */ // songSwipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { // @Override // public void onRefresh() { // initData(20); // } // }); // // // songListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { // @Override // public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // // Intent intent = new Intent(view.getContext(), CommentActivity.class); // intent.putExtra("Songs",songsList.get(position)); // startActivity(intent); // } // }); // // return view; // } // // /** // * 初始化数据 // */ // public void initData(final int songCount){ // final GsonRequest<List<Songs>> request = TingAPI.getSongsRequest(songCount); // // final Response.Listener<List<Songs>> response = new Response.Listener<List<Songs>>() { // @Override // public void onResponse(List<Songs> songs) { // songsList = songs; // songListView.setAdapter(new SongsListAdapter(view.getContext(), // R.layout.item_songs_list,songsList)); // songSwipe.setRefreshing(false); // } // }; // request.setSuccessListener(response); // RequestManager.addRequest(request, null); // } // }
import android.os.Bundle; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.View; import android.widget.AdapterView; import android.widget.LinearLayout; import android.widget.ListView; import com.music.ting.R; import com.music.ting.adapter.DrawerListAdapter; import com.music.ting.model.DrawerListBean; import com.music.ting.ui.fragment.LocalSongsFragment; import com.music.ting.ui.fragment.SongsListFragment; import java.util.ArrayList; import java.util.List;
package com.music.ting.ui.activity; /** * Created by Jun on 2015/5/10. */ public class MainActivity extends BaseActivity { private DrawerLayout mDrawerLayout; private ActionBarDrawerToggle mDrawerToggle; private Toolbar toolbar; private ListView drawerListView; private LinearLayout drawerLayout;//抽屉布局 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initToolbar();
// Path: app/src/main/java/com/music/ting/model/DrawerListBean.java // public class DrawerListBean { // // private String title; // private int titleImageId; // // public DrawerListBean(String title, int titleImageId){ // this.title = title; // this.titleImageId = titleImageId; // } // public void setTitle(String title) { // this.title = title; // } // // public String getTitle() { // return title; // } // // public void setTitleImageId(int titleImageId){ // this.titleImageId = titleImageId; // } // public int getTitleImageId(){ // return titleImageId; // } // } // // Path: app/src/main/java/com/music/ting/ui/fragment/SongsListFragment.java // public class SongsListFragment extends Fragment { // // private ListView songListView; // private SwipeRefreshLayout songSwipe; // private View view; // private List<Songs> songsList = new ArrayList<Songs>(); // // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // view = inflater.inflate(R.layout.fragment_songs_list,container,false); // // songListView = (ListView) view.findViewById(R.id.songs_list); // songSwipe = (SwipeRefreshLayout) view.findViewById(R.id.song_swipe); // // //给刷新控件一个颜色 // songSwipe.setColorSchemeColors(R.color.colorPrimary, R.color.colorPrimary, // R.color.colorPrimary,R.color.colorPrimary); // //刚进入到界面设置刷新控件正在刷新 // songSwipe.post(new Runnable() { // @Override // public void run() { // songSwipe.setRefreshing(true); // } // }); // //加载数据 // initData(20); // /** // * 刷新控件监听事件 // */ // songSwipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { // @Override // public void onRefresh() { // initData(20); // } // }); // // // songListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { // @Override // public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // // Intent intent = new Intent(view.getContext(), CommentActivity.class); // intent.putExtra("Songs",songsList.get(position)); // startActivity(intent); // } // }); // // return view; // } // // /** // * 初始化数据 // */ // public void initData(final int songCount){ // final GsonRequest<List<Songs>> request = TingAPI.getSongsRequest(songCount); // // final Response.Listener<List<Songs>> response = new Response.Listener<List<Songs>>() { // @Override // public void onResponse(List<Songs> songs) { // songsList = songs; // songListView.setAdapter(new SongsListAdapter(view.getContext(), // R.layout.item_songs_list,songsList)); // songSwipe.setRefreshing(false); // } // }; // request.setSuccessListener(response); // RequestManager.addRequest(request, null); // } // } // Path: app/src/main/java/com/music/ting/ui/activity/MainActivity.java import android.os.Bundle; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.View; import android.widget.AdapterView; import android.widget.LinearLayout; import android.widget.ListView; import com.music.ting.R; import com.music.ting.adapter.DrawerListAdapter; import com.music.ting.model.DrawerListBean; import com.music.ting.ui.fragment.LocalSongsFragment; import com.music.ting.ui.fragment.SongsListFragment; import java.util.ArrayList; import java.util.List; package com.music.ting.ui.activity; /** * Created by Jun on 2015/5/10. */ public class MainActivity extends BaseActivity { private DrawerLayout mDrawerLayout; private ActionBarDrawerToggle mDrawerToggle; private Toolbar toolbar; private ListView drawerListView; private LinearLayout drawerLayout;//抽屉布局 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initToolbar();
SongsListFragment fragment = new SongsListFragment();
Freelander/ting
app/src/main/java/com/music/ting/ui/activity/MainActivity.java
// Path: app/src/main/java/com/music/ting/model/DrawerListBean.java // public class DrawerListBean { // // private String title; // private int titleImageId; // // public DrawerListBean(String title, int titleImageId){ // this.title = title; // this.titleImageId = titleImageId; // } // public void setTitle(String title) { // this.title = title; // } // // public String getTitle() { // return title; // } // // public void setTitleImageId(int titleImageId){ // this.titleImageId = titleImageId; // } // public int getTitleImageId(){ // return titleImageId; // } // } // // Path: app/src/main/java/com/music/ting/ui/fragment/SongsListFragment.java // public class SongsListFragment extends Fragment { // // private ListView songListView; // private SwipeRefreshLayout songSwipe; // private View view; // private List<Songs> songsList = new ArrayList<Songs>(); // // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // view = inflater.inflate(R.layout.fragment_songs_list,container,false); // // songListView = (ListView) view.findViewById(R.id.songs_list); // songSwipe = (SwipeRefreshLayout) view.findViewById(R.id.song_swipe); // // //给刷新控件一个颜色 // songSwipe.setColorSchemeColors(R.color.colorPrimary, R.color.colorPrimary, // R.color.colorPrimary,R.color.colorPrimary); // //刚进入到界面设置刷新控件正在刷新 // songSwipe.post(new Runnable() { // @Override // public void run() { // songSwipe.setRefreshing(true); // } // }); // //加载数据 // initData(20); // /** // * 刷新控件监听事件 // */ // songSwipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { // @Override // public void onRefresh() { // initData(20); // } // }); // // // songListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { // @Override // public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // // Intent intent = new Intent(view.getContext(), CommentActivity.class); // intent.putExtra("Songs",songsList.get(position)); // startActivity(intent); // } // }); // // return view; // } // // /** // * 初始化数据 // */ // public void initData(final int songCount){ // final GsonRequest<List<Songs>> request = TingAPI.getSongsRequest(songCount); // // final Response.Listener<List<Songs>> response = new Response.Listener<List<Songs>>() { // @Override // public void onResponse(List<Songs> songs) { // songsList = songs; // songListView.setAdapter(new SongsListAdapter(view.getContext(), // R.layout.item_songs_list,songsList)); // songSwipe.setRefreshing(false); // } // }; // request.setSuccessListener(response); // RequestManager.addRequest(request, null); // } // }
import android.os.Bundle; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.View; import android.widget.AdapterView; import android.widget.LinearLayout; import android.widget.ListView; import com.music.ting.R; import com.music.ting.adapter.DrawerListAdapter; import com.music.ting.model.DrawerListBean; import com.music.ting.ui.fragment.LocalSongsFragment; import com.music.ting.ui.fragment.SongsListFragment; import java.util.ArrayList; import java.util.List;
switch (position){ case 0: //立即欣赏 SongsListFragment fragment = new SongsListFragment(); getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment) .show(fragment).commit(); mDrawerLayout.closeDrawer(drawerLayout); break; case 1: //我的乐库 LocalSongsFragment localSongsFragment = new LocalSongsFragment(); getSupportFragmentManager().beginTransaction() .replace(R.id.container, localSongsFragment) .show(localSongsFragment).commit(); mDrawerLayout.closeDrawer(drawerLayout); break; } //记录当前选中的位置 adapter.setSelectedPosition(position); adapter.notifyDataSetChanged(); } }); } /** * 抽屉导航 ListView 数据 * @return */
// Path: app/src/main/java/com/music/ting/model/DrawerListBean.java // public class DrawerListBean { // // private String title; // private int titleImageId; // // public DrawerListBean(String title, int titleImageId){ // this.title = title; // this.titleImageId = titleImageId; // } // public void setTitle(String title) { // this.title = title; // } // // public String getTitle() { // return title; // } // // public void setTitleImageId(int titleImageId){ // this.titleImageId = titleImageId; // } // public int getTitleImageId(){ // return titleImageId; // } // } // // Path: app/src/main/java/com/music/ting/ui/fragment/SongsListFragment.java // public class SongsListFragment extends Fragment { // // private ListView songListView; // private SwipeRefreshLayout songSwipe; // private View view; // private List<Songs> songsList = new ArrayList<Songs>(); // // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // view = inflater.inflate(R.layout.fragment_songs_list,container,false); // // songListView = (ListView) view.findViewById(R.id.songs_list); // songSwipe = (SwipeRefreshLayout) view.findViewById(R.id.song_swipe); // // //给刷新控件一个颜色 // songSwipe.setColorSchemeColors(R.color.colorPrimary, R.color.colorPrimary, // R.color.colorPrimary,R.color.colorPrimary); // //刚进入到界面设置刷新控件正在刷新 // songSwipe.post(new Runnable() { // @Override // public void run() { // songSwipe.setRefreshing(true); // } // }); // //加载数据 // initData(20); // /** // * 刷新控件监听事件 // */ // songSwipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { // @Override // public void onRefresh() { // initData(20); // } // }); // // // songListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { // @Override // public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // // Intent intent = new Intent(view.getContext(), CommentActivity.class); // intent.putExtra("Songs",songsList.get(position)); // startActivity(intent); // } // }); // // return view; // } // // /** // * 初始化数据 // */ // public void initData(final int songCount){ // final GsonRequest<List<Songs>> request = TingAPI.getSongsRequest(songCount); // // final Response.Listener<List<Songs>> response = new Response.Listener<List<Songs>>() { // @Override // public void onResponse(List<Songs> songs) { // songsList = songs; // songListView.setAdapter(new SongsListAdapter(view.getContext(), // R.layout.item_songs_list,songsList)); // songSwipe.setRefreshing(false); // } // }; // request.setSuccessListener(response); // RequestManager.addRequest(request, null); // } // } // Path: app/src/main/java/com/music/ting/ui/activity/MainActivity.java import android.os.Bundle; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.View; import android.widget.AdapterView; import android.widget.LinearLayout; import android.widget.ListView; import com.music.ting.R; import com.music.ting.adapter.DrawerListAdapter; import com.music.ting.model.DrawerListBean; import com.music.ting.ui.fragment.LocalSongsFragment; import com.music.ting.ui.fragment.SongsListFragment; import java.util.ArrayList; import java.util.List; switch (position){ case 0: //立即欣赏 SongsListFragment fragment = new SongsListFragment(); getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment) .show(fragment).commit(); mDrawerLayout.closeDrawer(drawerLayout); break; case 1: //我的乐库 LocalSongsFragment localSongsFragment = new LocalSongsFragment(); getSupportFragmentManager().beginTransaction() .replace(R.id.container, localSongsFragment) .show(localSongsFragment).commit(); mDrawerLayout.closeDrawer(drawerLayout); break; } //记录当前选中的位置 adapter.setSelectedPosition(position); adapter.notifyDataSetChanged(); } }); } /** * 抽屉导航 ListView 数据 * @return */
public List<DrawerListBean> initDrawerList(){
Freelander/ting
app/src/main/java/com/music/ting/ui/fragment/LikeSongsListFragment.java
// Path: app/src/main/java/com/music/ting/data/GsonRequest.java // public class GsonRequest<T> extends Request<T> { // private static final String TAG = "Ting"; // // private Gson GSON = new Gson(); // // private final Class<T> mClazz; // private Type type ; // // private Listener mListener; // private Map<String, String> mHeader; // // public GsonRequest(int method, String url, Class<T> clazz, Map<String, String> header, // Listener<T> listener, ErrorListener errorListener) { // super(method, url, errorListener); // mClazz = clazz; // mListener = listener; // mHeader = header; // } // // public GsonRequest(String url, ErrorListener errorListener){ // this(Method.GET, url, null, null, errorListener); // type = new TypeToken<List<Songs>>(){ // }.getType(); // } // public GsonRequest(String url,Class clazz, ErrorListener errorListener){ // this(Method.GET, url,clazz, null, null, errorListener); // type = new TypeToken<List<Comments>>(){ // }.getType(); // } // // // public GsonRequest(int method, String url, Class<T> clazz, Map<String, String> header, // ErrorListener errorListener) { // this(method, url, clazz, header, null, errorListener); // } // // public GsonRequest(String url, Class clazz, Listener<T> listener, ErrorListener errorListener) { // this(Method.GET, url, clazz, null, listener, errorListener); // } // // @Override // protected Response parseNetworkResponse(NetworkResponse response) { // try { // String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); // if (type != null) { // return Response.success(GSON.fromJson(json, type), // HttpHeaderParser.parseCacheHeaders(response)); // } else { // return Response.success(GSON.fromJson(json, mClazz), // HttpHeaderParser.parseCacheHeaders(response)); // } // } catch (UnsupportedEncodingException e) { // Log.e(TAG, e.getMessage(), e); // return Response.error(new ParseError(e)); // } catch (JsonSyntaxException e) { // Log.e(TAG, e.getMessage(), e); // return Response.error(new ParseError(e)); // } // } // // @Override // protected void deliverResponse(T response) { // if (mListener != null) { // mListener.onResponse(response); // } // } // // public void setSuccessListener(Listener listener) { // mListener = listener; // } // // } // // Path: app/src/main/java/com/music/ting/data/RequestManager.java // public final class RequestManager { // // private static final RequestQueue mRequestQueue = Volley.newRequestQueue(Ting.getInstance()); // // private RequestManager(){ // // } // // public static void addRequest(Request<?> request, Object tag){ // if(tag != null) { // request.setTag(tag); // } // mRequestQueue.add(request); // } // // public static void cancelAll(Object tag ){ // mRequestQueue.cancelAll(tag); // } // // public static RequestQueue getRequestQueue(){ // return mRequestQueue; // } // }
import android.annotation.SuppressLint; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.android.volley.Response; import com.music.ting.R; import com.music.ting.adapter.LikeSongsAdapter; import com.music.ting.data.GsonRequest; import com.music.ting.data.RequestManager; import com.music.ting.model.user.UserLikeSongs; import com.music.ting.utils.TingAPI; import butterknife.ButterKnife; import butterknife.InjectView;
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_user_songs, container, false); ButterKnife.inject(this, view); recyclerView.setLayoutManager(new LinearLayoutManager(view.getContext())); songsSwipe.setColorSchemeColors(R.color.colorPrimary, R.color.colorPrimary, R.color.colorPrimary, R.color.colorPrimary); songsSwipe.post(new Runnable() { @Override public void run() { songsSwipe.setRefreshing(true); } }); initData(); songsSwipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { initData(); } }); return view; } public void initData(){
// Path: app/src/main/java/com/music/ting/data/GsonRequest.java // public class GsonRequest<T> extends Request<T> { // private static final String TAG = "Ting"; // // private Gson GSON = new Gson(); // // private final Class<T> mClazz; // private Type type ; // // private Listener mListener; // private Map<String, String> mHeader; // // public GsonRequest(int method, String url, Class<T> clazz, Map<String, String> header, // Listener<T> listener, ErrorListener errorListener) { // super(method, url, errorListener); // mClazz = clazz; // mListener = listener; // mHeader = header; // } // // public GsonRequest(String url, ErrorListener errorListener){ // this(Method.GET, url, null, null, errorListener); // type = new TypeToken<List<Songs>>(){ // }.getType(); // } // public GsonRequest(String url,Class clazz, ErrorListener errorListener){ // this(Method.GET, url,clazz, null, null, errorListener); // type = new TypeToken<List<Comments>>(){ // }.getType(); // } // // // public GsonRequest(int method, String url, Class<T> clazz, Map<String, String> header, // ErrorListener errorListener) { // this(method, url, clazz, header, null, errorListener); // } // // public GsonRequest(String url, Class clazz, Listener<T> listener, ErrorListener errorListener) { // this(Method.GET, url, clazz, null, listener, errorListener); // } // // @Override // protected Response parseNetworkResponse(NetworkResponse response) { // try { // String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); // if (type != null) { // return Response.success(GSON.fromJson(json, type), // HttpHeaderParser.parseCacheHeaders(response)); // } else { // return Response.success(GSON.fromJson(json, mClazz), // HttpHeaderParser.parseCacheHeaders(response)); // } // } catch (UnsupportedEncodingException e) { // Log.e(TAG, e.getMessage(), e); // return Response.error(new ParseError(e)); // } catch (JsonSyntaxException e) { // Log.e(TAG, e.getMessage(), e); // return Response.error(new ParseError(e)); // } // } // // @Override // protected void deliverResponse(T response) { // if (mListener != null) { // mListener.onResponse(response); // } // } // // public void setSuccessListener(Listener listener) { // mListener = listener; // } // // } // // Path: app/src/main/java/com/music/ting/data/RequestManager.java // public final class RequestManager { // // private static final RequestQueue mRequestQueue = Volley.newRequestQueue(Ting.getInstance()); // // private RequestManager(){ // // } // // public static void addRequest(Request<?> request, Object tag){ // if(tag != null) { // request.setTag(tag); // } // mRequestQueue.add(request); // } // // public static void cancelAll(Object tag ){ // mRequestQueue.cancelAll(tag); // } // // public static RequestQueue getRequestQueue(){ // return mRequestQueue; // } // } // Path: app/src/main/java/com/music/ting/ui/fragment/LikeSongsListFragment.java import android.annotation.SuppressLint; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.android.volley.Response; import com.music.ting.R; import com.music.ting.adapter.LikeSongsAdapter; import com.music.ting.data.GsonRequest; import com.music.ting.data.RequestManager; import com.music.ting.model.user.UserLikeSongs; import com.music.ting.utils.TingAPI; import butterknife.ButterKnife; import butterknife.InjectView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_user_songs, container, false); ButterKnife.inject(this, view); recyclerView.setLayoutManager(new LinearLayoutManager(view.getContext())); songsSwipe.setColorSchemeColors(R.color.colorPrimary, R.color.colorPrimary, R.color.colorPrimary, R.color.colorPrimary); songsSwipe.post(new Runnable() { @Override public void run() { songsSwipe.setRefreshing(true); } }); initData(); songsSwipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { initData(); } }); return view; } public void initData(){
final GsonRequest<UserLikeSongs> request = TingAPI.getUserLikeSongs(userId);
Freelander/ting
app/src/main/java/com/music/ting/ui/fragment/LikeSongsListFragment.java
// Path: app/src/main/java/com/music/ting/data/GsonRequest.java // public class GsonRequest<T> extends Request<T> { // private static final String TAG = "Ting"; // // private Gson GSON = new Gson(); // // private final Class<T> mClazz; // private Type type ; // // private Listener mListener; // private Map<String, String> mHeader; // // public GsonRequest(int method, String url, Class<T> clazz, Map<String, String> header, // Listener<T> listener, ErrorListener errorListener) { // super(method, url, errorListener); // mClazz = clazz; // mListener = listener; // mHeader = header; // } // // public GsonRequest(String url, ErrorListener errorListener){ // this(Method.GET, url, null, null, errorListener); // type = new TypeToken<List<Songs>>(){ // }.getType(); // } // public GsonRequest(String url,Class clazz, ErrorListener errorListener){ // this(Method.GET, url,clazz, null, null, errorListener); // type = new TypeToken<List<Comments>>(){ // }.getType(); // } // // // public GsonRequest(int method, String url, Class<T> clazz, Map<String, String> header, // ErrorListener errorListener) { // this(method, url, clazz, header, null, errorListener); // } // // public GsonRequest(String url, Class clazz, Listener<T> listener, ErrorListener errorListener) { // this(Method.GET, url, clazz, null, listener, errorListener); // } // // @Override // protected Response parseNetworkResponse(NetworkResponse response) { // try { // String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); // if (type != null) { // return Response.success(GSON.fromJson(json, type), // HttpHeaderParser.parseCacheHeaders(response)); // } else { // return Response.success(GSON.fromJson(json, mClazz), // HttpHeaderParser.parseCacheHeaders(response)); // } // } catch (UnsupportedEncodingException e) { // Log.e(TAG, e.getMessage(), e); // return Response.error(new ParseError(e)); // } catch (JsonSyntaxException e) { // Log.e(TAG, e.getMessage(), e); // return Response.error(new ParseError(e)); // } // } // // @Override // protected void deliverResponse(T response) { // if (mListener != null) { // mListener.onResponse(response); // } // } // // public void setSuccessListener(Listener listener) { // mListener = listener; // } // // } // // Path: app/src/main/java/com/music/ting/data/RequestManager.java // public final class RequestManager { // // private static final RequestQueue mRequestQueue = Volley.newRequestQueue(Ting.getInstance()); // // private RequestManager(){ // // } // // public static void addRequest(Request<?> request, Object tag){ // if(tag != null) { // request.setTag(tag); // } // mRequestQueue.add(request); // } // // public static void cancelAll(Object tag ){ // mRequestQueue.cancelAll(tag); // } // // public static RequestQueue getRequestQueue(){ // return mRequestQueue; // } // }
import android.annotation.SuppressLint; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.android.volley.Response; import com.music.ting.R; import com.music.ting.adapter.LikeSongsAdapter; import com.music.ting.data.GsonRequest; import com.music.ting.data.RequestManager; import com.music.ting.model.user.UserLikeSongs; import com.music.ting.utils.TingAPI; import butterknife.ButterKnife; import butterknife.InjectView;
@Override public void run() { songsSwipe.setRefreshing(true); } }); initData(); songsSwipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { initData(); } }); return view; } public void initData(){ final GsonRequest<UserLikeSongs> request = TingAPI.getUserLikeSongs(userId); final Response.Listener<UserLikeSongs> response = new Response.Listener<UserLikeSongs>() { @Override public void onResponse(UserLikeSongs songs) { Log.i("UserSongs",songs.toString()+",UserId:"+userId); recyclerView.setAdapter(new LikeSongsAdapter(view.getContext(), songs)); songsSwipe.setRefreshing(false); } }; request.setSuccessListener(response);
// Path: app/src/main/java/com/music/ting/data/GsonRequest.java // public class GsonRequest<T> extends Request<T> { // private static final String TAG = "Ting"; // // private Gson GSON = new Gson(); // // private final Class<T> mClazz; // private Type type ; // // private Listener mListener; // private Map<String, String> mHeader; // // public GsonRequest(int method, String url, Class<T> clazz, Map<String, String> header, // Listener<T> listener, ErrorListener errorListener) { // super(method, url, errorListener); // mClazz = clazz; // mListener = listener; // mHeader = header; // } // // public GsonRequest(String url, ErrorListener errorListener){ // this(Method.GET, url, null, null, errorListener); // type = new TypeToken<List<Songs>>(){ // }.getType(); // } // public GsonRequest(String url,Class clazz, ErrorListener errorListener){ // this(Method.GET, url,clazz, null, null, errorListener); // type = new TypeToken<List<Comments>>(){ // }.getType(); // } // // // public GsonRequest(int method, String url, Class<T> clazz, Map<String, String> header, // ErrorListener errorListener) { // this(method, url, clazz, header, null, errorListener); // } // // public GsonRequest(String url, Class clazz, Listener<T> listener, ErrorListener errorListener) { // this(Method.GET, url, clazz, null, listener, errorListener); // } // // @Override // protected Response parseNetworkResponse(NetworkResponse response) { // try { // String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); // if (type != null) { // return Response.success(GSON.fromJson(json, type), // HttpHeaderParser.parseCacheHeaders(response)); // } else { // return Response.success(GSON.fromJson(json, mClazz), // HttpHeaderParser.parseCacheHeaders(response)); // } // } catch (UnsupportedEncodingException e) { // Log.e(TAG, e.getMessage(), e); // return Response.error(new ParseError(e)); // } catch (JsonSyntaxException e) { // Log.e(TAG, e.getMessage(), e); // return Response.error(new ParseError(e)); // } // } // // @Override // protected void deliverResponse(T response) { // if (mListener != null) { // mListener.onResponse(response); // } // } // // public void setSuccessListener(Listener listener) { // mListener = listener; // } // // } // // Path: app/src/main/java/com/music/ting/data/RequestManager.java // public final class RequestManager { // // private static final RequestQueue mRequestQueue = Volley.newRequestQueue(Ting.getInstance()); // // private RequestManager(){ // // } // // public static void addRequest(Request<?> request, Object tag){ // if(tag != null) { // request.setTag(tag); // } // mRequestQueue.add(request); // } // // public static void cancelAll(Object tag ){ // mRequestQueue.cancelAll(tag); // } // // public static RequestQueue getRequestQueue(){ // return mRequestQueue; // } // } // Path: app/src/main/java/com/music/ting/ui/fragment/LikeSongsListFragment.java import android.annotation.SuppressLint; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.android.volley.Response; import com.music.ting.R; import com.music.ting.adapter.LikeSongsAdapter; import com.music.ting.data.GsonRequest; import com.music.ting.data.RequestManager; import com.music.ting.model.user.UserLikeSongs; import com.music.ting.utils.TingAPI; import butterknife.ButterKnife; import butterknife.InjectView; @Override public void run() { songsSwipe.setRefreshing(true); } }); initData(); songsSwipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { initData(); } }); return view; } public void initData(){ final GsonRequest<UserLikeSongs> request = TingAPI.getUserLikeSongs(userId); final Response.Listener<UserLikeSongs> response = new Response.Listener<UserLikeSongs>() { @Override public void onResponse(UserLikeSongs songs) { Log.i("UserSongs",songs.toString()+",UserId:"+userId); recyclerView.setAdapter(new LikeSongsAdapter(view.getContext(), songs)); songsSwipe.setRefreshing(false); } }; request.setSuccessListener(response);
RequestManager.addRequest(request, userId);
Freelander/ting
app/src/main/java/com/music/ting/ui/fragment/DownLoadFragment.java
// Path: app/src/main/java/com/music/ting/model/FileInfo.java // public class FileInfo implements Serializable { // // private int id; // private String url; // private String fileName; // private int length; // private int finished; // // public FileInfo() { // } // // public FileInfo(int id, String url, String fileName, int length, int finished) { // this.id = id; // this.url = url; // this.fileName = fileName; // this.length = length; // this.finished = finished; // } // // @Override // public String toString() { // return "FileInfo{" + // "id=" + id + // ", url='" + url + '\'' + // ", fileName='" + fileName + '\'' + // ", length=" + length + // ", finished=" + finished + // '}'; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getfileName() { // return fileName; // } // // public void setfileName(String fileName) { // this.fileName = fileName; // } // // public int getLength() { // return length; // } // // public void setLength(int length) { // this.length = length; // } // // public int getFinished() { // return finished; // } // // public void setFinished(int finished) { // this.finished = finished; // } // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.daimajia.numberprogressbar.NumberProgressBar; import com.music.ting.R; import com.music.ting.model.FileInfo; import com.music.ting.service.DownloadService;
package com.music.ting.ui.fragment; /** * Created by Jun on 2015/6/6. */ public class DownLoadFragment extends Fragment { private View view; private ImageView downLoadControl, cancelDownLoad; private NumberProgressBar progressBar; private TextView songTitle; public static boolean isDownLoad = false; private boolean isPause = true;
// Path: app/src/main/java/com/music/ting/model/FileInfo.java // public class FileInfo implements Serializable { // // private int id; // private String url; // private String fileName; // private int length; // private int finished; // // public FileInfo() { // } // // public FileInfo(int id, String url, String fileName, int length, int finished) { // this.id = id; // this.url = url; // this.fileName = fileName; // this.length = length; // this.finished = finished; // } // // @Override // public String toString() { // return "FileInfo{" + // "id=" + id + // ", url='" + url + '\'' + // ", fileName='" + fileName + '\'' + // ", length=" + length + // ", finished=" + finished + // '}'; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public String getfileName() { // return fileName; // } // // public void setfileName(String fileName) { // this.fileName = fileName; // } // // public int getLength() { // return length; // } // // public void setLength(int length) { // this.length = length; // } // // public int getFinished() { // return finished; // } // // public void setFinished(int finished) { // this.finished = finished; // } // } // Path: app/src/main/java/com/music/ting/ui/fragment/DownLoadFragment.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.daimajia.numberprogressbar.NumberProgressBar; import com.music.ting.R; import com.music.ting.model.FileInfo; import com.music.ting.service.DownloadService; package com.music.ting.ui.fragment; /** * Created by Jun on 2015/6/6. */ public class DownLoadFragment extends Fragment { private View view; private ImageView downLoadControl, cancelDownLoad; private NumberProgressBar progressBar; private TextView songTitle; public static boolean isDownLoad = false; private boolean isPause = true;
private FileInfo mFileInfo;
Freelander/ting
app/src/main/java/com/music/ting/db/ThreadDAOImpl.java
// Path: app/src/main/java/com/music/ting/model/ThreadInfo.java // public class ThreadInfo { // // private int id; // private String url; // private int start; // private int end; // private int finished; // // public ThreadInfo() { // } // // public ThreadInfo(int id, String url, int start, int end, int finished) { // this.id = id; // this.url = url; // this.start = start; // this.end = end; // this.finished = finished; // } // // @Override // public String toString() { // return "ThreadInfo{" + // "id=" + id + // ", url='" + url + '\'' + // ", start=" + start + // ", end=" + end + // ", finished=" + finished + // '}'; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public int getStart() { // return start; // } // // public void setStart(int start) { // this.start = start; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public int getEnd() { // return end; // } // // public void setEnd(int end) { // this.end = end; // } // // public int getFinished() { // return finished; // } // // public void setFinished(int finished) { // this.finished = finished; // } // }
import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.music.ting.model.ThreadInfo; import java.util.ArrayList; import java.util.List;
package com.music.ting.db; /** * Created by Jun on 2015/6/4. * 数据访问接口实现 */ public class ThreadDAOImpl implements ThreadDAO { private DBHelper mHelper = null; public ThreadDAOImpl(Context context){ mHelper = new DBHelper(context);//创建数据访问对象 } @Override
// Path: app/src/main/java/com/music/ting/model/ThreadInfo.java // public class ThreadInfo { // // private int id; // private String url; // private int start; // private int end; // private int finished; // // public ThreadInfo() { // } // // public ThreadInfo(int id, String url, int start, int end, int finished) { // this.id = id; // this.url = url; // this.start = start; // this.end = end; // this.finished = finished; // } // // @Override // public String toString() { // return "ThreadInfo{" + // "id=" + id + // ", url='" + url + '\'' + // ", start=" + start + // ", end=" + end + // ", finished=" + finished + // '}'; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public int getStart() { // return start; // } // // public void setStart(int start) { // this.start = start; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // // public int getEnd() { // return end; // } // // public void setEnd(int end) { // this.end = end; // } // // public int getFinished() { // return finished; // } // // public void setFinished(int finished) { // this.finished = finished; // } // } // Path: app/src/main/java/com/music/ting/db/ThreadDAOImpl.java import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.music.ting.model.ThreadInfo; import java.util.ArrayList; import java.util.List; package com.music.ting.db; /** * Created by Jun on 2015/6/4. * 数据访问接口实现 */ public class ThreadDAOImpl implements ThreadDAO { private DBHelper mHelper = null; public ThreadDAOImpl(Context context){ mHelper = new DBHelper(context);//创建数据访问对象 } @Override
public void insertThread(ThreadInfo threadInfo) {
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenterImp.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java // public interface SubjectUseCase extends Interactor { // // interface Callback { // void onMissionAccomplished(Subject subject); // void onError(SubjectException ex); // } // // public void execute(Subject subject, final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java // public interface GetSubjectListUseCase extends Interactor { // // interface Callback{ // void onSubjectListLoaded(Collection<Subject> subjects); // void onError(SubjectException exception); // } // // public void execute(final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModelImp.java // public class SubjectViewModelImp implements SubjectViewModel { // // private Subject subject; // // public SubjectViewModelImp(String name) { // subject = new Subject(name); // } // // public SubjectViewModelImp(Subject subject) { // this.subject = subject; // } // // public int getId(){ // return this.subject.getId(); // } // // public String getName(){ // return this.subject.getName(); // } // // @Override // public boolean equals(Object o) { // boolean result = false; // if (o instanceof SubjectViewModel){ // SubjectViewModel model = (SubjectViewModel)o; // if (this.subject.getId() == model.getId() && this.subject.getName().equals(model.getName())){ // result = true; // } // } // return result; // } // // @Override // public String toString() { // return subject.getId()+" "+subject.getName(); // } // }
import android.content.Context; import android.util.Log; import com.tonilopezmr.sample.di.BasePresenter; import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.interactor.SubjectUseCase; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase; import com.tonilopezmr.sample.ui.view.SubjectListView; import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModel; import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModelImp; import java.util.ArrayList; import java.util.Collection; import javax.inject.Inject; import javax.inject.Named;
package com.tonilopezmr.sample.ui.presenter; /** * @author toni. */ public class SubjectListPresenterImp extends BasePresenter implements SubjectListPresenter { private SubjectListView view;
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java // public interface SubjectUseCase extends Interactor { // // interface Callback { // void onMissionAccomplished(Subject subject); // void onError(SubjectException ex); // } // // public void execute(Subject subject, final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java // public interface GetSubjectListUseCase extends Interactor { // // interface Callback{ // void onSubjectListLoaded(Collection<Subject> subjects); // void onError(SubjectException exception); // } // // public void execute(final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModelImp.java // public class SubjectViewModelImp implements SubjectViewModel { // // private Subject subject; // // public SubjectViewModelImp(String name) { // subject = new Subject(name); // } // // public SubjectViewModelImp(Subject subject) { // this.subject = subject; // } // // public int getId(){ // return this.subject.getId(); // } // // public String getName(){ // return this.subject.getName(); // } // // @Override // public boolean equals(Object o) { // boolean result = false; // if (o instanceof SubjectViewModel){ // SubjectViewModel model = (SubjectViewModel)o; // if (this.subject.getId() == model.getId() && this.subject.getName().equals(model.getName())){ // result = true; // } // } // return result; // } // // @Override // public String toString() { // return subject.getId()+" "+subject.getName(); // } // } // Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenterImp.java import android.content.Context; import android.util.Log; import com.tonilopezmr.sample.di.BasePresenter; import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.interactor.SubjectUseCase; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase; import com.tonilopezmr.sample.ui.view.SubjectListView; import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModel; import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModelImp; import java.util.ArrayList; import java.util.Collection; import javax.inject.Inject; import javax.inject.Named; package com.tonilopezmr.sample.ui.presenter; /** * @author toni. */ public class SubjectListPresenterImp extends BasePresenter implements SubjectListPresenter { private SubjectListView view;
private GetSubjectListUseCase subjectListUseCase;
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenterImp.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java // public interface SubjectUseCase extends Interactor { // // interface Callback { // void onMissionAccomplished(Subject subject); // void onError(SubjectException ex); // } // // public void execute(Subject subject, final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java // public interface GetSubjectListUseCase extends Interactor { // // interface Callback{ // void onSubjectListLoaded(Collection<Subject> subjects); // void onError(SubjectException exception); // } // // public void execute(final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModelImp.java // public class SubjectViewModelImp implements SubjectViewModel { // // private Subject subject; // // public SubjectViewModelImp(String name) { // subject = new Subject(name); // } // // public SubjectViewModelImp(Subject subject) { // this.subject = subject; // } // // public int getId(){ // return this.subject.getId(); // } // // public String getName(){ // return this.subject.getName(); // } // // @Override // public boolean equals(Object o) { // boolean result = false; // if (o instanceof SubjectViewModel){ // SubjectViewModel model = (SubjectViewModel)o; // if (this.subject.getId() == model.getId() && this.subject.getName().equals(model.getName())){ // result = true; // } // } // return result; // } // // @Override // public String toString() { // return subject.getId()+" "+subject.getName(); // } // }
import android.content.Context; import android.util.Log; import com.tonilopezmr.sample.di.BasePresenter; import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.interactor.SubjectUseCase; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase; import com.tonilopezmr.sample.ui.view.SubjectListView; import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModel; import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModelImp; import java.util.ArrayList; import java.util.Collection; import javax.inject.Inject; import javax.inject.Named;
package com.tonilopezmr.sample.ui.presenter; /** * @author toni. */ public class SubjectListPresenterImp extends BasePresenter implements SubjectListPresenter { private SubjectListView view; private GetSubjectListUseCase subjectListUseCase;
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java // public interface SubjectUseCase extends Interactor { // // interface Callback { // void onMissionAccomplished(Subject subject); // void onError(SubjectException ex); // } // // public void execute(Subject subject, final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java // public interface GetSubjectListUseCase extends Interactor { // // interface Callback{ // void onSubjectListLoaded(Collection<Subject> subjects); // void onError(SubjectException exception); // } // // public void execute(final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModelImp.java // public class SubjectViewModelImp implements SubjectViewModel { // // private Subject subject; // // public SubjectViewModelImp(String name) { // subject = new Subject(name); // } // // public SubjectViewModelImp(Subject subject) { // this.subject = subject; // } // // public int getId(){ // return this.subject.getId(); // } // // public String getName(){ // return this.subject.getName(); // } // // @Override // public boolean equals(Object o) { // boolean result = false; // if (o instanceof SubjectViewModel){ // SubjectViewModel model = (SubjectViewModel)o; // if (this.subject.getId() == model.getId() && this.subject.getName().equals(model.getName())){ // result = true; // } // } // return result; // } // // @Override // public String toString() { // return subject.getId()+" "+subject.getName(); // } // } // Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenterImp.java import android.content.Context; import android.util.Log; import com.tonilopezmr.sample.di.BasePresenter; import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.interactor.SubjectUseCase; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase; import com.tonilopezmr.sample.ui.view.SubjectListView; import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModel; import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModelImp; import java.util.ArrayList; import java.util.Collection; import javax.inject.Inject; import javax.inject.Named; package com.tonilopezmr.sample.ui.presenter; /** * @author toni. */ public class SubjectListPresenterImp extends BasePresenter implements SubjectListPresenter { private SubjectListView view; private GetSubjectListUseCase subjectListUseCase;
private SubjectUseCase createSubjectUseCase;
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenterImp.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java // public interface SubjectUseCase extends Interactor { // // interface Callback { // void onMissionAccomplished(Subject subject); // void onError(SubjectException ex); // } // // public void execute(Subject subject, final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java // public interface GetSubjectListUseCase extends Interactor { // // interface Callback{ // void onSubjectListLoaded(Collection<Subject> subjects); // void onError(SubjectException exception); // } // // public void execute(final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModelImp.java // public class SubjectViewModelImp implements SubjectViewModel { // // private Subject subject; // // public SubjectViewModelImp(String name) { // subject = new Subject(name); // } // // public SubjectViewModelImp(Subject subject) { // this.subject = subject; // } // // public int getId(){ // return this.subject.getId(); // } // // public String getName(){ // return this.subject.getName(); // } // // @Override // public boolean equals(Object o) { // boolean result = false; // if (o instanceof SubjectViewModel){ // SubjectViewModel model = (SubjectViewModel)o; // if (this.subject.getId() == model.getId() && this.subject.getName().equals(model.getName())){ // result = true; // } // } // return result; // } // // @Override // public String toString() { // return subject.getId()+" "+subject.getName(); // } // }
import android.content.Context; import android.util.Log; import com.tonilopezmr.sample.di.BasePresenter; import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.interactor.SubjectUseCase; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase; import com.tonilopezmr.sample.ui.view.SubjectListView; import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModel; import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModelImp; import java.util.ArrayList; import java.util.Collection; import javax.inject.Inject; import javax.inject.Named;
package com.tonilopezmr.sample.ui.presenter; /** * @author toni. */ public class SubjectListPresenterImp extends BasePresenter implements SubjectListPresenter { private SubjectListView view; private GetSubjectListUseCase subjectListUseCase; private SubjectUseCase createSubjectUseCase; private SubjectUseCase deleteSubjectUseCase; public SubjectListPresenterImp(Context context, GetSubjectListUseCase subjectListUseCase, SubjectUseCase createSubjectUseCase, @Named("delete usecase") SubjectUseCase deleteSubjectUseCase) { super(context); this.createSubjectUseCase = createSubjectUseCase; this.deleteSubjectUseCase = deleteSubjectUseCase; this.subjectListUseCase = subjectListUseCase; } @Override public void setView(SubjectListView view){ this.view = view; } @Override public void onInit() { view.showProgress(); showSubjects(); } private void showSubjects(){ subjectListUseCase.execute(new GetSubjectListUseCase.Callback() { @Override
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java // public interface SubjectUseCase extends Interactor { // // interface Callback { // void onMissionAccomplished(Subject subject); // void onError(SubjectException ex); // } // // public void execute(Subject subject, final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java // public interface GetSubjectListUseCase extends Interactor { // // interface Callback{ // void onSubjectListLoaded(Collection<Subject> subjects); // void onError(SubjectException exception); // } // // public void execute(final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModelImp.java // public class SubjectViewModelImp implements SubjectViewModel { // // private Subject subject; // // public SubjectViewModelImp(String name) { // subject = new Subject(name); // } // // public SubjectViewModelImp(Subject subject) { // this.subject = subject; // } // // public int getId(){ // return this.subject.getId(); // } // // public String getName(){ // return this.subject.getName(); // } // // @Override // public boolean equals(Object o) { // boolean result = false; // if (o instanceof SubjectViewModel){ // SubjectViewModel model = (SubjectViewModel)o; // if (this.subject.getId() == model.getId() && this.subject.getName().equals(model.getName())){ // result = true; // } // } // return result; // } // // @Override // public String toString() { // return subject.getId()+" "+subject.getName(); // } // } // Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenterImp.java import android.content.Context; import android.util.Log; import com.tonilopezmr.sample.di.BasePresenter; import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.interactor.SubjectUseCase; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase; import com.tonilopezmr.sample.ui.view.SubjectListView; import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModel; import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModelImp; import java.util.ArrayList; import java.util.Collection; import javax.inject.Inject; import javax.inject.Named; package com.tonilopezmr.sample.ui.presenter; /** * @author toni. */ public class SubjectListPresenterImp extends BasePresenter implements SubjectListPresenter { private SubjectListView view; private GetSubjectListUseCase subjectListUseCase; private SubjectUseCase createSubjectUseCase; private SubjectUseCase deleteSubjectUseCase; public SubjectListPresenterImp(Context context, GetSubjectListUseCase subjectListUseCase, SubjectUseCase createSubjectUseCase, @Named("delete usecase") SubjectUseCase deleteSubjectUseCase) { super(context); this.createSubjectUseCase = createSubjectUseCase; this.deleteSubjectUseCase = deleteSubjectUseCase; this.subjectListUseCase = subjectListUseCase; } @Override public void setView(SubjectListView view){ this.view = view; } @Override public void onInit() { view.showProgress(); showSubjects(); } private void showSubjects(){ subjectListUseCase.execute(new GetSubjectListUseCase.Callback() { @Override
public void onSubjectListLoaded(Collection<Subject> subjects) {
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenterImp.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java // public interface SubjectUseCase extends Interactor { // // interface Callback { // void onMissionAccomplished(Subject subject); // void onError(SubjectException ex); // } // // public void execute(Subject subject, final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java // public interface GetSubjectListUseCase extends Interactor { // // interface Callback{ // void onSubjectListLoaded(Collection<Subject> subjects); // void onError(SubjectException exception); // } // // public void execute(final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModelImp.java // public class SubjectViewModelImp implements SubjectViewModel { // // private Subject subject; // // public SubjectViewModelImp(String name) { // subject = new Subject(name); // } // // public SubjectViewModelImp(Subject subject) { // this.subject = subject; // } // // public int getId(){ // return this.subject.getId(); // } // // public String getName(){ // return this.subject.getName(); // } // // @Override // public boolean equals(Object o) { // boolean result = false; // if (o instanceof SubjectViewModel){ // SubjectViewModel model = (SubjectViewModel)o; // if (this.subject.getId() == model.getId() && this.subject.getName().equals(model.getName())){ // result = true; // } // } // return result; // } // // @Override // public String toString() { // return subject.getId()+" "+subject.getName(); // } // }
import android.content.Context; import android.util.Log; import com.tonilopezmr.sample.di.BasePresenter; import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.interactor.SubjectUseCase; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase; import com.tonilopezmr.sample.ui.view.SubjectListView; import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModel; import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModelImp; import java.util.ArrayList; import java.util.Collection; import javax.inject.Inject; import javax.inject.Named;
public SubjectListPresenterImp(Context context, GetSubjectListUseCase subjectListUseCase, SubjectUseCase createSubjectUseCase, @Named("delete usecase") SubjectUseCase deleteSubjectUseCase) { super(context); this.createSubjectUseCase = createSubjectUseCase; this.deleteSubjectUseCase = deleteSubjectUseCase; this.subjectListUseCase = subjectListUseCase; } @Override public void setView(SubjectListView view){ this.view = view; } @Override public void onInit() { view.showProgress(); showSubjects(); } private void showSubjects(){ subjectListUseCase.execute(new GetSubjectListUseCase.Callback() { @Override public void onSubjectListLoaded(Collection<Subject> subjects) { view.showSubjects(convertToViewModel(subjects)); view.hideProgress(); } @Override
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java // public interface SubjectUseCase extends Interactor { // // interface Callback { // void onMissionAccomplished(Subject subject); // void onError(SubjectException ex); // } // // public void execute(Subject subject, final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java // public interface GetSubjectListUseCase extends Interactor { // // interface Callback{ // void onSubjectListLoaded(Collection<Subject> subjects); // void onError(SubjectException exception); // } // // public void execute(final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModelImp.java // public class SubjectViewModelImp implements SubjectViewModel { // // private Subject subject; // // public SubjectViewModelImp(String name) { // subject = new Subject(name); // } // // public SubjectViewModelImp(Subject subject) { // this.subject = subject; // } // // public int getId(){ // return this.subject.getId(); // } // // public String getName(){ // return this.subject.getName(); // } // // @Override // public boolean equals(Object o) { // boolean result = false; // if (o instanceof SubjectViewModel){ // SubjectViewModel model = (SubjectViewModel)o; // if (this.subject.getId() == model.getId() && this.subject.getName().equals(model.getName())){ // result = true; // } // } // return result; // } // // @Override // public String toString() { // return subject.getId()+" "+subject.getName(); // } // } // Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenterImp.java import android.content.Context; import android.util.Log; import com.tonilopezmr.sample.di.BasePresenter; import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.interactor.SubjectUseCase; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase; import com.tonilopezmr.sample.ui.view.SubjectListView; import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModel; import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModelImp; import java.util.ArrayList; import java.util.Collection; import javax.inject.Inject; import javax.inject.Named; public SubjectListPresenterImp(Context context, GetSubjectListUseCase subjectListUseCase, SubjectUseCase createSubjectUseCase, @Named("delete usecase") SubjectUseCase deleteSubjectUseCase) { super(context); this.createSubjectUseCase = createSubjectUseCase; this.deleteSubjectUseCase = deleteSubjectUseCase; this.subjectListUseCase = subjectListUseCase; } @Override public void setView(SubjectListView view){ this.view = view; } @Override public void onInit() { view.showProgress(); showSubjects(); } private void showSubjects(){ subjectListUseCase.execute(new GetSubjectListUseCase.Callback() { @Override public void onSubjectListLoaded(Collection<Subject> subjects) { view.showSubjects(convertToViewModel(subjects)); view.hideProgress(); } @Override
public void onError(SubjectException exception) {
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenterImp.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java // public interface SubjectUseCase extends Interactor { // // interface Callback { // void onMissionAccomplished(Subject subject); // void onError(SubjectException ex); // } // // public void execute(Subject subject, final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java // public interface GetSubjectListUseCase extends Interactor { // // interface Callback{ // void onSubjectListLoaded(Collection<Subject> subjects); // void onError(SubjectException exception); // } // // public void execute(final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModelImp.java // public class SubjectViewModelImp implements SubjectViewModel { // // private Subject subject; // // public SubjectViewModelImp(String name) { // subject = new Subject(name); // } // // public SubjectViewModelImp(Subject subject) { // this.subject = subject; // } // // public int getId(){ // return this.subject.getId(); // } // // public String getName(){ // return this.subject.getName(); // } // // @Override // public boolean equals(Object o) { // boolean result = false; // if (o instanceof SubjectViewModel){ // SubjectViewModel model = (SubjectViewModel)o; // if (this.subject.getId() == model.getId() && this.subject.getName().equals(model.getName())){ // result = true; // } // } // return result; // } // // @Override // public String toString() { // return subject.getId()+" "+subject.getName(); // } // }
import android.content.Context; import android.util.Log; import com.tonilopezmr.sample.di.BasePresenter; import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.interactor.SubjectUseCase; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase; import com.tonilopezmr.sample.ui.view.SubjectListView; import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModel; import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModelImp; import java.util.ArrayList; import java.util.Collection; import javax.inject.Inject; import javax.inject.Named;
} @Override public void onInit() { view.showProgress(); showSubjects(); } private void showSubjects(){ subjectListUseCase.execute(new GetSubjectListUseCase.Callback() { @Override public void onSubjectListLoaded(Collection<Subject> subjects) { view.showSubjects(convertToViewModel(subjects)); view.hideProgress(); } @Override public void onError(SubjectException exception) { view.showMessage(exception.getMessage()); //For example view.hideProgress(); view.showLayoutError(); Log.i(getClass().toString(), "¡¡Show error!!"); } }); } private Collection<SubjectViewModel> convertToViewModel(Collection<Subject> subjectsCollection){ Collection<SubjectViewModel> subjectsViewModel = new ArrayList<>(); for (Subject subject : subjectsCollection){
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java // public interface SubjectUseCase extends Interactor { // // interface Callback { // void onMissionAccomplished(Subject subject); // void onError(SubjectException ex); // } // // public void execute(Subject subject, final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java // public interface GetSubjectListUseCase extends Interactor { // // interface Callback{ // void onSubjectListLoaded(Collection<Subject> subjects); // void onError(SubjectException exception); // } // // public void execute(final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModelImp.java // public class SubjectViewModelImp implements SubjectViewModel { // // private Subject subject; // // public SubjectViewModelImp(String name) { // subject = new Subject(name); // } // // public SubjectViewModelImp(Subject subject) { // this.subject = subject; // } // // public int getId(){ // return this.subject.getId(); // } // // public String getName(){ // return this.subject.getName(); // } // // @Override // public boolean equals(Object o) { // boolean result = false; // if (o instanceof SubjectViewModel){ // SubjectViewModel model = (SubjectViewModel)o; // if (this.subject.getId() == model.getId() && this.subject.getName().equals(model.getName())){ // result = true; // } // } // return result; // } // // @Override // public String toString() { // return subject.getId()+" "+subject.getName(); // } // } // Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenterImp.java import android.content.Context; import android.util.Log; import com.tonilopezmr.sample.di.BasePresenter; import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.interactor.SubjectUseCase; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase; import com.tonilopezmr.sample.ui.view.SubjectListView; import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModel; import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModelImp; import java.util.ArrayList; import java.util.Collection; import javax.inject.Inject; import javax.inject.Named; } @Override public void onInit() { view.showProgress(); showSubjects(); } private void showSubjects(){ subjectListUseCase.execute(new GetSubjectListUseCase.Callback() { @Override public void onSubjectListLoaded(Collection<Subject> subjects) { view.showSubjects(convertToViewModel(subjects)); view.hideProgress(); } @Override public void onError(SubjectException exception) { view.showMessage(exception.getMessage()); //For example view.hideProgress(); view.showLayoutError(); Log.i(getClass().toString(), "¡¡Show error!!"); } }); } private Collection<SubjectViewModel> convertToViewModel(Collection<Subject> subjectsCollection){ Collection<SubjectViewModel> subjectsViewModel = new ArrayList<>(); for (Subject subject : subjectsCollection){
subjectsViewModel.add(new SubjectViewModelImp(subject));
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/di/modules/ExecutorModule.java
// Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThreadImp.java // public class MainThreadImp implements MainThread{ // // private Handler handler; // // public MainThreadImp() { // this.handler = new Handler(Looper.getMainLooper()); // } // // @Override // public void post(final Runnable runnable) { // handler.post(runnable); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/ThreadExecutor.java // public class ThreadExecutor implements Executor{ // // private static final int CORE_POOL_SIZE = 3; // private static final int MAX_POOL_SIZE = 5; // private static final int KEEP_ALIVE_TIME = 120; // private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS; // private static final BlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingQueue<>(); // // private ThreadPoolExecutor threadPoolexecutor; // // public ThreadExecutor() { // int corePoolSize = CORE_POOL_SIZE; // int maxPoolSize = MAX_POOL_SIZE; // int keepAliveTime = KEEP_ALIVE_TIME; // TimeUnit timeUnit = TIME_UNIT; // BlockingQueue<Runnable> workQueue = WORK_QUEUE; // // threadPoolexecutor = // new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue); // } // // @Override // public void run(final Interactor interactor) { // if (interactor == null) { // throw new IllegalArgumentException("Interactor to execute can't be null"); // } // // threadPoolexecutor.submit(interactor); // } // // // }
import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; import com.tonilopezmr.sample.executor.MainThreadImp; import com.tonilopezmr.sample.executor.ThreadExecutor; import javax.inject.Singleton; import dagger.Module; import dagger.Provides;
package com.tonilopezmr.sample.di.modules; /** * * @author Toni */ @Module( complete = false, library = true ) public final class ExecutorModule { @Provides @Singleton
// Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThreadImp.java // public class MainThreadImp implements MainThread{ // // private Handler handler; // // public MainThreadImp() { // this.handler = new Handler(Looper.getMainLooper()); // } // // @Override // public void post(final Runnable runnable) { // handler.post(runnable); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/ThreadExecutor.java // public class ThreadExecutor implements Executor{ // // private static final int CORE_POOL_SIZE = 3; // private static final int MAX_POOL_SIZE = 5; // private static final int KEEP_ALIVE_TIME = 120; // private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS; // private static final BlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingQueue<>(); // // private ThreadPoolExecutor threadPoolexecutor; // // public ThreadExecutor() { // int corePoolSize = CORE_POOL_SIZE; // int maxPoolSize = MAX_POOL_SIZE; // int keepAliveTime = KEEP_ALIVE_TIME; // TimeUnit timeUnit = TIME_UNIT; // BlockingQueue<Runnable> workQueue = WORK_QUEUE; // // threadPoolexecutor = // new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue); // } // // @Override // public void run(final Interactor interactor) { // if (interactor == null) { // throw new IllegalArgumentException("Interactor to execute can't be null"); // } // // threadPoolexecutor.submit(interactor); // } // // // } // Path: app/src/main/java/com/tonilopezmr/sample/di/modules/ExecutorModule.java import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; import com.tonilopezmr.sample.executor.MainThreadImp; import com.tonilopezmr.sample.executor.ThreadExecutor; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; package com.tonilopezmr.sample.di.modules; /** * * @author Toni */ @Module( complete = false, library = true ) public final class ExecutorModule { @Provides @Singleton
public Executor provideThreadExecutor(){
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/di/modules/ExecutorModule.java
// Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThreadImp.java // public class MainThreadImp implements MainThread{ // // private Handler handler; // // public MainThreadImp() { // this.handler = new Handler(Looper.getMainLooper()); // } // // @Override // public void post(final Runnable runnable) { // handler.post(runnable); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/ThreadExecutor.java // public class ThreadExecutor implements Executor{ // // private static final int CORE_POOL_SIZE = 3; // private static final int MAX_POOL_SIZE = 5; // private static final int KEEP_ALIVE_TIME = 120; // private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS; // private static final BlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingQueue<>(); // // private ThreadPoolExecutor threadPoolexecutor; // // public ThreadExecutor() { // int corePoolSize = CORE_POOL_SIZE; // int maxPoolSize = MAX_POOL_SIZE; // int keepAliveTime = KEEP_ALIVE_TIME; // TimeUnit timeUnit = TIME_UNIT; // BlockingQueue<Runnable> workQueue = WORK_QUEUE; // // threadPoolexecutor = // new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue); // } // // @Override // public void run(final Interactor interactor) { // if (interactor == null) { // throw new IllegalArgumentException("Interactor to execute can't be null"); // } // // threadPoolexecutor.submit(interactor); // } // // // }
import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; import com.tonilopezmr.sample.executor.MainThreadImp; import com.tonilopezmr.sample.executor.ThreadExecutor; import javax.inject.Singleton; import dagger.Module; import dagger.Provides;
package com.tonilopezmr.sample.di.modules; /** * * @author Toni */ @Module( complete = false, library = true ) public final class ExecutorModule { @Provides @Singleton public Executor provideThreadExecutor(){
// Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThreadImp.java // public class MainThreadImp implements MainThread{ // // private Handler handler; // // public MainThreadImp() { // this.handler = new Handler(Looper.getMainLooper()); // } // // @Override // public void post(final Runnable runnable) { // handler.post(runnable); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/ThreadExecutor.java // public class ThreadExecutor implements Executor{ // // private static final int CORE_POOL_SIZE = 3; // private static final int MAX_POOL_SIZE = 5; // private static final int KEEP_ALIVE_TIME = 120; // private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS; // private static final BlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingQueue<>(); // // private ThreadPoolExecutor threadPoolexecutor; // // public ThreadExecutor() { // int corePoolSize = CORE_POOL_SIZE; // int maxPoolSize = MAX_POOL_SIZE; // int keepAliveTime = KEEP_ALIVE_TIME; // TimeUnit timeUnit = TIME_UNIT; // BlockingQueue<Runnable> workQueue = WORK_QUEUE; // // threadPoolexecutor = // new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue); // } // // @Override // public void run(final Interactor interactor) { // if (interactor == null) { // throw new IllegalArgumentException("Interactor to execute can't be null"); // } // // threadPoolexecutor.submit(interactor); // } // // // } // Path: app/src/main/java/com/tonilopezmr/sample/di/modules/ExecutorModule.java import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; import com.tonilopezmr.sample.executor.MainThreadImp; import com.tonilopezmr.sample.executor.ThreadExecutor; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; package com.tonilopezmr.sample.di.modules; /** * * @author Toni */ @Module( complete = false, library = true ) public final class ExecutorModule { @Provides @Singleton public Executor provideThreadExecutor(){
return new ThreadExecutor();
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/di/modules/ExecutorModule.java
// Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThreadImp.java // public class MainThreadImp implements MainThread{ // // private Handler handler; // // public MainThreadImp() { // this.handler = new Handler(Looper.getMainLooper()); // } // // @Override // public void post(final Runnable runnable) { // handler.post(runnable); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/ThreadExecutor.java // public class ThreadExecutor implements Executor{ // // private static final int CORE_POOL_SIZE = 3; // private static final int MAX_POOL_SIZE = 5; // private static final int KEEP_ALIVE_TIME = 120; // private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS; // private static final BlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingQueue<>(); // // private ThreadPoolExecutor threadPoolexecutor; // // public ThreadExecutor() { // int corePoolSize = CORE_POOL_SIZE; // int maxPoolSize = MAX_POOL_SIZE; // int keepAliveTime = KEEP_ALIVE_TIME; // TimeUnit timeUnit = TIME_UNIT; // BlockingQueue<Runnable> workQueue = WORK_QUEUE; // // threadPoolexecutor = // new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue); // } // // @Override // public void run(final Interactor interactor) { // if (interactor == null) { // throw new IllegalArgumentException("Interactor to execute can't be null"); // } // // threadPoolexecutor.submit(interactor); // } // // // }
import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; import com.tonilopezmr.sample.executor.MainThreadImp; import com.tonilopezmr.sample.executor.ThreadExecutor; import javax.inject.Singleton; import dagger.Module; import dagger.Provides;
package com.tonilopezmr.sample.di.modules; /** * * @author Toni */ @Module( complete = false, library = true ) public final class ExecutorModule { @Provides @Singleton public Executor provideThreadExecutor(){ return new ThreadExecutor(); } @Provides @Singleton
// Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThreadImp.java // public class MainThreadImp implements MainThread{ // // private Handler handler; // // public MainThreadImp() { // this.handler = new Handler(Looper.getMainLooper()); // } // // @Override // public void post(final Runnable runnable) { // handler.post(runnable); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/ThreadExecutor.java // public class ThreadExecutor implements Executor{ // // private static final int CORE_POOL_SIZE = 3; // private static final int MAX_POOL_SIZE = 5; // private static final int KEEP_ALIVE_TIME = 120; // private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS; // private static final BlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingQueue<>(); // // private ThreadPoolExecutor threadPoolexecutor; // // public ThreadExecutor() { // int corePoolSize = CORE_POOL_SIZE; // int maxPoolSize = MAX_POOL_SIZE; // int keepAliveTime = KEEP_ALIVE_TIME; // TimeUnit timeUnit = TIME_UNIT; // BlockingQueue<Runnable> workQueue = WORK_QUEUE; // // threadPoolexecutor = // new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue); // } // // @Override // public void run(final Interactor interactor) { // if (interactor == null) { // throw new IllegalArgumentException("Interactor to execute can't be null"); // } // // threadPoolexecutor.submit(interactor); // } // // // } // Path: app/src/main/java/com/tonilopezmr/sample/di/modules/ExecutorModule.java import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; import com.tonilopezmr.sample.executor.MainThreadImp; import com.tonilopezmr.sample.executor.ThreadExecutor; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; package com.tonilopezmr.sample.di.modules; /** * * @author Toni */ @Module( complete = false, library = true ) public final class ExecutorModule { @Provides @Singleton public Executor provideThreadExecutor(){ return new ThreadExecutor(); } @Provides @Singleton
public MainThread provideMainThreadImp(){
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/di/modules/ExecutorModule.java
// Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThreadImp.java // public class MainThreadImp implements MainThread{ // // private Handler handler; // // public MainThreadImp() { // this.handler = new Handler(Looper.getMainLooper()); // } // // @Override // public void post(final Runnable runnable) { // handler.post(runnable); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/ThreadExecutor.java // public class ThreadExecutor implements Executor{ // // private static final int CORE_POOL_SIZE = 3; // private static final int MAX_POOL_SIZE = 5; // private static final int KEEP_ALIVE_TIME = 120; // private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS; // private static final BlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingQueue<>(); // // private ThreadPoolExecutor threadPoolexecutor; // // public ThreadExecutor() { // int corePoolSize = CORE_POOL_SIZE; // int maxPoolSize = MAX_POOL_SIZE; // int keepAliveTime = KEEP_ALIVE_TIME; // TimeUnit timeUnit = TIME_UNIT; // BlockingQueue<Runnable> workQueue = WORK_QUEUE; // // threadPoolexecutor = // new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue); // } // // @Override // public void run(final Interactor interactor) { // if (interactor == null) { // throw new IllegalArgumentException("Interactor to execute can't be null"); // } // // threadPoolexecutor.submit(interactor); // } // // // }
import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; import com.tonilopezmr.sample.executor.MainThreadImp; import com.tonilopezmr.sample.executor.ThreadExecutor; import javax.inject.Singleton; import dagger.Module; import dagger.Provides;
package com.tonilopezmr.sample.di.modules; /** * * @author Toni */ @Module( complete = false, library = true ) public final class ExecutorModule { @Provides @Singleton public Executor provideThreadExecutor(){ return new ThreadExecutor(); } @Provides @Singleton public MainThread provideMainThreadImp(){
// Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThreadImp.java // public class MainThreadImp implements MainThread{ // // private Handler handler; // // public MainThreadImp() { // this.handler = new Handler(Looper.getMainLooper()); // } // // @Override // public void post(final Runnable runnable) { // handler.post(runnable); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/ThreadExecutor.java // public class ThreadExecutor implements Executor{ // // private static final int CORE_POOL_SIZE = 3; // private static final int MAX_POOL_SIZE = 5; // private static final int KEEP_ALIVE_TIME = 120; // private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS; // private static final BlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingQueue<>(); // // private ThreadPoolExecutor threadPoolexecutor; // // public ThreadExecutor() { // int corePoolSize = CORE_POOL_SIZE; // int maxPoolSize = MAX_POOL_SIZE; // int keepAliveTime = KEEP_ALIVE_TIME; // TimeUnit timeUnit = TIME_UNIT; // BlockingQueue<Runnable> workQueue = WORK_QUEUE; // // threadPoolexecutor = // new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue); // } // // @Override // public void run(final Interactor interactor) { // if (interactor == null) { // throw new IllegalArgumentException("Interactor to execute can't be null"); // } // // threadPoolexecutor.submit(interactor); // } // // // } // Path: app/src/main/java/com/tonilopezmr/sample/di/modules/ExecutorModule.java import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; import com.tonilopezmr.sample.executor.MainThreadImp; import com.tonilopezmr.sample.executor.ThreadExecutor; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; package com.tonilopezmr.sample.di.modules; /** * * @author Toni */ @Module( complete = false, library = true ) public final class ExecutorModule { @Provides @Singleton public Executor provideThreadExecutor(){ return new ThreadExecutor(); } @Provides @Singleton public MainThread provideMainThreadImp(){
return new MainThreadImp();
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // }
import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread;
package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { private Callback callback;
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // } // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { private Callback callback;
private Subject subject;
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // }
import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread;
package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { private Callback callback; private Subject subject;
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // } // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { private Callback callback; private Subject subject;
public DeleteSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) {
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // }
import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread;
package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { private Callback callback; private Subject subject;
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // } // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { private Callback callback; private Subject subject;
public DeleteSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) {
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // }
import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread;
package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { private Callback callback; private Subject subject;
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // } // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { private Callback callback; private Subject subject;
public DeleteSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) {
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // }
import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread;
package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { private Callback callback; private Subject subject; public DeleteSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { super(executor, mainThread, subjectRepository); } @Override public void execute(Subject subject, final Callback callback) { if (callback == null){ throw new IllegalArgumentException("Callback parameter can't be null"); } this.callback = callback; this.subject = subject; super.executor.run(this); } //Interactor Use case @Override public void run() { super.subjectRepository.deleteSubject(subject, new SubjectRepository.SubjectUseCase() { @Override public void onMissionAccomplished(final Subject subject) { DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { @Override public void run() { callback.onMissionAccomplished(subject); } }); } @Override
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // } // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { private Callback callback; private Subject subject; public DeleteSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { super(executor, mainThread, subjectRepository); } @Override public void execute(Subject subject, final Callback callback) { if (callback == null){ throw new IllegalArgumentException("Callback parameter can't be null"); } this.callback = callback; this.subject = subject; super.executor.run(this); } //Interactor Use case @Override public void run() { super.subjectRepository.deleteSubject(subject, new SubjectRepository.SubjectUseCase() { @Override public void onMissionAccomplished(final Subject subject) { DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { @Override public void run() { callback.onMissionAccomplished(subject); } }); } @Override
public void onError(final SubjectException subjectException) {
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // }
import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread;
package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public class CreateSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { private Callback callback;
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // } // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public class CreateSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { private Callback callback;
private Subject subject;
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // }
import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread;
package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public class CreateSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { private Callback callback; private Subject subject;
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // } // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public class CreateSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { private Callback callback; private Subject subject;
public CreateSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) {
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // }
import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread;
package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public class CreateSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { private Callback callback; private Subject subject;
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // } // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public class CreateSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { private Callback callback; private Subject subject;
public CreateSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) {
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // }
import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread;
package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public class CreateSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { private Callback callback; private Subject subject;
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // } // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public class CreateSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { private Callback callback; private Subject subject;
public CreateSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) {
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // }
import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread;
throw new IllegalArgumentException("Callback parameter can't be null"); } this.callback = callback; this.subject = subject; super.executor.run(this); } //Interactor Use case @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } super.subjectRepository.createSubject(this.subject, new SubjectRepository.SubjectUseCase() { @Override public void onMissionAccomplished(final Subject subject) { CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { @Override public void run() { callback.onMissionAccomplished(subject); } }); } @Override
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // } // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; throw new IllegalArgumentException("Callback parameter can't be null"); } this.callback = callback; this.subject = subject; super.executor.run(this); } //Interactor Use case @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } super.subjectRepository.createSubject(this.subject, new SubjectRepository.SubjectUseCase() { @Override public void onMissionAccomplished(final Subject subject) { CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { @Override public void run() { callback.onMissionAccomplished(subject); } }); } @Override
public void onError(final SubjectException subjectException) {