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
jfcorugedo/RJavaServer
src/test/java/com/jfcorugedo/rserver/engine/RServeEngineProviderServiceIT.java
// Path: src/main/java/com/jfcorugedo/rserver/common/collection/CollectionUtils.java // @SafeVarargs // public static <T> List<T> newList(T... values) { // List<T> arrayList = new ArrayList<>(values.length); // for(T element : values) { // arrayList.add(element); // } // // return arrayList; // } // // Path: src/main/java/com/jfcorugedo/rserver/Application.java // @SpringBootApplication // @EnableMetrics // public class Application { // // private static final Logger LOGGER = LoggerFactory.getLogger(Application.class); // // public static void main(String[] args) { // LOGGER.info("\n****************\n* rJava Server *\n****************\n"); // // SpringApplication app = new SpringApplication(Application.class); // app.setShowBanner(false); // SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args); // // // Check if the selected profile has been set as argument. // // if not the development profile will be added // addDefaultProfile(app, source); // // // // app.run(args); // } // // /** // * Set a default profile if it has not been set // */ // private static void addDefaultProfile(SpringApplication app, SimpleCommandLinePropertySource source) { // if (!source.containsProperty("spring.profiles.active")) { // app.setAdditionalProfiles("local"); // LOGGER.info("Staring application with profiles: local"); // } else { // LOGGER.info("Staring application with profiles: {}", source.getProperty("spring.profiles.active")); // } // } // // /** // * This method is needed because Sonar doesn't allow public constructors in a class with only static methods, // * but SpringBoot needs a public constructor in this class. // * This method should not be invoked // */ // public void avoidSonarViolation(){ // LOGGER.warn("This method should not be invoked"); // } // }
import static com.jfcorugedo.rserver.common.collection.CollectionUtils.newList; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import javax.inject.Inject; import org.apache.commons.math3.distribution.EnumeratedDistribution; import org.apache.commons.math3.util.Pair; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.rosuda.REngine.REXP; import org.rosuda.REngine.REXPDouble; import org.rosuda.REngine.REXPGenericVector; import org.rosuda.REngine.REXPInteger; import org.rosuda.REngine.REXPString; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.WebIntegrationTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.jfcorugedo.rserver.Application;
package com.jfcorugedo.rserver.engine; /** * In order to make these test work R_HOME environment variable must be present * * Export an environment variable with this value: * * R_HOME=/Library/Frameworks/R.framework/Resources * * @author jfcorugedo * */ @Ignore("These tests require R environment installed and R_HOME variable setted") @RunWith(SpringJUnit4ClassRunner.class)
// Path: src/main/java/com/jfcorugedo/rserver/common/collection/CollectionUtils.java // @SafeVarargs // public static <T> List<T> newList(T... values) { // List<T> arrayList = new ArrayList<>(values.length); // for(T element : values) { // arrayList.add(element); // } // // return arrayList; // } // // Path: src/main/java/com/jfcorugedo/rserver/Application.java // @SpringBootApplication // @EnableMetrics // public class Application { // // private static final Logger LOGGER = LoggerFactory.getLogger(Application.class); // // public static void main(String[] args) { // LOGGER.info("\n****************\n* rJava Server *\n****************\n"); // // SpringApplication app = new SpringApplication(Application.class); // app.setShowBanner(false); // SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args); // // // Check if the selected profile has been set as argument. // // if not the development profile will be added // addDefaultProfile(app, source); // // // // app.run(args); // } // // /** // * Set a default profile if it has not been set // */ // private static void addDefaultProfile(SpringApplication app, SimpleCommandLinePropertySource source) { // if (!source.containsProperty("spring.profiles.active")) { // app.setAdditionalProfiles("local"); // LOGGER.info("Staring application with profiles: local"); // } else { // LOGGER.info("Staring application with profiles: {}", source.getProperty("spring.profiles.active")); // } // } // // /** // * This method is needed because Sonar doesn't allow public constructors in a class with only static methods, // * but SpringBoot needs a public constructor in this class. // * This method should not be invoked // */ // public void avoidSonarViolation(){ // LOGGER.warn("This method should not be invoked"); // } // } // Path: src/test/java/com/jfcorugedo/rserver/engine/RServeEngineProviderServiceIT.java import static com.jfcorugedo.rserver.common.collection.CollectionUtils.newList; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import javax.inject.Inject; import org.apache.commons.math3.distribution.EnumeratedDistribution; import org.apache.commons.math3.util.Pair; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.rosuda.REngine.REXP; import org.rosuda.REngine.REXPDouble; import org.rosuda.REngine.REXPGenericVector; import org.rosuda.REngine.REXPInteger; import org.rosuda.REngine.REXPString; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.WebIntegrationTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.jfcorugedo.rserver.Application; package com.jfcorugedo.rserver.engine; /** * In order to make these test work R_HOME environment variable must be present * * Export an environment variable with this value: * * R_HOME=/Library/Frameworks/R.framework/Resources * * @author jfcorugedo * */ @Ignore("These tests require R environment installed and R_HOME variable setted") @RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
jfcorugedo/RJavaServer
src/test/java/com/jfcorugedo/rserver/engine/RServeEngineProviderServiceIT.java
// Path: src/main/java/com/jfcorugedo/rserver/common/collection/CollectionUtils.java // @SafeVarargs // public static <T> List<T> newList(T... values) { // List<T> arrayList = new ArrayList<>(values.length); // for(T element : values) { // arrayList.add(element); // } // // return arrayList; // } // // Path: src/main/java/com/jfcorugedo/rserver/Application.java // @SpringBootApplication // @EnableMetrics // public class Application { // // private static final Logger LOGGER = LoggerFactory.getLogger(Application.class); // // public static void main(String[] args) { // LOGGER.info("\n****************\n* rJava Server *\n****************\n"); // // SpringApplication app = new SpringApplication(Application.class); // app.setShowBanner(false); // SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args); // // // Check if the selected profile has been set as argument. // // if not the development profile will be added // addDefaultProfile(app, source); // // // // app.run(args); // } // // /** // * Set a default profile if it has not been set // */ // private static void addDefaultProfile(SpringApplication app, SimpleCommandLinePropertySource source) { // if (!source.containsProperty("spring.profiles.active")) { // app.setAdditionalProfiles("local"); // LOGGER.info("Staring application with profiles: local"); // } else { // LOGGER.info("Staring application with profiles: {}", source.getProperty("spring.profiles.active")); // } // } // // /** // * This method is needed because Sonar doesn't allow public constructors in a class with only static methods, // * but SpringBoot needs a public constructor in this class. // * This method should not be invoked // */ // public void avoidSonarViolation(){ // LOGGER.warn("This method should not be invoked"); // } // }
import static com.jfcorugedo.rserver.common.collection.CollectionUtils.newList; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import javax.inject.Inject; import org.apache.commons.math3.distribution.EnumeratedDistribution; import org.apache.commons.math3.util.Pair; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.rosuda.REngine.REXP; import org.rosuda.REngine.REXPDouble; import org.rosuda.REngine.REXPGenericVector; import org.rosuda.REngine.REXPInteger; import org.rosuda.REngine.REXPString; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.WebIntegrationTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.jfcorugedo.rserver.Application;
TEST_BIG_POPULATION[i*20+j] = TEST_POPULATION[j]; } } } @Inject private RServeEngineProviderService providerService; @Test public void testBlockFunction() throws Exception{ List<Double> bigPopulation = Arrays.stream(TEST_BIG_POPULATION).boxed().collect(Collectors.toList()); Collections.shuffle(bigPopulation); double[] shuffledPopulation = bigPopulation.stream().mapToDouble(Double::doubleValue).toArray(); REXP result = providerService.blockFunction(new REXPInteger(generateIds(200)), new REXPDouble(TEST_BIG_POPULATION), new REXPDouble(shuffledPopulation)); if(LOGGER.isInfoEnabled()) { LOGGER.info(blockResultToString(result)); } assertThat((((REXPString)((REXPGenericVector)result).asList().get(0)).asStrings())).hasSize(100); } @Test public void testGenericBlockFunction() { List<Double> bigPopulation = Arrays.stream(TEST_BIG_POPULATION).boxed().collect(Collectors.toList()); Collections.shuffle(bigPopulation); double[] shuffledPopulation = bigPopulation.stream().mapToDouble(Double::doubleValue).toArray();
// Path: src/main/java/com/jfcorugedo/rserver/common/collection/CollectionUtils.java // @SafeVarargs // public static <T> List<T> newList(T... values) { // List<T> arrayList = new ArrayList<>(values.length); // for(T element : values) { // arrayList.add(element); // } // // return arrayList; // } // // Path: src/main/java/com/jfcorugedo/rserver/Application.java // @SpringBootApplication // @EnableMetrics // public class Application { // // private static final Logger LOGGER = LoggerFactory.getLogger(Application.class); // // public static void main(String[] args) { // LOGGER.info("\n****************\n* rJava Server *\n****************\n"); // // SpringApplication app = new SpringApplication(Application.class); // app.setShowBanner(false); // SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args); // // // Check if the selected profile has been set as argument. // // if not the development profile will be added // addDefaultProfile(app, source); // // // // app.run(args); // } // // /** // * Set a default profile if it has not been set // */ // private static void addDefaultProfile(SpringApplication app, SimpleCommandLinePropertySource source) { // if (!source.containsProperty("spring.profiles.active")) { // app.setAdditionalProfiles("local"); // LOGGER.info("Staring application with profiles: local"); // } else { // LOGGER.info("Staring application with profiles: {}", source.getProperty("spring.profiles.active")); // } // } // // /** // * This method is needed because Sonar doesn't allow public constructors in a class with only static methods, // * but SpringBoot needs a public constructor in this class. // * This method should not be invoked // */ // public void avoidSonarViolation(){ // LOGGER.warn("This method should not be invoked"); // } // } // Path: src/test/java/com/jfcorugedo/rserver/engine/RServeEngineProviderServiceIT.java import static com.jfcorugedo.rserver.common.collection.CollectionUtils.newList; import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import javax.inject.Inject; import org.apache.commons.math3.distribution.EnumeratedDistribution; import org.apache.commons.math3.util.Pair; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.rosuda.REngine.REXP; import org.rosuda.REngine.REXPDouble; import org.rosuda.REngine.REXPGenericVector; import org.rosuda.REngine.REXPInteger; import org.rosuda.REngine.REXPString; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.WebIntegrationTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.jfcorugedo.rserver.Application; TEST_BIG_POPULATION[i*20+j] = TEST_POPULATION[j]; } } } @Inject private RServeEngineProviderService providerService; @Test public void testBlockFunction() throws Exception{ List<Double> bigPopulation = Arrays.stream(TEST_BIG_POPULATION).boxed().collect(Collectors.toList()); Collections.shuffle(bigPopulation); double[] shuffledPopulation = bigPopulation.stream().mapToDouble(Double::doubleValue).toArray(); REXP result = providerService.blockFunction(new REXPInteger(generateIds(200)), new REXPDouble(TEST_BIG_POPULATION), new REXPDouble(shuffledPopulation)); if(LOGGER.isInfoEnabled()) { LOGGER.info(blockResultToString(result)); } assertThat((((REXPString)((REXPGenericVector)result).asList().get(0)).asStrings())).hasSize(100); } @Test public void testGenericBlockFunction() { List<Double> bigPopulation = Arrays.stream(TEST_BIG_POPULATION).boxed().collect(Collectors.toList()); Collections.shuffle(bigPopulation); double[] shuffledPopulation = bigPopulation.stream().mapToDouble(Double::doubleValue).toArray();
REXP result = providerService.blockGeneralFunction(new REXPInteger(generateIds(200)), newList(new REXPString(generateRandomCities(200))), newList(new REXPDouble(shuffledPopulation)));
jfcorugedo/RJavaServer
src/main/java/com/jfcorugedo/rserver/generalization/algorithm/KolmogorovSmirnovTestImpl.java
// Path: src/main/java/com/jfcorugedo/rserver/service/RService.java // public interface RService { // // /** // * Groups the given values in pairs based on the correlation between values. // * // * For instance, given the following values: // * // * {1.0, 2.0, 2.0, 1.0} // * // * This function will return // * // * [{0,3}, {1,2}] // * // * So the first element in the values array must be paired with the fourth element of the array. // * Similarly, the second element of the array must be paired with the third element. // * // * @param values Values to be paired // * @return List of pairs. Each element in the list will have to indexes that point at the elements // * of the input array that must be paired // */ // List<int[]> groupValues(List<double[]> values); // // /** // * Groups the given values in pairs based on the correlation between values. // * // * For instance, given the following values: // * // * {"A", "B", "B", "A"} // * // * This function will return // * // * [{0,3}, {1,2}] // * // * So the first element in the values array must be paired with the fourth element of the array. // * Similarly, the second element of the array must be paired with the third element. // * // * @param values Values to be paired // * @return List of pairs. Each element in the list will have to indexes that point at the elements // * of the input array that must be paired // */ // List<int[]> groupDiscreteValues(List<String[]> values); // // /** // * Groups the given values in pairs based on the correlation between values. // * // * For instance, given the following values: // * // * {1.0, 2.0, 3.0, 4.0}, {"A", "A", "B", "B"} // * // * This function will return // * // * [{0,3}, {1,2}] // * // * So the first element in the values array must be paired with the fourth element of the array. // * Similarly, the second element of the array must be paired with the third element. // * // * @param values Values to be paired // * @return List of pairs. Each element in the list will have to indexes that point at the elements // * of the input array that must be paired // */ // List<int[]> groupMultipleValues(List<String[]> discreteValues, List<double[]> continuousValues); // // /** // * Computes the p-value, or observed significance level, of a two-sample Kolmogorov-Smirnov test // * evaluating the null hypothesis that x and y are samples drawn from the same probability distribution. // * // * @param x // * @param y // * @return // */ // double kolmogorovSmirnovTest(double[] x, double[] y); // // // /** // * This method returns the square root of the given value // * @param number // * @return // */ // double sqrt(double number); // }
import java.util.Arrays; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import com.codahale.metrics.annotation.Timed; import com.jfcorugedo.rserver.service.RService;
package com.jfcorugedo.rserver.generalization.algorithm; @Component public class KolmogorovSmirnovTestImpl implements KolmogorovSmirnovTest { private static final Logger LOGGER = LoggerFactory.getLogger(KolmogorovSmirnovTestImpl.class); /** Name of the algorithm used to compare two samples */ private static final String KS_TEST = "K-S test"; @Inject
// Path: src/main/java/com/jfcorugedo/rserver/service/RService.java // public interface RService { // // /** // * Groups the given values in pairs based on the correlation between values. // * // * For instance, given the following values: // * // * {1.0, 2.0, 2.0, 1.0} // * // * This function will return // * // * [{0,3}, {1,2}] // * // * So the first element in the values array must be paired with the fourth element of the array. // * Similarly, the second element of the array must be paired with the third element. // * // * @param values Values to be paired // * @return List of pairs. Each element in the list will have to indexes that point at the elements // * of the input array that must be paired // */ // List<int[]> groupValues(List<double[]> values); // // /** // * Groups the given values in pairs based on the correlation between values. // * // * For instance, given the following values: // * // * {"A", "B", "B", "A"} // * // * This function will return // * // * [{0,3}, {1,2}] // * // * So the first element in the values array must be paired with the fourth element of the array. // * Similarly, the second element of the array must be paired with the third element. // * // * @param values Values to be paired // * @return List of pairs. Each element in the list will have to indexes that point at the elements // * of the input array that must be paired // */ // List<int[]> groupDiscreteValues(List<String[]> values); // // /** // * Groups the given values in pairs based on the correlation between values. // * // * For instance, given the following values: // * // * {1.0, 2.0, 3.0, 4.0}, {"A", "A", "B", "B"} // * // * This function will return // * // * [{0,3}, {1,2}] // * // * So the first element in the values array must be paired with the fourth element of the array. // * Similarly, the second element of the array must be paired with the third element. // * // * @param values Values to be paired // * @return List of pairs. Each element in the list will have to indexes that point at the elements // * of the input array that must be paired // */ // List<int[]> groupMultipleValues(List<String[]> discreteValues, List<double[]> continuousValues); // // /** // * Computes the p-value, or observed significance level, of a two-sample Kolmogorov-Smirnov test // * evaluating the null hypothesis that x and y are samples drawn from the same probability distribution. // * // * @param x // * @param y // * @return // */ // double kolmogorovSmirnovTest(double[] x, double[] y); // // // /** // * This method returns the square root of the given value // * @param number // * @return // */ // double sqrt(double number); // } // Path: src/main/java/com/jfcorugedo/rserver/generalization/algorithm/KolmogorovSmirnovTestImpl.java import java.util.Arrays; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import com.codahale.metrics.annotation.Timed; import com.jfcorugedo.rserver.service.RService; package com.jfcorugedo.rserver.generalization.algorithm; @Component public class KolmogorovSmirnovTestImpl implements KolmogorovSmirnovTest { private static final Logger LOGGER = LoggerFactory.getLogger(KolmogorovSmirnovTestImpl.class); /** Name of the algorithm used to compare two samples */ private static final String KS_TEST = "K-S test"; @Inject
private RService rService;
jfcorugedo/RJavaServer
src/test/java/com/jfcorugedo/rserver/service/RServiceImplIT.java
// Path: src/main/java/com/jfcorugedo/rserver/common/collection/CollectionUtils.java // @SafeVarargs // public static <T> List<T> newList(T... values) { // List<T> arrayList = new ArrayList<>(values.length); // for(T element : values) { // arrayList.add(element); // } // // return arrayList; // } // // Path: src/main/java/com/jfcorugedo/rserver/Application.java // @SpringBootApplication // @EnableMetrics // public class Application { // // private static final Logger LOGGER = LoggerFactory.getLogger(Application.class); // // public static void main(String[] args) { // LOGGER.info("\n****************\n* rJava Server *\n****************\n"); // // SpringApplication app = new SpringApplication(Application.class); // app.setShowBanner(false); // SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args); // // // Check if the selected profile has been set as argument. // // if not the development profile will be added // addDefaultProfile(app, source); // // // // app.run(args); // } // // /** // * Set a default profile if it has not been set // */ // private static void addDefaultProfile(SpringApplication app, SimpleCommandLinePropertySource source) { // if (!source.containsProperty("spring.profiles.active")) { // app.setAdditionalProfiles("local"); // LOGGER.info("Staring application with profiles: local"); // } else { // LOGGER.info("Staring application with profiles: {}", source.getProperty("spring.profiles.active")); // } // } // // /** // * This method is needed because Sonar doesn't allow public constructors in a class with only static methods, // * but SpringBoot needs a public constructor in this class. // * This method should not be invoked // */ // public void avoidSonarViolation(){ // LOGGER.warn("This method should not be invoked"); // } // }
import static com.jfcorugedo.rserver.common.collection.CollectionUtils.newList; import static org.assertj.core.api.Assertions.assertThat; import java.util.Random; import javax.inject.Inject; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.WebIntegrationTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.jfcorugedo.rserver.Application;
package com.jfcorugedo.rserver.service; @Ignore("These tests requires R environment installed") @RunWith(SpringJUnit4ClassRunner.class)
// Path: src/main/java/com/jfcorugedo/rserver/common/collection/CollectionUtils.java // @SafeVarargs // public static <T> List<T> newList(T... values) { // List<T> arrayList = new ArrayList<>(values.length); // for(T element : values) { // arrayList.add(element); // } // // return arrayList; // } // // Path: src/main/java/com/jfcorugedo/rserver/Application.java // @SpringBootApplication // @EnableMetrics // public class Application { // // private static final Logger LOGGER = LoggerFactory.getLogger(Application.class); // // public static void main(String[] args) { // LOGGER.info("\n****************\n* rJava Server *\n****************\n"); // // SpringApplication app = new SpringApplication(Application.class); // app.setShowBanner(false); // SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args); // // // Check if the selected profile has been set as argument. // // if not the development profile will be added // addDefaultProfile(app, source); // // // // app.run(args); // } // // /** // * Set a default profile if it has not been set // */ // private static void addDefaultProfile(SpringApplication app, SimpleCommandLinePropertySource source) { // if (!source.containsProperty("spring.profiles.active")) { // app.setAdditionalProfiles("local"); // LOGGER.info("Staring application with profiles: local"); // } else { // LOGGER.info("Staring application with profiles: {}", source.getProperty("spring.profiles.active")); // } // } // // /** // * This method is needed because Sonar doesn't allow public constructors in a class with only static methods, // * but SpringBoot needs a public constructor in this class. // * This method should not be invoked // */ // public void avoidSonarViolation(){ // LOGGER.warn("This method should not be invoked"); // } // } // Path: src/test/java/com/jfcorugedo/rserver/service/RServiceImplIT.java import static com.jfcorugedo.rserver.common.collection.CollectionUtils.newList; import static org.assertj.core.api.Assertions.assertThat; import java.util.Random; import javax.inject.Inject; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.WebIntegrationTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.jfcorugedo.rserver.Application; package com.jfcorugedo.rserver.service; @Ignore("These tests requires R environment installed") @RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
jfcorugedo/RJavaServer
src/test/java/com/jfcorugedo/rserver/service/RServiceImplIT.java
// Path: src/main/java/com/jfcorugedo/rserver/common/collection/CollectionUtils.java // @SafeVarargs // public static <T> List<T> newList(T... values) { // List<T> arrayList = new ArrayList<>(values.length); // for(T element : values) { // arrayList.add(element); // } // // return arrayList; // } // // Path: src/main/java/com/jfcorugedo/rserver/Application.java // @SpringBootApplication // @EnableMetrics // public class Application { // // private static final Logger LOGGER = LoggerFactory.getLogger(Application.class); // // public static void main(String[] args) { // LOGGER.info("\n****************\n* rJava Server *\n****************\n"); // // SpringApplication app = new SpringApplication(Application.class); // app.setShowBanner(false); // SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args); // // // Check if the selected profile has been set as argument. // // if not the development profile will be added // addDefaultProfile(app, source); // // // // app.run(args); // } // // /** // * Set a default profile if it has not been set // */ // private static void addDefaultProfile(SpringApplication app, SimpleCommandLinePropertySource source) { // if (!source.containsProperty("spring.profiles.active")) { // app.setAdditionalProfiles("local"); // LOGGER.info("Staring application with profiles: local"); // } else { // LOGGER.info("Staring application with profiles: {}", source.getProperty("spring.profiles.active")); // } // } // // /** // * This method is needed because Sonar doesn't allow public constructors in a class with only static methods, // * but SpringBoot needs a public constructor in this class. // * This method should not be invoked // */ // public void avoidSonarViolation(){ // LOGGER.warn("This method should not be invoked"); // } // }
import static com.jfcorugedo.rserver.common.collection.CollectionUtils.newList; import static org.assertj.core.api.Assertions.assertThat; import java.util.Random; import javax.inject.Inject; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.WebIntegrationTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.jfcorugedo.rserver.Application;
TEST_POPULATION[11] = 11; TEST_POPULATION[12] = 14; TEST_POPULATION[13] = 13; TEST_POPULATION[14] = 16; TEST_POPULATION[15] = 18; TEST_POPULATION[16] = 19; TEST_POPULATION[17] = 12; TEST_POPULATION[18] = 0; TEST_POPULATION[19] = 4; } public static final double[] TEST_BIG_POPULATION = new double[200]; static{ for(int i = 0 ; i < 10 ; i++) { for(int j = 0 ; j < 20 ; j++) { TEST_BIG_POPULATION[i*20+j] = TEST_POPULATION[j]; } } } @Inject private RServiceImpl service; @Test public void testBlockFunction() { for(int i = 0 ; i < 2 ; i++) { if(LOGGER.isInfoEnabled()) { LOGGER.info(Integer.toString(i)); }
// Path: src/main/java/com/jfcorugedo/rserver/common/collection/CollectionUtils.java // @SafeVarargs // public static <T> List<T> newList(T... values) { // List<T> arrayList = new ArrayList<>(values.length); // for(T element : values) { // arrayList.add(element); // } // // return arrayList; // } // // Path: src/main/java/com/jfcorugedo/rserver/Application.java // @SpringBootApplication // @EnableMetrics // public class Application { // // private static final Logger LOGGER = LoggerFactory.getLogger(Application.class); // // public static void main(String[] args) { // LOGGER.info("\n****************\n* rJava Server *\n****************\n"); // // SpringApplication app = new SpringApplication(Application.class); // app.setShowBanner(false); // SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args); // // // Check if the selected profile has been set as argument. // // if not the development profile will be added // addDefaultProfile(app, source); // // // // app.run(args); // } // // /** // * Set a default profile if it has not been set // */ // private static void addDefaultProfile(SpringApplication app, SimpleCommandLinePropertySource source) { // if (!source.containsProperty("spring.profiles.active")) { // app.setAdditionalProfiles("local"); // LOGGER.info("Staring application with profiles: local"); // } else { // LOGGER.info("Staring application with profiles: {}", source.getProperty("spring.profiles.active")); // } // } // // /** // * This method is needed because Sonar doesn't allow public constructors in a class with only static methods, // * but SpringBoot needs a public constructor in this class. // * This method should not be invoked // */ // public void avoidSonarViolation(){ // LOGGER.warn("This method should not be invoked"); // } // } // Path: src/test/java/com/jfcorugedo/rserver/service/RServiceImplIT.java import static com.jfcorugedo.rserver.common.collection.CollectionUtils.newList; import static org.assertj.core.api.Assertions.assertThat; import java.util.Random; import javax.inject.Inject; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.WebIntegrationTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.jfcorugedo.rserver.Application; TEST_POPULATION[11] = 11; TEST_POPULATION[12] = 14; TEST_POPULATION[13] = 13; TEST_POPULATION[14] = 16; TEST_POPULATION[15] = 18; TEST_POPULATION[16] = 19; TEST_POPULATION[17] = 12; TEST_POPULATION[18] = 0; TEST_POPULATION[19] = 4; } public static final double[] TEST_BIG_POPULATION = new double[200]; static{ for(int i = 0 ; i < 10 ; i++) { for(int j = 0 ; j < 20 ; j++) { TEST_BIG_POPULATION[i*20+j] = TEST_POPULATION[j]; } } } @Inject private RServiceImpl service; @Test public void testBlockFunction() { for(int i = 0 ; i < 2 ; i++) { if(LOGGER.isInfoEnabled()) { LOGGER.info(Integer.toString(i)); }
service.groupValues(newList(TEST_BIG_POPULATION));
ashishbhandari/RetailStore
app/src/androidTest/java/com/crazymin2/retailstore/MainActivityTests.java
// Path: app/src/main/java/com/crazymin2/retailstore/home/MainActivity.java // public class MainActivity extends BaseActivity implements CommonTabFragment.TabListener { // // // private static final String TAG = MainActivity.class.getSimpleName(); // // public StaggeredGridLayoutManager mStaggeredLayoutManager; // // View pager and adapter (for narrow mode) // @Bind(R.id.view_pager) // ViewPager mViewPager; // @Bind(R.id.sliding_tabs) // TabLayout mTabLayout; // // // OurViewPagerAdapter mViewPagerAdapter = null; // private Set<CommonTabFragment> mTabFragments = new HashSet<CommonTabFragment>(); // // // titles for tab layout items (indices must correspond to the above) // private static final int[] TAB_TITLE_RES_ID = new int[]{ // R.string.tab_item_my_category // }; // // private CollectionRecyclerView mRecyclerView; // public CategoryTabFragment.TabAdapter mAdapter; // // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.bind(this); // // renderTabsWithPage(); // } // // private void renderTabsWithPage() { // // mViewPagerAdapter = new OurViewPagerAdapter(getFragmentManager()); // mViewPager.setAdapter(mViewPagerAdapter); // // mTabLayout.setTabsFromPagerAdapter(mViewPagerAdapter); // // mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { // @Override // public void onTabSelected(TabLayout.Tab tab) { // // mViewPager.setCurrentItem(tab.getPosition(), true); // // } // // @Override // public void onTabUnselected(TabLayout.Tab tab) { // // Do nothing // } // // @Override // public void onTabReselected(TabLayout.Tab tab) { // // Do nothing // } // }); // mViewPager.setPageMargin(getResources() // .getDimensionPixelSize(R.dimen.home_page_margin)); // mViewPager.setPageMarginDrawable(R.drawable.page_margin); // // createTabLayoutContentDescriptions(); // } // // private void createTabLayoutContentDescriptions() { // for (int i = 0; i < TAB_TITLE_RES_ID.length; i++) { // mTabLayout.setContentDescription(getString(TAB_TITLE_RES_ID[i])); // } // } // // @Override // public void onTabFragmentViewCreated(Fragment fragment) { // mStaggeredLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL); // mRecyclerView = (CollectionRecyclerView) fragment.getView().findViewById(R.id.list); // mRecyclerView.setLayoutManager(mStaggeredLayoutManager); // mRecyclerView.setHasFixedSize(true); // mAdapter = new CategoryTabFragment.TabAdapter(this); // mRecyclerView.setAdapter(mAdapter); // mAdapter.setOnItemClickListener(onItemClickListener); // enableActionBarAutoHide(mRecyclerView); // } // // private CategoryTabFragment.TabAdapter.OnItemClickListener onItemClickListener = new CategoryTabFragment.TabAdapter.OnItemClickListener() { // // @Override // public void onItemClick(View v, int position) { // int categoryId = mAdapter.getCategoryId(position); // // Intent intent = new Intent(getApplicationContext(), ProductActivity.class); // intent.putExtra(ProductActivity.SELECTED_CATEGORY_ID, categoryId); // startActivity(intent); // } // }; // // @Override // public void onTabFragmentAttached(Fragment fragment) { // mTabFragments.add((CommonTabFragment) fragment); // } // // @Override // public void onTabFragmentDetached(Fragment fragment) { // mTabFragments.remove(fragment); // } // // private class OurViewPagerAdapter extends FragmentPagerAdapter { // // private Fragment mCurrentFragment; // // public OurViewPagerAdapter(FragmentManager fm) { // super(fm); // } // // public Fragment getCurrentFragment() { // return mCurrentFragment; // } // // // @Override // public void setPrimaryItem(ViewGroup container, int position, Object object) { // if (getCurrentFragment() != object) { // mCurrentFragment = ((Fragment) object); // } // super.setPrimaryItem(container, position, object); // } // // @Override // public Fragment getItem(int position) { // LOGD(TAG, "Creating fragment #" + position); // // Fragment frag = new CategoryTabFragment(); // // return frag; // } // // @Override // public int getCount() { // return TAB_TITLE_RES_ID.length; // } // // @Override // public CharSequence getPageTitle(int position) { // return getString(TAB_TITLE_RES_ID[position]); // } // } // // }
import android.test.ActivityInstrumentationTestCase2; import com.crazymin2.retailstore.home.MainActivity;
package com.crazymin2.retailstore; /** * Created by b_ashish on 01-Mar-16. */ public class MainActivityTests extends ActivityInstrumentationTestCase2 { public MainActivityTests(Class activityClass) {
// Path: app/src/main/java/com/crazymin2/retailstore/home/MainActivity.java // public class MainActivity extends BaseActivity implements CommonTabFragment.TabListener { // // // private static final String TAG = MainActivity.class.getSimpleName(); // // public StaggeredGridLayoutManager mStaggeredLayoutManager; // // View pager and adapter (for narrow mode) // @Bind(R.id.view_pager) // ViewPager mViewPager; // @Bind(R.id.sliding_tabs) // TabLayout mTabLayout; // // // OurViewPagerAdapter mViewPagerAdapter = null; // private Set<CommonTabFragment> mTabFragments = new HashSet<CommonTabFragment>(); // // // titles for tab layout items (indices must correspond to the above) // private static final int[] TAB_TITLE_RES_ID = new int[]{ // R.string.tab_item_my_category // }; // // private CollectionRecyclerView mRecyclerView; // public CategoryTabFragment.TabAdapter mAdapter; // // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); // ButterKnife.bind(this); // // renderTabsWithPage(); // } // // private void renderTabsWithPage() { // // mViewPagerAdapter = new OurViewPagerAdapter(getFragmentManager()); // mViewPager.setAdapter(mViewPagerAdapter); // // mTabLayout.setTabsFromPagerAdapter(mViewPagerAdapter); // // mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { // @Override // public void onTabSelected(TabLayout.Tab tab) { // // mViewPager.setCurrentItem(tab.getPosition(), true); // // } // // @Override // public void onTabUnselected(TabLayout.Tab tab) { // // Do nothing // } // // @Override // public void onTabReselected(TabLayout.Tab tab) { // // Do nothing // } // }); // mViewPager.setPageMargin(getResources() // .getDimensionPixelSize(R.dimen.home_page_margin)); // mViewPager.setPageMarginDrawable(R.drawable.page_margin); // // createTabLayoutContentDescriptions(); // } // // private void createTabLayoutContentDescriptions() { // for (int i = 0; i < TAB_TITLE_RES_ID.length; i++) { // mTabLayout.setContentDescription(getString(TAB_TITLE_RES_ID[i])); // } // } // // @Override // public void onTabFragmentViewCreated(Fragment fragment) { // mStaggeredLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL); // mRecyclerView = (CollectionRecyclerView) fragment.getView().findViewById(R.id.list); // mRecyclerView.setLayoutManager(mStaggeredLayoutManager); // mRecyclerView.setHasFixedSize(true); // mAdapter = new CategoryTabFragment.TabAdapter(this); // mRecyclerView.setAdapter(mAdapter); // mAdapter.setOnItemClickListener(onItemClickListener); // enableActionBarAutoHide(mRecyclerView); // } // // private CategoryTabFragment.TabAdapter.OnItemClickListener onItemClickListener = new CategoryTabFragment.TabAdapter.OnItemClickListener() { // // @Override // public void onItemClick(View v, int position) { // int categoryId = mAdapter.getCategoryId(position); // // Intent intent = new Intent(getApplicationContext(), ProductActivity.class); // intent.putExtra(ProductActivity.SELECTED_CATEGORY_ID, categoryId); // startActivity(intent); // } // }; // // @Override // public void onTabFragmentAttached(Fragment fragment) { // mTabFragments.add((CommonTabFragment) fragment); // } // // @Override // public void onTabFragmentDetached(Fragment fragment) { // mTabFragments.remove(fragment); // } // // private class OurViewPagerAdapter extends FragmentPagerAdapter { // // private Fragment mCurrentFragment; // // public OurViewPagerAdapter(FragmentManager fm) { // super(fm); // } // // public Fragment getCurrentFragment() { // return mCurrentFragment; // } // // // @Override // public void setPrimaryItem(ViewGroup container, int position, Object object) { // if (getCurrentFragment() != object) { // mCurrentFragment = ((Fragment) object); // } // super.setPrimaryItem(container, position, object); // } // // @Override // public Fragment getItem(int position) { // LOGD(TAG, "Creating fragment #" + position); // // Fragment frag = new CategoryTabFragment(); // // return frag; // } // // @Override // public int getCount() { // return TAB_TITLE_RES_ID.length; // } // // @Override // public CharSequence getPageTitle(int position) { // return getString(TAB_TITLE_RES_ID[position]); // } // } // // } // Path: app/src/androidTest/java/com/crazymin2/retailstore/MainActivityTests.java import android.test.ActivityInstrumentationTestCase2; import com.crazymin2.retailstore.home.MainActivity; package com.crazymin2.retailstore; /** * Created by b_ashish on 01-Mar-16. */ public class MainActivityTests extends ActivityInstrumentationTestCase2 { public MainActivityTests(Class activityClass) {
super(MainActivity.class);
ashishbhandari/RetailStore
app/src/main/java/com/crazymin2/retailstore/database/DatabaseHelper.java
// Path: app/src/main/java/com/crazymin2/retailstore/ApplicationController.java // public class ApplicationController extends Application { // // private static ApplicationController mInstance; // // @Override // public void onCreate() { // super.onCreate(); // mInstance = this; // } // // public static synchronized ApplicationController getInstance() { // return mInstance; // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/util/LogUtils.java // public static void LOGD(final String tag, String message) { // if (LOGGING_ENABLED){ // if (Log.isLoggable(tag, Log.DEBUG)) { // Log.d(tag, message); // } // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/util/LogUtils.java // public static String makeLogTag(String str) { // if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) { // return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1); // } // // return LOG_PREFIX + str; // }
import android.content.Context; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.crazymin2.retailstore.ApplicationController; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import static com.crazymin2.retailstore.util.LogUtils.LOGD; import static com.crazymin2.retailstore.util.LogUtils.makeLogTag;
package com.crazymin2.retailstore.database; public class DatabaseHelper extends SQLiteOpenHelper { private static final String TAG = makeLogTag(DatabaseHelper.class); /** * Database Version */ private static final int DB_VERSION = 1; private String databasePath; private SQLiteDatabase mDataBase; private Context mContext; /** * Database Name */ private static final String DB_NAME = "retail_store"; /** * Constructor Takes and keeps a reference of the passed context in order to access to the * application assets and resources. * * @param context */ public DatabaseHelper(Context context) { this(context, DB_NAME, DB_VERSION); } /** * Constructor of class. Database Helper class for creating database. * * @param context * @param DB_NAME * @param version */ private DatabaseHelper(Context context, String DB_NAME, int version) { super(context, DB_NAME, null, version);
// Path: app/src/main/java/com/crazymin2/retailstore/ApplicationController.java // public class ApplicationController extends Application { // // private static ApplicationController mInstance; // // @Override // public void onCreate() { // super.onCreate(); // mInstance = this; // } // // public static synchronized ApplicationController getInstance() { // return mInstance; // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/util/LogUtils.java // public static void LOGD(final String tag, String message) { // if (LOGGING_ENABLED){ // if (Log.isLoggable(tag, Log.DEBUG)) { // Log.d(tag, message); // } // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/util/LogUtils.java // public static String makeLogTag(String str) { // if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) { // return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1); // } // // return LOG_PREFIX + str; // } // Path: app/src/main/java/com/crazymin2/retailstore/database/DatabaseHelper.java import android.content.Context; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.crazymin2.retailstore.ApplicationController; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import static com.crazymin2.retailstore.util.LogUtils.LOGD; import static com.crazymin2.retailstore.util.LogUtils.makeLogTag; package com.crazymin2.retailstore.database; public class DatabaseHelper extends SQLiteOpenHelper { private static final String TAG = makeLogTag(DatabaseHelper.class); /** * Database Version */ private static final int DB_VERSION = 1; private String databasePath; private SQLiteDatabase mDataBase; private Context mContext; /** * Database Name */ private static final String DB_NAME = "retail_store"; /** * Constructor Takes and keeps a reference of the passed context in order to access to the * application assets and resources. * * @param context */ public DatabaseHelper(Context context) { this(context, DB_NAME, DB_VERSION); } /** * Constructor of class. Database Helper class for creating database. * * @param context * @param DB_NAME * @param version */ private DatabaseHelper(Context context, String DB_NAME, int version) { super(context, DB_NAME, null, version);
this.databasePath = ApplicationController.getInstance().getFilesDir().getParentFile().getPath() + "/databases/";
ashishbhandari/RetailStore
app/src/main/java/com/crazymin2/retailstore/database/DatabaseHelper.java
// Path: app/src/main/java/com/crazymin2/retailstore/ApplicationController.java // public class ApplicationController extends Application { // // private static ApplicationController mInstance; // // @Override // public void onCreate() { // super.onCreate(); // mInstance = this; // } // // public static synchronized ApplicationController getInstance() { // return mInstance; // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/util/LogUtils.java // public static void LOGD(final String tag, String message) { // if (LOGGING_ENABLED){ // if (Log.isLoggable(tag, Log.DEBUG)) { // Log.d(tag, message); // } // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/util/LogUtils.java // public static String makeLogTag(String str) { // if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) { // return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1); // } // // return LOG_PREFIX + str; // }
import android.content.Context; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.crazymin2.retailstore.ApplicationController; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import static com.crazymin2.retailstore.util.LogUtils.LOGD; import static com.crazymin2.retailstore.util.LogUtils.makeLogTag;
package com.crazymin2.retailstore.database; public class DatabaseHelper extends SQLiteOpenHelper { private static final String TAG = makeLogTag(DatabaseHelper.class); /** * Database Version */ private static final int DB_VERSION = 1; private String databasePath; private SQLiteDatabase mDataBase; private Context mContext; /** * Database Name */ private static final String DB_NAME = "retail_store"; /** * Constructor Takes and keeps a reference of the passed context in order to access to the * application assets and resources. * * @param context */ public DatabaseHelper(Context context) { this(context, DB_NAME, DB_VERSION); } /** * Constructor of class. Database Helper class for creating database. * * @param context * @param DB_NAME * @param version */ private DatabaseHelper(Context context, String DB_NAME, int version) { super(context, DB_NAME, null, version); this.databasePath = ApplicationController.getInstance().getFilesDir().getParentFile().getPath() + "/databases/"; this.mContext = context; try {
// Path: app/src/main/java/com/crazymin2/retailstore/ApplicationController.java // public class ApplicationController extends Application { // // private static ApplicationController mInstance; // // @Override // public void onCreate() { // super.onCreate(); // mInstance = this; // } // // public static synchronized ApplicationController getInstance() { // return mInstance; // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/util/LogUtils.java // public static void LOGD(final String tag, String message) { // if (LOGGING_ENABLED){ // if (Log.isLoggable(tag, Log.DEBUG)) { // Log.d(tag, message); // } // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/util/LogUtils.java // public static String makeLogTag(String str) { // if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) { // return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1); // } // // return LOG_PREFIX + str; // } // Path: app/src/main/java/com/crazymin2/retailstore/database/DatabaseHelper.java import android.content.Context; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.crazymin2.retailstore.ApplicationController; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import static com.crazymin2.retailstore.util.LogUtils.LOGD; import static com.crazymin2.retailstore.util.LogUtils.makeLogTag; package com.crazymin2.retailstore.database; public class DatabaseHelper extends SQLiteOpenHelper { private static final String TAG = makeLogTag(DatabaseHelper.class); /** * Database Version */ private static final int DB_VERSION = 1; private String databasePath; private SQLiteDatabase mDataBase; private Context mContext; /** * Database Name */ private static final String DB_NAME = "retail_store"; /** * Constructor Takes and keeps a reference of the passed context in order to access to the * application assets and resources. * * @param context */ public DatabaseHelper(Context context) { this(context, DB_NAME, DB_VERSION); } /** * Constructor of class. Database Helper class for creating database. * * @param context * @param DB_NAME * @param version */ private DatabaseHelper(Context context, String DB_NAME, int version) { super(context, DB_NAME, null, version); this.databasePath = ApplicationController.getInstance().getFilesDir().getParentFile().getPath() + "/databases/"; this.mContext = context; try {
LOGD(TAG, "Initializing database..." + DB_NAME);
ashishbhandari/RetailStore
app/src/main/java/com/crazymin2/retailstore/database/DatabaseManager.java
// Path: app/src/main/java/com/crazymin2/retailstore/ApplicationController.java // public class ApplicationController extends Application { // // private static ApplicationController mInstance; // // @Override // public void onCreate() { // super.onCreate(); // mInstance = this; // } // // public static synchronized ApplicationController getInstance() { // return mInstance; // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/home/data/Category.java // public class Category { // // public int id; // public int categoryId; // public String imageUrlOriginal; // public String imageUrlThumb; // public String imageUrlSmall; // public String imageUrlMedium; // public String name; // // } // // Path: app/src/main/java/com/crazymin2/retailstore/home/data/Product.java // public class Product implements Parcelable { // // public int id; // public int categoryId; // public int productId; // public String price; // public String imageUrlOriginal; // public String imageUrlThumb; // public String imageUrlSmall; // public String imageUrlMedium; // public String name; // // /* // * Utility variables which are supposed to work for item deletion and addition // */ // public boolean isInCart = false; // public double totalPrice = 0; // // public Product(){ // // } // // // protected Product(Parcel in) { // id = in.readInt(); // categoryId = in.readInt(); // productId = in.readInt(); // price = in.readString(); // imageUrlOriginal = in.readString(); // imageUrlThumb = in.readString(); // imageUrlSmall = in.readString(); // imageUrlMedium = in.readString(); // name = in.readString(); // isInCart = in.readByte() != 0; // totalPrice = in.readDouble(); // } // // public static final Creator<Product> CREATOR = new Creator<Product>() { // @Override // public Product createFromParcel(Parcel in) { // return new Product(in); // } // // @Override // public Product[] newArray(int size) { // return new Product[size]; // } // }; // // /* // * (non-Javadoc) // * // * @see java.lang.Object#equals(java.lang.Object) // * // * Please don not override toString() method it will give response which cause override method // * equals() failure. // * // * the reason behind to override equals and hashCode method is to compare added cart products in // * local database with the products coming from server on basis of unique product id. // */ // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Product other = (Product) obj; // if (id != other.id) // return false; // return true; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + id; // return result; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeInt(categoryId); // dest.writeInt(productId); // dest.writeString(price); // dest.writeString(imageUrlOriginal); // dest.writeString(imageUrlThumb); // dest.writeString(imageUrlSmall); // dest.writeString(imageUrlMedium); // dest.writeString(name); // dest.writeByte((byte) (isInCart ? 1 : 0)); // dest.writeDouble(totalPrice); // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/util/LogUtils.java // public static void LOGE(final String tag, String message) { // if (LOGGING_ENABLED){ // Log.e(tag, message); // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/util/LogUtils.java // public static String makeLogTag(String str) { // if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) { // return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1); // } // // return LOG_PREFIX + str; // }
import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.crazymin2.retailstore.ApplicationController; import com.crazymin2.retailstore.home.data.Category; import com.crazymin2.retailstore.home.data.Product; import java.util.ArrayList; import static com.crazymin2.retailstore.util.LogUtils.LOGE; import static com.crazymin2.retailstore.util.LogUtils.makeLogTag;
* get long value of the database column * * @return String */ private long getLongValue(Cursor cursor, String columnName) { return cursor.getLong(getColumnIndex(cursor, columnName)); } /** * get Integer value of the database column * * @return int */ private int getIntValue(Cursor cursor, String columnName) { try { return cursor.getInt(getColumnIndex(cursor, columnName)); } catch (Exception e) { return 0; } } /** * get long value of the database column * * @return String */ private double getDoubleValue(Cursor cursor, String columnName) { return cursor.getDouble(getColumnIndex(cursor, columnName)); }
// Path: app/src/main/java/com/crazymin2/retailstore/ApplicationController.java // public class ApplicationController extends Application { // // private static ApplicationController mInstance; // // @Override // public void onCreate() { // super.onCreate(); // mInstance = this; // } // // public static synchronized ApplicationController getInstance() { // return mInstance; // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/home/data/Category.java // public class Category { // // public int id; // public int categoryId; // public String imageUrlOriginal; // public String imageUrlThumb; // public String imageUrlSmall; // public String imageUrlMedium; // public String name; // // } // // Path: app/src/main/java/com/crazymin2/retailstore/home/data/Product.java // public class Product implements Parcelable { // // public int id; // public int categoryId; // public int productId; // public String price; // public String imageUrlOriginal; // public String imageUrlThumb; // public String imageUrlSmall; // public String imageUrlMedium; // public String name; // // /* // * Utility variables which are supposed to work for item deletion and addition // */ // public boolean isInCart = false; // public double totalPrice = 0; // // public Product(){ // // } // // // protected Product(Parcel in) { // id = in.readInt(); // categoryId = in.readInt(); // productId = in.readInt(); // price = in.readString(); // imageUrlOriginal = in.readString(); // imageUrlThumb = in.readString(); // imageUrlSmall = in.readString(); // imageUrlMedium = in.readString(); // name = in.readString(); // isInCart = in.readByte() != 0; // totalPrice = in.readDouble(); // } // // public static final Creator<Product> CREATOR = new Creator<Product>() { // @Override // public Product createFromParcel(Parcel in) { // return new Product(in); // } // // @Override // public Product[] newArray(int size) { // return new Product[size]; // } // }; // // /* // * (non-Javadoc) // * // * @see java.lang.Object#equals(java.lang.Object) // * // * Please don not override toString() method it will give response which cause override method // * equals() failure. // * // * the reason behind to override equals and hashCode method is to compare added cart products in // * local database with the products coming from server on basis of unique product id. // */ // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Product other = (Product) obj; // if (id != other.id) // return false; // return true; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + id; // return result; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeInt(categoryId); // dest.writeInt(productId); // dest.writeString(price); // dest.writeString(imageUrlOriginal); // dest.writeString(imageUrlThumb); // dest.writeString(imageUrlSmall); // dest.writeString(imageUrlMedium); // dest.writeString(name); // dest.writeByte((byte) (isInCart ? 1 : 0)); // dest.writeDouble(totalPrice); // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/util/LogUtils.java // public static void LOGE(final String tag, String message) { // if (LOGGING_ENABLED){ // Log.e(tag, message); // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/util/LogUtils.java // public static String makeLogTag(String str) { // if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) { // return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1); // } // // return LOG_PREFIX + str; // } // Path: app/src/main/java/com/crazymin2/retailstore/database/DatabaseManager.java import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.crazymin2.retailstore.ApplicationController; import com.crazymin2.retailstore.home.data.Category; import com.crazymin2.retailstore.home.data.Product; import java.util.ArrayList; import static com.crazymin2.retailstore.util.LogUtils.LOGE; import static com.crazymin2.retailstore.util.LogUtils.makeLogTag; * get long value of the database column * * @return String */ private long getLongValue(Cursor cursor, String columnName) { return cursor.getLong(getColumnIndex(cursor, columnName)); } /** * get Integer value of the database column * * @return int */ private int getIntValue(Cursor cursor, String columnName) { try { return cursor.getInt(getColumnIndex(cursor, columnName)); } catch (Exception e) { return 0; } } /** * get long value of the database column * * @return String */ private double getDoubleValue(Cursor cursor, String columnName) { return cursor.getDouble(getColumnIndex(cursor, columnName)); }
public ArrayList<Category> getCategories() {
ashishbhandari/RetailStore
app/src/main/java/com/crazymin2/retailstore/database/DatabaseManager.java
// Path: app/src/main/java/com/crazymin2/retailstore/ApplicationController.java // public class ApplicationController extends Application { // // private static ApplicationController mInstance; // // @Override // public void onCreate() { // super.onCreate(); // mInstance = this; // } // // public static synchronized ApplicationController getInstance() { // return mInstance; // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/home/data/Category.java // public class Category { // // public int id; // public int categoryId; // public String imageUrlOriginal; // public String imageUrlThumb; // public String imageUrlSmall; // public String imageUrlMedium; // public String name; // // } // // Path: app/src/main/java/com/crazymin2/retailstore/home/data/Product.java // public class Product implements Parcelable { // // public int id; // public int categoryId; // public int productId; // public String price; // public String imageUrlOriginal; // public String imageUrlThumb; // public String imageUrlSmall; // public String imageUrlMedium; // public String name; // // /* // * Utility variables which are supposed to work for item deletion and addition // */ // public boolean isInCart = false; // public double totalPrice = 0; // // public Product(){ // // } // // // protected Product(Parcel in) { // id = in.readInt(); // categoryId = in.readInt(); // productId = in.readInt(); // price = in.readString(); // imageUrlOriginal = in.readString(); // imageUrlThumb = in.readString(); // imageUrlSmall = in.readString(); // imageUrlMedium = in.readString(); // name = in.readString(); // isInCart = in.readByte() != 0; // totalPrice = in.readDouble(); // } // // public static final Creator<Product> CREATOR = new Creator<Product>() { // @Override // public Product createFromParcel(Parcel in) { // return new Product(in); // } // // @Override // public Product[] newArray(int size) { // return new Product[size]; // } // }; // // /* // * (non-Javadoc) // * // * @see java.lang.Object#equals(java.lang.Object) // * // * Please don not override toString() method it will give response which cause override method // * equals() failure. // * // * the reason behind to override equals and hashCode method is to compare added cart products in // * local database with the products coming from server on basis of unique product id. // */ // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Product other = (Product) obj; // if (id != other.id) // return false; // return true; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + id; // return result; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeInt(categoryId); // dest.writeInt(productId); // dest.writeString(price); // dest.writeString(imageUrlOriginal); // dest.writeString(imageUrlThumb); // dest.writeString(imageUrlSmall); // dest.writeString(imageUrlMedium); // dest.writeString(name); // dest.writeByte((byte) (isInCart ? 1 : 0)); // dest.writeDouble(totalPrice); // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/util/LogUtils.java // public static void LOGE(final String tag, String message) { // if (LOGGING_ENABLED){ // Log.e(tag, message); // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/util/LogUtils.java // public static String makeLogTag(String str) { // if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) { // return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1); // } // // return LOG_PREFIX + str; // }
import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.crazymin2.retailstore.ApplicationController; import com.crazymin2.retailstore.home.data.Category; import com.crazymin2.retailstore.home.data.Product; import java.util.ArrayList; import static com.crazymin2.retailstore.util.LogUtils.LOGE; import static com.crazymin2.retailstore.util.LogUtils.makeLogTag;
return cursor.getLong(getColumnIndex(cursor, columnName)); } /** * get Integer value of the database column * * @return int */ private int getIntValue(Cursor cursor, String columnName) { try { return cursor.getInt(getColumnIndex(cursor, columnName)); } catch (Exception e) { return 0; } } /** * get long value of the database column * * @return String */ private double getDoubleValue(Cursor cursor, String columnName) { return cursor.getDouble(getColumnIndex(cursor, columnName)); } public ArrayList<Category> getCategories() { SQLiteDatabase database = null; ArrayList<Category> categories = new ArrayList<Category>(); Cursor cursor = null; try {
// Path: app/src/main/java/com/crazymin2/retailstore/ApplicationController.java // public class ApplicationController extends Application { // // private static ApplicationController mInstance; // // @Override // public void onCreate() { // super.onCreate(); // mInstance = this; // } // // public static synchronized ApplicationController getInstance() { // return mInstance; // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/home/data/Category.java // public class Category { // // public int id; // public int categoryId; // public String imageUrlOriginal; // public String imageUrlThumb; // public String imageUrlSmall; // public String imageUrlMedium; // public String name; // // } // // Path: app/src/main/java/com/crazymin2/retailstore/home/data/Product.java // public class Product implements Parcelable { // // public int id; // public int categoryId; // public int productId; // public String price; // public String imageUrlOriginal; // public String imageUrlThumb; // public String imageUrlSmall; // public String imageUrlMedium; // public String name; // // /* // * Utility variables which are supposed to work for item deletion and addition // */ // public boolean isInCart = false; // public double totalPrice = 0; // // public Product(){ // // } // // // protected Product(Parcel in) { // id = in.readInt(); // categoryId = in.readInt(); // productId = in.readInt(); // price = in.readString(); // imageUrlOriginal = in.readString(); // imageUrlThumb = in.readString(); // imageUrlSmall = in.readString(); // imageUrlMedium = in.readString(); // name = in.readString(); // isInCart = in.readByte() != 0; // totalPrice = in.readDouble(); // } // // public static final Creator<Product> CREATOR = new Creator<Product>() { // @Override // public Product createFromParcel(Parcel in) { // return new Product(in); // } // // @Override // public Product[] newArray(int size) { // return new Product[size]; // } // }; // // /* // * (non-Javadoc) // * // * @see java.lang.Object#equals(java.lang.Object) // * // * Please don not override toString() method it will give response which cause override method // * equals() failure. // * // * the reason behind to override equals and hashCode method is to compare added cart products in // * local database with the products coming from server on basis of unique product id. // */ // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Product other = (Product) obj; // if (id != other.id) // return false; // return true; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + id; // return result; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeInt(categoryId); // dest.writeInt(productId); // dest.writeString(price); // dest.writeString(imageUrlOriginal); // dest.writeString(imageUrlThumb); // dest.writeString(imageUrlSmall); // dest.writeString(imageUrlMedium); // dest.writeString(name); // dest.writeByte((byte) (isInCart ? 1 : 0)); // dest.writeDouble(totalPrice); // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/util/LogUtils.java // public static void LOGE(final String tag, String message) { // if (LOGGING_ENABLED){ // Log.e(tag, message); // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/util/LogUtils.java // public static String makeLogTag(String str) { // if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) { // return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1); // } // // return LOG_PREFIX + str; // } // Path: app/src/main/java/com/crazymin2/retailstore/database/DatabaseManager.java import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.crazymin2.retailstore.ApplicationController; import com.crazymin2.retailstore.home.data.Category; import com.crazymin2.retailstore.home.data.Product; import java.util.ArrayList; import static com.crazymin2.retailstore.util.LogUtils.LOGE; import static com.crazymin2.retailstore.util.LogUtils.makeLogTag; return cursor.getLong(getColumnIndex(cursor, columnName)); } /** * get Integer value of the database column * * @return int */ private int getIntValue(Cursor cursor, String columnName) { try { return cursor.getInt(getColumnIndex(cursor, columnName)); } catch (Exception e) { return 0; } } /** * get long value of the database column * * @return String */ private double getDoubleValue(Cursor cursor, String columnName) { return cursor.getDouble(getColumnIndex(cursor, columnName)); } public ArrayList<Category> getCategories() { SQLiteDatabase database = null; ArrayList<Category> categories = new ArrayList<Category>(); Cursor cursor = null; try {
DatabaseHelper dbHelper = new DatabaseHelper(ApplicationController.getInstance());
ashishbhandari/RetailStore
app/src/main/java/com/crazymin2/retailstore/database/DatabaseManager.java
// Path: app/src/main/java/com/crazymin2/retailstore/ApplicationController.java // public class ApplicationController extends Application { // // private static ApplicationController mInstance; // // @Override // public void onCreate() { // super.onCreate(); // mInstance = this; // } // // public static synchronized ApplicationController getInstance() { // return mInstance; // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/home/data/Category.java // public class Category { // // public int id; // public int categoryId; // public String imageUrlOriginal; // public String imageUrlThumb; // public String imageUrlSmall; // public String imageUrlMedium; // public String name; // // } // // Path: app/src/main/java/com/crazymin2/retailstore/home/data/Product.java // public class Product implements Parcelable { // // public int id; // public int categoryId; // public int productId; // public String price; // public String imageUrlOriginal; // public String imageUrlThumb; // public String imageUrlSmall; // public String imageUrlMedium; // public String name; // // /* // * Utility variables which are supposed to work for item deletion and addition // */ // public boolean isInCart = false; // public double totalPrice = 0; // // public Product(){ // // } // // // protected Product(Parcel in) { // id = in.readInt(); // categoryId = in.readInt(); // productId = in.readInt(); // price = in.readString(); // imageUrlOriginal = in.readString(); // imageUrlThumb = in.readString(); // imageUrlSmall = in.readString(); // imageUrlMedium = in.readString(); // name = in.readString(); // isInCart = in.readByte() != 0; // totalPrice = in.readDouble(); // } // // public static final Creator<Product> CREATOR = new Creator<Product>() { // @Override // public Product createFromParcel(Parcel in) { // return new Product(in); // } // // @Override // public Product[] newArray(int size) { // return new Product[size]; // } // }; // // /* // * (non-Javadoc) // * // * @see java.lang.Object#equals(java.lang.Object) // * // * Please don not override toString() method it will give response which cause override method // * equals() failure. // * // * the reason behind to override equals and hashCode method is to compare added cart products in // * local database with the products coming from server on basis of unique product id. // */ // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Product other = (Product) obj; // if (id != other.id) // return false; // return true; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + id; // return result; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeInt(categoryId); // dest.writeInt(productId); // dest.writeString(price); // dest.writeString(imageUrlOriginal); // dest.writeString(imageUrlThumb); // dest.writeString(imageUrlSmall); // dest.writeString(imageUrlMedium); // dest.writeString(name); // dest.writeByte((byte) (isInCart ? 1 : 0)); // dest.writeDouble(totalPrice); // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/util/LogUtils.java // public static void LOGE(final String tag, String message) { // if (LOGGING_ENABLED){ // Log.e(tag, message); // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/util/LogUtils.java // public static String makeLogTag(String str) { // if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) { // return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1); // } // // return LOG_PREFIX + str; // }
import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.crazymin2.retailstore.ApplicationController; import com.crazymin2.retailstore.home.data.Category; import com.crazymin2.retailstore.home.data.Product; import java.util.ArrayList; import static com.crazymin2.retailstore.util.LogUtils.LOGE; import static com.crazymin2.retailstore.util.LogUtils.makeLogTag;
database = dbHelper.getReadableDatabase(); cursor = database.query(CATEGORY.TABLE_NAME, null, null, null, null, null, null); if (cursor.moveToFirst()) { do { Category category = new Category(); category.id = getIntValue(cursor, CATEGORY._ID); category.categoryId = getIntValue(cursor, CATEGORY.CATEGORY_ID); category.imageUrlOriginal = getStringValue(cursor, CATEGORY.IMAGE_URL_ORIGINAL); category.imageUrlThumb = getStringValue(cursor, CATEGORY.IMAGE_URL_THUMB); category.imageUrlSmall = getStringValue(cursor, CATEGORY.IMAGE_URL_SMALL); category.imageUrlMedium = getStringValue(cursor, CATEGORY.IMAGE_URL_MEDIUM); category.name = getStringValue(cursor, CATEGORY.NAME); categories.add(category); } while (cursor.moveToNext()); } } catch (Exception e) { e.printStackTrace(); } finally { if (database != null) { database.close(); } if (cursor != null && !cursor.isClosed()) { cursor.close(); } } return categories; }
// Path: app/src/main/java/com/crazymin2/retailstore/ApplicationController.java // public class ApplicationController extends Application { // // private static ApplicationController mInstance; // // @Override // public void onCreate() { // super.onCreate(); // mInstance = this; // } // // public static synchronized ApplicationController getInstance() { // return mInstance; // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/home/data/Category.java // public class Category { // // public int id; // public int categoryId; // public String imageUrlOriginal; // public String imageUrlThumb; // public String imageUrlSmall; // public String imageUrlMedium; // public String name; // // } // // Path: app/src/main/java/com/crazymin2/retailstore/home/data/Product.java // public class Product implements Parcelable { // // public int id; // public int categoryId; // public int productId; // public String price; // public String imageUrlOriginal; // public String imageUrlThumb; // public String imageUrlSmall; // public String imageUrlMedium; // public String name; // // /* // * Utility variables which are supposed to work for item deletion and addition // */ // public boolean isInCart = false; // public double totalPrice = 0; // // public Product(){ // // } // // // protected Product(Parcel in) { // id = in.readInt(); // categoryId = in.readInt(); // productId = in.readInt(); // price = in.readString(); // imageUrlOriginal = in.readString(); // imageUrlThumb = in.readString(); // imageUrlSmall = in.readString(); // imageUrlMedium = in.readString(); // name = in.readString(); // isInCart = in.readByte() != 0; // totalPrice = in.readDouble(); // } // // public static final Creator<Product> CREATOR = new Creator<Product>() { // @Override // public Product createFromParcel(Parcel in) { // return new Product(in); // } // // @Override // public Product[] newArray(int size) { // return new Product[size]; // } // }; // // /* // * (non-Javadoc) // * // * @see java.lang.Object#equals(java.lang.Object) // * // * Please don not override toString() method it will give response which cause override method // * equals() failure. // * // * the reason behind to override equals and hashCode method is to compare added cart products in // * local database with the products coming from server on basis of unique product id. // */ // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Product other = (Product) obj; // if (id != other.id) // return false; // return true; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + id; // return result; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeInt(categoryId); // dest.writeInt(productId); // dest.writeString(price); // dest.writeString(imageUrlOriginal); // dest.writeString(imageUrlThumb); // dest.writeString(imageUrlSmall); // dest.writeString(imageUrlMedium); // dest.writeString(name); // dest.writeByte((byte) (isInCart ? 1 : 0)); // dest.writeDouble(totalPrice); // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/util/LogUtils.java // public static void LOGE(final String tag, String message) { // if (LOGGING_ENABLED){ // Log.e(tag, message); // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/util/LogUtils.java // public static String makeLogTag(String str) { // if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) { // return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1); // } // // return LOG_PREFIX + str; // } // Path: app/src/main/java/com/crazymin2/retailstore/database/DatabaseManager.java import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.crazymin2.retailstore.ApplicationController; import com.crazymin2.retailstore.home.data.Category; import com.crazymin2.retailstore.home.data.Product; import java.util.ArrayList; import static com.crazymin2.retailstore.util.LogUtils.LOGE; import static com.crazymin2.retailstore.util.LogUtils.makeLogTag; database = dbHelper.getReadableDatabase(); cursor = database.query(CATEGORY.TABLE_NAME, null, null, null, null, null, null); if (cursor.moveToFirst()) { do { Category category = new Category(); category.id = getIntValue(cursor, CATEGORY._ID); category.categoryId = getIntValue(cursor, CATEGORY.CATEGORY_ID); category.imageUrlOriginal = getStringValue(cursor, CATEGORY.IMAGE_URL_ORIGINAL); category.imageUrlThumb = getStringValue(cursor, CATEGORY.IMAGE_URL_THUMB); category.imageUrlSmall = getStringValue(cursor, CATEGORY.IMAGE_URL_SMALL); category.imageUrlMedium = getStringValue(cursor, CATEGORY.IMAGE_URL_MEDIUM); category.name = getStringValue(cursor, CATEGORY.NAME); categories.add(category); } while (cursor.moveToNext()); } } catch (Exception e) { e.printStackTrace(); } finally { if (database != null) { database.close(); } if (cursor != null && !cursor.isClosed()) { cursor.close(); } } return categories; }
public ArrayList<Product> getProductsByCategory(int categoryId) {
ashishbhandari/RetailStore
app/src/main/java/com/crazymin2/retailstore/database/DatabaseManager.java
// Path: app/src/main/java/com/crazymin2/retailstore/ApplicationController.java // public class ApplicationController extends Application { // // private static ApplicationController mInstance; // // @Override // public void onCreate() { // super.onCreate(); // mInstance = this; // } // // public static synchronized ApplicationController getInstance() { // return mInstance; // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/home/data/Category.java // public class Category { // // public int id; // public int categoryId; // public String imageUrlOriginal; // public String imageUrlThumb; // public String imageUrlSmall; // public String imageUrlMedium; // public String name; // // } // // Path: app/src/main/java/com/crazymin2/retailstore/home/data/Product.java // public class Product implements Parcelable { // // public int id; // public int categoryId; // public int productId; // public String price; // public String imageUrlOriginal; // public String imageUrlThumb; // public String imageUrlSmall; // public String imageUrlMedium; // public String name; // // /* // * Utility variables which are supposed to work for item deletion and addition // */ // public boolean isInCart = false; // public double totalPrice = 0; // // public Product(){ // // } // // // protected Product(Parcel in) { // id = in.readInt(); // categoryId = in.readInt(); // productId = in.readInt(); // price = in.readString(); // imageUrlOriginal = in.readString(); // imageUrlThumb = in.readString(); // imageUrlSmall = in.readString(); // imageUrlMedium = in.readString(); // name = in.readString(); // isInCart = in.readByte() != 0; // totalPrice = in.readDouble(); // } // // public static final Creator<Product> CREATOR = new Creator<Product>() { // @Override // public Product createFromParcel(Parcel in) { // return new Product(in); // } // // @Override // public Product[] newArray(int size) { // return new Product[size]; // } // }; // // /* // * (non-Javadoc) // * // * @see java.lang.Object#equals(java.lang.Object) // * // * Please don not override toString() method it will give response which cause override method // * equals() failure. // * // * the reason behind to override equals and hashCode method is to compare added cart products in // * local database with the products coming from server on basis of unique product id. // */ // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Product other = (Product) obj; // if (id != other.id) // return false; // return true; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + id; // return result; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeInt(categoryId); // dest.writeInt(productId); // dest.writeString(price); // dest.writeString(imageUrlOriginal); // dest.writeString(imageUrlThumb); // dest.writeString(imageUrlSmall); // dest.writeString(imageUrlMedium); // dest.writeString(name); // dest.writeByte((byte) (isInCart ? 1 : 0)); // dest.writeDouble(totalPrice); // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/util/LogUtils.java // public static void LOGE(final String tag, String message) { // if (LOGGING_ENABLED){ // Log.e(tag, message); // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/util/LogUtils.java // public static String makeLogTag(String str) { // if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) { // return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1); // } // // return LOG_PREFIX + str; // }
import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.crazymin2.retailstore.ApplicationController; import com.crazymin2.retailstore.home.data.Category; import com.crazymin2.retailstore.home.data.Product; import java.util.ArrayList; import static com.crazymin2.retailstore.util.LogUtils.LOGE; import static com.crazymin2.retailstore.util.LogUtils.makeLogTag;
if (database != null) { database.close(); } if (cursor != null && !cursor.isClosed()) { cursor.close(); } } return products; } public boolean saveCartProduct(Product myCartProduct) { SQLiteDatabase database = null; try { DatabaseHelper dbHelper = new DatabaseHelper(ApplicationController.getInstance()); database = dbHelper.openDataBase(); ContentValues contentValues = new ContentValues(); contentValues.put(CART_PRODUCT.CATEGORY_ID, myCartProduct.categoryId); contentValues.put(CART_PRODUCT.PRODUCT_ID, myCartProduct.productId); contentValues.put(CART_PRODUCT.TOTAL_PRICE, myCartProduct.totalPrice); long productId = database.insert(CART_PRODUCT.TABLE_NAME, null, contentValues); if (productId == -1) { return false; } return true; } catch (Exception e) { e.printStackTrace();
// Path: app/src/main/java/com/crazymin2/retailstore/ApplicationController.java // public class ApplicationController extends Application { // // private static ApplicationController mInstance; // // @Override // public void onCreate() { // super.onCreate(); // mInstance = this; // } // // public static synchronized ApplicationController getInstance() { // return mInstance; // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/home/data/Category.java // public class Category { // // public int id; // public int categoryId; // public String imageUrlOriginal; // public String imageUrlThumb; // public String imageUrlSmall; // public String imageUrlMedium; // public String name; // // } // // Path: app/src/main/java/com/crazymin2/retailstore/home/data/Product.java // public class Product implements Parcelable { // // public int id; // public int categoryId; // public int productId; // public String price; // public String imageUrlOriginal; // public String imageUrlThumb; // public String imageUrlSmall; // public String imageUrlMedium; // public String name; // // /* // * Utility variables which are supposed to work for item deletion and addition // */ // public boolean isInCart = false; // public double totalPrice = 0; // // public Product(){ // // } // // // protected Product(Parcel in) { // id = in.readInt(); // categoryId = in.readInt(); // productId = in.readInt(); // price = in.readString(); // imageUrlOriginal = in.readString(); // imageUrlThumb = in.readString(); // imageUrlSmall = in.readString(); // imageUrlMedium = in.readString(); // name = in.readString(); // isInCart = in.readByte() != 0; // totalPrice = in.readDouble(); // } // // public static final Creator<Product> CREATOR = new Creator<Product>() { // @Override // public Product createFromParcel(Parcel in) { // return new Product(in); // } // // @Override // public Product[] newArray(int size) { // return new Product[size]; // } // }; // // /* // * (non-Javadoc) // * // * @see java.lang.Object#equals(java.lang.Object) // * // * Please don not override toString() method it will give response which cause override method // * equals() failure. // * // * the reason behind to override equals and hashCode method is to compare added cart products in // * local database with the products coming from server on basis of unique product id. // */ // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Product other = (Product) obj; // if (id != other.id) // return false; // return true; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + id; // return result; // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeInt(categoryId); // dest.writeInt(productId); // dest.writeString(price); // dest.writeString(imageUrlOriginal); // dest.writeString(imageUrlThumb); // dest.writeString(imageUrlSmall); // dest.writeString(imageUrlMedium); // dest.writeString(name); // dest.writeByte((byte) (isInCart ? 1 : 0)); // dest.writeDouble(totalPrice); // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/util/LogUtils.java // public static void LOGE(final String tag, String message) { // if (LOGGING_ENABLED){ // Log.e(tag, message); // } // } // // Path: app/src/main/java/com/crazymin2/retailstore/util/LogUtils.java // public static String makeLogTag(String str) { // if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) { // return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1); // } // // return LOG_PREFIX + str; // } // Path: app/src/main/java/com/crazymin2/retailstore/database/DatabaseManager.java import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.crazymin2.retailstore.ApplicationController; import com.crazymin2.retailstore.home.data.Category; import com.crazymin2.retailstore.home.data.Product; import java.util.ArrayList; import static com.crazymin2.retailstore.util.LogUtils.LOGE; import static com.crazymin2.retailstore.util.LogUtils.makeLogTag; if (database != null) { database.close(); } if (cursor != null && !cursor.isClosed()) { cursor.close(); } } return products; } public boolean saveCartProduct(Product myCartProduct) { SQLiteDatabase database = null; try { DatabaseHelper dbHelper = new DatabaseHelper(ApplicationController.getInstance()); database = dbHelper.openDataBase(); ContentValues contentValues = new ContentValues(); contentValues.put(CART_PRODUCT.CATEGORY_ID, myCartProduct.categoryId); contentValues.put(CART_PRODUCT.PRODUCT_ID, myCartProduct.productId); contentValues.put(CART_PRODUCT.TOTAL_PRICE, myCartProduct.totalPrice); long productId = database.insert(CART_PRODUCT.TABLE_NAME, null, contentValues); if (productId == -1) { return false; } return true; } catch (Exception e) { e.printStackTrace();
LOGE(TAG, "Exception in saving product in cart ", e);
benashford/jresp
src/test/java/jresp/ClientTest.java
// Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // }
import jresp.protocol.RespType; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.stream.IntStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull;
/* * Copyright 2015 Ben Ashford * * 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 jresp; public class ClientTest extends JRESPTest { private Connection con;
// Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // } // Path: src/test/java/jresp/ClientTest.java import jresp.protocol.RespType; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.stream.IntStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; /* * Copyright 2015 Ben Ashford * * 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 jresp; public class ClientTest extends JRESPTest { private Connection con;
private List<RespType> results = new ArrayList<>();
benashford/jresp
src/main/java/jresp/RespDecoder.java
// Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // }
import jresp.protocol.RespType; import jresp.state.*; import java.nio.ByteBuffer; import java.util.function.Consumer;
/* * Copyright 2015 Ben Ashford * * 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 jresp; public class RespDecoder { private SimpleStrState simpleStrDecoder = new SimpleStrState(); private ErrState errDecoder = new ErrState(); private IntState intDecoder = new IntState(); private BulkStrState bulkStrDecoder; private State state = null; RespDecoder() { bulkStrDecoder = new BulkStrState(this); }
// Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // } // Path: src/main/java/jresp/RespDecoder.java import jresp.protocol.RespType; import jresp.state.*; import java.nio.ByteBuffer; import java.util.function.Consumer; /* * Copyright 2015 Ben Ashford * * 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 jresp; public class RespDecoder { private SimpleStrState simpleStrDecoder = new SimpleStrState(); private ErrState errDecoder = new ErrState(); private IntState intDecoder = new IntState(); private BulkStrState bulkStrDecoder; private State state = null; RespDecoder() { bulkStrDecoder = new BulkStrState(this); }
protected void decode(ByteBuffer in, Consumer<RespType> out) {
benashford/jresp
src/main/java/jresp/state/ScannableState.java
// Path: src/main/java/jresp/protocol/Resp.java // public class Resp { // public static final byte[] CRLF; // // private static final int CACHED_LONGS = 32; // // public static final byte[][] LONGS = new byte[CACHED_LONGS][]; // private static final byte[] MINUS_ONE = l2ba(-1); // // static { // try { // CRLF = "\r\n".getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // // for (int i = 0; i < CACHED_LONGS; i++) { // LONGS[i] = l2ba(i); // } // } // // private static byte[] l2ba(long val) { // try { // return Long.toString(val).getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // static byte[] longToByteArray(long val) { // if (val == -1) { // return MINUS_ONE; // } else if (val < CACHED_LONGS) { // return LONGS[(int)val]; // } else { // return l2ba(val); // } // } // // /** // * Pick an existing, or create a new ByteBuffer // */ // static ByteBuffer buffer(Deque<ByteBuffer> buffers, int size) { // if (!buffers.isEmpty()) { // ByteBuffer last = buffers.peekLast(); // if (last.remaining() >= size) { // return last; // } // } // ByteBuffer newBuffer = ByteBuffer.allocate(Math.max(1460, size)); // buffers.add(newBuffer); // return newBuffer; // } // }
import jresp.protocol.Resp; import java.nio.ByteBuffer; import java.nio.charset.Charset;
/* * Copyright 2015 Ben Ashford * * 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 jresp.state; abstract class ScannableState implements State { private static final int DEFAULT_SIZE = 32; private static final int MAXIMUM_SIZE = 32 * 1000; private byte[] buffer = new byte[DEFAULT_SIZE]; private int idx = 0; public ScannableState reset() { if (buffer.length > MAXIMUM_SIZE) { buffer = new byte[DEFAULT_SIZE]; } idx = 0; return this; } @Override public boolean decode(ByteBuffer in) { int available = in.remaining(); if (available > 0) { for (int i = 0; i < available; i++) { byte b = in.get();
// Path: src/main/java/jresp/protocol/Resp.java // public class Resp { // public static final byte[] CRLF; // // private static final int CACHED_LONGS = 32; // // public static final byte[][] LONGS = new byte[CACHED_LONGS][]; // private static final byte[] MINUS_ONE = l2ba(-1); // // static { // try { // CRLF = "\r\n".getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // // for (int i = 0; i < CACHED_LONGS; i++) { // LONGS[i] = l2ba(i); // } // } // // private static byte[] l2ba(long val) { // try { // return Long.toString(val).getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // static byte[] longToByteArray(long val) { // if (val == -1) { // return MINUS_ONE; // } else if (val < CACHED_LONGS) { // return LONGS[(int)val]; // } else { // return l2ba(val); // } // } // // /** // * Pick an existing, or create a new ByteBuffer // */ // static ByteBuffer buffer(Deque<ByteBuffer> buffers, int size) { // if (!buffers.isEmpty()) { // ByteBuffer last = buffers.peekLast(); // if (last.remaining() >= size) { // return last; // } // } // ByteBuffer newBuffer = ByteBuffer.allocate(Math.max(1460, size)); // buffers.add(newBuffer); // return newBuffer; // } // } // Path: src/main/java/jresp/state/ScannableState.java import jresp.protocol.Resp; import java.nio.ByteBuffer; import java.nio.charset.Charset; /* * Copyright 2015 Ben Ashford * * 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 jresp.state; abstract class ScannableState implements State { private static final int DEFAULT_SIZE = 32; private static final int MAXIMUM_SIZE = 32 * 1000; private byte[] buffer = new byte[DEFAULT_SIZE]; private int idx = 0; public ScannableState reset() { if (buffer.length > MAXIMUM_SIZE) { buffer = new byte[DEFAULT_SIZE]; } idx = 0; return this; } @Override public boolean decode(ByteBuffer in) { int available = in.remaining(); if (available > 0) { for (int i = 0; i < available; i++) { byte b = in.get();
if (idx > 0 && buffer[idx - 1] == Resp.CRLF[0] && b == Resp.CRLF[1]) {
benashford/jresp
src/main/java/jresp/state/ErrState.java
// Path: src/main/java/jresp/protocol/Err.java // public class Err implements RespType { // private String payload; // // public Err(String payload) { // this.payload = payload; // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), payload); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // try { // byte[] bytes = payload.getBytes("UTF-8"); // int size = 1 + bytes.length + 2; // // ByteBuffer o = Resp.buffer(out, size); // // o.put((byte)'-'); // o.put(bytes); // o.put(Resp.CRLF); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // @Override // public Object unwrap() { // return payload; // } // } // // Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // }
import jresp.protocol.Err; import jresp.protocol.RespType;
/* * Copyright 2015 Ben Ashford * * 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 jresp.state; public class ErrState extends ScannableState { @Override
// Path: src/main/java/jresp/protocol/Err.java // public class Err implements RespType { // private String payload; // // public Err(String payload) { // this.payload = payload; // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), payload); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // try { // byte[] bytes = payload.getBytes("UTF-8"); // int size = 1 + bytes.length + 2; // // ByteBuffer o = Resp.buffer(out, size); // // o.put((byte)'-'); // o.put(bytes); // o.put(Resp.CRLF); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // @Override // public Object unwrap() { // return payload; // } // } // // Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // } // Path: src/main/java/jresp/state/ErrState.java import jresp.protocol.Err; import jresp.protocol.RespType; /* * Copyright 2015 Ben Ashford * * 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 jresp.state; public class ErrState extends ScannableState { @Override
public RespType finish() {
benashford/jresp
src/main/java/jresp/state/ErrState.java
// Path: src/main/java/jresp/protocol/Err.java // public class Err implements RespType { // private String payload; // // public Err(String payload) { // this.payload = payload; // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), payload); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // try { // byte[] bytes = payload.getBytes("UTF-8"); // int size = 1 + bytes.length + 2; // // ByteBuffer o = Resp.buffer(out, size); // // o.put((byte)'-'); // o.put(bytes); // o.put(Resp.CRLF); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // @Override // public Object unwrap() { // return payload; // } // } // // Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // }
import jresp.protocol.Err; import jresp.protocol.RespType;
/* * Copyright 2015 Ben Ashford * * 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 jresp.state; public class ErrState extends ScannableState { @Override public RespType finish() {
// Path: src/main/java/jresp/protocol/Err.java // public class Err implements RespType { // private String payload; // // public Err(String payload) { // this.payload = payload; // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), payload); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // try { // byte[] bytes = payload.getBytes("UTF-8"); // int size = 1 + bytes.length + 2; // // ByteBuffer o = Resp.buffer(out, size); // // o.put((byte)'-'); // o.put(bytes); // o.put(Resp.CRLF); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // @Override // public Object unwrap() { // return payload; // } // } // // Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // } // Path: src/main/java/jresp/state/ErrState.java import jresp.protocol.Err; import jresp.protocol.RespType; /* * Copyright 2015 Ben Ashford * * 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 jresp.state; public class ErrState extends ScannableState { @Override public RespType finish() {
return new Err(bufferAsString());
benashford/jresp
src/main/java/jresp/state/AryState.java
// Path: src/main/java/jresp/RespDecoder.java // public class RespDecoder { // // private SimpleStrState simpleStrDecoder = new SimpleStrState(); // private ErrState errDecoder = new ErrState(); // private IntState intDecoder = new IntState(); // private BulkStrState bulkStrDecoder; // // private State state = null; // // RespDecoder() { // bulkStrDecoder = new BulkStrState(this); // } // // protected void decode(ByteBuffer in, Consumer<RespType> out) { // while (true) { // int availableBytes = in.remaining(); // if (availableBytes == 0) { // // // // We need more bytes // // // break; // } // // if (state == null) { // // // // There is no current state, so read the next byte // // // char nextChar = (char) in.get(); // state = nextState(nextChar); // } // if (state.decode(in)) { // out.accept(state.finish()); // state = null; // } else { // // // // We need more bytes // // // break; // } // } // } // // public State nextState(char token) { // switch (token) { // case '+': // return simpleStrDecoder.reset(); // case '-': // return errDecoder.reset(); // case ':': // return intDecoder.reset(); // case '$': // return bulkStrDecoder.reset(); // case '*': // return new AryState(this); // default: // throw new IllegalStateException(String.format("Unknown token %s", token)); // } // } // // public IntState intDecoder() { // return (IntState)intDecoder.reset(); // } // } // // Path: src/main/java/jresp/protocol/Ary.java // public class Ary implements RespType { // private List<RespType> payload; // // public Ary(List<RespType> payload) { // this.payload = payload; // } // // public Ary(RespType... payload) { // this.payload = Arrays.asList(payload); // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), payload); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // byte[] header = Resp.longToByteArray(payload.size()); // int size = 1 + header.length + 2; // ByteBuffer o = Resp.buffer(out, size); // o.put((byte)'*'); // o.put(header); // o.put(Resp.CRLF); // payload.stream().forEach(x -> x.writeBytes(out)); // } // // public List<RespType> raw() { // return payload; // } // // @Override // public Object unwrap() { // return payload.stream().map(RespType::unwrap).collect(Collectors.toList()); // } // // @Override // public int hashCode() { // return payload.hashCode(); // } // // @Override // public boolean equals(Object o) { // if (o instanceof Ary) { // Ary a = (Ary)o; // return payload.equals(a.payload); // } else { // return false; // } // } // } // // Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // }
import jresp.RespDecoder; import jresp.protocol.Ary; import jresp.protocol.RespType; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List;
/* * Copyright 2015 Ben Ashford * * 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 jresp.state; public class AryState implements State { private RespDecoder parent; private IntState intState; private Integer aryLength = null;
// Path: src/main/java/jresp/RespDecoder.java // public class RespDecoder { // // private SimpleStrState simpleStrDecoder = new SimpleStrState(); // private ErrState errDecoder = new ErrState(); // private IntState intDecoder = new IntState(); // private BulkStrState bulkStrDecoder; // // private State state = null; // // RespDecoder() { // bulkStrDecoder = new BulkStrState(this); // } // // protected void decode(ByteBuffer in, Consumer<RespType> out) { // while (true) { // int availableBytes = in.remaining(); // if (availableBytes == 0) { // // // // We need more bytes // // // break; // } // // if (state == null) { // // // // There is no current state, so read the next byte // // // char nextChar = (char) in.get(); // state = nextState(nextChar); // } // if (state.decode(in)) { // out.accept(state.finish()); // state = null; // } else { // // // // We need more bytes // // // break; // } // } // } // // public State nextState(char token) { // switch (token) { // case '+': // return simpleStrDecoder.reset(); // case '-': // return errDecoder.reset(); // case ':': // return intDecoder.reset(); // case '$': // return bulkStrDecoder.reset(); // case '*': // return new AryState(this); // default: // throw new IllegalStateException(String.format("Unknown token %s", token)); // } // } // // public IntState intDecoder() { // return (IntState)intDecoder.reset(); // } // } // // Path: src/main/java/jresp/protocol/Ary.java // public class Ary implements RespType { // private List<RespType> payload; // // public Ary(List<RespType> payload) { // this.payload = payload; // } // // public Ary(RespType... payload) { // this.payload = Arrays.asList(payload); // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), payload); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // byte[] header = Resp.longToByteArray(payload.size()); // int size = 1 + header.length + 2; // ByteBuffer o = Resp.buffer(out, size); // o.put((byte)'*'); // o.put(header); // o.put(Resp.CRLF); // payload.stream().forEach(x -> x.writeBytes(out)); // } // // public List<RespType> raw() { // return payload; // } // // @Override // public Object unwrap() { // return payload.stream().map(RespType::unwrap).collect(Collectors.toList()); // } // // @Override // public int hashCode() { // return payload.hashCode(); // } // // @Override // public boolean equals(Object o) { // if (o instanceof Ary) { // Ary a = (Ary)o; // return payload.equals(a.payload); // } else { // return false; // } // } // } // // Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // } // Path: src/main/java/jresp/state/AryState.java import jresp.RespDecoder; import jresp.protocol.Ary; import jresp.protocol.RespType; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; /* * Copyright 2015 Ben Ashford * * 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 jresp.state; public class AryState implements State { private RespDecoder parent; private IntState intState; private Integer aryLength = null;
private List<RespType> ary = null;
benashford/jresp
src/main/java/jresp/state/AryState.java
// Path: src/main/java/jresp/RespDecoder.java // public class RespDecoder { // // private SimpleStrState simpleStrDecoder = new SimpleStrState(); // private ErrState errDecoder = new ErrState(); // private IntState intDecoder = new IntState(); // private BulkStrState bulkStrDecoder; // // private State state = null; // // RespDecoder() { // bulkStrDecoder = new BulkStrState(this); // } // // protected void decode(ByteBuffer in, Consumer<RespType> out) { // while (true) { // int availableBytes = in.remaining(); // if (availableBytes == 0) { // // // // We need more bytes // // // break; // } // // if (state == null) { // // // // There is no current state, so read the next byte // // // char nextChar = (char) in.get(); // state = nextState(nextChar); // } // if (state.decode(in)) { // out.accept(state.finish()); // state = null; // } else { // // // // We need more bytes // // // break; // } // } // } // // public State nextState(char token) { // switch (token) { // case '+': // return simpleStrDecoder.reset(); // case '-': // return errDecoder.reset(); // case ':': // return intDecoder.reset(); // case '$': // return bulkStrDecoder.reset(); // case '*': // return new AryState(this); // default: // throw new IllegalStateException(String.format("Unknown token %s", token)); // } // } // // public IntState intDecoder() { // return (IntState)intDecoder.reset(); // } // } // // Path: src/main/java/jresp/protocol/Ary.java // public class Ary implements RespType { // private List<RespType> payload; // // public Ary(List<RespType> payload) { // this.payload = payload; // } // // public Ary(RespType... payload) { // this.payload = Arrays.asList(payload); // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), payload); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // byte[] header = Resp.longToByteArray(payload.size()); // int size = 1 + header.length + 2; // ByteBuffer o = Resp.buffer(out, size); // o.put((byte)'*'); // o.put(header); // o.put(Resp.CRLF); // payload.stream().forEach(x -> x.writeBytes(out)); // } // // public List<RespType> raw() { // return payload; // } // // @Override // public Object unwrap() { // return payload.stream().map(RespType::unwrap).collect(Collectors.toList()); // } // // @Override // public int hashCode() { // return payload.hashCode(); // } // // @Override // public boolean equals(Object o) { // if (o instanceof Ary) { // Ary a = (Ary)o; // return payload.equals(a.payload); // } else { // return false; // } // } // } // // Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // }
import jresp.RespDecoder; import jresp.protocol.Ary; import jresp.protocol.RespType; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List;
if (aryLength == 0) { // // This is an empty array, so there will be no "nextState", so let's short-cut proceedings here // return true; } } } if (in.remaining() == 0) { return false; } if (nextState == null) { nextState = parent.nextState((char) in.get()); } if (nextState.decode(in)) { ary.add(nextState.finish()); if (ary.size() == aryLength) { return true; } else { nextState = null; // Lets go around again, there's (probably more to do). } } else { return false; } } } @Override public RespType finish() {
// Path: src/main/java/jresp/RespDecoder.java // public class RespDecoder { // // private SimpleStrState simpleStrDecoder = new SimpleStrState(); // private ErrState errDecoder = new ErrState(); // private IntState intDecoder = new IntState(); // private BulkStrState bulkStrDecoder; // // private State state = null; // // RespDecoder() { // bulkStrDecoder = new BulkStrState(this); // } // // protected void decode(ByteBuffer in, Consumer<RespType> out) { // while (true) { // int availableBytes = in.remaining(); // if (availableBytes == 0) { // // // // We need more bytes // // // break; // } // // if (state == null) { // // // // There is no current state, so read the next byte // // // char nextChar = (char) in.get(); // state = nextState(nextChar); // } // if (state.decode(in)) { // out.accept(state.finish()); // state = null; // } else { // // // // We need more bytes // // // break; // } // } // } // // public State nextState(char token) { // switch (token) { // case '+': // return simpleStrDecoder.reset(); // case '-': // return errDecoder.reset(); // case ':': // return intDecoder.reset(); // case '$': // return bulkStrDecoder.reset(); // case '*': // return new AryState(this); // default: // throw new IllegalStateException(String.format("Unknown token %s", token)); // } // } // // public IntState intDecoder() { // return (IntState)intDecoder.reset(); // } // } // // Path: src/main/java/jresp/protocol/Ary.java // public class Ary implements RespType { // private List<RespType> payload; // // public Ary(List<RespType> payload) { // this.payload = payload; // } // // public Ary(RespType... payload) { // this.payload = Arrays.asList(payload); // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), payload); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // byte[] header = Resp.longToByteArray(payload.size()); // int size = 1 + header.length + 2; // ByteBuffer o = Resp.buffer(out, size); // o.put((byte)'*'); // o.put(header); // o.put(Resp.CRLF); // payload.stream().forEach(x -> x.writeBytes(out)); // } // // public List<RespType> raw() { // return payload; // } // // @Override // public Object unwrap() { // return payload.stream().map(RespType::unwrap).collect(Collectors.toList()); // } // // @Override // public int hashCode() { // return payload.hashCode(); // } // // @Override // public boolean equals(Object o) { // if (o instanceof Ary) { // Ary a = (Ary)o; // return payload.equals(a.payload); // } else { // return false; // } // } // } // // Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // } // Path: src/main/java/jresp/state/AryState.java import jresp.RespDecoder; import jresp.protocol.Ary; import jresp.protocol.RespType; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; if (aryLength == 0) { // // This is an empty array, so there will be no "nextState", so let's short-cut proceedings here // return true; } } } if (in.remaining() == 0) { return false; } if (nextState == null) { nextState = parent.nextState((char) in.get()); } if (nextState.decode(in)) { ary.add(nextState.finish()); if (ary.size() == aryLength) { return true; } else { nextState = null; // Lets go around again, there's (probably more to do). } } else { return false; } } } @Override public RespType finish() {
return new Ary(ary);
benashford/jresp
src/main/java/jresp/state/BulkStrState.java
// Path: src/main/java/jresp/RespDecoder.java // public class RespDecoder { // // private SimpleStrState simpleStrDecoder = new SimpleStrState(); // private ErrState errDecoder = new ErrState(); // private IntState intDecoder = new IntState(); // private BulkStrState bulkStrDecoder; // // private State state = null; // // RespDecoder() { // bulkStrDecoder = new BulkStrState(this); // } // // protected void decode(ByteBuffer in, Consumer<RespType> out) { // while (true) { // int availableBytes = in.remaining(); // if (availableBytes == 0) { // // // // We need more bytes // // // break; // } // // if (state == null) { // // // // There is no current state, so read the next byte // // // char nextChar = (char) in.get(); // state = nextState(nextChar); // } // if (state.decode(in)) { // out.accept(state.finish()); // state = null; // } else { // // // // We need more bytes // // // break; // } // } // } // // public State nextState(char token) { // switch (token) { // case '+': // return simpleStrDecoder.reset(); // case '-': // return errDecoder.reset(); // case ':': // return intDecoder.reset(); // case '$': // return bulkStrDecoder.reset(); // case '*': // return new AryState(this); // default: // throw new IllegalStateException(String.format("Unknown token %s", token)); // } // } // // public IntState intDecoder() { // return (IntState)intDecoder.reset(); // } // } // // Path: src/main/java/jresp/protocol/BulkStr.java // public class BulkStr implements RespType { // private static final Map<String, BulkStr> cache = Collections.synchronizedMap(new HashMap<>()); // // private byte[] payload; // // public BulkStr(String s) { // try { // payload = s.getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // public BulkStr(byte[] s) { // payload = s; // } // // public BulkStr() { // this.payload = null; // } // // public static BulkStr get(String str) { // BulkStr val = cache.get(str); // if (val == null) { // val = new BulkStr(str); // cache.put(str, val); // } // return val; // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), Arrays.toString(payload)); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // int size = 1; // byte[] header; // if (payload == null) { // header = Resp.longToByteArray(-1); // } else { // header = Resp.longToByteArray(payload.length); // size += 2 + payload.length; // } // size += 2 + header.length; // // ByteBuffer o = Resp.buffer(out, size); // o.put((byte)'$'); // o.put(header); // if (payload != null) { // o.put(Resp.CRLF); // o.put(payload); // } // o.put(Resp.CRLF); // } // // public byte[] raw() { // return payload; // } // // @Override // public Object unwrap() { // if (payload == null) { // return null; // } // try { // return new String(payload, "UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // @Override // public int hashCode() { // return Arrays.hashCode(payload); // } // // @Override // public boolean equals(Object o) { // if (o instanceof BulkStr) { // BulkStr bs = (BulkStr)o; // return Arrays.equals(payload, bs.payload); // } else { // return false; // } // } // } // // Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // }
import jresp.RespDecoder; import jresp.protocol.BulkStr; import jresp.protocol.RespType; import java.nio.ByteBuffer;
/* * Copyright 2015 Ben Ashford * * 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 jresp.state; public class BulkStrState implements State { private static final int DEFAULT_SIZE = 32; private static final int MAXIMUM_SIZE = DEFAULT_SIZE * 1000;
// Path: src/main/java/jresp/RespDecoder.java // public class RespDecoder { // // private SimpleStrState simpleStrDecoder = new SimpleStrState(); // private ErrState errDecoder = new ErrState(); // private IntState intDecoder = new IntState(); // private BulkStrState bulkStrDecoder; // // private State state = null; // // RespDecoder() { // bulkStrDecoder = new BulkStrState(this); // } // // protected void decode(ByteBuffer in, Consumer<RespType> out) { // while (true) { // int availableBytes = in.remaining(); // if (availableBytes == 0) { // // // // We need more bytes // // // break; // } // // if (state == null) { // // // // There is no current state, so read the next byte // // // char nextChar = (char) in.get(); // state = nextState(nextChar); // } // if (state.decode(in)) { // out.accept(state.finish()); // state = null; // } else { // // // // We need more bytes // // // break; // } // } // } // // public State nextState(char token) { // switch (token) { // case '+': // return simpleStrDecoder.reset(); // case '-': // return errDecoder.reset(); // case ':': // return intDecoder.reset(); // case '$': // return bulkStrDecoder.reset(); // case '*': // return new AryState(this); // default: // throw new IllegalStateException(String.format("Unknown token %s", token)); // } // } // // public IntState intDecoder() { // return (IntState)intDecoder.reset(); // } // } // // Path: src/main/java/jresp/protocol/BulkStr.java // public class BulkStr implements RespType { // private static final Map<String, BulkStr> cache = Collections.synchronizedMap(new HashMap<>()); // // private byte[] payload; // // public BulkStr(String s) { // try { // payload = s.getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // public BulkStr(byte[] s) { // payload = s; // } // // public BulkStr() { // this.payload = null; // } // // public static BulkStr get(String str) { // BulkStr val = cache.get(str); // if (val == null) { // val = new BulkStr(str); // cache.put(str, val); // } // return val; // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), Arrays.toString(payload)); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // int size = 1; // byte[] header; // if (payload == null) { // header = Resp.longToByteArray(-1); // } else { // header = Resp.longToByteArray(payload.length); // size += 2 + payload.length; // } // size += 2 + header.length; // // ByteBuffer o = Resp.buffer(out, size); // o.put((byte)'$'); // o.put(header); // if (payload != null) { // o.put(Resp.CRLF); // o.put(payload); // } // o.put(Resp.CRLF); // } // // public byte[] raw() { // return payload; // } // // @Override // public Object unwrap() { // if (payload == null) { // return null; // } // try { // return new String(payload, "UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // @Override // public int hashCode() { // return Arrays.hashCode(payload); // } // // @Override // public boolean equals(Object o) { // if (o instanceof BulkStr) { // BulkStr bs = (BulkStr)o; // return Arrays.equals(payload, bs.payload); // } else { // return false; // } // } // } // // Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // } // Path: src/main/java/jresp/state/BulkStrState.java import jresp.RespDecoder; import jresp.protocol.BulkStr; import jresp.protocol.RespType; import java.nio.ByteBuffer; /* * Copyright 2015 Ben Ashford * * 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 jresp.state; public class BulkStrState implements State { private static final int DEFAULT_SIZE = 32; private static final int MAXIMUM_SIZE = DEFAULT_SIZE * 1000;
private RespDecoder parent;
benashford/jresp
src/main/java/jresp/state/BulkStrState.java
// Path: src/main/java/jresp/RespDecoder.java // public class RespDecoder { // // private SimpleStrState simpleStrDecoder = new SimpleStrState(); // private ErrState errDecoder = new ErrState(); // private IntState intDecoder = new IntState(); // private BulkStrState bulkStrDecoder; // // private State state = null; // // RespDecoder() { // bulkStrDecoder = new BulkStrState(this); // } // // protected void decode(ByteBuffer in, Consumer<RespType> out) { // while (true) { // int availableBytes = in.remaining(); // if (availableBytes == 0) { // // // // We need more bytes // // // break; // } // // if (state == null) { // // // // There is no current state, so read the next byte // // // char nextChar = (char) in.get(); // state = nextState(nextChar); // } // if (state.decode(in)) { // out.accept(state.finish()); // state = null; // } else { // // // // We need more bytes // // // break; // } // } // } // // public State nextState(char token) { // switch (token) { // case '+': // return simpleStrDecoder.reset(); // case '-': // return errDecoder.reset(); // case ':': // return intDecoder.reset(); // case '$': // return bulkStrDecoder.reset(); // case '*': // return new AryState(this); // default: // throw new IllegalStateException(String.format("Unknown token %s", token)); // } // } // // public IntState intDecoder() { // return (IntState)intDecoder.reset(); // } // } // // Path: src/main/java/jresp/protocol/BulkStr.java // public class BulkStr implements RespType { // private static final Map<String, BulkStr> cache = Collections.synchronizedMap(new HashMap<>()); // // private byte[] payload; // // public BulkStr(String s) { // try { // payload = s.getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // public BulkStr(byte[] s) { // payload = s; // } // // public BulkStr() { // this.payload = null; // } // // public static BulkStr get(String str) { // BulkStr val = cache.get(str); // if (val == null) { // val = new BulkStr(str); // cache.put(str, val); // } // return val; // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), Arrays.toString(payload)); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // int size = 1; // byte[] header; // if (payload == null) { // header = Resp.longToByteArray(-1); // } else { // header = Resp.longToByteArray(payload.length); // size += 2 + payload.length; // } // size += 2 + header.length; // // ByteBuffer o = Resp.buffer(out, size); // o.put((byte)'$'); // o.put(header); // if (payload != null) { // o.put(Resp.CRLF); // o.put(payload); // } // o.put(Resp.CRLF); // } // // public byte[] raw() { // return payload; // } // // @Override // public Object unwrap() { // if (payload == null) { // return null; // } // try { // return new String(payload, "UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // @Override // public int hashCode() { // return Arrays.hashCode(payload); // } // // @Override // public boolean equals(Object o) { // if (o instanceof BulkStr) { // BulkStr bs = (BulkStr)o; // return Arrays.equals(payload, bs.payload); // } else { // return false; // } // } // } // // Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // }
import jresp.RespDecoder; import jresp.protocol.BulkStr; import jresp.protocol.RespType; import java.nio.ByteBuffer;
if (len < 0) { stringLength = -1; } else { stringLength = (int)(len + 2); // To account for CRLF } } else { return false; } } if (stringLength < 0) { return true; } else { if (buffer == null || buffer.length < stringLength) { buffer = new byte[stringLength]; } int diff = stringLength - idx; if (diff == 0) { return true; } else if (diff < 0) { throw new IllegalStateException("Got too much data"); } else { int readable = Math.min(diff, in.remaining()); in.get(buffer, idx, readable); idx += readable; return readable == diff; } } } @Override
// Path: src/main/java/jresp/RespDecoder.java // public class RespDecoder { // // private SimpleStrState simpleStrDecoder = new SimpleStrState(); // private ErrState errDecoder = new ErrState(); // private IntState intDecoder = new IntState(); // private BulkStrState bulkStrDecoder; // // private State state = null; // // RespDecoder() { // bulkStrDecoder = new BulkStrState(this); // } // // protected void decode(ByteBuffer in, Consumer<RespType> out) { // while (true) { // int availableBytes = in.remaining(); // if (availableBytes == 0) { // // // // We need more bytes // // // break; // } // // if (state == null) { // // // // There is no current state, so read the next byte // // // char nextChar = (char) in.get(); // state = nextState(nextChar); // } // if (state.decode(in)) { // out.accept(state.finish()); // state = null; // } else { // // // // We need more bytes // // // break; // } // } // } // // public State nextState(char token) { // switch (token) { // case '+': // return simpleStrDecoder.reset(); // case '-': // return errDecoder.reset(); // case ':': // return intDecoder.reset(); // case '$': // return bulkStrDecoder.reset(); // case '*': // return new AryState(this); // default: // throw new IllegalStateException(String.format("Unknown token %s", token)); // } // } // // public IntState intDecoder() { // return (IntState)intDecoder.reset(); // } // } // // Path: src/main/java/jresp/protocol/BulkStr.java // public class BulkStr implements RespType { // private static final Map<String, BulkStr> cache = Collections.synchronizedMap(new HashMap<>()); // // private byte[] payload; // // public BulkStr(String s) { // try { // payload = s.getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // public BulkStr(byte[] s) { // payload = s; // } // // public BulkStr() { // this.payload = null; // } // // public static BulkStr get(String str) { // BulkStr val = cache.get(str); // if (val == null) { // val = new BulkStr(str); // cache.put(str, val); // } // return val; // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), Arrays.toString(payload)); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // int size = 1; // byte[] header; // if (payload == null) { // header = Resp.longToByteArray(-1); // } else { // header = Resp.longToByteArray(payload.length); // size += 2 + payload.length; // } // size += 2 + header.length; // // ByteBuffer o = Resp.buffer(out, size); // o.put((byte)'$'); // o.put(header); // if (payload != null) { // o.put(Resp.CRLF); // o.put(payload); // } // o.put(Resp.CRLF); // } // // public byte[] raw() { // return payload; // } // // @Override // public Object unwrap() { // if (payload == null) { // return null; // } // try { // return new String(payload, "UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // @Override // public int hashCode() { // return Arrays.hashCode(payload); // } // // @Override // public boolean equals(Object o) { // if (o instanceof BulkStr) { // BulkStr bs = (BulkStr)o; // return Arrays.equals(payload, bs.payload); // } else { // return false; // } // } // } // // Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // } // Path: src/main/java/jresp/state/BulkStrState.java import jresp.RespDecoder; import jresp.protocol.BulkStr; import jresp.protocol.RespType; import java.nio.ByteBuffer; if (len < 0) { stringLength = -1; } else { stringLength = (int)(len + 2); // To account for CRLF } } else { return false; } } if (stringLength < 0) { return true; } else { if (buffer == null || buffer.length < stringLength) { buffer = new byte[stringLength]; } int diff = stringLength - idx; if (diff == 0) { return true; } else if (diff < 0) { throw new IllegalStateException("Got too much data"); } else { int readable = Math.min(diff, in.remaining()); in.get(buffer, idx, readable); idx += readable; return readable == diff; } } } @Override
public RespType finish() {
benashford/jresp
src/main/java/jresp/state/BulkStrState.java
// Path: src/main/java/jresp/RespDecoder.java // public class RespDecoder { // // private SimpleStrState simpleStrDecoder = new SimpleStrState(); // private ErrState errDecoder = new ErrState(); // private IntState intDecoder = new IntState(); // private BulkStrState bulkStrDecoder; // // private State state = null; // // RespDecoder() { // bulkStrDecoder = new BulkStrState(this); // } // // protected void decode(ByteBuffer in, Consumer<RespType> out) { // while (true) { // int availableBytes = in.remaining(); // if (availableBytes == 0) { // // // // We need more bytes // // // break; // } // // if (state == null) { // // // // There is no current state, so read the next byte // // // char nextChar = (char) in.get(); // state = nextState(nextChar); // } // if (state.decode(in)) { // out.accept(state.finish()); // state = null; // } else { // // // // We need more bytes // // // break; // } // } // } // // public State nextState(char token) { // switch (token) { // case '+': // return simpleStrDecoder.reset(); // case '-': // return errDecoder.reset(); // case ':': // return intDecoder.reset(); // case '$': // return bulkStrDecoder.reset(); // case '*': // return new AryState(this); // default: // throw new IllegalStateException(String.format("Unknown token %s", token)); // } // } // // public IntState intDecoder() { // return (IntState)intDecoder.reset(); // } // } // // Path: src/main/java/jresp/protocol/BulkStr.java // public class BulkStr implements RespType { // private static final Map<String, BulkStr> cache = Collections.synchronizedMap(new HashMap<>()); // // private byte[] payload; // // public BulkStr(String s) { // try { // payload = s.getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // public BulkStr(byte[] s) { // payload = s; // } // // public BulkStr() { // this.payload = null; // } // // public static BulkStr get(String str) { // BulkStr val = cache.get(str); // if (val == null) { // val = new BulkStr(str); // cache.put(str, val); // } // return val; // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), Arrays.toString(payload)); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // int size = 1; // byte[] header; // if (payload == null) { // header = Resp.longToByteArray(-1); // } else { // header = Resp.longToByteArray(payload.length); // size += 2 + payload.length; // } // size += 2 + header.length; // // ByteBuffer o = Resp.buffer(out, size); // o.put((byte)'$'); // o.put(header); // if (payload != null) { // o.put(Resp.CRLF); // o.put(payload); // } // o.put(Resp.CRLF); // } // // public byte[] raw() { // return payload; // } // // @Override // public Object unwrap() { // if (payload == null) { // return null; // } // try { // return new String(payload, "UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // @Override // public int hashCode() { // return Arrays.hashCode(payload); // } // // @Override // public boolean equals(Object o) { // if (o instanceof BulkStr) { // BulkStr bs = (BulkStr)o; // return Arrays.equals(payload, bs.payload); // } else { // return false; // } // } // } // // Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // }
import jresp.RespDecoder; import jresp.protocol.BulkStr; import jresp.protocol.RespType; import java.nio.ByteBuffer;
} else { stringLength = (int)(len + 2); // To account for CRLF } } else { return false; } } if (stringLength < 0) { return true; } else { if (buffer == null || buffer.length < stringLength) { buffer = new byte[stringLength]; } int diff = stringLength - idx; if (diff == 0) { return true; } else if (diff < 0) { throw new IllegalStateException("Got too much data"); } else { int readable = Math.min(diff, in.remaining()); in.get(buffer, idx, readable); idx += readable; return readable == diff; } } } @Override public RespType finish() { if (stringLength < 0) {
// Path: src/main/java/jresp/RespDecoder.java // public class RespDecoder { // // private SimpleStrState simpleStrDecoder = new SimpleStrState(); // private ErrState errDecoder = new ErrState(); // private IntState intDecoder = new IntState(); // private BulkStrState bulkStrDecoder; // // private State state = null; // // RespDecoder() { // bulkStrDecoder = new BulkStrState(this); // } // // protected void decode(ByteBuffer in, Consumer<RespType> out) { // while (true) { // int availableBytes = in.remaining(); // if (availableBytes == 0) { // // // // We need more bytes // // // break; // } // // if (state == null) { // // // // There is no current state, so read the next byte // // // char nextChar = (char) in.get(); // state = nextState(nextChar); // } // if (state.decode(in)) { // out.accept(state.finish()); // state = null; // } else { // // // // We need more bytes // // // break; // } // } // } // // public State nextState(char token) { // switch (token) { // case '+': // return simpleStrDecoder.reset(); // case '-': // return errDecoder.reset(); // case ':': // return intDecoder.reset(); // case '$': // return bulkStrDecoder.reset(); // case '*': // return new AryState(this); // default: // throw new IllegalStateException(String.format("Unknown token %s", token)); // } // } // // public IntState intDecoder() { // return (IntState)intDecoder.reset(); // } // } // // Path: src/main/java/jresp/protocol/BulkStr.java // public class BulkStr implements RespType { // private static final Map<String, BulkStr> cache = Collections.synchronizedMap(new HashMap<>()); // // private byte[] payload; // // public BulkStr(String s) { // try { // payload = s.getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // public BulkStr(byte[] s) { // payload = s; // } // // public BulkStr() { // this.payload = null; // } // // public static BulkStr get(String str) { // BulkStr val = cache.get(str); // if (val == null) { // val = new BulkStr(str); // cache.put(str, val); // } // return val; // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), Arrays.toString(payload)); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // int size = 1; // byte[] header; // if (payload == null) { // header = Resp.longToByteArray(-1); // } else { // header = Resp.longToByteArray(payload.length); // size += 2 + payload.length; // } // size += 2 + header.length; // // ByteBuffer o = Resp.buffer(out, size); // o.put((byte)'$'); // o.put(header); // if (payload != null) { // o.put(Resp.CRLF); // o.put(payload); // } // o.put(Resp.CRLF); // } // // public byte[] raw() { // return payload; // } // // @Override // public Object unwrap() { // if (payload == null) { // return null; // } // try { // return new String(payload, "UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // @Override // public int hashCode() { // return Arrays.hashCode(payload); // } // // @Override // public boolean equals(Object o) { // if (o instanceof BulkStr) { // BulkStr bs = (BulkStr)o; // return Arrays.equals(payload, bs.payload); // } else { // return false; // } // } // } // // Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // } // Path: src/main/java/jresp/state/BulkStrState.java import jresp.RespDecoder; import jresp.protocol.BulkStr; import jresp.protocol.RespType; import java.nio.ByteBuffer; } else { stringLength = (int)(len + 2); // To account for CRLF } } else { return false; } } if (stringLength < 0) { return true; } else { if (buffer == null || buffer.length < stringLength) { buffer = new byte[stringLength]; } int diff = stringLength - idx; if (diff == 0) { return true; } else if (diff < 0) { throw new IllegalStateException("Got too much data"); } else { int readable = Math.min(diff, in.remaining()); in.get(buffer, idx, readable); idx += readable; return readable == diff; } } } @Override public RespType finish() { if (stringLength < 0) {
return new BulkStr();
benashford/jresp
src/main/java/jresp/state/IntState.java
// Path: src/main/java/jresp/protocol/Int.java // public class Int implements RespType { // private long payload; // // public Int(long payload) { // this.payload = payload; // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), payload); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // byte[] bytes = Resp.longToByteArray(payload); // int size = 1 + bytes.length + 2; // ByteBuffer o = Resp.buffer(out, size); // o.put((byte) ':'); // o.put(bytes); // o.put(Resp.CRLF); // } // // @Override // public Object unwrap() { // return payload; // } // // @Override // public int hashCode() { // return Long.hashCode(payload); // } // // @Override // public boolean equals(Object o) { // if (o instanceof Int) { // Int i = (Int)o; // return payload == i.payload; // } else { // return false; // } // } // } // // Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // }
import jresp.protocol.Int; import jresp.protocol.RespType;
/* * Copyright 2015 Ben Ashford * * 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 jresp.state; public class IntState extends ScannableState { @Override
// Path: src/main/java/jresp/protocol/Int.java // public class Int implements RespType { // private long payload; // // public Int(long payload) { // this.payload = payload; // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), payload); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // byte[] bytes = Resp.longToByteArray(payload); // int size = 1 + bytes.length + 2; // ByteBuffer o = Resp.buffer(out, size); // o.put((byte) ':'); // o.put(bytes); // o.put(Resp.CRLF); // } // // @Override // public Object unwrap() { // return payload; // } // // @Override // public int hashCode() { // return Long.hashCode(payload); // } // // @Override // public boolean equals(Object o) { // if (o instanceof Int) { // Int i = (Int)o; // return payload == i.payload; // } else { // return false; // } // } // } // // Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // } // Path: src/main/java/jresp/state/IntState.java import jresp.protocol.Int; import jresp.protocol.RespType; /* * Copyright 2015 Ben Ashford * * 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 jresp.state; public class IntState extends ScannableState { @Override
public RespType finish() {
benashford/jresp
src/main/java/jresp/state/IntState.java
// Path: src/main/java/jresp/protocol/Int.java // public class Int implements RespType { // private long payload; // // public Int(long payload) { // this.payload = payload; // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), payload); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // byte[] bytes = Resp.longToByteArray(payload); // int size = 1 + bytes.length + 2; // ByteBuffer o = Resp.buffer(out, size); // o.put((byte) ':'); // o.put(bytes); // o.put(Resp.CRLF); // } // // @Override // public Object unwrap() { // return payload; // } // // @Override // public int hashCode() { // return Long.hashCode(payload); // } // // @Override // public boolean equals(Object o) { // if (o instanceof Int) { // Int i = (Int)o; // return payload == i.payload; // } else { // return false; // } // } // } // // Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // }
import jresp.protocol.Int; import jresp.protocol.RespType;
/* * Copyright 2015 Ben Ashford * * 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 jresp.state; public class IntState extends ScannableState { @Override public RespType finish() {
// Path: src/main/java/jresp/protocol/Int.java // public class Int implements RespType { // private long payload; // // public Int(long payload) { // this.payload = payload; // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), payload); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // byte[] bytes = Resp.longToByteArray(payload); // int size = 1 + bytes.length + 2; // ByteBuffer o = Resp.buffer(out, size); // o.put((byte) ':'); // o.put(bytes); // o.put(Resp.CRLF); // } // // @Override // public Object unwrap() { // return payload; // } // // @Override // public int hashCode() { // return Long.hashCode(payload); // } // // @Override // public boolean equals(Object o) { // if (o instanceof Int) { // Int i = (Int)o; // return payload == i.payload; // } else { // return false; // } // } // } // // Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // } // Path: src/main/java/jresp/state/IntState.java import jresp.protocol.Int; import jresp.protocol.RespType; /* * Copyright 2015 Ben Ashford * * 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 jresp.state; public class IntState extends ScannableState { @Override public RespType finish() {
return new Int(finishInt());
benashford/jresp
src/main/java/jresp/state/State.java
// Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // }
import jresp.protocol.RespType; import java.nio.ByteBuffer;
/* * Copyright 2015 Ben Ashford * * 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 jresp.state; public interface State { boolean decode(ByteBuffer in);
// Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // } // Path: src/main/java/jresp/state/State.java import jresp.protocol.RespType; import java.nio.ByteBuffer; /* * Copyright 2015 Ben Ashford * * 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 jresp.state; public interface State { boolean decode(ByteBuffer in);
RespType finish();
benashford/jresp
src/test/java/jresp/JRESPTest.java
// Path: src/main/java/jresp/protocol/Ary.java // public class Ary implements RespType { // private List<RespType> payload; // // public Ary(List<RespType> payload) { // this.payload = payload; // } // // public Ary(RespType... payload) { // this.payload = Arrays.asList(payload); // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), payload); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // byte[] header = Resp.longToByteArray(payload.size()); // int size = 1 + header.length + 2; // ByteBuffer o = Resp.buffer(out, size); // o.put((byte)'*'); // o.put(header); // o.put(Resp.CRLF); // payload.stream().forEach(x -> x.writeBytes(out)); // } // // public List<RespType> raw() { // return payload; // } // // @Override // public Object unwrap() { // return payload.stream().map(RespType::unwrap).collect(Collectors.toList()); // } // // @Override // public int hashCode() { // return payload.hashCode(); // } // // @Override // public boolean equals(Object o) { // if (o instanceof Ary) { // Ary a = (Ary)o; // return payload.equals(a.payload); // } else { // return false; // } // } // } // // Path: src/main/java/jresp/protocol/BulkStr.java // public class BulkStr implements RespType { // private static final Map<String, BulkStr> cache = Collections.synchronizedMap(new HashMap<>()); // // private byte[] payload; // // public BulkStr(String s) { // try { // payload = s.getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // public BulkStr(byte[] s) { // payload = s; // } // // public BulkStr() { // this.payload = null; // } // // public static BulkStr get(String str) { // BulkStr val = cache.get(str); // if (val == null) { // val = new BulkStr(str); // cache.put(str, val); // } // return val; // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), Arrays.toString(payload)); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // int size = 1; // byte[] header; // if (payload == null) { // header = Resp.longToByteArray(-1); // } else { // header = Resp.longToByteArray(payload.length); // size += 2 + payload.length; // } // size += 2 + header.length; // // ByteBuffer o = Resp.buffer(out, size); // o.put((byte)'$'); // o.put(header); // if (payload != null) { // o.put(Resp.CRLF); // o.put(payload); // } // o.put(Resp.CRLF); // } // // public byte[] raw() { // return payload; // } // // @Override // public Object unwrap() { // if (payload == null) { // return null; // } // try { // return new String(payload, "UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // @Override // public int hashCode() { // return Arrays.hashCode(payload); // } // // @Override // public boolean equals(Object o) { // if (o instanceof BulkStr) { // BulkStr bs = (BulkStr)o; // return Arrays.equals(payload, bs.payload); // } else { // return false; // } // } // } // // Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // }
import jresp.protocol.Ary; import jresp.protocol.BulkStr; import jresp.protocol.RespType; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit;
/* * Copyright 2015 Ben Ashford * * 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 jresp; public class JRESPTest { protected static final Responses NULL_RESPONSES = response -> { // nothing }; protected Client client; protected CountDownLatch latch; protected void setup() throws Exception { client = new Client("localhost", 6379); client.setDb(2); } protected void teardown() throws Exception { client.shutdown(); }
// Path: src/main/java/jresp/protocol/Ary.java // public class Ary implements RespType { // private List<RespType> payload; // // public Ary(List<RespType> payload) { // this.payload = payload; // } // // public Ary(RespType... payload) { // this.payload = Arrays.asList(payload); // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), payload); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // byte[] header = Resp.longToByteArray(payload.size()); // int size = 1 + header.length + 2; // ByteBuffer o = Resp.buffer(out, size); // o.put((byte)'*'); // o.put(header); // o.put(Resp.CRLF); // payload.stream().forEach(x -> x.writeBytes(out)); // } // // public List<RespType> raw() { // return payload; // } // // @Override // public Object unwrap() { // return payload.stream().map(RespType::unwrap).collect(Collectors.toList()); // } // // @Override // public int hashCode() { // return payload.hashCode(); // } // // @Override // public boolean equals(Object o) { // if (o instanceof Ary) { // Ary a = (Ary)o; // return payload.equals(a.payload); // } else { // return false; // } // } // } // // Path: src/main/java/jresp/protocol/BulkStr.java // public class BulkStr implements RespType { // private static final Map<String, BulkStr> cache = Collections.synchronizedMap(new HashMap<>()); // // private byte[] payload; // // public BulkStr(String s) { // try { // payload = s.getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // public BulkStr(byte[] s) { // payload = s; // } // // public BulkStr() { // this.payload = null; // } // // public static BulkStr get(String str) { // BulkStr val = cache.get(str); // if (val == null) { // val = new BulkStr(str); // cache.put(str, val); // } // return val; // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), Arrays.toString(payload)); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // int size = 1; // byte[] header; // if (payload == null) { // header = Resp.longToByteArray(-1); // } else { // header = Resp.longToByteArray(payload.length); // size += 2 + payload.length; // } // size += 2 + header.length; // // ByteBuffer o = Resp.buffer(out, size); // o.put((byte)'$'); // o.put(header); // if (payload != null) { // o.put(Resp.CRLF); // o.put(payload); // } // o.put(Resp.CRLF); // } // // public byte[] raw() { // return payload; // } // // @Override // public Object unwrap() { // if (payload == null) { // return null; // } // try { // return new String(payload, "UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // @Override // public int hashCode() { // return Arrays.hashCode(payload); // } // // @Override // public boolean equals(Object o) { // if (o instanceof BulkStr) { // BulkStr bs = (BulkStr)o; // return Arrays.equals(payload, bs.payload); // } else { // return false; // } // } // } // // Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // } // Path: src/test/java/jresp/JRESPTest.java import jresp.protocol.Ary; import jresp.protocol.BulkStr; import jresp.protocol.RespType; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /* * Copyright 2015 Ben Ashford * * 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 jresp; public class JRESPTest { protected static final Responses NULL_RESPONSES = response -> { // nothing }; protected Client client; protected CountDownLatch latch; protected void setup() throws Exception { client = new Client("localhost", 6379); client.setDb(2); } protected void teardown() throws Exception { client.shutdown(); }
protected static Ary command(String name, RespType... options) {
benashford/jresp
src/test/java/jresp/JRESPTest.java
// Path: src/main/java/jresp/protocol/Ary.java // public class Ary implements RespType { // private List<RespType> payload; // // public Ary(List<RespType> payload) { // this.payload = payload; // } // // public Ary(RespType... payload) { // this.payload = Arrays.asList(payload); // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), payload); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // byte[] header = Resp.longToByteArray(payload.size()); // int size = 1 + header.length + 2; // ByteBuffer o = Resp.buffer(out, size); // o.put((byte)'*'); // o.put(header); // o.put(Resp.CRLF); // payload.stream().forEach(x -> x.writeBytes(out)); // } // // public List<RespType> raw() { // return payload; // } // // @Override // public Object unwrap() { // return payload.stream().map(RespType::unwrap).collect(Collectors.toList()); // } // // @Override // public int hashCode() { // return payload.hashCode(); // } // // @Override // public boolean equals(Object o) { // if (o instanceof Ary) { // Ary a = (Ary)o; // return payload.equals(a.payload); // } else { // return false; // } // } // } // // Path: src/main/java/jresp/protocol/BulkStr.java // public class BulkStr implements RespType { // private static final Map<String, BulkStr> cache = Collections.synchronizedMap(new HashMap<>()); // // private byte[] payload; // // public BulkStr(String s) { // try { // payload = s.getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // public BulkStr(byte[] s) { // payload = s; // } // // public BulkStr() { // this.payload = null; // } // // public static BulkStr get(String str) { // BulkStr val = cache.get(str); // if (val == null) { // val = new BulkStr(str); // cache.put(str, val); // } // return val; // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), Arrays.toString(payload)); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // int size = 1; // byte[] header; // if (payload == null) { // header = Resp.longToByteArray(-1); // } else { // header = Resp.longToByteArray(payload.length); // size += 2 + payload.length; // } // size += 2 + header.length; // // ByteBuffer o = Resp.buffer(out, size); // o.put((byte)'$'); // o.put(header); // if (payload != null) { // o.put(Resp.CRLF); // o.put(payload); // } // o.put(Resp.CRLF); // } // // public byte[] raw() { // return payload; // } // // @Override // public Object unwrap() { // if (payload == null) { // return null; // } // try { // return new String(payload, "UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // @Override // public int hashCode() { // return Arrays.hashCode(payload); // } // // @Override // public boolean equals(Object o) { // if (o instanceof BulkStr) { // BulkStr bs = (BulkStr)o; // return Arrays.equals(payload, bs.payload); // } else { // return false; // } // } // } // // Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // }
import jresp.protocol.Ary; import jresp.protocol.BulkStr; import jresp.protocol.RespType; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit;
/* * Copyright 2015 Ben Ashford * * 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 jresp; public class JRESPTest { protected static final Responses NULL_RESPONSES = response -> { // nothing }; protected Client client; protected CountDownLatch latch; protected void setup() throws Exception { client = new Client("localhost", 6379); client.setDb(2); } protected void teardown() throws Exception { client.shutdown(); }
// Path: src/main/java/jresp/protocol/Ary.java // public class Ary implements RespType { // private List<RespType> payload; // // public Ary(List<RespType> payload) { // this.payload = payload; // } // // public Ary(RespType... payload) { // this.payload = Arrays.asList(payload); // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), payload); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // byte[] header = Resp.longToByteArray(payload.size()); // int size = 1 + header.length + 2; // ByteBuffer o = Resp.buffer(out, size); // o.put((byte)'*'); // o.put(header); // o.put(Resp.CRLF); // payload.stream().forEach(x -> x.writeBytes(out)); // } // // public List<RespType> raw() { // return payload; // } // // @Override // public Object unwrap() { // return payload.stream().map(RespType::unwrap).collect(Collectors.toList()); // } // // @Override // public int hashCode() { // return payload.hashCode(); // } // // @Override // public boolean equals(Object o) { // if (o instanceof Ary) { // Ary a = (Ary)o; // return payload.equals(a.payload); // } else { // return false; // } // } // } // // Path: src/main/java/jresp/protocol/BulkStr.java // public class BulkStr implements RespType { // private static final Map<String, BulkStr> cache = Collections.synchronizedMap(new HashMap<>()); // // private byte[] payload; // // public BulkStr(String s) { // try { // payload = s.getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // public BulkStr(byte[] s) { // payload = s; // } // // public BulkStr() { // this.payload = null; // } // // public static BulkStr get(String str) { // BulkStr val = cache.get(str); // if (val == null) { // val = new BulkStr(str); // cache.put(str, val); // } // return val; // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), Arrays.toString(payload)); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // int size = 1; // byte[] header; // if (payload == null) { // header = Resp.longToByteArray(-1); // } else { // header = Resp.longToByteArray(payload.length); // size += 2 + payload.length; // } // size += 2 + header.length; // // ByteBuffer o = Resp.buffer(out, size); // o.put((byte)'$'); // o.put(header); // if (payload != null) { // o.put(Resp.CRLF); // o.put(payload); // } // o.put(Resp.CRLF); // } // // public byte[] raw() { // return payload; // } // // @Override // public Object unwrap() { // if (payload == null) { // return null; // } // try { // return new String(payload, "UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // @Override // public int hashCode() { // return Arrays.hashCode(payload); // } // // @Override // public boolean equals(Object o) { // if (o instanceof BulkStr) { // BulkStr bs = (BulkStr)o; // return Arrays.equals(payload, bs.payload); // } else { // return false; // } // } // } // // Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // } // Path: src/test/java/jresp/JRESPTest.java import jresp.protocol.Ary; import jresp.protocol.BulkStr; import jresp.protocol.RespType; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /* * Copyright 2015 Ben Ashford * * 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 jresp; public class JRESPTest { protected static final Responses NULL_RESPONSES = response -> { // nothing }; protected Client client; protected CountDownLatch latch; protected void setup() throws Exception { client = new Client("localhost", 6379); client.setDb(2); } protected void teardown() throws Exception { client.shutdown(); }
protected static Ary command(String name, RespType... options) {
benashford/jresp
src/test/java/jresp/JRESPTest.java
// Path: src/main/java/jresp/protocol/Ary.java // public class Ary implements RespType { // private List<RespType> payload; // // public Ary(List<RespType> payload) { // this.payload = payload; // } // // public Ary(RespType... payload) { // this.payload = Arrays.asList(payload); // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), payload); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // byte[] header = Resp.longToByteArray(payload.size()); // int size = 1 + header.length + 2; // ByteBuffer o = Resp.buffer(out, size); // o.put((byte)'*'); // o.put(header); // o.put(Resp.CRLF); // payload.stream().forEach(x -> x.writeBytes(out)); // } // // public List<RespType> raw() { // return payload; // } // // @Override // public Object unwrap() { // return payload.stream().map(RespType::unwrap).collect(Collectors.toList()); // } // // @Override // public int hashCode() { // return payload.hashCode(); // } // // @Override // public boolean equals(Object o) { // if (o instanceof Ary) { // Ary a = (Ary)o; // return payload.equals(a.payload); // } else { // return false; // } // } // } // // Path: src/main/java/jresp/protocol/BulkStr.java // public class BulkStr implements RespType { // private static final Map<String, BulkStr> cache = Collections.synchronizedMap(new HashMap<>()); // // private byte[] payload; // // public BulkStr(String s) { // try { // payload = s.getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // public BulkStr(byte[] s) { // payload = s; // } // // public BulkStr() { // this.payload = null; // } // // public static BulkStr get(String str) { // BulkStr val = cache.get(str); // if (val == null) { // val = new BulkStr(str); // cache.put(str, val); // } // return val; // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), Arrays.toString(payload)); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // int size = 1; // byte[] header; // if (payload == null) { // header = Resp.longToByteArray(-1); // } else { // header = Resp.longToByteArray(payload.length); // size += 2 + payload.length; // } // size += 2 + header.length; // // ByteBuffer o = Resp.buffer(out, size); // o.put((byte)'$'); // o.put(header); // if (payload != null) { // o.put(Resp.CRLF); // o.put(payload); // } // o.put(Resp.CRLF); // } // // public byte[] raw() { // return payload; // } // // @Override // public Object unwrap() { // if (payload == null) { // return null; // } // try { // return new String(payload, "UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // @Override // public int hashCode() { // return Arrays.hashCode(payload); // } // // @Override // public boolean equals(Object o) { // if (o instanceof BulkStr) { // BulkStr bs = (BulkStr)o; // return Arrays.equals(payload, bs.payload); // } else { // return false; // } // } // } // // Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // }
import jresp.protocol.Ary; import jresp.protocol.BulkStr; import jresp.protocol.RespType; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit;
/* * Copyright 2015 Ben Ashford * * 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 jresp; public class JRESPTest { protected static final Responses NULL_RESPONSES = response -> { // nothing }; protected Client client; protected CountDownLatch latch; protected void setup() throws Exception { client = new Client("localhost", 6379); client.setDb(2); } protected void teardown() throws Exception { client.shutdown(); } protected static Ary command(String name, RespType... options) { List<RespType> elements = new ArrayList<>(options.length + 1);
// Path: src/main/java/jresp/protocol/Ary.java // public class Ary implements RespType { // private List<RespType> payload; // // public Ary(List<RespType> payload) { // this.payload = payload; // } // // public Ary(RespType... payload) { // this.payload = Arrays.asList(payload); // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), payload); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // byte[] header = Resp.longToByteArray(payload.size()); // int size = 1 + header.length + 2; // ByteBuffer o = Resp.buffer(out, size); // o.put((byte)'*'); // o.put(header); // o.put(Resp.CRLF); // payload.stream().forEach(x -> x.writeBytes(out)); // } // // public List<RespType> raw() { // return payload; // } // // @Override // public Object unwrap() { // return payload.stream().map(RespType::unwrap).collect(Collectors.toList()); // } // // @Override // public int hashCode() { // return payload.hashCode(); // } // // @Override // public boolean equals(Object o) { // if (o instanceof Ary) { // Ary a = (Ary)o; // return payload.equals(a.payload); // } else { // return false; // } // } // } // // Path: src/main/java/jresp/protocol/BulkStr.java // public class BulkStr implements RespType { // private static final Map<String, BulkStr> cache = Collections.synchronizedMap(new HashMap<>()); // // private byte[] payload; // // public BulkStr(String s) { // try { // payload = s.getBytes("UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // public BulkStr(byte[] s) { // payload = s; // } // // public BulkStr() { // this.payload = null; // } // // public static BulkStr get(String str) { // BulkStr val = cache.get(str); // if (val == null) { // val = new BulkStr(str); // cache.put(str, val); // } // return val; // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), Arrays.toString(payload)); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // int size = 1; // byte[] header; // if (payload == null) { // header = Resp.longToByteArray(-1); // } else { // header = Resp.longToByteArray(payload.length); // size += 2 + payload.length; // } // size += 2 + header.length; // // ByteBuffer o = Resp.buffer(out, size); // o.put((byte)'$'); // o.put(header); // if (payload != null) { // o.put(Resp.CRLF); // o.put(payload); // } // o.put(Resp.CRLF); // } // // public byte[] raw() { // return payload; // } // // @Override // public Object unwrap() { // if (payload == null) { // return null; // } // try { // return new String(payload, "UTF-8"); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // @Override // public int hashCode() { // return Arrays.hashCode(payload); // } // // @Override // public boolean equals(Object o) { // if (o instanceof BulkStr) { // BulkStr bs = (BulkStr)o; // return Arrays.equals(payload, bs.payload); // } else { // return false; // } // } // } // // Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // } // Path: src/test/java/jresp/JRESPTest.java import jresp.protocol.Ary; import jresp.protocol.BulkStr; import jresp.protocol.RespType; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /* * Copyright 2015 Ben Ashford * * 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 jresp; public class JRESPTest { protected static final Responses NULL_RESPONSES = response -> { // nothing }; protected Client client; protected CountDownLatch latch; protected void setup() throws Exception { client = new Client("localhost", 6379); client.setDb(2); } protected void teardown() throws Exception { client.shutdown(); } protected static Ary command(String name, RespType... options) { List<RespType> elements = new ArrayList<>(options.length + 1);
elements.add(new BulkStr(name));
benashford/jresp
src/main/java/jresp/state/SimpleStrState.java
// Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // } // // Path: src/main/java/jresp/protocol/SimpleStr.java // public class SimpleStr implements RespType { // private String payload; // // public SimpleStr(String str) { // payload = str; // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), payload); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // try { // byte[] bytes = payload.getBytes("UTF-8"); // int size = 1 + bytes.length + 2; // ByteBuffer o = Resp.buffer(out, size); // // o.put((byte) '+'); // o.put(bytes); // o.put(Resp.CRLF); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // @Override // public Object unwrap() { // return payload; // } // // @Override // public int hashCode() { // return payload.hashCode(); // } // // @Override // public boolean equals(Object o) { // if (o instanceof SimpleStr) { // SimpleStr ss = (SimpleStr)o; // return payload.equals(ss.payload); // } else { // return false; // } // } // }
import jresp.protocol.RespType; import jresp.protocol.SimpleStr;
/* * Copyright 2015 Ben Ashford * * 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 jresp.state; public class SimpleStrState extends ScannableState { @Override
// Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // } // // Path: src/main/java/jresp/protocol/SimpleStr.java // public class SimpleStr implements RespType { // private String payload; // // public SimpleStr(String str) { // payload = str; // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), payload); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // try { // byte[] bytes = payload.getBytes("UTF-8"); // int size = 1 + bytes.length + 2; // ByteBuffer o = Resp.buffer(out, size); // // o.put((byte) '+'); // o.put(bytes); // o.put(Resp.CRLF); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // @Override // public Object unwrap() { // return payload; // } // // @Override // public int hashCode() { // return payload.hashCode(); // } // // @Override // public boolean equals(Object o) { // if (o instanceof SimpleStr) { // SimpleStr ss = (SimpleStr)o; // return payload.equals(ss.payload); // } else { // return false; // } // } // } // Path: src/main/java/jresp/state/SimpleStrState.java import jresp.protocol.RespType; import jresp.protocol.SimpleStr; /* * Copyright 2015 Ben Ashford * * 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 jresp.state; public class SimpleStrState extends ScannableState { @Override
public RespType finish() {
benashford/jresp
src/main/java/jresp/state/SimpleStrState.java
// Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // } // // Path: src/main/java/jresp/protocol/SimpleStr.java // public class SimpleStr implements RespType { // private String payload; // // public SimpleStr(String str) { // payload = str; // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), payload); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // try { // byte[] bytes = payload.getBytes("UTF-8"); // int size = 1 + bytes.length + 2; // ByteBuffer o = Resp.buffer(out, size); // // o.put((byte) '+'); // o.put(bytes); // o.put(Resp.CRLF); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // @Override // public Object unwrap() { // return payload; // } // // @Override // public int hashCode() { // return payload.hashCode(); // } // // @Override // public boolean equals(Object o) { // if (o instanceof SimpleStr) { // SimpleStr ss = (SimpleStr)o; // return payload.equals(ss.payload); // } else { // return false; // } // } // }
import jresp.protocol.RespType; import jresp.protocol.SimpleStr;
/* * Copyright 2015 Ben Ashford * * 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 jresp.state; public class SimpleStrState extends ScannableState { @Override public RespType finish() {
// Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // } // // Path: src/main/java/jresp/protocol/SimpleStr.java // public class SimpleStr implements RespType { // private String payload; // // public SimpleStr(String str) { // payload = str; // } // // public String toString() { // return String.format("%s[%s]", getClass().getName(), payload); // } // // @Override // public void writeBytes(Deque<ByteBuffer> out) { // try { // byte[] bytes = payload.getBytes("UTF-8"); // int size = 1 + bytes.length + 2; // ByteBuffer o = Resp.buffer(out, size); // // o.put((byte) '+'); // o.put(bytes); // o.put(Resp.CRLF); // } catch (UnsupportedEncodingException e) { // throw new IllegalStateException(e); // } // } // // @Override // public Object unwrap() { // return payload; // } // // @Override // public int hashCode() { // return payload.hashCode(); // } // // @Override // public boolean equals(Object o) { // if (o instanceof SimpleStr) { // SimpleStr ss = (SimpleStr)o; // return payload.equals(ss.payload); // } else { // return false; // } // } // } // Path: src/main/java/jresp/state/SimpleStrState.java import jresp.protocol.RespType; import jresp.protocol.SimpleStr; /* * Copyright 2015 Ben Ashford * * 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 jresp.state; public class SimpleStrState extends ScannableState { @Override public RespType finish() {
return new SimpleStr(bufferAsString());
benashford/jresp
src/test/java/jresp/pool/SharedConnectionTest.java
// Path: src/test/java/jresp/JRESPTest.java // public class JRESPTest { // protected static final Responses NULL_RESPONSES = response -> { // // nothing // }; // // protected Client client; // protected CountDownLatch latch; // // protected void setup() throws Exception { // client = new Client("localhost", 6379); // client.setDb(2); // } // // protected void teardown() throws Exception { // client.shutdown(); // } // // protected static Ary command(String name, RespType... options) { // List<RespType> elements = new ArrayList<>(options.length + 1); // elements.add(new BulkStr(name)); // elements.addAll(Arrays.asList(options)); // // return new Ary(elements); // } // // protected static RespType ping() { // return command("PING"); // } // // protected static RespType flushDB() { // return command("FLUSHDB"); // } // // protected static RespType get(String key) { // return command("GET", new BulkStr(key)); // } // // protected static RespType set(String key, String value) { // return command("SET", new BulkStr(key), new BulkStr(value)); // } // // protected static RespType sadd(String key, String value) { // return command("SADD", new BulkStr(key), new BulkStr(value)); // } // // protected static RespType smembers(String key) { // return command("SMEMBERS", new BulkStr(key)); // } // // protected static RespType hgetall(String key) { // return command("HGETALL", new BulkStr(key)); // } // // protected static RespType blpop(String key, int timeout) { // return command("BLPOP", new BulkStr(key), new BulkStr(Integer.toString(timeout))); // } // // protected static RespType rpush(String key, String value) { // return command("RPUSH", new BulkStr(key), new BulkStr(value)); // } // // protected static RespType publish(String channel, String payload) { // return command("PUBLISH", new BulkStr(channel), new BulkStr(payload)); // } // // protected void await() { // try { // boolean success = latch.await(5, TimeUnit.SECONDS); // if (!success) { // throw new AssertionError("Timed out waiting"); // } // } catch (InterruptedException e) { // throw new IllegalStateException(e); // } // } // } // // Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // }
import jresp.JRESPTest; import jresp.protocol.RespType; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.stream.IntStream; import static org.junit.Assert.*;
@After public void teardown() throws Exception { super.teardown(); } @Test public void testGetSet() throws Exception { latch = new CountDownLatch(1); String[] value = new String[1]; sharedConnection.write(set("KEY-1", "VALUE-1"), NULL_RESPONSES); sharedConnection.write(get("KEY-1"), resp -> { value[0] = (String)resp.unwrap(); latch.countDown(); }); await(); assertEquals("VALUE-1", value[0]); } @Test public void thousandPingTest() throws Exception { int numPings = 1000; int runs = 1; for (int n = 0; n < runs; n++) { long start = System.nanoTime(); latch = new CountDownLatch(numPings);
// Path: src/test/java/jresp/JRESPTest.java // public class JRESPTest { // protected static final Responses NULL_RESPONSES = response -> { // // nothing // }; // // protected Client client; // protected CountDownLatch latch; // // protected void setup() throws Exception { // client = new Client("localhost", 6379); // client.setDb(2); // } // // protected void teardown() throws Exception { // client.shutdown(); // } // // protected static Ary command(String name, RespType... options) { // List<RespType> elements = new ArrayList<>(options.length + 1); // elements.add(new BulkStr(name)); // elements.addAll(Arrays.asList(options)); // // return new Ary(elements); // } // // protected static RespType ping() { // return command("PING"); // } // // protected static RespType flushDB() { // return command("FLUSHDB"); // } // // protected static RespType get(String key) { // return command("GET", new BulkStr(key)); // } // // protected static RespType set(String key, String value) { // return command("SET", new BulkStr(key), new BulkStr(value)); // } // // protected static RespType sadd(String key, String value) { // return command("SADD", new BulkStr(key), new BulkStr(value)); // } // // protected static RespType smembers(String key) { // return command("SMEMBERS", new BulkStr(key)); // } // // protected static RespType hgetall(String key) { // return command("HGETALL", new BulkStr(key)); // } // // protected static RespType blpop(String key, int timeout) { // return command("BLPOP", new BulkStr(key), new BulkStr(Integer.toString(timeout))); // } // // protected static RespType rpush(String key, String value) { // return command("RPUSH", new BulkStr(key), new BulkStr(value)); // } // // protected static RespType publish(String channel, String payload) { // return command("PUBLISH", new BulkStr(channel), new BulkStr(payload)); // } // // protected void await() { // try { // boolean success = latch.await(5, TimeUnit.SECONDS); // if (!success) { // throw new AssertionError("Timed out waiting"); // } // } catch (InterruptedException e) { // throw new IllegalStateException(e); // } // } // } // // Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // } // Path: src/test/java/jresp/pool/SharedConnectionTest.java import jresp.JRESPTest; import jresp.protocol.RespType; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.stream.IntStream; import static org.junit.Assert.*; @After public void teardown() throws Exception { super.teardown(); } @Test public void testGetSet() throws Exception { latch = new CountDownLatch(1); String[] value = new String[1]; sharedConnection.write(set("KEY-1", "VALUE-1"), NULL_RESPONSES); sharedConnection.write(get("KEY-1"), resp -> { value[0] = (String)resp.unwrap(); latch.countDown(); }); await(); assertEquals("VALUE-1", value[0]); } @Test public void thousandPingTest() throws Exception { int numPings = 1000; int runs = 1; for (int n = 0; n < runs; n++) { long start = System.nanoTime(); latch = new CountDownLatch(numPings);
List<RespType> results = new ArrayList<>(numPings);
benashford/jresp
src/test/java/jresp/pool/BorrowedConnectionTest.java
// Path: src/test/java/jresp/JRESPTest.java // public class JRESPTest { // protected static final Responses NULL_RESPONSES = response -> { // // nothing // }; // // protected Client client; // protected CountDownLatch latch; // // protected void setup() throws Exception { // client = new Client("localhost", 6379); // client.setDb(2); // } // // protected void teardown() throws Exception { // client.shutdown(); // } // // protected static Ary command(String name, RespType... options) { // List<RespType> elements = new ArrayList<>(options.length + 1); // elements.add(new BulkStr(name)); // elements.addAll(Arrays.asList(options)); // // return new Ary(elements); // } // // protected static RespType ping() { // return command("PING"); // } // // protected static RespType flushDB() { // return command("FLUSHDB"); // } // // protected static RespType get(String key) { // return command("GET", new BulkStr(key)); // } // // protected static RespType set(String key, String value) { // return command("SET", new BulkStr(key), new BulkStr(value)); // } // // protected static RespType sadd(String key, String value) { // return command("SADD", new BulkStr(key), new BulkStr(value)); // } // // protected static RespType smembers(String key) { // return command("SMEMBERS", new BulkStr(key)); // } // // protected static RespType hgetall(String key) { // return command("HGETALL", new BulkStr(key)); // } // // protected static RespType blpop(String key, int timeout) { // return command("BLPOP", new BulkStr(key), new BulkStr(Integer.toString(timeout))); // } // // protected static RespType rpush(String key, String value) { // return command("RPUSH", new BulkStr(key), new BulkStr(value)); // } // // protected static RespType publish(String channel, String payload) { // return command("PUBLISH", new BulkStr(channel), new BulkStr(payload)); // } // // protected void await() { // try { // boolean success = latch.await(5, TimeUnit.SECONDS); // if (!success) { // throw new AssertionError("Timed out waiting"); // } // } catch (InterruptedException e) { // throw new IllegalStateException(e); // } // } // } // // Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // }
import jresp.JRESPTest; import jresp.protocol.RespType; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import java.util.concurrent.CountDownLatch; import static org.junit.Assert.assertEquals;
/* * Copyright 2015 Ben Ashford * * 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 jresp.pool; public class BorrowedConnectionTest extends JRESPTest { private Pool pool; private SingleCommandConnection con; @Before public void setup() throws Exception { super.setup(); pool = new Pool(client); con = pool.getBorrowed(); con.write(flushDB(), NULL_RESPONSES); } @After public void teardown() throws Exception { pool.returnBorrowed(con); super.teardown(); } @Test public void blpopTest() throws Exception { latch = new CountDownLatch(1);
// Path: src/test/java/jresp/JRESPTest.java // public class JRESPTest { // protected static final Responses NULL_RESPONSES = response -> { // // nothing // }; // // protected Client client; // protected CountDownLatch latch; // // protected void setup() throws Exception { // client = new Client("localhost", 6379); // client.setDb(2); // } // // protected void teardown() throws Exception { // client.shutdown(); // } // // protected static Ary command(String name, RespType... options) { // List<RespType> elements = new ArrayList<>(options.length + 1); // elements.add(new BulkStr(name)); // elements.addAll(Arrays.asList(options)); // // return new Ary(elements); // } // // protected static RespType ping() { // return command("PING"); // } // // protected static RespType flushDB() { // return command("FLUSHDB"); // } // // protected static RespType get(String key) { // return command("GET", new BulkStr(key)); // } // // protected static RespType set(String key, String value) { // return command("SET", new BulkStr(key), new BulkStr(value)); // } // // protected static RespType sadd(String key, String value) { // return command("SADD", new BulkStr(key), new BulkStr(value)); // } // // protected static RespType smembers(String key) { // return command("SMEMBERS", new BulkStr(key)); // } // // protected static RespType hgetall(String key) { // return command("HGETALL", new BulkStr(key)); // } // // protected static RespType blpop(String key, int timeout) { // return command("BLPOP", new BulkStr(key), new BulkStr(Integer.toString(timeout))); // } // // protected static RespType rpush(String key, String value) { // return command("RPUSH", new BulkStr(key), new BulkStr(value)); // } // // protected static RespType publish(String channel, String payload) { // return command("PUBLISH", new BulkStr(channel), new BulkStr(payload)); // } // // protected void await() { // try { // boolean success = latch.await(5, TimeUnit.SECONDS); // if (!success) { // throw new AssertionError("Timed out waiting"); // } // } catch (InterruptedException e) { // throw new IllegalStateException(e); // } // } // } // // Path: src/main/java/jresp/protocol/RespType.java // public interface RespType { // /** // * Write the RESP form to the ByteBuf // */ // void writeBytes(Deque<ByteBuffer> out); // // /** // * Return the high-level Java equivalent. // */ // Object unwrap(); // } // Path: src/test/java/jresp/pool/BorrowedConnectionTest.java import jresp.JRESPTest; import jresp.protocol.RespType; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import java.util.concurrent.CountDownLatch; import static org.junit.Assert.assertEquals; /* * Copyright 2015 Ben Ashford * * 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 jresp.pool; public class BorrowedConnectionTest extends JRESPTest { private Pool pool; private SingleCommandConnection con; @Before public void setup() throws Exception { super.setup(); pool = new Pool(client); con = pool.getBorrowed(); con.write(flushDB(), NULL_RESPONSES); } @After public void teardown() throws Exception { pool.returnBorrowed(con); super.teardown(); } @Test public void blpopTest() throws Exception { latch = new CountDownLatch(1);
RespType[] responses = new RespType[1];
jenshadlich/s3srv
src/test/java/de/jeha/s3srv/common/s3/RequestContextTest.java
// Path: src/main/java/de/jeha/s3srv/common/http/Headers.java // public class Headers { // // public static String AUTHORIZATION = "Authorization"; // public static String CONNECTION = "Connection"; // public static String CONTENT_MD5 = "Content-MD5"; // public static String CONTENT_LENGTH = "Content-Length"; // public static String CONTENT_TYPE = "Content-Type"; // public static String DATE = "Date"; // public static String ETAG = "ETag"; // public static String HOST = "Host"; // public static String LAST_MODIFIED = "Last-Modified"; // public static String LOCATION = "Location"; // // // a-amz // public static String X_AMZ_ACL = "x-amz-acl"; // // }
import de.jeha.s3srv.common.http.Headers; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import javax.servlet.http.HttpServletRequest; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.when;
package de.jeha.s3srv.common.s3; /** * @author jenshadlich@googlemail.com */ public class RequestContextTest { @Test public void test() { final HttpServletRequest mockedRequest = Mockito.mock(HttpServletRequest.class); when(mockedRequest.getServerName()).thenReturn("localhost");
// Path: src/main/java/de/jeha/s3srv/common/http/Headers.java // public class Headers { // // public static String AUTHORIZATION = "Authorization"; // public static String CONNECTION = "Connection"; // public static String CONTENT_MD5 = "Content-MD5"; // public static String CONTENT_LENGTH = "Content-Length"; // public static String CONTENT_TYPE = "Content-Type"; // public static String DATE = "Date"; // public static String ETAG = "ETag"; // public static String HOST = "Host"; // public static String LAST_MODIFIED = "Last-Modified"; // public static String LOCATION = "Location"; // // // a-amz // public static String X_AMZ_ACL = "x-amz-acl"; // // } // Path: src/test/java/de/jeha/s3srv/common/s3/RequestContextTest.java import de.jeha.s3srv.common.http.Headers; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import javax.servlet.http.HttpServletRequest; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.when; package de.jeha.s3srv.common.s3; /** * @author jenshadlich@googlemail.com */ public class RequestContextTest { @Test public void test() { final HttpServletRequest mockedRequest = Mockito.mock(HttpServletRequest.class); when(mockedRequest.getServerName()).thenReturn("localhost");
when(mockedRequest.getHeader(Headers.HOST)).thenReturn("");
jenshadlich/s3srv
src/test/java/de/jeha/s3srv/api/ListAllMyBucketsResultSerializationTest.java
// Path: src/main/java/de/jeha/s3srv/xml/JaxbMarshaller.java // public class JaxbMarshaller { // // private static Marshaller MARSHALLER = null; // private static Unmarshaller UNMARSHALLER = null; // // static { // try { // MARSHALLER = JaxbContextHolder.getContext().createMarshaller(); // MARSHALLER.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // MARSHALLER.setProperty(Marshaller.JAXB_FRAGMENT, true); // } catch (JAXBException e) { // throw new RuntimeException("Unable to initialize JAXB Marshaller", e); // } // try { // UNMARSHALLER = JaxbContextHolder.getContext().createUnmarshaller(); // } catch (JAXBException e) { // throw new RuntimeException("Unable to initialize JAXB Unmarshaller", e); // } // } // // public synchronized static String marshall(Object object) throws JAXBException, IOException { // StringWriter stringWriter = new StringWriter(); // stringWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); // stringWriter.append("\n"); // // MARSHALLER.marshal(object, stringWriter); // stringWriter.close(); // // return stringWriter.toString(); // } // // public synchronized static <T> T unmarshall(String xml, Class<T> clazz) throws JAXBException, IOException { // return UNMARSHALLER.unmarshal(new StreamSource(new StringReader(xml)), clazz).getValue(); // } // // }
import de.jeha.s3srv.xml.JaxbMarshaller; import org.junit.jupiter.api.Test; import javax.xml.bind.JAXBException; import java.io.IOException; import java.time.Instant; import java.util.Collections; import static org.junit.jupiter.api.Assertions.assertEquals;
package de.jeha.s3srv.api; /** * @author jenshadlich@googlemail.com */ public class ListAllMyBucketsResultSerializationTest { @Test public void test() throws JAXBException, IOException { ListAllMyBucketsResult response = new ListAllMyBucketsResult( new Owner("foo", "bar"), Collections.singletonList(new ListAllMyBucketsResult.BucketsEntry( "test", Instant.parse("2006-02-03T16:45:09.001Z"))));
// Path: src/main/java/de/jeha/s3srv/xml/JaxbMarshaller.java // public class JaxbMarshaller { // // private static Marshaller MARSHALLER = null; // private static Unmarshaller UNMARSHALLER = null; // // static { // try { // MARSHALLER = JaxbContextHolder.getContext().createMarshaller(); // MARSHALLER.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // MARSHALLER.setProperty(Marshaller.JAXB_FRAGMENT, true); // } catch (JAXBException e) { // throw new RuntimeException("Unable to initialize JAXB Marshaller", e); // } // try { // UNMARSHALLER = JaxbContextHolder.getContext().createUnmarshaller(); // } catch (JAXBException e) { // throw new RuntimeException("Unable to initialize JAXB Unmarshaller", e); // } // } // // public synchronized static String marshall(Object object) throws JAXBException, IOException { // StringWriter stringWriter = new StringWriter(); // stringWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); // stringWriter.append("\n"); // // MARSHALLER.marshal(object, stringWriter); // stringWriter.close(); // // return stringWriter.toString(); // } // // public synchronized static <T> T unmarshall(String xml, Class<T> clazz) throws JAXBException, IOException { // return UNMARSHALLER.unmarshal(new StreamSource(new StringReader(xml)), clazz).getValue(); // } // // } // Path: src/test/java/de/jeha/s3srv/api/ListAllMyBucketsResultSerializationTest.java import de.jeha.s3srv.xml.JaxbMarshaller; import org.junit.jupiter.api.Test; import javax.xml.bind.JAXBException; import java.io.IOException; import java.time.Instant; import java.util.Collections; import static org.junit.jupiter.api.Assertions.assertEquals; package de.jeha.s3srv.api; /** * @author jenshadlich@googlemail.com */ public class ListAllMyBucketsResultSerializationTest { @Test public void test() throws JAXBException, IOException { ListAllMyBucketsResult response = new ListAllMyBucketsResult( new Owner("foo", "bar"), Collections.singletonList(new ListAllMyBucketsResult.BucketsEntry( "test", Instant.parse("2006-02-03T16:45:09.001Z"))));
final String responseXml = JaxbMarshaller.marshall(response);
jenshadlich/s3srv
src/test/java/de/jeha/s3srv/api/ErrorResponseSerializationTest.java
// Path: src/main/java/de/jeha/s3srv/common/errors/ErrorCodes.java // public enum ErrorCodes { // // ACCESS_DENIED( // "AccessDenied", // "Access Denied", // 403 // ), // BAD_DIGEST( // "BadDigest", // "The Content-MD5 you specified did not match what we received.", // 400 // ), // BUCKET_ALREADY_EXISTS( // "BucketAlreadyExists", // "The requested bucket name is not available. The bucket namespace is shared by all users of the system. Please select a different name and try again.", // 409 // ), // BUCKET_NOT_EMPTY( // "BucketNotEmpty", // "The bucket you tried to delete is not empty.", // 409 // ), // INVALID_ACCESS_KEY_ID( // "InvalidAccessKeyId", // "The access key Id you provided does not exist in our records.", // 403 // ), // INVALID_BUCKET_NAME( // "InvalidBucketName", // "The specified bucket is not valid.", // 400 // ), // INTERNAL_ERROR( // "InternalError", // "We encountered an internal error. Please try again.", // 500 // ), // NO_SUCH_BUCKET( // "NoSuchBucket", // "The specified bucket does not exist.", // 404 // ), // SERVICE_UNAVAILABLE( // "ServiceUnavailable", // "Reduce your request rate.", // 503 // ), // SIGNATURE_DOES_NOT_MATCH( // "SignatureDoesNotMatch", // "The request signature we calculated does not match the signature you provided. Check your secret access key and signing method.", // 403 // ); // // private final String code; // private final String description; // private final int statusCode; // // ErrorCodes(String code, String description, int statusCode) { // this.code = code; // this.description = description; // this.statusCode = statusCode; // } // // public String getCode() { // return code; // } // // public String getDescription() { // return description; // } // // public int getStatusCode() { // return statusCode; // } // // } // // Path: src/main/java/de/jeha/s3srv/xml/JaxbMarshaller.java // public class JaxbMarshaller { // // private static Marshaller MARSHALLER = null; // private static Unmarshaller UNMARSHALLER = null; // // static { // try { // MARSHALLER = JaxbContextHolder.getContext().createMarshaller(); // MARSHALLER.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // MARSHALLER.setProperty(Marshaller.JAXB_FRAGMENT, true); // } catch (JAXBException e) { // throw new RuntimeException("Unable to initialize JAXB Marshaller", e); // } // try { // UNMARSHALLER = JaxbContextHolder.getContext().createUnmarshaller(); // } catch (JAXBException e) { // throw new RuntimeException("Unable to initialize JAXB Unmarshaller", e); // } // } // // public synchronized static String marshall(Object object) throws JAXBException, IOException { // StringWriter stringWriter = new StringWriter(); // stringWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); // stringWriter.append("\n"); // // MARSHALLER.marshal(object, stringWriter); // stringWriter.close(); // // return stringWriter.toString(); // } // // public synchronized static <T> T unmarshall(String xml, Class<T> clazz) throws JAXBException, IOException { // return UNMARSHALLER.unmarshal(new StreamSource(new StringReader(xml)), clazz).getValue(); // } // // }
import de.jeha.s3srv.common.errors.ErrorCodes; import de.jeha.s3srv.xml.JaxbMarshaller; import org.junit.jupiter.api.Test; import javax.xml.bind.JAXBException; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals;
package de.jeha.s3srv.api; /** * @author jenshadlich@googlemail.com */ public class ErrorResponseSerializationTest { @Test public void test() throws JAXBException, IOException { ErrorResponse response =
// Path: src/main/java/de/jeha/s3srv/common/errors/ErrorCodes.java // public enum ErrorCodes { // // ACCESS_DENIED( // "AccessDenied", // "Access Denied", // 403 // ), // BAD_DIGEST( // "BadDigest", // "The Content-MD5 you specified did not match what we received.", // 400 // ), // BUCKET_ALREADY_EXISTS( // "BucketAlreadyExists", // "The requested bucket name is not available. The bucket namespace is shared by all users of the system. Please select a different name and try again.", // 409 // ), // BUCKET_NOT_EMPTY( // "BucketNotEmpty", // "The bucket you tried to delete is not empty.", // 409 // ), // INVALID_ACCESS_KEY_ID( // "InvalidAccessKeyId", // "The access key Id you provided does not exist in our records.", // 403 // ), // INVALID_BUCKET_NAME( // "InvalidBucketName", // "The specified bucket is not valid.", // 400 // ), // INTERNAL_ERROR( // "InternalError", // "We encountered an internal error. Please try again.", // 500 // ), // NO_SUCH_BUCKET( // "NoSuchBucket", // "The specified bucket does not exist.", // 404 // ), // SERVICE_UNAVAILABLE( // "ServiceUnavailable", // "Reduce your request rate.", // 503 // ), // SIGNATURE_DOES_NOT_MATCH( // "SignatureDoesNotMatch", // "The request signature we calculated does not match the signature you provided. Check your secret access key and signing method.", // 403 // ); // // private final String code; // private final String description; // private final int statusCode; // // ErrorCodes(String code, String description, int statusCode) { // this.code = code; // this.description = description; // this.statusCode = statusCode; // } // // public String getCode() { // return code; // } // // public String getDescription() { // return description; // } // // public int getStatusCode() { // return statusCode; // } // // } // // Path: src/main/java/de/jeha/s3srv/xml/JaxbMarshaller.java // public class JaxbMarshaller { // // private static Marshaller MARSHALLER = null; // private static Unmarshaller UNMARSHALLER = null; // // static { // try { // MARSHALLER = JaxbContextHolder.getContext().createMarshaller(); // MARSHALLER.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // MARSHALLER.setProperty(Marshaller.JAXB_FRAGMENT, true); // } catch (JAXBException e) { // throw new RuntimeException("Unable to initialize JAXB Marshaller", e); // } // try { // UNMARSHALLER = JaxbContextHolder.getContext().createUnmarshaller(); // } catch (JAXBException e) { // throw new RuntimeException("Unable to initialize JAXB Unmarshaller", e); // } // } // // public synchronized static String marshall(Object object) throws JAXBException, IOException { // StringWriter stringWriter = new StringWriter(); // stringWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); // stringWriter.append("\n"); // // MARSHALLER.marshal(object, stringWriter); // stringWriter.close(); // // return stringWriter.toString(); // } // // public synchronized static <T> T unmarshall(String xml, Class<T> clazz) throws JAXBException, IOException { // return UNMARSHALLER.unmarshal(new StreamSource(new StringReader(xml)), clazz).getValue(); // } // // } // Path: src/test/java/de/jeha/s3srv/api/ErrorResponseSerializationTest.java import de.jeha.s3srv.common.errors.ErrorCodes; import de.jeha.s3srv.xml.JaxbMarshaller; import org.junit.jupiter.api.Test; import javax.xml.bind.JAXBException; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals; package de.jeha.s3srv.api; /** * @author jenshadlich@googlemail.com */ public class ErrorResponseSerializationTest { @Test public void test() throws JAXBException, IOException { ErrorResponse response =
new ErrorResponse(ErrorCodes.SERVICE_UNAVAILABLE.getCode(), ErrorCodes.SERVICE_UNAVAILABLE.getDescription(), null, null);
jenshadlich/s3srv
src/test/java/de/jeha/s3srv/api/ErrorResponseSerializationTest.java
// Path: src/main/java/de/jeha/s3srv/common/errors/ErrorCodes.java // public enum ErrorCodes { // // ACCESS_DENIED( // "AccessDenied", // "Access Denied", // 403 // ), // BAD_DIGEST( // "BadDigest", // "The Content-MD5 you specified did not match what we received.", // 400 // ), // BUCKET_ALREADY_EXISTS( // "BucketAlreadyExists", // "The requested bucket name is not available. The bucket namespace is shared by all users of the system. Please select a different name and try again.", // 409 // ), // BUCKET_NOT_EMPTY( // "BucketNotEmpty", // "The bucket you tried to delete is not empty.", // 409 // ), // INVALID_ACCESS_KEY_ID( // "InvalidAccessKeyId", // "The access key Id you provided does not exist in our records.", // 403 // ), // INVALID_BUCKET_NAME( // "InvalidBucketName", // "The specified bucket is not valid.", // 400 // ), // INTERNAL_ERROR( // "InternalError", // "We encountered an internal error. Please try again.", // 500 // ), // NO_SUCH_BUCKET( // "NoSuchBucket", // "The specified bucket does not exist.", // 404 // ), // SERVICE_UNAVAILABLE( // "ServiceUnavailable", // "Reduce your request rate.", // 503 // ), // SIGNATURE_DOES_NOT_MATCH( // "SignatureDoesNotMatch", // "The request signature we calculated does not match the signature you provided. Check your secret access key and signing method.", // 403 // ); // // private final String code; // private final String description; // private final int statusCode; // // ErrorCodes(String code, String description, int statusCode) { // this.code = code; // this.description = description; // this.statusCode = statusCode; // } // // public String getCode() { // return code; // } // // public String getDescription() { // return description; // } // // public int getStatusCode() { // return statusCode; // } // // } // // Path: src/main/java/de/jeha/s3srv/xml/JaxbMarshaller.java // public class JaxbMarshaller { // // private static Marshaller MARSHALLER = null; // private static Unmarshaller UNMARSHALLER = null; // // static { // try { // MARSHALLER = JaxbContextHolder.getContext().createMarshaller(); // MARSHALLER.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // MARSHALLER.setProperty(Marshaller.JAXB_FRAGMENT, true); // } catch (JAXBException e) { // throw new RuntimeException("Unable to initialize JAXB Marshaller", e); // } // try { // UNMARSHALLER = JaxbContextHolder.getContext().createUnmarshaller(); // } catch (JAXBException e) { // throw new RuntimeException("Unable to initialize JAXB Unmarshaller", e); // } // } // // public synchronized static String marshall(Object object) throws JAXBException, IOException { // StringWriter stringWriter = new StringWriter(); // stringWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); // stringWriter.append("\n"); // // MARSHALLER.marshal(object, stringWriter); // stringWriter.close(); // // return stringWriter.toString(); // } // // public synchronized static <T> T unmarshall(String xml, Class<T> clazz) throws JAXBException, IOException { // return UNMARSHALLER.unmarshal(new StreamSource(new StringReader(xml)), clazz).getValue(); // } // // }
import de.jeha.s3srv.common.errors.ErrorCodes; import de.jeha.s3srv.xml.JaxbMarshaller; import org.junit.jupiter.api.Test; import javax.xml.bind.JAXBException; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals;
package de.jeha.s3srv.api; /** * @author jenshadlich@googlemail.com */ public class ErrorResponseSerializationTest { @Test public void test() throws JAXBException, IOException { ErrorResponse response = new ErrorResponse(ErrorCodes.SERVICE_UNAVAILABLE.getCode(), ErrorCodes.SERVICE_UNAVAILABLE.getDescription(), null, null);
// Path: src/main/java/de/jeha/s3srv/common/errors/ErrorCodes.java // public enum ErrorCodes { // // ACCESS_DENIED( // "AccessDenied", // "Access Denied", // 403 // ), // BAD_DIGEST( // "BadDigest", // "The Content-MD5 you specified did not match what we received.", // 400 // ), // BUCKET_ALREADY_EXISTS( // "BucketAlreadyExists", // "The requested bucket name is not available. The bucket namespace is shared by all users of the system. Please select a different name and try again.", // 409 // ), // BUCKET_NOT_EMPTY( // "BucketNotEmpty", // "The bucket you tried to delete is not empty.", // 409 // ), // INVALID_ACCESS_KEY_ID( // "InvalidAccessKeyId", // "The access key Id you provided does not exist in our records.", // 403 // ), // INVALID_BUCKET_NAME( // "InvalidBucketName", // "The specified bucket is not valid.", // 400 // ), // INTERNAL_ERROR( // "InternalError", // "We encountered an internal error. Please try again.", // 500 // ), // NO_SUCH_BUCKET( // "NoSuchBucket", // "The specified bucket does not exist.", // 404 // ), // SERVICE_UNAVAILABLE( // "ServiceUnavailable", // "Reduce your request rate.", // 503 // ), // SIGNATURE_DOES_NOT_MATCH( // "SignatureDoesNotMatch", // "The request signature we calculated does not match the signature you provided. Check your secret access key and signing method.", // 403 // ); // // private final String code; // private final String description; // private final int statusCode; // // ErrorCodes(String code, String description, int statusCode) { // this.code = code; // this.description = description; // this.statusCode = statusCode; // } // // public String getCode() { // return code; // } // // public String getDescription() { // return description; // } // // public int getStatusCode() { // return statusCode; // } // // } // // Path: src/main/java/de/jeha/s3srv/xml/JaxbMarshaller.java // public class JaxbMarshaller { // // private static Marshaller MARSHALLER = null; // private static Unmarshaller UNMARSHALLER = null; // // static { // try { // MARSHALLER = JaxbContextHolder.getContext().createMarshaller(); // MARSHALLER.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // MARSHALLER.setProperty(Marshaller.JAXB_FRAGMENT, true); // } catch (JAXBException e) { // throw new RuntimeException("Unable to initialize JAXB Marshaller", e); // } // try { // UNMARSHALLER = JaxbContextHolder.getContext().createUnmarshaller(); // } catch (JAXBException e) { // throw new RuntimeException("Unable to initialize JAXB Unmarshaller", e); // } // } // // public synchronized static String marshall(Object object) throws JAXBException, IOException { // StringWriter stringWriter = new StringWriter(); // stringWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); // stringWriter.append("\n"); // // MARSHALLER.marshal(object, stringWriter); // stringWriter.close(); // // return stringWriter.toString(); // } // // public synchronized static <T> T unmarshall(String xml, Class<T> clazz) throws JAXBException, IOException { // return UNMARSHALLER.unmarshal(new StreamSource(new StringReader(xml)), clazz).getValue(); // } // // } // Path: src/test/java/de/jeha/s3srv/api/ErrorResponseSerializationTest.java import de.jeha.s3srv.common.errors.ErrorCodes; import de.jeha.s3srv.xml.JaxbMarshaller; import org.junit.jupiter.api.Test; import javax.xml.bind.JAXBException; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals; package de.jeha.s3srv.api; /** * @author jenshadlich@googlemail.com */ public class ErrorResponseSerializationTest { @Test public void test() throws JAXBException, IOException { ErrorResponse response = new ErrorResponse(ErrorCodes.SERVICE_UNAVAILABLE.getCode(), ErrorCodes.SERVICE_UNAVAILABLE.getDescription(), null, null);
final String responseXml = JaxbMarshaller.marshall(response);
jenshadlich/s3srv
src/test/java/de/jeha/s3srv/api/AccessControlPolicySerializationTest.java
// Path: src/main/java/de/jeha/s3srv/common/acl/ACLPermissions.java // public enum ACLPermissions { // READ, // WRITE, // READ_ACP, // WRITE_ACP, // FULL_CONTROL; // } // // Path: src/main/java/de/jeha/s3srv/xml/JaxbMarshaller.java // public class JaxbMarshaller { // // private static Marshaller MARSHALLER = null; // private static Unmarshaller UNMARSHALLER = null; // // static { // try { // MARSHALLER = JaxbContextHolder.getContext().createMarshaller(); // MARSHALLER.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // MARSHALLER.setProperty(Marshaller.JAXB_FRAGMENT, true); // } catch (JAXBException e) { // throw new RuntimeException("Unable to initialize JAXB Marshaller", e); // } // try { // UNMARSHALLER = JaxbContextHolder.getContext().createUnmarshaller(); // } catch (JAXBException e) { // throw new RuntimeException("Unable to initialize JAXB Unmarshaller", e); // } // } // // public synchronized static String marshall(Object object) throws JAXBException, IOException { // StringWriter stringWriter = new StringWriter(); // stringWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); // stringWriter.append("\n"); // // MARSHALLER.marshal(object, stringWriter); // stringWriter.close(); // // return stringWriter.toString(); // } // // public synchronized static <T> T unmarshall(String xml, Class<T> clazz) throws JAXBException, IOException { // return UNMARSHALLER.unmarshal(new StreamSource(new StringReader(xml)), clazz).getValue(); // } // // }
import de.jeha.s3srv.common.acl.ACLPermissions; import de.jeha.s3srv.xml.JaxbMarshaller; import org.junit.jupiter.api.Test; import javax.xml.bind.JAXBException; import java.io.IOException; import java.util.Collections; import static org.junit.jupiter.api.Assertions.assertEquals;
package de.jeha.s3srv.api; /** * @author jenshadlich@googlemail.com */ public class AccessControlPolicySerializationTest { @Test public void test() throws JAXBException, IOException { AccessControlPolicy response = new AccessControlPolicy( new Owner("foo", "bar"),
// Path: src/main/java/de/jeha/s3srv/common/acl/ACLPermissions.java // public enum ACLPermissions { // READ, // WRITE, // READ_ACP, // WRITE_ACP, // FULL_CONTROL; // } // // Path: src/main/java/de/jeha/s3srv/xml/JaxbMarshaller.java // public class JaxbMarshaller { // // private static Marshaller MARSHALLER = null; // private static Unmarshaller UNMARSHALLER = null; // // static { // try { // MARSHALLER = JaxbContextHolder.getContext().createMarshaller(); // MARSHALLER.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // MARSHALLER.setProperty(Marshaller.JAXB_FRAGMENT, true); // } catch (JAXBException e) { // throw new RuntimeException("Unable to initialize JAXB Marshaller", e); // } // try { // UNMARSHALLER = JaxbContextHolder.getContext().createUnmarshaller(); // } catch (JAXBException e) { // throw new RuntimeException("Unable to initialize JAXB Unmarshaller", e); // } // } // // public synchronized static String marshall(Object object) throws JAXBException, IOException { // StringWriter stringWriter = new StringWriter(); // stringWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); // stringWriter.append("\n"); // // MARSHALLER.marshal(object, stringWriter); // stringWriter.close(); // // return stringWriter.toString(); // } // // public synchronized static <T> T unmarshall(String xml, Class<T> clazz) throws JAXBException, IOException { // return UNMARSHALLER.unmarshal(new StreamSource(new StringReader(xml)), clazz).getValue(); // } // // } // Path: src/test/java/de/jeha/s3srv/api/AccessControlPolicySerializationTest.java import de.jeha.s3srv.common.acl.ACLPermissions; import de.jeha.s3srv.xml.JaxbMarshaller; import org.junit.jupiter.api.Test; import javax.xml.bind.JAXBException; import java.io.IOException; import java.util.Collections; import static org.junit.jupiter.api.Assertions.assertEquals; package de.jeha.s3srv.api; /** * @author jenshadlich@googlemail.com */ public class AccessControlPolicySerializationTest { @Test public void test() throws JAXBException, IOException { AccessControlPolicy response = new AccessControlPolicy( new Owner("foo", "bar"),
Collections.singletonList(new AccessControlPolicy.Grant(new Grantee("foo", "bar"), ACLPermissions.FULL_CONTROL.name())));
jenshadlich/s3srv
src/test/java/de/jeha/s3srv/api/AccessControlPolicySerializationTest.java
// Path: src/main/java/de/jeha/s3srv/common/acl/ACLPermissions.java // public enum ACLPermissions { // READ, // WRITE, // READ_ACP, // WRITE_ACP, // FULL_CONTROL; // } // // Path: src/main/java/de/jeha/s3srv/xml/JaxbMarshaller.java // public class JaxbMarshaller { // // private static Marshaller MARSHALLER = null; // private static Unmarshaller UNMARSHALLER = null; // // static { // try { // MARSHALLER = JaxbContextHolder.getContext().createMarshaller(); // MARSHALLER.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // MARSHALLER.setProperty(Marshaller.JAXB_FRAGMENT, true); // } catch (JAXBException e) { // throw new RuntimeException("Unable to initialize JAXB Marshaller", e); // } // try { // UNMARSHALLER = JaxbContextHolder.getContext().createUnmarshaller(); // } catch (JAXBException e) { // throw new RuntimeException("Unable to initialize JAXB Unmarshaller", e); // } // } // // public synchronized static String marshall(Object object) throws JAXBException, IOException { // StringWriter stringWriter = new StringWriter(); // stringWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); // stringWriter.append("\n"); // // MARSHALLER.marshal(object, stringWriter); // stringWriter.close(); // // return stringWriter.toString(); // } // // public synchronized static <T> T unmarshall(String xml, Class<T> clazz) throws JAXBException, IOException { // return UNMARSHALLER.unmarshal(new StreamSource(new StringReader(xml)), clazz).getValue(); // } // // }
import de.jeha.s3srv.common.acl.ACLPermissions; import de.jeha.s3srv.xml.JaxbMarshaller; import org.junit.jupiter.api.Test; import javax.xml.bind.JAXBException; import java.io.IOException; import java.util.Collections; import static org.junit.jupiter.api.Assertions.assertEquals;
package de.jeha.s3srv.api; /** * @author jenshadlich@googlemail.com */ public class AccessControlPolicySerializationTest { @Test public void test() throws JAXBException, IOException { AccessControlPolicy response = new AccessControlPolicy( new Owner("foo", "bar"), Collections.singletonList(new AccessControlPolicy.Grant(new Grantee("foo", "bar"), ACLPermissions.FULL_CONTROL.name())));
// Path: src/main/java/de/jeha/s3srv/common/acl/ACLPermissions.java // public enum ACLPermissions { // READ, // WRITE, // READ_ACP, // WRITE_ACP, // FULL_CONTROL; // } // // Path: src/main/java/de/jeha/s3srv/xml/JaxbMarshaller.java // public class JaxbMarshaller { // // private static Marshaller MARSHALLER = null; // private static Unmarshaller UNMARSHALLER = null; // // static { // try { // MARSHALLER = JaxbContextHolder.getContext().createMarshaller(); // MARSHALLER.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // MARSHALLER.setProperty(Marshaller.JAXB_FRAGMENT, true); // } catch (JAXBException e) { // throw new RuntimeException("Unable to initialize JAXB Marshaller", e); // } // try { // UNMARSHALLER = JaxbContextHolder.getContext().createUnmarshaller(); // } catch (JAXBException e) { // throw new RuntimeException("Unable to initialize JAXB Unmarshaller", e); // } // } // // public synchronized static String marshall(Object object) throws JAXBException, IOException { // StringWriter stringWriter = new StringWriter(); // stringWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); // stringWriter.append("\n"); // // MARSHALLER.marshal(object, stringWriter); // stringWriter.close(); // // return stringWriter.toString(); // } // // public synchronized static <T> T unmarshall(String xml, Class<T> clazz) throws JAXBException, IOException { // return UNMARSHALLER.unmarshal(new StreamSource(new StringReader(xml)), clazz).getValue(); // } // // } // Path: src/test/java/de/jeha/s3srv/api/AccessControlPolicySerializationTest.java import de.jeha.s3srv.common.acl.ACLPermissions; import de.jeha.s3srv.xml.JaxbMarshaller; import org.junit.jupiter.api.Test; import javax.xml.bind.JAXBException; import java.io.IOException; import java.util.Collections; import static org.junit.jupiter.api.Assertions.assertEquals; package de.jeha.s3srv.api; /** * @author jenshadlich@googlemail.com */ public class AccessControlPolicySerializationTest { @Test public void test() throws JAXBException, IOException { AccessControlPolicy response = new AccessControlPolicy( new Owner("foo", "bar"), Collections.singletonList(new AccessControlPolicy.Grant(new Grantee("foo", "bar"), ACLPermissions.FULL_CONTROL.name())));
final String responseXml = JaxbMarshaller.marshall(response);
jenshadlich/s3srv
src/main/java/de/jeha/s3srv/model/S3Object.java
// Path: src/main/java/de/jeha/s3srv/storage/InputStreamCallback.java // public interface InputStreamCallback { // // InputStream getInputStream(); // // }
import de.jeha.s3srv.storage.InputStreamCallback; import java.io.InputStream; import java.time.Instant;
package de.jeha.s3srv.model; /** * @author jenshadlich@googlemail.com */ public class S3Object { private final S3Bucket bucket; private final String key; private final String md5; private final String eTag; private final Integer size; private final Instant lastModified;
// Path: src/main/java/de/jeha/s3srv/storage/InputStreamCallback.java // public interface InputStreamCallback { // // InputStream getInputStream(); // // } // Path: src/main/java/de/jeha/s3srv/model/S3Object.java import de.jeha.s3srv.storage.InputStreamCallback; import java.io.InputStream; import java.time.Instant; package de.jeha.s3srv.model; /** * @author jenshadlich@googlemail.com */ public class S3Object { private final S3Bucket bucket; private final String key; private final String md5; private final String eTag; private final Integer size; private final Instant lastModified;
private final InputStreamCallback inputStreamCallback;
jenshadlich/s3srv
src/main/java/de/jeha/s3srv/tools/GenerateRandomCredentials.java
// Path: src/main/java/de/jeha/s3srv/common/security/Credentials.java // public class Credentials { // // private final static String ACCESS_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // private final static int ACCESS_KEY_LENGTH = 20; // // private final static String SECRET_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // private final static String SECRET_KEY_CHARS_WITH_SPECIAL_CHARS = SECRET_KEY_CHARS + "/+"; // private final static int SECRET_KEY_LENGTH = 40; // // private final String accessKey; // private final String secretKey; // // public Credentials(String accessKey, String secretKey) { // this.accessKey = accessKey; // this.secretKey = secretKey; // } // // public String getAccessKey() { // return accessKey; // } // // public String getSecretKey() { // return secretKey; // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @return randomly generated credentials // */ // public static Credentials generateRandom() { // return generateRandom(true); // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @param includeSpecialChars include special chars ('/' and '+') for secret keys // * @return randomly generated credentials // */ // public static Credentials generateRandom(boolean includeSpecialChars) { // String accessKey = RandomStringUtils.random(ACCESS_KEY_LENGTH, ACCESS_KEY_CHARS); // String secretKey = RandomStringUtils.random( // SECRET_KEY_LENGTH, // includeSpecialChars ? SECRET_KEY_CHARS_WITH_SPECIAL_CHARS : SECRET_KEY_CHARS // ); // // return new Credentials(accessKey, secretKey); // } // // public void print() { // System.out.println(); // System.out.println("accessKey: " + accessKey); // System.out.println("secretKey: " + secretKey); // System.out.println(); // } // // }
import de.jeha.s3srv.common.security.Credentials;
package de.jeha.s3srv.tools; /** * @author jenshadlich@googlemail.com */ public class GenerateRandomCredentials { public static void main(String... args) {
// Path: src/main/java/de/jeha/s3srv/common/security/Credentials.java // public class Credentials { // // private final static String ACCESS_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // private final static int ACCESS_KEY_LENGTH = 20; // // private final static String SECRET_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // private final static String SECRET_KEY_CHARS_WITH_SPECIAL_CHARS = SECRET_KEY_CHARS + "/+"; // private final static int SECRET_KEY_LENGTH = 40; // // private final String accessKey; // private final String secretKey; // // public Credentials(String accessKey, String secretKey) { // this.accessKey = accessKey; // this.secretKey = secretKey; // } // // public String getAccessKey() { // return accessKey; // } // // public String getSecretKey() { // return secretKey; // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @return randomly generated credentials // */ // public static Credentials generateRandom() { // return generateRandom(true); // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @param includeSpecialChars include special chars ('/' and '+') for secret keys // * @return randomly generated credentials // */ // public static Credentials generateRandom(boolean includeSpecialChars) { // String accessKey = RandomStringUtils.random(ACCESS_KEY_LENGTH, ACCESS_KEY_CHARS); // String secretKey = RandomStringUtils.random( // SECRET_KEY_LENGTH, // includeSpecialChars ? SECRET_KEY_CHARS_WITH_SPECIAL_CHARS : SECRET_KEY_CHARS // ); // // return new Credentials(accessKey, secretKey); // } // // public void print() { // System.out.println(); // System.out.println("accessKey: " + accessKey); // System.out.println("secretKey: " + secretKey); // System.out.println(); // } // // } // Path: src/main/java/de/jeha/s3srv/tools/GenerateRandomCredentials.java import de.jeha.s3srv.common.security.Credentials; package de.jeha.s3srv.tools; /** * @author jenshadlich@googlemail.com */ public class GenerateRandomCredentials { public static void main(String... args) {
final Credentials credentials = Credentials.generateRandom(false);
jenshadlich/s3srv
src/main/java/de/jeha/s3srv/config/S3SrvConfiguration.java
// Path: src/main/java/de/jeha/s3srv/common/security/Credentials.java // public class Credentials { // // private final static String ACCESS_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // private final static int ACCESS_KEY_LENGTH = 20; // // private final static String SECRET_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // private final static String SECRET_KEY_CHARS_WITH_SPECIAL_CHARS = SECRET_KEY_CHARS + "/+"; // private final static int SECRET_KEY_LENGTH = 40; // // private final String accessKey; // private final String secretKey; // // public Credentials(String accessKey, String secretKey) { // this.accessKey = accessKey; // this.secretKey = secretKey; // } // // public String getAccessKey() { // return accessKey; // } // // public String getSecretKey() { // return secretKey; // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @return randomly generated credentials // */ // public static Credentials generateRandom() { // return generateRandom(true); // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @param includeSpecialChars include special chars ('/' and '+') for secret keys // * @return randomly generated credentials // */ // public static Credentials generateRandom(boolean includeSpecialChars) { // String accessKey = RandomStringUtils.random(ACCESS_KEY_LENGTH, ACCESS_KEY_CHARS); // String secretKey = RandomStringUtils.random( // SECRET_KEY_LENGTH, // includeSpecialChars ? SECRET_KEY_CHARS_WITH_SPECIAL_CHARS : SECRET_KEY_CHARS // ); // // return new Credentials(accessKey, secretKey); // } // // public void print() { // System.out.println(); // System.out.println("accessKey: " + accessKey); // System.out.println("secretKey: " + secretKey); // System.out.println(); // } // // }
import com.fasterxml.jackson.annotation.JsonProperty; import de.jeha.s3srv.common.security.Credentials; import io.dropwizard.Configuration; import org.hibernate.validator.constraints.Length; import javax.validation.Valid; import javax.validation.constraints.NotNull;
package de.jeha.s3srv.config; /** * @author jenshadlich@googlemail.com */ public class S3SrvConfiguration extends Configuration { @JsonProperty @NotNull @Length(min = 20, max = 20) private String accessKey; @JsonProperty @NotNull @Length(min = 40, max = 40) private String secretKey; @NotNull @Valid private StorageBackendFactory storageBackend; @JsonProperty private boolean jerseyLoggingFilterEnabled = false; public String getAccessKey() { return accessKey; } public String getSecretKey() { return secretKey; }
// Path: src/main/java/de/jeha/s3srv/common/security/Credentials.java // public class Credentials { // // private final static String ACCESS_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // private final static int ACCESS_KEY_LENGTH = 20; // // private final static String SECRET_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // private final static String SECRET_KEY_CHARS_WITH_SPECIAL_CHARS = SECRET_KEY_CHARS + "/+"; // private final static int SECRET_KEY_LENGTH = 40; // // private final String accessKey; // private final String secretKey; // // public Credentials(String accessKey, String secretKey) { // this.accessKey = accessKey; // this.secretKey = secretKey; // } // // public String getAccessKey() { // return accessKey; // } // // public String getSecretKey() { // return secretKey; // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @return randomly generated credentials // */ // public static Credentials generateRandom() { // return generateRandom(true); // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @param includeSpecialChars include special chars ('/' and '+') for secret keys // * @return randomly generated credentials // */ // public static Credentials generateRandom(boolean includeSpecialChars) { // String accessKey = RandomStringUtils.random(ACCESS_KEY_LENGTH, ACCESS_KEY_CHARS); // String secretKey = RandomStringUtils.random( // SECRET_KEY_LENGTH, // includeSpecialChars ? SECRET_KEY_CHARS_WITH_SPECIAL_CHARS : SECRET_KEY_CHARS // ); // // return new Credentials(accessKey, secretKey); // } // // public void print() { // System.out.println(); // System.out.println("accessKey: " + accessKey); // System.out.println("secretKey: " + secretKey); // System.out.println(); // } // // } // Path: src/main/java/de/jeha/s3srv/config/S3SrvConfiguration.java import com.fasterxml.jackson.annotation.JsonProperty; import de.jeha.s3srv.common.security.Credentials; import io.dropwizard.Configuration; import org.hibernate.validator.constraints.Length; import javax.validation.Valid; import javax.validation.constraints.NotNull; package de.jeha.s3srv.config; /** * @author jenshadlich@googlemail.com */ public class S3SrvConfiguration extends Configuration { @JsonProperty @NotNull @Length(min = 20, max = 20) private String accessKey; @JsonProperty @NotNull @Length(min = 40, max = 40) private String secretKey; @NotNull @Valid private StorageBackendFactory storageBackend; @JsonProperty private boolean jerseyLoggingFilterEnabled = false; public String getAccessKey() { return accessKey; } public String getSecretKey() { return secretKey; }
public Credentials buildCredentials() {
jenshadlich/s3srv
src/test/java/de/jeha/s3srv/operations/buckets/CreateBucketTest.java
// Path: src/main/java/de/jeha/s3srv/common/http/Headers.java // public class Headers { // // public static String AUTHORIZATION = "Authorization"; // public static String CONNECTION = "Connection"; // public static String CONTENT_MD5 = "Content-MD5"; // public static String CONTENT_LENGTH = "Content-Length"; // public static String CONTENT_TYPE = "Content-Type"; // public static String DATE = "Date"; // public static String ETAG = "ETag"; // public static String HOST = "Host"; // public static String LAST_MODIFIED = "Last-Modified"; // public static String LOCATION = "Location"; // // // a-amz // public static String X_AMZ_ACL = "x-amz-acl"; // // } // // Path: src/main/java/de/jeha/s3srv/common/security/Credentials.java // public class Credentials { // // private final static String ACCESS_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // private final static int ACCESS_KEY_LENGTH = 20; // // private final static String SECRET_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // private final static String SECRET_KEY_CHARS_WITH_SPECIAL_CHARS = SECRET_KEY_CHARS + "/+"; // private final static int SECRET_KEY_LENGTH = 40; // // private final String accessKey; // private final String secretKey; // // public Credentials(String accessKey, String secretKey) { // this.accessKey = accessKey; // this.secretKey = secretKey; // } // // public String getAccessKey() { // return accessKey; // } // // public String getSecretKey() { // return secretKey; // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @return randomly generated credentials // */ // public static Credentials generateRandom() { // return generateRandom(true); // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @param includeSpecialChars include special chars ('/' and '+') for secret keys // * @return randomly generated credentials // */ // public static Credentials generateRandom(boolean includeSpecialChars) { // String accessKey = RandomStringUtils.random(ACCESS_KEY_LENGTH, ACCESS_KEY_CHARS); // String secretKey = RandomStringUtils.random( // SECRET_KEY_LENGTH, // includeSpecialChars ? SECRET_KEY_CHARS_WITH_SPECIAL_CHARS : SECRET_KEY_CHARS // ); // // return new Credentials(accessKey, secretKey); // } // // public void print() { // System.out.println(); // System.out.println("accessKey: " + accessKey); // System.out.println("secretKey: " + secretKey); // System.out.println(); // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3User.java // public class S3User { // // private final String id; // private final String displayName; // private final Credentials credentials; // // public S3User(String id, String displayName, Credentials credentials) { // this.id = id; // this.displayName = displayName; // this.credentials = credentials; // } // // public String getId() { // return id; // } // // public String getDisplayName() { // return displayName; // } // // public Credentials getCredentials() { // return credentials; // } // // } // // Path: src/main/java/de/jeha/s3srv/storage/StorageBackend.java // public interface StorageBackend extends HealthAware { // // List<S3Bucket> listBuckets(); // // void createBucket(S3User user, String bucket); // // boolean doesBucketExist(String bucket); // // S3Bucket getBucket(String bucket); // // void deleteBucket(String bucket); // // S3Object createObject(String bucket, String key, InputStream contentStream, int contentLength, // String expectedMD5, String contentType) // throws IOException, BadDigestException; // // boolean doesObjectExist(String bucket, String key); // // List<S3Object> listObjects(String bucket, int max); // // S3Object getObject(String bucket, String key); // // void deleteObject(String bucket, String key); // // /** // * @todo maybe separate storage backends for data and account data // */ // S3User getUserByAccessId(String accessKey); // // }
import de.jeha.s3srv.common.http.Headers; import de.jeha.s3srv.common.security.Credentials; import de.jeha.s3srv.model.S3User; import de.jeha.s3srv.storage.StorageBackend; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.Response; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
package de.jeha.s3srv.operations.buckets; /** * @author jenshadlich@googlemail.com */ public class CreateBucketTest { @Test public void test() { final HttpServletRequest mockedRequest = Mockito.mock(HttpServletRequest.class);
// Path: src/main/java/de/jeha/s3srv/common/http/Headers.java // public class Headers { // // public static String AUTHORIZATION = "Authorization"; // public static String CONNECTION = "Connection"; // public static String CONTENT_MD5 = "Content-MD5"; // public static String CONTENT_LENGTH = "Content-Length"; // public static String CONTENT_TYPE = "Content-Type"; // public static String DATE = "Date"; // public static String ETAG = "ETag"; // public static String HOST = "Host"; // public static String LAST_MODIFIED = "Last-Modified"; // public static String LOCATION = "Location"; // // // a-amz // public static String X_AMZ_ACL = "x-amz-acl"; // // } // // Path: src/main/java/de/jeha/s3srv/common/security/Credentials.java // public class Credentials { // // private final static String ACCESS_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // private final static int ACCESS_KEY_LENGTH = 20; // // private final static String SECRET_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // private final static String SECRET_KEY_CHARS_WITH_SPECIAL_CHARS = SECRET_KEY_CHARS + "/+"; // private final static int SECRET_KEY_LENGTH = 40; // // private final String accessKey; // private final String secretKey; // // public Credentials(String accessKey, String secretKey) { // this.accessKey = accessKey; // this.secretKey = secretKey; // } // // public String getAccessKey() { // return accessKey; // } // // public String getSecretKey() { // return secretKey; // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @return randomly generated credentials // */ // public static Credentials generateRandom() { // return generateRandom(true); // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @param includeSpecialChars include special chars ('/' and '+') for secret keys // * @return randomly generated credentials // */ // public static Credentials generateRandom(boolean includeSpecialChars) { // String accessKey = RandomStringUtils.random(ACCESS_KEY_LENGTH, ACCESS_KEY_CHARS); // String secretKey = RandomStringUtils.random( // SECRET_KEY_LENGTH, // includeSpecialChars ? SECRET_KEY_CHARS_WITH_SPECIAL_CHARS : SECRET_KEY_CHARS // ); // // return new Credentials(accessKey, secretKey); // } // // public void print() { // System.out.println(); // System.out.println("accessKey: " + accessKey); // System.out.println("secretKey: " + secretKey); // System.out.println(); // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3User.java // public class S3User { // // private final String id; // private final String displayName; // private final Credentials credentials; // // public S3User(String id, String displayName, Credentials credentials) { // this.id = id; // this.displayName = displayName; // this.credentials = credentials; // } // // public String getId() { // return id; // } // // public String getDisplayName() { // return displayName; // } // // public Credentials getCredentials() { // return credentials; // } // // } // // Path: src/main/java/de/jeha/s3srv/storage/StorageBackend.java // public interface StorageBackend extends HealthAware { // // List<S3Bucket> listBuckets(); // // void createBucket(S3User user, String bucket); // // boolean doesBucketExist(String bucket); // // S3Bucket getBucket(String bucket); // // void deleteBucket(String bucket); // // S3Object createObject(String bucket, String key, InputStream contentStream, int contentLength, // String expectedMD5, String contentType) // throws IOException, BadDigestException; // // boolean doesObjectExist(String bucket, String key); // // List<S3Object> listObjects(String bucket, int max); // // S3Object getObject(String bucket, String key); // // void deleteObject(String bucket, String key); // // /** // * @todo maybe separate storage backends for data and account data // */ // S3User getUserByAccessId(String accessKey); // // } // Path: src/test/java/de/jeha/s3srv/operations/buckets/CreateBucketTest.java import de.jeha.s3srv.common.http.Headers; import de.jeha.s3srv.common.security.Credentials; import de.jeha.s3srv.model.S3User; import de.jeha.s3srv.storage.StorageBackend; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.Response; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; package de.jeha.s3srv.operations.buckets; /** * @author jenshadlich@googlemail.com */ public class CreateBucketTest { @Test public void test() { final HttpServletRequest mockedRequest = Mockito.mock(HttpServletRequest.class);
when(mockedRequest.getHeader(Headers.AUTHORIZATION)).thenReturn("AWS foo:4AvYjPkzjOQWie8IKBTRSuUayPI=");
jenshadlich/s3srv
src/test/java/de/jeha/s3srv/operations/buckets/CreateBucketTest.java
// Path: src/main/java/de/jeha/s3srv/common/http/Headers.java // public class Headers { // // public static String AUTHORIZATION = "Authorization"; // public static String CONNECTION = "Connection"; // public static String CONTENT_MD5 = "Content-MD5"; // public static String CONTENT_LENGTH = "Content-Length"; // public static String CONTENT_TYPE = "Content-Type"; // public static String DATE = "Date"; // public static String ETAG = "ETag"; // public static String HOST = "Host"; // public static String LAST_MODIFIED = "Last-Modified"; // public static String LOCATION = "Location"; // // // a-amz // public static String X_AMZ_ACL = "x-amz-acl"; // // } // // Path: src/main/java/de/jeha/s3srv/common/security/Credentials.java // public class Credentials { // // private final static String ACCESS_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // private final static int ACCESS_KEY_LENGTH = 20; // // private final static String SECRET_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // private final static String SECRET_KEY_CHARS_WITH_SPECIAL_CHARS = SECRET_KEY_CHARS + "/+"; // private final static int SECRET_KEY_LENGTH = 40; // // private final String accessKey; // private final String secretKey; // // public Credentials(String accessKey, String secretKey) { // this.accessKey = accessKey; // this.secretKey = secretKey; // } // // public String getAccessKey() { // return accessKey; // } // // public String getSecretKey() { // return secretKey; // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @return randomly generated credentials // */ // public static Credentials generateRandom() { // return generateRandom(true); // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @param includeSpecialChars include special chars ('/' and '+') for secret keys // * @return randomly generated credentials // */ // public static Credentials generateRandom(boolean includeSpecialChars) { // String accessKey = RandomStringUtils.random(ACCESS_KEY_LENGTH, ACCESS_KEY_CHARS); // String secretKey = RandomStringUtils.random( // SECRET_KEY_LENGTH, // includeSpecialChars ? SECRET_KEY_CHARS_WITH_SPECIAL_CHARS : SECRET_KEY_CHARS // ); // // return new Credentials(accessKey, secretKey); // } // // public void print() { // System.out.println(); // System.out.println("accessKey: " + accessKey); // System.out.println("secretKey: " + secretKey); // System.out.println(); // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3User.java // public class S3User { // // private final String id; // private final String displayName; // private final Credentials credentials; // // public S3User(String id, String displayName, Credentials credentials) { // this.id = id; // this.displayName = displayName; // this.credentials = credentials; // } // // public String getId() { // return id; // } // // public String getDisplayName() { // return displayName; // } // // public Credentials getCredentials() { // return credentials; // } // // } // // Path: src/main/java/de/jeha/s3srv/storage/StorageBackend.java // public interface StorageBackend extends HealthAware { // // List<S3Bucket> listBuckets(); // // void createBucket(S3User user, String bucket); // // boolean doesBucketExist(String bucket); // // S3Bucket getBucket(String bucket); // // void deleteBucket(String bucket); // // S3Object createObject(String bucket, String key, InputStream contentStream, int contentLength, // String expectedMD5, String contentType) // throws IOException, BadDigestException; // // boolean doesObjectExist(String bucket, String key); // // List<S3Object> listObjects(String bucket, int max); // // S3Object getObject(String bucket, String key); // // void deleteObject(String bucket, String key); // // /** // * @todo maybe separate storage backends for data and account data // */ // S3User getUserByAccessId(String accessKey); // // }
import de.jeha.s3srv.common.http.Headers; import de.jeha.s3srv.common.security.Credentials; import de.jeha.s3srv.model.S3User; import de.jeha.s3srv.storage.StorageBackend; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.Response; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
package de.jeha.s3srv.operations.buckets; /** * @author jenshadlich@googlemail.com */ public class CreateBucketTest { @Test public void test() { final HttpServletRequest mockedRequest = Mockito.mock(HttpServletRequest.class); when(mockedRequest.getHeader(Headers.AUTHORIZATION)).thenReturn("AWS foo:4AvYjPkzjOQWie8IKBTRSuUayPI="); when(mockedRequest.getHeader(Headers.DATE)).thenReturn("Wed, 06 Jul 2016 15:53:17 GMT"); when(mockedRequest.getMethod()).thenReturn("MOCK");
// Path: src/main/java/de/jeha/s3srv/common/http/Headers.java // public class Headers { // // public static String AUTHORIZATION = "Authorization"; // public static String CONNECTION = "Connection"; // public static String CONTENT_MD5 = "Content-MD5"; // public static String CONTENT_LENGTH = "Content-Length"; // public static String CONTENT_TYPE = "Content-Type"; // public static String DATE = "Date"; // public static String ETAG = "ETag"; // public static String HOST = "Host"; // public static String LAST_MODIFIED = "Last-Modified"; // public static String LOCATION = "Location"; // // // a-amz // public static String X_AMZ_ACL = "x-amz-acl"; // // } // // Path: src/main/java/de/jeha/s3srv/common/security/Credentials.java // public class Credentials { // // private final static String ACCESS_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // private final static int ACCESS_KEY_LENGTH = 20; // // private final static String SECRET_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // private final static String SECRET_KEY_CHARS_WITH_SPECIAL_CHARS = SECRET_KEY_CHARS + "/+"; // private final static int SECRET_KEY_LENGTH = 40; // // private final String accessKey; // private final String secretKey; // // public Credentials(String accessKey, String secretKey) { // this.accessKey = accessKey; // this.secretKey = secretKey; // } // // public String getAccessKey() { // return accessKey; // } // // public String getSecretKey() { // return secretKey; // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @return randomly generated credentials // */ // public static Credentials generateRandom() { // return generateRandom(true); // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @param includeSpecialChars include special chars ('/' and '+') for secret keys // * @return randomly generated credentials // */ // public static Credentials generateRandom(boolean includeSpecialChars) { // String accessKey = RandomStringUtils.random(ACCESS_KEY_LENGTH, ACCESS_KEY_CHARS); // String secretKey = RandomStringUtils.random( // SECRET_KEY_LENGTH, // includeSpecialChars ? SECRET_KEY_CHARS_WITH_SPECIAL_CHARS : SECRET_KEY_CHARS // ); // // return new Credentials(accessKey, secretKey); // } // // public void print() { // System.out.println(); // System.out.println("accessKey: " + accessKey); // System.out.println("secretKey: " + secretKey); // System.out.println(); // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3User.java // public class S3User { // // private final String id; // private final String displayName; // private final Credentials credentials; // // public S3User(String id, String displayName, Credentials credentials) { // this.id = id; // this.displayName = displayName; // this.credentials = credentials; // } // // public String getId() { // return id; // } // // public String getDisplayName() { // return displayName; // } // // public Credentials getCredentials() { // return credentials; // } // // } // // Path: src/main/java/de/jeha/s3srv/storage/StorageBackend.java // public interface StorageBackend extends HealthAware { // // List<S3Bucket> listBuckets(); // // void createBucket(S3User user, String bucket); // // boolean doesBucketExist(String bucket); // // S3Bucket getBucket(String bucket); // // void deleteBucket(String bucket); // // S3Object createObject(String bucket, String key, InputStream contentStream, int contentLength, // String expectedMD5, String contentType) // throws IOException, BadDigestException; // // boolean doesObjectExist(String bucket, String key); // // List<S3Object> listObjects(String bucket, int max); // // S3Object getObject(String bucket, String key); // // void deleteObject(String bucket, String key); // // /** // * @todo maybe separate storage backends for data and account data // */ // S3User getUserByAccessId(String accessKey); // // } // Path: src/test/java/de/jeha/s3srv/operations/buckets/CreateBucketTest.java import de.jeha.s3srv.common.http.Headers; import de.jeha.s3srv.common.security.Credentials; import de.jeha.s3srv.model.S3User; import de.jeha.s3srv.storage.StorageBackend; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.Response; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; package de.jeha.s3srv.operations.buckets; /** * @author jenshadlich@googlemail.com */ public class CreateBucketTest { @Test public void test() { final HttpServletRequest mockedRequest = Mockito.mock(HttpServletRequest.class); when(mockedRequest.getHeader(Headers.AUTHORIZATION)).thenReturn("AWS foo:4AvYjPkzjOQWie8IKBTRSuUayPI="); when(mockedRequest.getHeader(Headers.DATE)).thenReturn("Wed, 06 Jul 2016 15:53:17 GMT"); when(mockedRequest.getMethod()).thenReturn("MOCK");
final S3User s3user = new S3User("1", "foo", new Credentials("foo", "bar"));
jenshadlich/s3srv
src/test/java/de/jeha/s3srv/operations/buckets/CreateBucketTest.java
// Path: src/main/java/de/jeha/s3srv/common/http/Headers.java // public class Headers { // // public static String AUTHORIZATION = "Authorization"; // public static String CONNECTION = "Connection"; // public static String CONTENT_MD5 = "Content-MD5"; // public static String CONTENT_LENGTH = "Content-Length"; // public static String CONTENT_TYPE = "Content-Type"; // public static String DATE = "Date"; // public static String ETAG = "ETag"; // public static String HOST = "Host"; // public static String LAST_MODIFIED = "Last-Modified"; // public static String LOCATION = "Location"; // // // a-amz // public static String X_AMZ_ACL = "x-amz-acl"; // // } // // Path: src/main/java/de/jeha/s3srv/common/security/Credentials.java // public class Credentials { // // private final static String ACCESS_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // private final static int ACCESS_KEY_LENGTH = 20; // // private final static String SECRET_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // private final static String SECRET_KEY_CHARS_WITH_SPECIAL_CHARS = SECRET_KEY_CHARS + "/+"; // private final static int SECRET_KEY_LENGTH = 40; // // private final String accessKey; // private final String secretKey; // // public Credentials(String accessKey, String secretKey) { // this.accessKey = accessKey; // this.secretKey = secretKey; // } // // public String getAccessKey() { // return accessKey; // } // // public String getSecretKey() { // return secretKey; // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @return randomly generated credentials // */ // public static Credentials generateRandom() { // return generateRandom(true); // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @param includeSpecialChars include special chars ('/' and '+') for secret keys // * @return randomly generated credentials // */ // public static Credentials generateRandom(boolean includeSpecialChars) { // String accessKey = RandomStringUtils.random(ACCESS_KEY_LENGTH, ACCESS_KEY_CHARS); // String secretKey = RandomStringUtils.random( // SECRET_KEY_LENGTH, // includeSpecialChars ? SECRET_KEY_CHARS_WITH_SPECIAL_CHARS : SECRET_KEY_CHARS // ); // // return new Credentials(accessKey, secretKey); // } // // public void print() { // System.out.println(); // System.out.println("accessKey: " + accessKey); // System.out.println("secretKey: " + secretKey); // System.out.println(); // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3User.java // public class S3User { // // private final String id; // private final String displayName; // private final Credentials credentials; // // public S3User(String id, String displayName, Credentials credentials) { // this.id = id; // this.displayName = displayName; // this.credentials = credentials; // } // // public String getId() { // return id; // } // // public String getDisplayName() { // return displayName; // } // // public Credentials getCredentials() { // return credentials; // } // // } // // Path: src/main/java/de/jeha/s3srv/storage/StorageBackend.java // public interface StorageBackend extends HealthAware { // // List<S3Bucket> listBuckets(); // // void createBucket(S3User user, String bucket); // // boolean doesBucketExist(String bucket); // // S3Bucket getBucket(String bucket); // // void deleteBucket(String bucket); // // S3Object createObject(String bucket, String key, InputStream contentStream, int contentLength, // String expectedMD5, String contentType) // throws IOException, BadDigestException; // // boolean doesObjectExist(String bucket, String key); // // List<S3Object> listObjects(String bucket, int max); // // S3Object getObject(String bucket, String key); // // void deleteObject(String bucket, String key); // // /** // * @todo maybe separate storage backends for data and account data // */ // S3User getUserByAccessId(String accessKey); // // }
import de.jeha.s3srv.common.http.Headers; import de.jeha.s3srv.common.security.Credentials; import de.jeha.s3srv.model.S3User; import de.jeha.s3srv.storage.StorageBackend; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.Response; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
package de.jeha.s3srv.operations.buckets; /** * @author jenshadlich@googlemail.com */ public class CreateBucketTest { @Test public void test() { final HttpServletRequest mockedRequest = Mockito.mock(HttpServletRequest.class); when(mockedRequest.getHeader(Headers.AUTHORIZATION)).thenReturn("AWS foo:4AvYjPkzjOQWie8IKBTRSuUayPI="); when(mockedRequest.getHeader(Headers.DATE)).thenReturn("Wed, 06 Jul 2016 15:53:17 GMT"); when(mockedRequest.getMethod()).thenReturn("MOCK");
// Path: src/main/java/de/jeha/s3srv/common/http/Headers.java // public class Headers { // // public static String AUTHORIZATION = "Authorization"; // public static String CONNECTION = "Connection"; // public static String CONTENT_MD5 = "Content-MD5"; // public static String CONTENT_LENGTH = "Content-Length"; // public static String CONTENT_TYPE = "Content-Type"; // public static String DATE = "Date"; // public static String ETAG = "ETag"; // public static String HOST = "Host"; // public static String LAST_MODIFIED = "Last-Modified"; // public static String LOCATION = "Location"; // // // a-amz // public static String X_AMZ_ACL = "x-amz-acl"; // // } // // Path: src/main/java/de/jeha/s3srv/common/security/Credentials.java // public class Credentials { // // private final static String ACCESS_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // private final static int ACCESS_KEY_LENGTH = 20; // // private final static String SECRET_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // private final static String SECRET_KEY_CHARS_WITH_SPECIAL_CHARS = SECRET_KEY_CHARS + "/+"; // private final static int SECRET_KEY_LENGTH = 40; // // private final String accessKey; // private final String secretKey; // // public Credentials(String accessKey, String secretKey) { // this.accessKey = accessKey; // this.secretKey = secretKey; // } // // public String getAccessKey() { // return accessKey; // } // // public String getSecretKey() { // return secretKey; // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @return randomly generated credentials // */ // public static Credentials generateRandom() { // return generateRandom(true); // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @param includeSpecialChars include special chars ('/' and '+') for secret keys // * @return randomly generated credentials // */ // public static Credentials generateRandom(boolean includeSpecialChars) { // String accessKey = RandomStringUtils.random(ACCESS_KEY_LENGTH, ACCESS_KEY_CHARS); // String secretKey = RandomStringUtils.random( // SECRET_KEY_LENGTH, // includeSpecialChars ? SECRET_KEY_CHARS_WITH_SPECIAL_CHARS : SECRET_KEY_CHARS // ); // // return new Credentials(accessKey, secretKey); // } // // public void print() { // System.out.println(); // System.out.println("accessKey: " + accessKey); // System.out.println("secretKey: " + secretKey); // System.out.println(); // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3User.java // public class S3User { // // private final String id; // private final String displayName; // private final Credentials credentials; // // public S3User(String id, String displayName, Credentials credentials) { // this.id = id; // this.displayName = displayName; // this.credentials = credentials; // } // // public String getId() { // return id; // } // // public String getDisplayName() { // return displayName; // } // // public Credentials getCredentials() { // return credentials; // } // // } // // Path: src/main/java/de/jeha/s3srv/storage/StorageBackend.java // public interface StorageBackend extends HealthAware { // // List<S3Bucket> listBuckets(); // // void createBucket(S3User user, String bucket); // // boolean doesBucketExist(String bucket); // // S3Bucket getBucket(String bucket); // // void deleteBucket(String bucket); // // S3Object createObject(String bucket, String key, InputStream contentStream, int contentLength, // String expectedMD5, String contentType) // throws IOException, BadDigestException; // // boolean doesObjectExist(String bucket, String key); // // List<S3Object> listObjects(String bucket, int max); // // S3Object getObject(String bucket, String key); // // void deleteObject(String bucket, String key); // // /** // * @todo maybe separate storage backends for data and account data // */ // S3User getUserByAccessId(String accessKey); // // } // Path: src/test/java/de/jeha/s3srv/operations/buckets/CreateBucketTest.java import de.jeha.s3srv.common.http.Headers; import de.jeha.s3srv.common.security.Credentials; import de.jeha.s3srv.model.S3User; import de.jeha.s3srv.storage.StorageBackend; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.Response; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; package de.jeha.s3srv.operations.buckets; /** * @author jenshadlich@googlemail.com */ public class CreateBucketTest { @Test public void test() { final HttpServletRequest mockedRequest = Mockito.mock(HttpServletRequest.class); when(mockedRequest.getHeader(Headers.AUTHORIZATION)).thenReturn("AWS foo:4AvYjPkzjOQWie8IKBTRSuUayPI="); when(mockedRequest.getHeader(Headers.DATE)).thenReturn("Wed, 06 Jul 2016 15:53:17 GMT"); when(mockedRequest.getMethod()).thenReturn("MOCK");
final S3User s3user = new S3User("1", "foo", new Credentials("foo", "bar"));
jenshadlich/s3srv
src/test/java/de/jeha/s3srv/operations/buckets/CreateBucketTest.java
// Path: src/main/java/de/jeha/s3srv/common/http/Headers.java // public class Headers { // // public static String AUTHORIZATION = "Authorization"; // public static String CONNECTION = "Connection"; // public static String CONTENT_MD5 = "Content-MD5"; // public static String CONTENT_LENGTH = "Content-Length"; // public static String CONTENT_TYPE = "Content-Type"; // public static String DATE = "Date"; // public static String ETAG = "ETag"; // public static String HOST = "Host"; // public static String LAST_MODIFIED = "Last-Modified"; // public static String LOCATION = "Location"; // // // a-amz // public static String X_AMZ_ACL = "x-amz-acl"; // // } // // Path: src/main/java/de/jeha/s3srv/common/security/Credentials.java // public class Credentials { // // private final static String ACCESS_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // private final static int ACCESS_KEY_LENGTH = 20; // // private final static String SECRET_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // private final static String SECRET_KEY_CHARS_WITH_SPECIAL_CHARS = SECRET_KEY_CHARS + "/+"; // private final static int SECRET_KEY_LENGTH = 40; // // private final String accessKey; // private final String secretKey; // // public Credentials(String accessKey, String secretKey) { // this.accessKey = accessKey; // this.secretKey = secretKey; // } // // public String getAccessKey() { // return accessKey; // } // // public String getSecretKey() { // return secretKey; // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @return randomly generated credentials // */ // public static Credentials generateRandom() { // return generateRandom(true); // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @param includeSpecialChars include special chars ('/' and '+') for secret keys // * @return randomly generated credentials // */ // public static Credentials generateRandom(boolean includeSpecialChars) { // String accessKey = RandomStringUtils.random(ACCESS_KEY_LENGTH, ACCESS_KEY_CHARS); // String secretKey = RandomStringUtils.random( // SECRET_KEY_LENGTH, // includeSpecialChars ? SECRET_KEY_CHARS_WITH_SPECIAL_CHARS : SECRET_KEY_CHARS // ); // // return new Credentials(accessKey, secretKey); // } // // public void print() { // System.out.println(); // System.out.println("accessKey: " + accessKey); // System.out.println("secretKey: " + secretKey); // System.out.println(); // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3User.java // public class S3User { // // private final String id; // private final String displayName; // private final Credentials credentials; // // public S3User(String id, String displayName, Credentials credentials) { // this.id = id; // this.displayName = displayName; // this.credentials = credentials; // } // // public String getId() { // return id; // } // // public String getDisplayName() { // return displayName; // } // // public Credentials getCredentials() { // return credentials; // } // // } // // Path: src/main/java/de/jeha/s3srv/storage/StorageBackend.java // public interface StorageBackend extends HealthAware { // // List<S3Bucket> listBuckets(); // // void createBucket(S3User user, String bucket); // // boolean doesBucketExist(String bucket); // // S3Bucket getBucket(String bucket); // // void deleteBucket(String bucket); // // S3Object createObject(String bucket, String key, InputStream contentStream, int contentLength, // String expectedMD5, String contentType) // throws IOException, BadDigestException; // // boolean doesObjectExist(String bucket, String key); // // List<S3Object> listObjects(String bucket, int max); // // S3Object getObject(String bucket, String key); // // void deleteObject(String bucket, String key); // // /** // * @todo maybe separate storage backends for data and account data // */ // S3User getUserByAccessId(String accessKey); // // }
import de.jeha.s3srv.common.http.Headers; import de.jeha.s3srv.common.security.Credentials; import de.jeha.s3srv.model.S3User; import de.jeha.s3srv.storage.StorageBackend; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.Response; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
package de.jeha.s3srv.operations.buckets; /** * @author jenshadlich@googlemail.com */ public class CreateBucketTest { @Test public void test() { final HttpServletRequest mockedRequest = Mockito.mock(HttpServletRequest.class); when(mockedRequest.getHeader(Headers.AUTHORIZATION)).thenReturn("AWS foo:4AvYjPkzjOQWie8IKBTRSuUayPI="); when(mockedRequest.getHeader(Headers.DATE)).thenReturn("Wed, 06 Jul 2016 15:53:17 GMT"); when(mockedRequest.getMethod()).thenReturn("MOCK"); final S3User s3user = new S3User("1", "foo", new Credentials("foo", "bar"));
// Path: src/main/java/de/jeha/s3srv/common/http/Headers.java // public class Headers { // // public static String AUTHORIZATION = "Authorization"; // public static String CONNECTION = "Connection"; // public static String CONTENT_MD5 = "Content-MD5"; // public static String CONTENT_LENGTH = "Content-Length"; // public static String CONTENT_TYPE = "Content-Type"; // public static String DATE = "Date"; // public static String ETAG = "ETag"; // public static String HOST = "Host"; // public static String LAST_MODIFIED = "Last-Modified"; // public static String LOCATION = "Location"; // // // a-amz // public static String X_AMZ_ACL = "x-amz-acl"; // // } // // Path: src/main/java/de/jeha/s3srv/common/security/Credentials.java // public class Credentials { // // private final static String ACCESS_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // private final static int ACCESS_KEY_LENGTH = 20; // // private final static String SECRET_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // private final static String SECRET_KEY_CHARS_WITH_SPECIAL_CHARS = SECRET_KEY_CHARS + "/+"; // private final static int SECRET_KEY_LENGTH = 40; // // private final String accessKey; // private final String secretKey; // // public Credentials(String accessKey, String secretKey) { // this.accessKey = accessKey; // this.secretKey = secretKey; // } // // public String getAccessKey() { // return accessKey; // } // // public String getSecretKey() { // return secretKey; // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @return randomly generated credentials // */ // public static Credentials generateRandom() { // return generateRandom(true); // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @param includeSpecialChars include special chars ('/' and '+') for secret keys // * @return randomly generated credentials // */ // public static Credentials generateRandom(boolean includeSpecialChars) { // String accessKey = RandomStringUtils.random(ACCESS_KEY_LENGTH, ACCESS_KEY_CHARS); // String secretKey = RandomStringUtils.random( // SECRET_KEY_LENGTH, // includeSpecialChars ? SECRET_KEY_CHARS_WITH_SPECIAL_CHARS : SECRET_KEY_CHARS // ); // // return new Credentials(accessKey, secretKey); // } // // public void print() { // System.out.println(); // System.out.println("accessKey: " + accessKey); // System.out.println("secretKey: " + secretKey); // System.out.println(); // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3User.java // public class S3User { // // private final String id; // private final String displayName; // private final Credentials credentials; // // public S3User(String id, String displayName, Credentials credentials) { // this.id = id; // this.displayName = displayName; // this.credentials = credentials; // } // // public String getId() { // return id; // } // // public String getDisplayName() { // return displayName; // } // // public Credentials getCredentials() { // return credentials; // } // // } // // Path: src/main/java/de/jeha/s3srv/storage/StorageBackend.java // public interface StorageBackend extends HealthAware { // // List<S3Bucket> listBuckets(); // // void createBucket(S3User user, String bucket); // // boolean doesBucketExist(String bucket); // // S3Bucket getBucket(String bucket); // // void deleteBucket(String bucket); // // S3Object createObject(String bucket, String key, InputStream contentStream, int contentLength, // String expectedMD5, String contentType) // throws IOException, BadDigestException; // // boolean doesObjectExist(String bucket, String key); // // List<S3Object> listObjects(String bucket, int max); // // S3Object getObject(String bucket, String key); // // void deleteObject(String bucket, String key); // // /** // * @todo maybe separate storage backends for data and account data // */ // S3User getUserByAccessId(String accessKey); // // } // Path: src/test/java/de/jeha/s3srv/operations/buckets/CreateBucketTest.java import de.jeha.s3srv.common.http.Headers; import de.jeha.s3srv.common.security.Credentials; import de.jeha.s3srv.model.S3User; import de.jeha.s3srv.storage.StorageBackend; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.Response; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; package de.jeha.s3srv.operations.buckets; /** * @author jenshadlich@googlemail.com */ public class CreateBucketTest { @Test public void test() { final HttpServletRequest mockedRequest = Mockito.mock(HttpServletRequest.class); when(mockedRequest.getHeader(Headers.AUTHORIZATION)).thenReturn("AWS foo:4AvYjPkzjOQWie8IKBTRSuUayPI="); when(mockedRequest.getHeader(Headers.DATE)).thenReturn("Wed, 06 Jul 2016 15:53:17 GMT"); when(mockedRequest.getMethod()).thenReturn("MOCK"); final S3User s3user = new S3User("1", "foo", new Credentials("foo", "bar"));
final StorageBackend mockedStorageBackend = Mockito.mock(StorageBackend.class);
jenshadlich/s3srv
src/main/java/de/jeha/s3srv/api/ListAllMyBucketsResult.java
// Path: src/main/java/de/jeha/s3srv/xml/InstantXmlAdapter.java // public class InstantXmlAdapter extends XmlAdapter<String, Instant> { // // private final DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT; // // @Override // public Instant unmarshal(String value) throws Exception { // return value != null ? formatter.parse(value, Instant::from) : null; // } // // @Override // public String marshal(Instant value) throws Exception { // return value != null ? formatter.format(value) : null; // } // // }
import de.jeha.s3srv.xml.InstantXmlAdapter; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.time.Instant; import java.util.ArrayList; import java.util.List;
package de.jeha.s3srv.api; /** * @author jenshadlich@googlemail.com */ @XmlRootElement(name = "ListAllMyBucketsResult") public class ListAllMyBucketsResult { @XmlElement(name = "Owner") private Owner owner; @XmlElementWrapper(name = "Buckets") @XmlElement(name = "Bucket") private List<BucketsEntry> buckets = new ArrayList<>(); public ListAllMyBucketsResult() { } public ListAllMyBucketsResult(Owner owner, List<BucketsEntry> entries) { this.owner = owner; buckets.addAll(entries); } public Owner getOwner() { return owner; } public List<BucketsEntry> getBuckets() { return buckets; } public static class BucketsEntry { @XmlElement(name = "Name") private String name;
// Path: src/main/java/de/jeha/s3srv/xml/InstantXmlAdapter.java // public class InstantXmlAdapter extends XmlAdapter<String, Instant> { // // private final DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT; // // @Override // public Instant unmarshal(String value) throws Exception { // return value != null ? formatter.parse(value, Instant::from) : null; // } // // @Override // public String marshal(Instant value) throws Exception { // return value != null ? formatter.format(value) : null; // } // // } // Path: src/main/java/de/jeha/s3srv/api/ListAllMyBucketsResult.java import de.jeha.s3srv.xml.InstantXmlAdapter; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.time.Instant; import java.util.ArrayList; import java.util.List; package de.jeha.s3srv.api; /** * @author jenshadlich@googlemail.com */ @XmlRootElement(name = "ListAllMyBucketsResult") public class ListAllMyBucketsResult { @XmlElement(name = "Owner") private Owner owner; @XmlElementWrapper(name = "Buckets") @XmlElement(name = "Bucket") private List<BucketsEntry> buckets = new ArrayList<>(); public ListAllMyBucketsResult() { } public ListAllMyBucketsResult(Owner owner, List<BucketsEntry> entries) { this.owner = owner; buckets.addAll(entries); } public Owner getOwner() { return owner; } public List<BucketsEntry> getBuckets() { return buckets; } public static class BucketsEntry { @XmlElement(name = "Name") private String name;
@XmlJavaTypeAdapter(InstantXmlAdapter.class)
jenshadlich/s3srv
src/main/java/de/jeha/s3srv/storage/StorageBackend.java
// Path: src/main/java/de/jeha/s3srv/common/errors/BadDigestException.java // public class BadDigestException extends Exception { // // public BadDigestException(String message) { // super(message); // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3Bucket.java // public class S3Bucket { // // private final S3User owner; // private final String name; // private final Instant creationDate; // // public S3Bucket(S3User owner, String name) { // this.owner = owner; // this.name = name; // this.creationDate = Instant.now(); // } // // public S3User getOwner() { // return owner; // } // // public String getName() { // return name; // } // // public Instant getCreationDate() { // return creationDate; // } // // public boolean isOwnedBy(S3User user) { // return owner.getId().equals(user.getId()); // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3Object.java // public class S3Object { // // private final S3Bucket bucket; // private final String key; // private final String md5; // private final String eTag; // private final Integer size; // private final Instant lastModified; // private final InputStreamCallback inputStreamCallback; // private final String contentType; // // public S3Object(S3Bucket bucket, String key, String md5, String eTag, Integer size, Instant lastModified, // InputStreamCallback inputStreamCallback, String contentType) { // this.bucket = bucket; // this.key = key; // this.md5 = md5; // this.eTag = eTag; // this.size = size; // this.lastModified = lastModified; // this.inputStreamCallback = inputStreamCallback; // this.contentType = contentType; // } // // public S3Bucket getBucket() { // return bucket; // } // // public String getKey() { // return key; // } // // public String getMD5() { // return md5; // } // // public String getETag() { // return eTag; // } // // public Integer getSize() { // return size; // } // // public Instant getLastModified() { // return lastModified; // } // // public InputStream getInputStream() { // return inputStreamCallback.getInputStream(); // } // // public String getContentType() { // return contentType; // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3User.java // public class S3User { // // private final String id; // private final String displayName; // private final Credentials credentials; // // public S3User(String id, String displayName, Credentials credentials) { // this.id = id; // this.displayName = displayName; // this.credentials = credentials; // } // // public String getId() { // return id; // } // // public String getDisplayName() { // return displayName; // } // // public Credentials getCredentials() { // return credentials; // } // // }
import de.jeha.s3srv.common.errors.BadDigestException; import de.jeha.s3srv.model.S3Bucket; import de.jeha.s3srv.model.S3Object; import de.jeha.s3srv.model.S3User; import java.io.IOException; import java.io.InputStream; import java.util.List;
package de.jeha.s3srv.storage; /** * @author jenshadlich@googlemail.com */ public interface StorageBackend extends HealthAware { List<S3Bucket> listBuckets();
// Path: src/main/java/de/jeha/s3srv/common/errors/BadDigestException.java // public class BadDigestException extends Exception { // // public BadDigestException(String message) { // super(message); // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3Bucket.java // public class S3Bucket { // // private final S3User owner; // private final String name; // private final Instant creationDate; // // public S3Bucket(S3User owner, String name) { // this.owner = owner; // this.name = name; // this.creationDate = Instant.now(); // } // // public S3User getOwner() { // return owner; // } // // public String getName() { // return name; // } // // public Instant getCreationDate() { // return creationDate; // } // // public boolean isOwnedBy(S3User user) { // return owner.getId().equals(user.getId()); // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3Object.java // public class S3Object { // // private final S3Bucket bucket; // private final String key; // private final String md5; // private final String eTag; // private final Integer size; // private final Instant lastModified; // private final InputStreamCallback inputStreamCallback; // private final String contentType; // // public S3Object(S3Bucket bucket, String key, String md5, String eTag, Integer size, Instant lastModified, // InputStreamCallback inputStreamCallback, String contentType) { // this.bucket = bucket; // this.key = key; // this.md5 = md5; // this.eTag = eTag; // this.size = size; // this.lastModified = lastModified; // this.inputStreamCallback = inputStreamCallback; // this.contentType = contentType; // } // // public S3Bucket getBucket() { // return bucket; // } // // public String getKey() { // return key; // } // // public String getMD5() { // return md5; // } // // public String getETag() { // return eTag; // } // // public Integer getSize() { // return size; // } // // public Instant getLastModified() { // return lastModified; // } // // public InputStream getInputStream() { // return inputStreamCallback.getInputStream(); // } // // public String getContentType() { // return contentType; // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3User.java // public class S3User { // // private final String id; // private final String displayName; // private final Credentials credentials; // // public S3User(String id, String displayName, Credentials credentials) { // this.id = id; // this.displayName = displayName; // this.credentials = credentials; // } // // public String getId() { // return id; // } // // public String getDisplayName() { // return displayName; // } // // public Credentials getCredentials() { // return credentials; // } // // } // Path: src/main/java/de/jeha/s3srv/storage/StorageBackend.java import de.jeha.s3srv.common.errors.BadDigestException; import de.jeha.s3srv.model.S3Bucket; import de.jeha.s3srv.model.S3Object; import de.jeha.s3srv.model.S3User; import java.io.IOException; import java.io.InputStream; import java.util.List; package de.jeha.s3srv.storage; /** * @author jenshadlich@googlemail.com */ public interface StorageBackend extends HealthAware { List<S3Bucket> listBuckets();
void createBucket(S3User user, String bucket);
jenshadlich/s3srv
src/main/java/de/jeha/s3srv/storage/StorageBackend.java
// Path: src/main/java/de/jeha/s3srv/common/errors/BadDigestException.java // public class BadDigestException extends Exception { // // public BadDigestException(String message) { // super(message); // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3Bucket.java // public class S3Bucket { // // private final S3User owner; // private final String name; // private final Instant creationDate; // // public S3Bucket(S3User owner, String name) { // this.owner = owner; // this.name = name; // this.creationDate = Instant.now(); // } // // public S3User getOwner() { // return owner; // } // // public String getName() { // return name; // } // // public Instant getCreationDate() { // return creationDate; // } // // public boolean isOwnedBy(S3User user) { // return owner.getId().equals(user.getId()); // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3Object.java // public class S3Object { // // private final S3Bucket bucket; // private final String key; // private final String md5; // private final String eTag; // private final Integer size; // private final Instant lastModified; // private final InputStreamCallback inputStreamCallback; // private final String contentType; // // public S3Object(S3Bucket bucket, String key, String md5, String eTag, Integer size, Instant lastModified, // InputStreamCallback inputStreamCallback, String contentType) { // this.bucket = bucket; // this.key = key; // this.md5 = md5; // this.eTag = eTag; // this.size = size; // this.lastModified = lastModified; // this.inputStreamCallback = inputStreamCallback; // this.contentType = contentType; // } // // public S3Bucket getBucket() { // return bucket; // } // // public String getKey() { // return key; // } // // public String getMD5() { // return md5; // } // // public String getETag() { // return eTag; // } // // public Integer getSize() { // return size; // } // // public Instant getLastModified() { // return lastModified; // } // // public InputStream getInputStream() { // return inputStreamCallback.getInputStream(); // } // // public String getContentType() { // return contentType; // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3User.java // public class S3User { // // private final String id; // private final String displayName; // private final Credentials credentials; // // public S3User(String id, String displayName, Credentials credentials) { // this.id = id; // this.displayName = displayName; // this.credentials = credentials; // } // // public String getId() { // return id; // } // // public String getDisplayName() { // return displayName; // } // // public Credentials getCredentials() { // return credentials; // } // // }
import de.jeha.s3srv.common.errors.BadDigestException; import de.jeha.s3srv.model.S3Bucket; import de.jeha.s3srv.model.S3Object; import de.jeha.s3srv.model.S3User; import java.io.IOException; import java.io.InputStream; import java.util.List;
package de.jeha.s3srv.storage; /** * @author jenshadlich@googlemail.com */ public interface StorageBackend extends HealthAware { List<S3Bucket> listBuckets(); void createBucket(S3User user, String bucket); boolean doesBucketExist(String bucket); S3Bucket getBucket(String bucket); void deleteBucket(String bucket);
// Path: src/main/java/de/jeha/s3srv/common/errors/BadDigestException.java // public class BadDigestException extends Exception { // // public BadDigestException(String message) { // super(message); // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3Bucket.java // public class S3Bucket { // // private final S3User owner; // private final String name; // private final Instant creationDate; // // public S3Bucket(S3User owner, String name) { // this.owner = owner; // this.name = name; // this.creationDate = Instant.now(); // } // // public S3User getOwner() { // return owner; // } // // public String getName() { // return name; // } // // public Instant getCreationDate() { // return creationDate; // } // // public boolean isOwnedBy(S3User user) { // return owner.getId().equals(user.getId()); // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3Object.java // public class S3Object { // // private final S3Bucket bucket; // private final String key; // private final String md5; // private final String eTag; // private final Integer size; // private final Instant lastModified; // private final InputStreamCallback inputStreamCallback; // private final String contentType; // // public S3Object(S3Bucket bucket, String key, String md5, String eTag, Integer size, Instant lastModified, // InputStreamCallback inputStreamCallback, String contentType) { // this.bucket = bucket; // this.key = key; // this.md5 = md5; // this.eTag = eTag; // this.size = size; // this.lastModified = lastModified; // this.inputStreamCallback = inputStreamCallback; // this.contentType = contentType; // } // // public S3Bucket getBucket() { // return bucket; // } // // public String getKey() { // return key; // } // // public String getMD5() { // return md5; // } // // public String getETag() { // return eTag; // } // // public Integer getSize() { // return size; // } // // public Instant getLastModified() { // return lastModified; // } // // public InputStream getInputStream() { // return inputStreamCallback.getInputStream(); // } // // public String getContentType() { // return contentType; // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3User.java // public class S3User { // // private final String id; // private final String displayName; // private final Credentials credentials; // // public S3User(String id, String displayName, Credentials credentials) { // this.id = id; // this.displayName = displayName; // this.credentials = credentials; // } // // public String getId() { // return id; // } // // public String getDisplayName() { // return displayName; // } // // public Credentials getCredentials() { // return credentials; // } // // } // Path: src/main/java/de/jeha/s3srv/storage/StorageBackend.java import de.jeha.s3srv.common.errors.BadDigestException; import de.jeha.s3srv.model.S3Bucket; import de.jeha.s3srv.model.S3Object; import de.jeha.s3srv.model.S3User; import java.io.IOException; import java.io.InputStream; import java.util.List; package de.jeha.s3srv.storage; /** * @author jenshadlich@googlemail.com */ public interface StorageBackend extends HealthAware { List<S3Bucket> listBuckets(); void createBucket(S3User user, String bucket); boolean doesBucketExist(String bucket); S3Bucket getBucket(String bucket); void deleteBucket(String bucket);
S3Object createObject(String bucket, String key, InputStream contentStream, int contentLength,
jenshadlich/s3srv
src/main/java/de/jeha/s3srv/storage/StorageBackend.java
// Path: src/main/java/de/jeha/s3srv/common/errors/BadDigestException.java // public class BadDigestException extends Exception { // // public BadDigestException(String message) { // super(message); // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3Bucket.java // public class S3Bucket { // // private final S3User owner; // private final String name; // private final Instant creationDate; // // public S3Bucket(S3User owner, String name) { // this.owner = owner; // this.name = name; // this.creationDate = Instant.now(); // } // // public S3User getOwner() { // return owner; // } // // public String getName() { // return name; // } // // public Instant getCreationDate() { // return creationDate; // } // // public boolean isOwnedBy(S3User user) { // return owner.getId().equals(user.getId()); // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3Object.java // public class S3Object { // // private final S3Bucket bucket; // private final String key; // private final String md5; // private final String eTag; // private final Integer size; // private final Instant lastModified; // private final InputStreamCallback inputStreamCallback; // private final String contentType; // // public S3Object(S3Bucket bucket, String key, String md5, String eTag, Integer size, Instant lastModified, // InputStreamCallback inputStreamCallback, String contentType) { // this.bucket = bucket; // this.key = key; // this.md5 = md5; // this.eTag = eTag; // this.size = size; // this.lastModified = lastModified; // this.inputStreamCallback = inputStreamCallback; // this.contentType = contentType; // } // // public S3Bucket getBucket() { // return bucket; // } // // public String getKey() { // return key; // } // // public String getMD5() { // return md5; // } // // public String getETag() { // return eTag; // } // // public Integer getSize() { // return size; // } // // public Instant getLastModified() { // return lastModified; // } // // public InputStream getInputStream() { // return inputStreamCallback.getInputStream(); // } // // public String getContentType() { // return contentType; // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3User.java // public class S3User { // // private final String id; // private final String displayName; // private final Credentials credentials; // // public S3User(String id, String displayName, Credentials credentials) { // this.id = id; // this.displayName = displayName; // this.credentials = credentials; // } // // public String getId() { // return id; // } // // public String getDisplayName() { // return displayName; // } // // public Credentials getCredentials() { // return credentials; // } // // }
import de.jeha.s3srv.common.errors.BadDigestException; import de.jeha.s3srv.model.S3Bucket; import de.jeha.s3srv.model.S3Object; import de.jeha.s3srv.model.S3User; import java.io.IOException; import java.io.InputStream; import java.util.List;
package de.jeha.s3srv.storage; /** * @author jenshadlich@googlemail.com */ public interface StorageBackend extends HealthAware { List<S3Bucket> listBuckets(); void createBucket(S3User user, String bucket); boolean doesBucketExist(String bucket); S3Bucket getBucket(String bucket); void deleteBucket(String bucket); S3Object createObject(String bucket, String key, InputStream contentStream, int contentLength, String expectedMD5, String contentType)
// Path: src/main/java/de/jeha/s3srv/common/errors/BadDigestException.java // public class BadDigestException extends Exception { // // public BadDigestException(String message) { // super(message); // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3Bucket.java // public class S3Bucket { // // private final S3User owner; // private final String name; // private final Instant creationDate; // // public S3Bucket(S3User owner, String name) { // this.owner = owner; // this.name = name; // this.creationDate = Instant.now(); // } // // public S3User getOwner() { // return owner; // } // // public String getName() { // return name; // } // // public Instant getCreationDate() { // return creationDate; // } // // public boolean isOwnedBy(S3User user) { // return owner.getId().equals(user.getId()); // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3Object.java // public class S3Object { // // private final S3Bucket bucket; // private final String key; // private final String md5; // private final String eTag; // private final Integer size; // private final Instant lastModified; // private final InputStreamCallback inputStreamCallback; // private final String contentType; // // public S3Object(S3Bucket bucket, String key, String md5, String eTag, Integer size, Instant lastModified, // InputStreamCallback inputStreamCallback, String contentType) { // this.bucket = bucket; // this.key = key; // this.md5 = md5; // this.eTag = eTag; // this.size = size; // this.lastModified = lastModified; // this.inputStreamCallback = inputStreamCallback; // this.contentType = contentType; // } // // public S3Bucket getBucket() { // return bucket; // } // // public String getKey() { // return key; // } // // public String getMD5() { // return md5; // } // // public String getETag() { // return eTag; // } // // public Integer getSize() { // return size; // } // // public Instant getLastModified() { // return lastModified; // } // // public InputStream getInputStream() { // return inputStreamCallback.getInputStream(); // } // // public String getContentType() { // return contentType; // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3User.java // public class S3User { // // private final String id; // private final String displayName; // private final Credentials credentials; // // public S3User(String id, String displayName, Credentials credentials) { // this.id = id; // this.displayName = displayName; // this.credentials = credentials; // } // // public String getId() { // return id; // } // // public String getDisplayName() { // return displayName; // } // // public Credentials getCredentials() { // return credentials; // } // // } // Path: src/main/java/de/jeha/s3srv/storage/StorageBackend.java import de.jeha.s3srv.common.errors.BadDigestException; import de.jeha.s3srv.model.S3Bucket; import de.jeha.s3srv.model.S3Object; import de.jeha.s3srv.model.S3User; import java.io.IOException; import java.io.InputStream; import java.util.List; package de.jeha.s3srv.storage; /** * @author jenshadlich@googlemail.com */ public interface StorageBackend extends HealthAware { List<S3Bucket> listBuckets(); void createBucket(S3User user, String bucket); boolean doesBucketExist(String bucket); S3Bucket getBucket(String bucket); void deleteBucket(String bucket); S3Object createObject(String bucket, String key, InputStream contentStream, int contentLength, String expectedMD5, String contentType)
throws IOException, BadDigestException;
jenshadlich/s3srv
src/main/java/de/jeha/s3srv/common/s3/RequestContext.java
// Path: src/main/java/de/jeha/s3srv/common/http/Headers.java // public class Headers { // // public static String AUTHORIZATION = "Authorization"; // public static String CONNECTION = "Connection"; // public static String CONTENT_MD5 = "Content-MD5"; // public static String CONTENT_LENGTH = "Content-Length"; // public static String CONTENT_TYPE = "Content-Type"; // public static String DATE = "Date"; // public static String ETAG = "ETag"; // public static String HOST = "Host"; // public static String LAST_MODIFIED = "Last-Modified"; // public static String LOCATION = "Location"; // // // a-amz // public static String X_AMZ_ACL = "x-amz-acl"; // // }
import de.jeha.s3srv.common.http.Headers; import org.apache.commons.lang3.StringUtils; import javax.servlet.http.HttpServletRequest;
package de.jeha.s3srv.common.s3; /** * @author jenshadlich@googlemail.com */ public class RequestContext { private final boolean pathStyle; private final String bucket; private final String key; private RequestContext(boolean pathStyle, String bucket, String key) { this.pathStyle = pathStyle; this.bucket = bucket; this.key = key; } public static RequestContext build(HttpServletRequest request) { final String requestUri = request.getRequestURI();
// Path: src/main/java/de/jeha/s3srv/common/http/Headers.java // public class Headers { // // public static String AUTHORIZATION = "Authorization"; // public static String CONNECTION = "Connection"; // public static String CONTENT_MD5 = "Content-MD5"; // public static String CONTENT_LENGTH = "Content-Length"; // public static String CONTENT_TYPE = "Content-Type"; // public static String DATE = "Date"; // public static String ETAG = "ETag"; // public static String HOST = "Host"; // public static String LAST_MODIFIED = "Last-Modified"; // public static String LOCATION = "Location"; // // // a-amz // public static String X_AMZ_ACL = "x-amz-acl"; // // } // Path: src/main/java/de/jeha/s3srv/common/s3/RequestContext.java import de.jeha.s3srv.common.http.Headers; import org.apache.commons.lang3.StringUtils; import javax.servlet.http.HttpServletRequest; package de.jeha.s3srv.common.s3; /** * @author jenshadlich@googlemail.com */ public class RequestContext { private final boolean pathStyle; private final String bucket; private final String key; private RequestContext(boolean pathStyle, String bucket, String key) { this.pathStyle = pathStyle; this.bucket = bucket; this.key = key; } public static RequestContext build(HttpServletRequest request) { final String requestUri = request.getRequestURI();
final String hostHeader = request.getHeader(Headers.HOST);
jenshadlich/s3srv
src/main/java/de/jeha/s3srv/config/StorageBackendFactory.java
// Path: src/main/java/de/jeha/s3srv/common/security/Credentials.java // public class Credentials { // // private final static String ACCESS_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // private final static int ACCESS_KEY_LENGTH = 20; // // private final static String SECRET_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // private final static String SECRET_KEY_CHARS_WITH_SPECIAL_CHARS = SECRET_KEY_CHARS + "/+"; // private final static int SECRET_KEY_LENGTH = 40; // // private final String accessKey; // private final String secretKey; // // public Credentials(String accessKey, String secretKey) { // this.accessKey = accessKey; // this.secretKey = secretKey; // } // // public String getAccessKey() { // return accessKey; // } // // public String getSecretKey() { // return secretKey; // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @return randomly generated credentials // */ // public static Credentials generateRandom() { // return generateRandom(true); // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @param includeSpecialChars include special chars ('/' and '+') for secret keys // * @return randomly generated credentials // */ // public static Credentials generateRandom(boolean includeSpecialChars) { // String accessKey = RandomStringUtils.random(ACCESS_KEY_LENGTH, ACCESS_KEY_CHARS); // String secretKey = RandomStringUtils.random( // SECRET_KEY_LENGTH, // includeSpecialChars ? SECRET_KEY_CHARS_WITH_SPECIAL_CHARS : SECRET_KEY_CHARS // ); // // return new Credentials(accessKey, secretKey); // } // // public void print() { // System.out.println(); // System.out.println("accessKey: " + accessKey); // System.out.println("secretKey: " + secretKey); // System.out.println(); // } // // } // // Path: src/main/java/de/jeha/s3srv/storage/StorageBackend.java // public interface StorageBackend extends HealthAware { // // List<S3Bucket> listBuckets(); // // void createBucket(S3User user, String bucket); // // boolean doesBucketExist(String bucket); // // S3Bucket getBucket(String bucket); // // void deleteBucket(String bucket); // // S3Object createObject(String bucket, String key, InputStream contentStream, int contentLength, // String expectedMD5, String contentType) // throws IOException, BadDigestException; // // boolean doesObjectExist(String bucket, String key); // // List<S3Object> listObjects(String bucket, int max); // // S3Object getObject(String bucket, String key); // // void deleteObject(String bucket, String key); // // /** // * @todo maybe separate storage backends for data and account data // */ // S3User getUserByAccessId(String accessKey); // // }
import com.fasterxml.jackson.annotation.JsonTypeInfo; import de.jeha.s3srv.common.security.Credentials; import de.jeha.s3srv.storage.StorageBackend; import io.dropwizard.jackson.Discoverable;
package de.jeha.s3srv.config; /** * @author jenshadlich@googlemail.com */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") public interface StorageBackendFactory extends Discoverable {
// Path: src/main/java/de/jeha/s3srv/common/security/Credentials.java // public class Credentials { // // private final static String ACCESS_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // private final static int ACCESS_KEY_LENGTH = 20; // // private final static String SECRET_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // private final static String SECRET_KEY_CHARS_WITH_SPECIAL_CHARS = SECRET_KEY_CHARS + "/+"; // private final static int SECRET_KEY_LENGTH = 40; // // private final String accessKey; // private final String secretKey; // // public Credentials(String accessKey, String secretKey) { // this.accessKey = accessKey; // this.secretKey = secretKey; // } // // public String getAccessKey() { // return accessKey; // } // // public String getSecretKey() { // return secretKey; // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @return randomly generated credentials // */ // public static Credentials generateRandom() { // return generateRandom(true); // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @param includeSpecialChars include special chars ('/' and '+') for secret keys // * @return randomly generated credentials // */ // public static Credentials generateRandom(boolean includeSpecialChars) { // String accessKey = RandomStringUtils.random(ACCESS_KEY_LENGTH, ACCESS_KEY_CHARS); // String secretKey = RandomStringUtils.random( // SECRET_KEY_LENGTH, // includeSpecialChars ? SECRET_KEY_CHARS_WITH_SPECIAL_CHARS : SECRET_KEY_CHARS // ); // // return new Credentials(accessKey, secretKey); // } // // public void print() { // System.out.println(); // System.out.println("accessKey: " + accessKey); // System.out.println("secretKey: " + secretKey); // System.out.println(); // } // // } // // Path: src/main/java/de/jeha/s3srv/storage/StorageBackend.java // public interface StorageBackend extends HealthAware { // // List<S3Bucket> listBuckets(); // // void createBucket(S3User user, String bucket); // // boolean doesBucketExist(String bucket); // // S3Bucket getBucket(String bucket); // // void deleteBucket(String bucket); // // S3Object createObject(String bucket, String key, InputStream contentStream, int contentLength, // String expectedMD5, String contentType) // throws IOException, BadDigestException; // // boolean doesObjectExist(String bucket, String key); // // List<S3Object> listObjects(String bucket, int max); // // S3Object getObject(String bucket, String key); // // void deleteObject(String bucket, String key); // // /** // * @todo maybe separate storage backends for data and account data // */ // S3User getUserByAccessId(String accessKey); // // } // Path: src/main/java/de/jeha/s3srv/config/StorageBackendFactory.java import com.fasterxml.jackson.annotation.JsonTypeInfo; import de.jeha.s3srv.common.security.Credentials; import de.jeha.s3srv.storage.StorageBackend; import io.dropwizard.jackson.Discoverable; package de.jeha.s3srv.config; /** * @author jenshadlich@googlemail.com */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") public interface StorageBackendFactory extends Discoverable {
StorageBackend build(Credentials credentials);
jenshadlich/s3srv
src/main/java/de/jeha/s3srv/config/StorageBackendFactory.java
// Path: src/main/java/de/jeha/s3srv/common/security/Credentials.java // public class Credentials { // // private final static String ACCESS_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // private final static int ACCESS_KEY_LENGTH = 20; // // private final static String SECRET_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // private final static String SECRET_KEY_CHARS_WITH_SPECIAL_CHARS = SECRET_KEY_CHARS + "/+"; // private final static int SECRET_KEY_LENGTH = 40; // // private final String accessKey; // private final String secretKey; // // public Credentials(String accessKey, String secretKey) { // this.accessKey = accessKey; // this.secretKey = secretKey; // } // // public String getAccessKey() { // return accessKey; // } // // public String getSecretKey() { // return secretKey; // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @return randomly generated credentials // */ // public static Credentials generateRandom() { // return generateRandom(true); // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @param includeSpecialChars include special chars ('/' and '+') for secret keys // * @return randomly generated credentials // */ // public static Credentials generateRandom(boolean includeSpecialChars) { // String accessKey = RandomStringUtils.random(ACCESS_KEY_LENGTH, ACCESS_KEY_CHARS); // String secretKey = RandomStringUtils.random( // SECRET_KEY_LENGTH, // includeSpecialChars ? SECRET_KEY_CHARS_WITH_SPECIAL_CHARS : SECRET_KEY_CHARS // ); // // return new Credentials(accessKey, secretKey); // } // // public void print() { // System.out.println(); // System.out.println("accessKey: " + accessKey); // System.out.println("secretKey: " + secretKey); // System.out.println(); // } // // } // // Path: src/main/java/de/jeha/s3srv/storage/StorageBackend.java // public interface StorageBackend extends HealthAware { // // List<S3Bucket> listBuckets(); // // void createBucket(S3User user, String bucket); // // boolean doesBucketExist(String bucket); // // S3Bucket getBucket(String bucket); // // void deleteBucket(String bucket); // // S3Object createObject(String bucket, String key, InputStream contentStream, int contentLength, // String expectedMD5, String contentType) // throws IOException, BadDigestException; // // boolean doesObjectExist(String bucket, String key); // // List<S3Object> listObjects(String bucket, int max); // // S3Object getObject(String bucket, String key); // // void deleteObject(String bucket, String key); // // /** // * @todo maybe separate storage backends for data and account data // */ // S3User getUserByAccessId(String accessKey); // // }
import com.fasterxml.jackson.annotation.JsonTypeInfo; import de.jeha.s3srv.common.security.Credentials; import de.jeha.s3srv.storage.StorageBackend; import io.dropwizard.jackson.Discoverable;
package de.jeha.s3srv.config; /** * @author jenshadlich@googlemail.com */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") public interface StorageBackendFactory extends Discoverable {
// Path: src/main/java/de/jeha/s3srv/common/security/Credentials.java // public class Credentials { // // private final static String ACCESS_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // private final static int ACCESS_KEY_LENGTH = 20; // // private final static String SECRET_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // private final static String SECRET_KEY_CHARS_WITH_SPECIAL_CHARS = SECRET_KEY_CHARS + "/+"; // private final static int SECRET_KEY_LENGTH = 40; // // private final String accessKey; // private final String secretKey; // // public Credentials(String accessKey, String secretKey) { // this.accessKey = accessKey; // this.secretKey = secretKey; // } // // public String getAccessKey() { // return accessKey; // } // // public String getSecretKey() { // return secretKey; // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @return randomly generated credentials // */ // public static Credentials generateRandom() { // return generateRandom(true); // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @param includeSpecialChars include special chars ('/' and '+') for secret keys // * @return randomly generated credentials // */ // public static Credentials generateRandom(boolean includeSpecialChars) { // String accessKey = RandomStringUtils.random(ACCESS_KEY_LENGTH, ACCESS_KEY_CHARS); // String secretKey = RandomStringUtils.random( // SECRET_KEY_LENGTH, // includeSpecialChars ? SECRET_KEY_CHARS_WITH_SPECIAL_CHARS : SECRET_KEY_CHARS // ); // // return new Credentials(accessKey, secretKey); // } // // public void print() { // System.out.println(); // System.out.println("accessKey: " + accessKey); // System.out.println("secretKey: " + secretKey); // System.out.println(); // } // // } // // Path: src/main/java/de/jeha/s3srv/storage/StorageBackend.java // public interface StorageBackend extends HealthAware { // // List<S3Bucket> listBuckets(); // // void createBucket(S3User user, String bucket); // // boolean doesBucketExist(String bucket); // // S3Bucket getBucket(String bucket); // // void deleteBucket(String bucket); // // S3Object createObject(String bucket, String key, InputStream contentStream, int contentLength, // String expectedMD5, String contentType) // throws IOException, BadDigestException; // // boolean doesObjectExist(String bucket, String key); // // List<S3Object> listObjects(String bucket, int max); // // S3Object getObject(String bucket, String key); // // void deleteObject(String bucket, String key); // // /** // * @todo maybe separate storage backends for data and account data // */ // S3User getUserByAccessId(String accessKey); // // } // Path: src/main/java/de/jeha/s3srv/config/StorageBackendFactory.java import com.fasterxml.jackson.annotation.JsonTypeInfo; import de.jeha.s3srv.common.security.Credentials; import de.jeha.s3srv.storage.StorageBackend; import io.dropwizard.jackson.Discoverable; package de.jeha.s3srv.config; /** * @author jenshadlich@googlemail.com */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") public interface StorageBackendFactory extends Discoverable {
StorageBackend build(Credentials credentials);
jenshadlich/s3srv
src/test/java/de/jeha/s3srv/storage/backends/InMemoryStorageBackendTest.java
// Path: src/main/java/de/jeha/s3srv/common/errors/BadDigestException.java // public class BadDigestException extends Exception { // // public BadDigestException(String message) { // super(message); // } // // } // // Path: src/main/java/de/jeha/s3srv/common/security/Credentials.java // public class Credentials { // // private final static String ACCESS_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // private final static int ACCESS_KEY_LENGTH = 20; // // private final static String SECRET_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // private final static String SECRET_KEY_CHARS_WITH_SPECIAL_CHARS = SECRET_KEY_CHARS + "/+"; // private final static int SECRET_KEY_LENGTH = 40; // // private final String accessKey; // private final String secretKey; // // public Credentials(String accessKey, String secretKey) { // this.accessKey = accessKey; // this.secretKey = secretKey; // } // // public String getAccessKey() { // return accessKey; // } // // public String getSecretKey() { // return secretKey; // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @return randomly generated credentials // */ // public static Credentials generateRandom() { // return generateRandom(true); // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @param includeSpecialChars include special chars ('/' and '+') for secret keys // * @return randomly generated credentials // */ // public static Credentials generateRandom(boolean includeSpecialChars) { // String accessKey = RandomStringUtils.random(ACCESS_KEY_LENGTH, ACCESS_KEY_CHARS); // String secretKey = RandomStringUtils.random( // SECRET_KEY_LENGTH, // includeSpecialChars ? SECRET_KEY_CHARS_WITH_SPECIAL_CHARS : SECRET_KEY_CHARS // ); // // return new Credentials(accessKey, secretKey); // } // // public void print() { // System.out.println(); // System.out.println("accessKey: " + accessKey); // System.out.println("secretKey: " + secretKey); // System.out.println(); // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3Object.java // public class S3Object { // // private final S3Bucket bucket; // private final String key; // private final String md5; // private final String eTag; // private final Integer size; // private final Instant lastModified; // private final InputStreamCallback inputStreamCallback; // private final String contentType; // // public S3Object(S3Bucket bucket, String key, String md5, String eTag, Integer size, Instant lastModified, // InputStreamCallback inputStreamCallback, String contentType) { // this.bucket = bucket; // this.key = key; // this.md5 = md5; // this.eTag = eTag; // this.size = size; // this.lastModified = lastModified; // this.inputStreamCallback = inputStreamCallback; // this.contentType = contentType; // } // // public S3Bucket getBucket() { // return bucket; // } // // public String getKey() { // return key; // } // // public String getMD5() { // return md5; // } // // public String getETag() { // return eTag; // } // // public Integer getSize() { // return size; // } // // public Instant getLastModified() { // return lastModified; // } // // public InputStream getInputStream() { // return inputStreamCallback.getInputStream(); // } // // public String getContentType() { // return contentType; // } // // } // // Path: src/main/java/de/jeha/s3srv/storage/StorageBackend.java // public interface StorageBackend extends HealthAware { // // List<S3Bucket> listBuckets(); // // void createBucket(S3User user, String bucket); // // boolean doesBucketExist(String bucket); // // S3Bucket getBucket(String bucket); // // void deleteBucket(String bucket); // // S3Object createObject(String bucket, String key, InputStream contentStream, int contentLength, // String expectedMD5, String contentType) // throws IOException, BadDigestException; // // boolean doesObjectExist(String bucket, String key); // // List<S3Object> listObjects(String bucket, int max); // // S3Object getObject(String bucket, String key); // // void deleteObject(String bucket, String key); // // /** // * @todo maybe separate storage backends for data and account data // */ // S3User getUserByAccessId(String accessKey); // // }
import de.jeha.s3srv.common.errors.BadDigestException; import de.jeha.s3srv.common.security.Credentials; import de.jeha.s3srv.model.S3Object; import de.jeha.s3srv.storage.StorageBackend; import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull;
package de.jeha.s3srv.storage.backends; /** * @author jenshadlich@googlemail.com */ public class InMemoryStorageBackendTest { @Test
// Path: src/main/java/de/jeha/s3srv/common/errors/BadDigestException.java // public class BadDigestException extends Exception { // // public BadDigestException(String message) { // super(message); // } // // } // // Path: src/main/java/de/jeha/s3srv/common/security/Credentials.java // public class Credentials { // // private final static String ACCESS_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // private final static int ACCESS_KEY_LENGTH = 20; // // private final static String SECRET_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // private final static String SECRET_KEY_CHARS_WITH_SPECIAL_CHARS = SECRET_KEY_CHARS + "/+"; // private final static int SECRET_KEY_LENGTH = 40; // // private final String accessKey; // private final String secretKey; // // public Credentials(String accessKey, String secretKey) { // this.accessKey = accessKey; // this.secretKey = secretKey; // } // // public String getAccessKey() { // return accessKey; // } // // public String getSecretKey() { // return secretKey; // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @return randomly generated credentials // */ // public static Credentials generateRandom() { // return generateRandom(true); // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @param includeSpecialChars include special chars ('/' and '+') for secret keys // * @return randomly generated credentials // */ // public static Credentials generateRandom(boolean includeSpecialChars) { // String accessKey = RandomStringUtils.random(ACCESS_KEY_LENGTH, ACCESS_KEY_CHARS); // String secretKey = RandomStringUtils.random( // SECRET_KEY_LENGTH, // includeSpecialChars ? SECRET_KEY_CHARS_WITH_SPECIAL_CHARS : SECRET_KEY_CHARS // ); // // return new Credentials(accessKey, secretKey); // } // // public void print() { // System.out.println(); // System.out.println("accessKey: " + accessKey); // System.out.println("secretKey: " + secretKey); // System.out.println(); // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3Object.java // public class S3Object { // // private final S3Bucket bucket; // private final String key; // private final String md5; // private final String eTag; // private final Integer size; // private final Instant lastModified; // private final InputStreamCallback inputStreamCallback; // private final String contentType; // // public S3Object(S3Bucket bucket, String key, String md5, String eTag, Integer size, Instant lastModified, // InputStreamCallback inputStreamCallback, String contentType) { // this.bucket = bucket; // this.key = key; // this.md5 = md5; // this.eTag = eTag; // this.size = size; // this.lastModified = lastModified; // this.inputStreamCallback = inputStreamCallback; // this.contentType = contentType; // } // // public S3Bucket getBucket() { // return bucket; // } // // public String getKey() { // return key; // } // // public String getMD5() { // return md5; // } // // public String getETag() { // return eTag; // } // // public Integer getSize() { // return size; // } // // public Instant getLastModified() { // return lastModified; // } // // public InputStream getInputStream() { // return inputStreamCallback.getInputStream(); // } // // public String getContentType() { // return contentType; // } // // } // // Path: src/main/java/de/jeha/s3srv/storage/StorageBackend.java // public interface StorageBackend extends HealthAware { // // List<S3Bucket> listBuckets(); // // void createBucket(S3User user, String bucket); // // boolean doesBucketExist(String bucket); // // S3Bucket getBucket(String bucket); // // void deleteBucket(String bucket); // // S3Object createObject(String bucket, String key, InputStream contentStream, int contentLength, // String expectedMD5, String contentType) // throws IOException, BadDigestException; // // boolean doesObjectExist(String bucket, String key); // // List<S3Object> listObjects(String bucket, int max); // // S3Object getObject(String bucket, String key); // // void deleteObject(String bucket, String key); // // /** // * @todo maybe separate storage backends for data and account data // */ // S3User getUserByAccessId(String accessKey); // // } // Path: src/test/java/de/jeha/s3srv/storage/backends/InMemoryStorageBackendTest.java import de.jeha.s3srv.common.errors.BadDigestException; import de.jeha.s3srv.common.security.Credentials; import de.jeha.s3srv.model.S3Object; import de.jeha.s3srv.storage.StorageBackend; import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; package de.jeha.s3srv.storage.backends; /** * @author jenshadlich@googlemail.com */ public class InMemoryStorageBackendTest { @Test
public void test() throws IOException, BadDigestException {
jenshadlich/s3srv
src/test/java/de/jeha/s3srv/storage/backends/InMemoryStorageBackendTest.java
// Path: src/main/java/de/jeha/s3srv/common/errors/BadDigestException.java // public class BadDigestException extends Exception { // // public BadDigestException(String message) { // super(message); // } // // } // // Path: src/main/java/de/jeha/s3srv/common/security/Credentials.java // public class Credentials { // // private final static String ACCESS_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // private final static int ACCESS_KEY_LENGTH = 20; // // private final static String SECRET_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // private final static String SECRET_KEY_CHARS_WITH_SPECIAL_CHARS = SECRET_KEY_CHARS + "/+"; // private final static int SECRET_KEY_LENGTH = 40; // // private final String accessKey; // private final String secretKey; // // public Credentials(String accessKey, String secretKey) { // this.accessKey = accessKey; // this.secretKey = secretKey; // } // // public String getAccessKey() { // return accessKey; // } // // public String getSecretKey() { // return secretKey; // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @return randomly generated credentials // */ // public static Credentials generateRandom() { // return generateRandom(true); // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @param includeSpecialChars include special chars ('/' and '+') for secret keys // * @return randomly generated credentials // */ // public static Credentials generateRandom(boolean includeSpecialChars) { // String accessKey = RandomStringUtils.random(ACCESS_KEY_LENGTH, ACCESS_KEY_CHARS); // String secretKey = RandomStringUtils.random( // SECRET_KEY_LENGTH, // includeSpecialChars ? SECRET_KEY_CHARS_WITH_SPECIAL_CHARS : SECRET_KEY_CHARS // ); // // return new Credentials(accessKey, secretKey); // } // // public void print() { // System.out.println(); // System.out.println("accessKey: " + accessKey); // System.out.println("secretKey: " + secretKey); // System.out.println(); // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3Object.java // public class S3Object { // // private final S3Bucket bucket; // private final String key; // private final String md5; // private final String eTag; // private final Integer size; // private final Instant lastModified; // private final InputStreamCallback inputStreamCallback; // private final String contentType; // // public S3Object(S3Bucket bucket, String key, String md5, String eTag, Integer size, Instant lastModified, // InputStreamCallback inputStreamCallback, String contentType) { // this.bucket = bucket; // this.key = key; // this.md5 = md5; // this.eTag = eTag; // this.size = size; // this.lastModified = lastModified; // this.inputStreamCallback = inputStreamCallback; // this.contentType = contentType; // } // // public S3Bucket getBucket() { // return bucket; // } // // public String getKey() { // return key; // } // // public String getMD5() { // return md5; // } // // public String getETag() { // return eTag; // } // // public Integer getSize() { // return size; // } // // public Instant getLastModified() { // return lastModified; // } // // public InputStream getInputStream() { // return inputStreamCallback.getInputStream(); // } // // public String getContentType() { // return contentType; // } // // } // // Path: src/main/java/de/jeha/s3srv/storage/StorageBackend.java // public interface StorageBackend extends HealthAware { // // List<S3Bucket> listBuckets(); // // void createBucket(S3User user, String bucket); // // boolean doesBucketExist(String bucket); // // S3Bucket getBucket(String bucket); // // void deleteBucket(String bucket); // // S3Object createObject(String bucket, String key, InputStream contentStream, int contentLength, // String expectedMD5, String contentType) // throws IOException, BadDigestException; // // boolean doesObjectExist(String bucket, String key); // // List<S3Object> listObjects(String bucket, int max); // // S3Object getObject(String bucket, String key); // // void deleteObject(String bucket, String key); // // /** // * @todo maybe separate storage backends for data and account data // */ // S3User getUserByAccessId(String accessKey); // // }
import de.jeha.s3srv.common.errors.BadDigestException; import de.jeha.s3srv.common.security.Credentials; import de.jeha.s3srv.model.S3Object; import de.jeha.s3srv.storage.StorageBackend; import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull;
package de.jeha.s3srv.storage.backends; /** * @author jenshadlich@googlemail.com */ public class InMemoryStorageBackendTest { @Test public void test() throws IOException, BadDigestException {
// Path: src/main/java/de/jeha/s3srv/common/errors/BadDigestException.java // public class BadDigestException extends Exception { // // public BadDigestException(String message) { // super(message); // } // // } // // Path: src/main/java/de/jeha/s3srv/common/security/Credentials.java // public class Credentials { // // private final static String ACCESS_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // private final static int ACCESS_KEY_LENGTH = 20; // // private final static String SECRET_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // private final static String SECRET_KEY_CHARS_WITH_SPECIAL_CHARS = SECRET_KEY_CHARS + "/+"; // private final static int SECRET_KEY_LENGTH = 40; // // private final String accessKey; // private final String secretKey; // // public Credentials(String accessKey, String secretKey) { // this.accessKey = accessKey; // this.secretKey = secretKey; // } // // public String getAccessKey() { // return accessKey; // } // // public String getSecretKey() { // return secretKey; // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @return randomly generated credentials // */ // public static Credentials generateRandom() { // return generateRandom(true); // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @param includeSpecialChars include special chars ('/' and '+') for secret keys // * @return randomly generated credentials // */ // public static Credentials generateRandom(boolean includeSpecialChars) { // String accessKey = RandomStringUtils.random(ACCESS_KEY_LENGTH, ACCESS_KEY_CHARS); // String secretKey = RandomStringUtils.random( // SECRET_KEY_LENGTH, // includeSpecialChars ? SECRET_KEY_CHARS_WITH_SPECIAL_CHARS : SECRET_KEY_CHARS // ); // // return new Credentials(accessKey, secretKey); // } // // public void print() { // System.out.println(); // System.out.println("accessKey: " + accessKey); // System.out.println("secretKey: " + secretKey); // System.out.println(); // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3Object.java // public class S3Object { // // private final S3Bucket bucket; // private final String key; // private final String md5; // private final String eTag; // private final Integer size; // private final Instant lastModified; // private final InputStreamCallback inputStreamCallback; // private final String contentType; // // public S3Object(S3Bucket bucket, String key, String md5, String eTag, Integer size, Instant lastModified, // InputStreamCallback inputStreamCallback, String contentType) { // this.bucket = bucket; // this.key = key; // this.md5 = md5; // this.eTag = eTag; // this.size = size; // this.lastModified = lastModified; // this.inputStreamCallback = inputStreamCallback; // this.contentType = contentType; // } // // public S3Bucket getBucket() { // return bucket; // } // // public String getKey() { // return key; // } // // public String getMD5() { // return md5; // } // // public String getETag() { // return eTag; // } // // public Integer getSize() { // return size; // } // // public Instant getLastModified() { // return lastModified; // } // // public InputStream getInputStream() { // return inputStreamCallback.getInputStream(); // } // // public String getContentType() { // return contentType; // } // // } // // Path: src/main/java/de/jeha/s3srv/storage/StorageBackend.java // public interface StorageBackend extends HealthAware { // // List<S3Bucket> listBuckets(); // // void createBucket(S3User user, String bucket); // // boolean doesBucketExist(String bucket); // // S3Bucket getBucket(String bucket); // // void deleteBucket(String bucket); // // S3Object createObject(String bucket, String key, InputStream contentStream, int contentLength, // String expectedMD5, String contentType) // throws IOException, BadDigestException; // // boolean doesObjectExist(String bucket, String key); // // List<S3Object> listObjects(String bucket, int max); // // S3Object getObject(String bucket, String key); // // void deleteObject(String bucket, String key); // // /** // * @todo maybe separate storage backends for data and account data // */ // S3User getUserByAccessId(String accessKey); // // } // Path: src/test/java/de/jeha/s3srv/storage/backends/InMemoryStorageBackendTest.java import de.jeha.s3srv.common.errors.BadDigestException; import de.jeha.s3srv.common.security.Credentials; import de.jeha.s3srv.model.S3Object; import de.jeha.s3srv.storage.StorageBackend; import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; package de.jeha.s3srv.storage.backends; /** * @author jenshadlich@googlemail.com */ public class InMemoryStorageBackendTest { @Test public void test() throws IOException, BadDigestException {
StorageBackend storageBackend = new InMemoryStorageBackend(new Credentials("foo", "bar"));
jenshadlich/s3srv
src/test/java/de/jeha/s3srv/storage/backends/InMemoryStorageBackendTest.java
// Path: src/main/java/de/jeha/s3srv/common/errors/BadDigestException.java // public class BadDigestException extends Exception { // // public BadDigestException(String message) { // super(message); // } // // } // // Path: src/main/java/de/jeha/s3srv/common/security/Credentials.java // public class Credentials { // // private final static String ACCESS_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // private final static int ACCESS_KEY_LENGTH = 20; // // private final static String SECRET_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // private final static String SECRET_KEY_CHARS_WITH_SPECIAL_CHARS = SECRET_KEY_CHARS + "/+"; // private final static int SECRET_KEY_LENGTH = 40; // // private final String accessKey; // private final String secretKey; // // public Credentials(String accessKey, String secretKey) { // this.accessKey = accessKey; // this.secretKey = secretKey; // } // // public String getAccessKey() { // return accessKey; // } // // public String getSecretKey() { // return secretKey; // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @return randomly generated credentials // */ // public static Credentials generateRandom() { // return generateRandom(true); // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @param includeSpecialChars include special chars ('/' and '+') for secret keys // * @return randomly generated credentials // */ // public static Credentials generateRandom(boolean includeSpecialChars) { // String accessKey = RandomStringUtils.random(ACCESS_KEY_LENGTH, ACCESS_KEY_CHARS); // String secretKey = RandomStringUtils.random( // SECRET_KEY_LENGTH, // includeSpecialChars ? SECRET_KEY_CHARS_WITH_SPECIAL_CHARS : SECRET_KEY_CHARS // ); // // return new Credentials(accessKey, secretKey); // } // // public void print() { // System.out.println(); // System.out.println("accessKey: " + accessKey); // System.out.println("secretKey: " + secretKey); // System.out.println(); // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3Object.java // public class S3Object { // // private final S3Bucket bucket; // private final String key; // private final String md5; // private final String eTag; // private final Integer size; // private final Instant lastModified; // private final InputStreamCallback inputStreamCallback; // private final String contentType; // // public S3Object(S3Bucket bucket, String key, String md5, String eTag, Integer size, Instant lastModified, // InputStreamCallback inputStreamCallback, String contentType) { // this.bucket = bucket; // this.key = key; // this.md5 = md5; // this.eTag = eTag; // this.size = size; // this.lastModified = lastModified; // this.inputStreamCallback = inputStreamCallback; // this.contentType = contentType; // } // // public S3Bucket getBucket() { // return bucket; // } // // public String getKey() { // return key; // } // // public String getMD5() { // return md5; // } // // public String getETag() { // return eTag; // } // // public Integer getSize() { // return size; // } // // public Instant getLastModified() { // return lastModified; // } // // public InputStream getInputStream() { // return inputStreamCallback.getInputStream(); // } // // public String getContentType() { // return contentType; // } // // } // // Path: src/main/java/de/jeha/s3srv/storage/StorageBackend.java // public interface StorageBackend extends HealthAware { // // List<S3Bucket> listBuckets(); // // void createBucket(S3User user, String bucket); // // boolean doesBucketExist(String bucket); // // S3Bucket getBucket(String bucket); // // void deleteBucket(String bucket); // // S3Object createObject(String bucket, String key, InputStream contentStream, int contentLength, // String expectedMD5, String contentType) // throws IOException, BadDigestException; // // boolean doesObjectExist(String bucket, String key); // // List<S3Object> listObjects(String bucket, int max); // // S3Object getObject(String bucket, String key); // // void deleteObject(String bucket, String key); // // /** // * @todo maybe separate storage backends for data and account data // */ // S3User getUserByAccessId(String accessKey); // // }
import de.jeha.s3srv.common.errors.BadDigestException; import de.jeha.s3srv.common.security.Credentials; import de.jeha.s3srv.model.S3Object; import de.jeha.s3srv.storage.StorageBackend; import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull;
package de.jeha.s3srv.storage.backends; /** * @author jenshadlich@googlemail.com */ public class InMemoryStorageBackendTest { @Test public void test() throws IOException, BadDigestException {
// Path: src/main/java/de/jeha/s3srv/common/errors/BadDigestException.java // public class BadDigestException extends Exception { // // public BadDigestException(String message) { // super(message); // } // // } // // Path: src/main/java/de/jeha/s3srv/common/security/Credentials.java // public class Credentials { // // private final static String ACCESS_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // private final static int ACCESS_KEY_LENGTH = 20; // // private final static String SECRET_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // private final static String SECRET_KEY_CHARS_WITH_SPECIAL_CHARS = SECRET_KEY_CHARS + "/+"; // private final static int SECRET_KEY_LENGTH = 40; // // private final String accessKey; // private final String secretKey; // // public Credentials(String accessKey, String secretKey) { // this.accessKey = accessKey; // this.secretKey = secretKey; // } // // public String getAccessKey() { // return accessKey; // } // // public String getSecretKey() { // return secretKey; // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @return randomly generated credentials // */ // public static Credentials generateRandom() { // return generateRandom(true); // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @param includeSpecialChars include special chars ('/' and '+') for secret keys // * @return randomly generated credentials // */ // public static Credentials generateRandom(boolean includeSpecialChars) { // String accessKey = RandomStringUtils.random(ACCESS_KEY_LENGTH, ACCESS_KEY_CHARS); // String secretKey = RandomStringUtils.random( // SECRET_KEY_LENGTH, // includeSpecialChars ? SECRET_KEY_CHARS_WITH_SPECIAL_CHARS : SECRET_KEY_CHARS // ); // // return new Credentials(accessKey, secretKey); // } // // public void print() { // System.out.println(); // System.out.println("accessKey: " + accessKey); // System.out.println("secretKey: " + secretKey); // System.out.println(); // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3Object.java // public class S3Object { // // private final S3Bucket bucket; // private final String key; // private final String md5; // private final String eTag; // private final Integer size; // private final Instant lastModified; // private final InputStreamCallback inputStreamCallback; // private final String contentType; // // public S3Object(S3Bucket bucket, String key, String md5, String eTag, Integer size, Instant lastModified, // InputStreamCallback inputStreamCallback, String contentType) { // this.bucket = bucket; // this.key = key; // this.md5 = md5; // this.eTag = eTag; // this.size = size; // this.lastModified = lastModified; // this.inputStreamCallback = inputStreamCallback; // this.contentType = contentType; // } // // public S3Bucket getBucket() { // return bucket; // } // // public String getKey() { // return key; // } // // public String getMD5() { // return md5; // } // // public String getETag() { // return eTag; // } // // public Integer getSize() { // return size; // } // // public Instant getLastModified() { // return lastModified; // } // // public InputStream getInputStream() { // return inputStreamCallback.getInputStream(); // } // // public String getContentType() { // return contentType; // } // // } // // Path: src/main/java/de/jeha/s3srv/storage/StorageBackend.java // public interface StorageBackend extends HealthAware { // // List<S3Bucket> listBuckets(); // // void createBucket(S3User user, String bucket); // // boolean doesBucketExist(String bucket); // // S3Bucket getBucket(String bucket); // // void deleteBucket(String bucket); // // S3Object createObject(String bucket, String key, InputStream contentStream, int contentLength, // String expectedMD5, String contentType) // throws IOException, BadDigestException; // // boolean doesObjectExist(String bucket, String key); // // List<S3Object> listObjects(String bucket, int max); // // S3Object getObject(String bucket, String key); // // void deleteObject(String bucket, String key); // // /** // * @todo maybe separate storage backends for data and account data // */ // S3User getUserByAccessId(String accessKey); // // } // Path: src/test/java/de/jeha/s3srv/storage/backends/InMemoryStorageBackendTest.java import de.jeha.s3srv.common.errors.BadDigestException; import de.jeha.s3srv.common.security.Credentials; import de.jeha.s3srv.model.S3Object; import de.jeha.s3srv.storage.StorageBackend; import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; package de.jeha.s3srv.storage.backends; /** * @author jenshadlich@googlemail.com */ public class InMemoryStorageBackendTest { @Test public void test() throws IOException, BadDigestException {
StorageBackend storageBackend = new InMemoryStorageBackend(new Credentials("foo", "bar"));
jenshadlich/s3srv
src/test/java/de/jeha/s3srv/storage/backends/InMemoryStorageBackendTest.java
// Path: src/main/java/de/jeha/s3srv/common/errors/BadDigestException.java // public class BadDigestException extends Exception { // // public BadDigestException(String message) { // super(message); // } // // } // // Path: src/main/java/de/jeha/s3srv/common/security/Credentials.java // public class Credentials { // // private final static String ACCESS_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // private final static int ACCESS_KEY_LENGTH = 20; // // private final static String SECRET_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // private final static String SECRET_KEY_CHARS_WITH_SPECIAL_CHARS = SECRET_KEY_CHARS + "/+"; // private final static int SECRET_KEY_LENGTH = 40; // // private final String accessKey; // private final String secretKey; // // public Credentials(String accessKey, String secretKey) { // this.accessKey = accessKey; // this.secretKey = secretKey; // } // // public String getAccessKey() { // return accessKey; // } // // public String getSecretKey() { // return secretKey; // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @return randomly generated credentials // */ // public static Credentials generateRandom() { // return generateRandom(true); // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @param includeSpecialChars include special chars ('/' and '+') for secret keys // * @return randomly generated credentials // */ // public static Credentials generateRandom(boolean includeSpecialChars) { // String accessKey = RandomStringUtils.random(ACCESS_KEY_LENGTH, ACCESS_KEY_CHARS); // String secretKey = RandomStringUtils.random( // SECRET_KEY_LENGTH, // includeSpecialChars ? SECRET_KEY_CHARS_WITH_SPECIAL_CHARS : SECRET_KEY_CHARS // ); // // return new Credentials(accessKey, secretKey); // } // // public void print() { // System.out.println(); // System.out.println("accessKey: " + accessKey); // System.out.println("secretKey: " + secretKey); // System.out.println(); // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3Object.java // public class S3Object { // // private final S3Bucket bucket; // private final String key; // private final String md5; // private final String eTag; // private final Integer size; // private final Instant lastModified; // private final InputStreamCallback inputStreamCallback; // private final String contentType; // // public S3Object(S3Bucket bucket, String key, String md5, String eTag, Integer size, Instant lastModified, // InputStreamCallback inputStreamCallback, String contentType) { // this.bucket = bucket; // this.key = key; // this.md5 = md5; // this.eTag = eTag; // this.size = size; // this.lastModified = lastModified; // this.inputStreamCallback = inputStreamCallback; // this.contentType = contentType; // } // // public S3Bucket getBucket() { // return bucket; // } // // public String getKey() { // return key; // } // // public String getMD5() { // return md5; // } // // public String getETag() { // return eTag; // } // // public Integer getSize() { // return size; // } // // public Instant getLastModified() { // return lastModified; // } // // public InputStream getInputStream() { // return inputStreamCallback.getInputStream(); // } // // public String getContentType() { // return contentType; // } // // } // // Path: src/main/java/de/jeha/s3srv/storage/StorageBackend.java // public interface StorageBackend extends HealthAware { // // List<S3Bucket> listBuckets(); // // void createBucket(S3User user, String bucket); // // boolean doesBucketExist(String bucket); // // S3Bucket getBucket(String bucket); // // void deleteBucket(String bucket); // // S3Object createObject(String bucket, String key, InputStream contentStream, int contentLength, // String expectedMD5, String contentType) // throws IOException, BadDigestException; // // boolean doesObjectExist(String bucket, String key); // // List<S3Object> listObjects(String bucket, int max); // // S3Object getObject(String bucket, String key); // // void deleteObject(String bucket, String key); // // /** // * @todo maybe separate storage backends for data and account data // */ // S3User getUserByAccessId(String accessKey); // // }
import de.jeha.s3srv.common.errors.BadDigestException; import de.jeha.s3srv.common.security.Credentials; import de.jeha.s3srv.model.S3Object; import de.jeha.s3srv.storage.StorageBackend; import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull;
package de.jeha.s3srv.storage.backends; /** * @author jenshadlich@googlemail.com */ public class InMemoryStorageBackendTest { @Test public void test() throws IOException, BadDigestException { StorageBackend storageBackend = new InMemoryStorageBackend(new Credentials("foo", "bar")); final String content = "content";
// Path: src/main/java/de/jeha/s3srv/common/errors/BadDigestException.java // public class BadDigestException extends Exception { // // public BadDigestException(String message) { // super(message); // } // // } // // Path: src/main/java/de/jeha/s3srv/common/security/Credentials.java // public class Credentials { // // private final static String ACCESS_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // private final static int ACCESS_KEY_LENGTH = 20; // // private final static String SECRET_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // private final static String SECRET_KEY_CHARS_WITH_SPECIAL_CHARS = SECRET_KEY_CHARS + "/+"; // private final static int SECRET_KEY_LENGTH = 40; // // private final String accessKey; // private final String secretKey; // // public Credentials(String accessKey, String secretKey) { // this.accessKey = accessKey; // this.secretKey = secretKey; // } // // public String getAccessKey() { // return accessKey; // } // // public String getSecretKey() { // return secretKey; // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @return randomly generated credentials // */ // public static Credentials generateRandom() { // return generateRandom(true); // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @param includeSpecialChars include special chars ('/' and '+') for secret keys // * @return randomly generated credentials // */ // public static Credentials generateRandom(boolean includeSpecialChars) { // String accessKey = RandomStringUtils.random(ACCESS_KEY_LENGTH, ACCESS_KEY_CHARS); // String secretKey = RandomStringUtils.random( // SECRET_KEY_LENGTH, // includeSpecialChars ? SECRET_KEY_CHARS_WITH_SPECIAL_CHARS : SECRET_KEY_CHARS // ); // // return new Credentials(accessKey, secretKey); // } // // public void print() { // System.out.println(); // System.out.println("accessKey: " + accessKey); // System.out.println("secretKey: " + secretKey); // System.out.println(); // } // // } // // Path: src/main/java/de/jeha/s3srv/model/S3Object.java // public class S3Object { // // private final S3Bucket bucket; // private final String key; // private final String md5; // private final String eTag; // private final Integer size; // private final Instant lastModified; // private final InputStreamCallback inputStreamCallback; // private final String contentType; // // public S3Object(S3Bucket bucket, String key, String md5, String eTag, Integer size, Instant lastModified, // InputStreamCallback inputStreamCallback, String contentType) { // this.bucket = bucket; // this.key = key; // this.md5 = md5; // this.eTag = eTag; // this.size = size; // this.lastModified = lastModified; // this.inputStreamCallback = inputStreamCallback; // this.contentType = contentType; // } // // public S3Bucket getBucket() { // return bucket; // } // // public String getKey() { // return key; // } // // public String getMD5() { // return md5; // } // // public String getETag() { // return eTag; // } // // public Integer getSize() { // return size; // } // // public Instant getLastModified() { // return lastModified; // } // // public InputStream getInputStream() { // return inputStreamCallback.getInputStream(); // } // // public String getContentType() { // return contentType; // } // // } // // Path: src/main/java/de/jeha/s3srv/storage/StorageBackend.java // public interface StorageBackend extends HealthAware { // // List<S3Bucket> listBuckets(); // // void createBucket(S3User user, String bucket); // // boolean doesBucketExist(String bucket); // // S3Bucket getBucket(String bucket); // // void deleteBucket(String bucket); // // S3Object createObject(String bucket, String key, InputStream contentStream, int contentLength, // String expectedMD5, String contentType) // throws IOException, BadDigestException; // // boolean doesObjectExist(String bucket, String key); // // List<S3Object> listObjects(String bucket, int max); // // S3Object getObject(String bucket, String key); // // void deleteObject(String bucket, String key); // // /** // * @todo maybe separate storage backends for data and account data // */ // S3User getUserByAccessId(String accessKey); // // } // Path: src/test/java/de/jeha/s3srv/storage/backends/InMemoryStorageBackendTest.java import de.jeha.s3srv.common.errors.BadDigestException; import de.jeha.s3srv.common.security.Credentials; import de.jeha.s3srv.model.S3Object; import de.jeha.s3srv.storage.StorageBackend; import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; package de.jeha.s3srv.storage.backends; /** * @author jenshadlich@googlemail.com */ public class InMemoryStorageBackendTest { @Test public void test() throws IOException, BadDigestException { StorageBackend storageBackend = new InMemoryStorageBackend(new Credentials("foo", "bar")); final String content = "content";
final S3Object object = storageBackend.createObject(
jenshadlich/s3srv
src/test/java/de/jeha/s3srv/api/ListBucketResultSerializationTest.java
// Path: src/main/java/de/jeha/s3srv/xml/JaxbMarshaller.java // public class JaxbMarshaller { // // private static Marshaller MARSHALLER = null; // private static Unmarshaller UNMARSHALLER = null; // // static { // try { // MARSHALLER = JaxbContextHolder.getContext().createMarshaller(); // MARSHALLER.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // MARSHALLER.setProperty(Marshaller.JAXB_FRAGMENT, true); // } catch (JAXBException e) { // throw new RuntimeException("Unable to initialize JAXB Marshaller", e); // } // try { // UNMARSHALLER = JaxbContextHolder.getContext().createUnmarshaller(); // } catch (JAXBException e) { // throw new RuntimeException("Unable to initialize JAXB Unmarshaller", e); // } // } // // public synchronized static String marshall(Object object) throws JAXBException, IOException { // StringWriter stringWriter = new StringWriter(); // stringWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); // stringWriter.append("\n"); // // MARSHALLER.marshal(object, stringWriter); // stringWriter.close(); // // return stringWriter.toString(); // } // // public synchronized static <T> T unmarshall(String xml, Class<T> clazz) throws JAXBException, IOException { // return UNMARSHALLER.unmarshal(new StreamSource(new StringReader(xml)), clazz).getValue(); // } // // }
import de.jeha.s3srv.xml.JaxbMarshaller; import org.junit.jupiter.api.Test; import javax.xml.bind.JAXBException; import java.io.IOException; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import static org.junit.jupiter.api.Assertions.assertEquals;
package de.jeha.s3srv.api; /** * @author jenshadlich@googlemail.com */ public class ListBucketResultSerializationTest { @Test public void test() throws JAXBException, IOException { ListBucketResult response = new ListBucketResult( "test-bucket", 1, 1000, Collections.singletonList(new ListBucketResult.ContentsEntry( "test-object", Instant.parse("2009-10-12T17:50:30.001Z"), "\"fba9dede5f27731c9771645a39863328\"", 434234)));
// Path: src/main/java/de/jeha/s3srv/xml/JaxbMarshaller.java // public class JaxbMarshaller { // // private static Marshaller MARSHALLER = null; // private static Unmarshaller UNMARSHALLER = null; // // static { // try { // MARSHALLER = JaxbContextHolder.getContext().createMarshaller(); // MARSHALLER.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // MARSHALLER.setProperty(Marshaller.JAXB_FRAGMENT, true); // } catch (JAXBException e) { // throw new RuntimeException("Unable to initialize JAXB Marshaller", e); // } // try { // UNMARSHALLER = JaxbContextHolder.getContext().createUnmarshaller(); // } catch (JAXBException e) { // throw new RuntimeException("Unable to initialize JAXB Unmarshaller", e); // } // } // // public synchronized static String marshall(Object object) throws JAXBException, IOException { // StringWriter stringWriter = new StringWriter(); // stringWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); // stringWriter.append("\n"); // // MARSHALLER.marshal(object, stringWriter); // stringWriter.close(); // // return stringWriter.toString(); // } // // public synchronized static <T> T unmarshall(String xml, Class<T> clazz) throws JAXBException, IOException { // return UNMARSHALLER.unmarshal(new StreamSource(new StringReader(xml)), clazz).getValue(); // } // // } // Path: src/test/java/de/jeha/s3srv/api/ListBucketResultSerializationTest.java import de.jeha.s3srv.xml.JaxbMarshaller; import org.junit.jupiter.api.Test; import javax.xml.bind.JAXBException; import java.io.IOException; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import static org.junit.jupiter.api.Assertions.assertEquals; package de.jeha.s3srv.api; /** * @author jenshadlich@googlemail.com */ public class ListBucketResultSerializationTest { @Test public void test() throws JAXBException, IOException { ListBucketResult response = new ListBucketResult( "test-bucket", 1, 1000, Collections.singletonList(new ListBucketResult.ContentsEntry( "test-object", Instant.parse("2009-10-12T17:50:30.001Z"), "\"fba9dede5f27731c9771645a39863328\"", 434234)));
final String responseXml = JaxbMarshaller.marshall(response);
jenshadlich/s3srv
src/main/java/de/jeha/s3srv/api/ListBucketResult.java
// Path: src/main/java/de/jeha/s3srv/xml/InstantXmlAdapter.java // public class InstantXmlAdapter extends XmlAdapter<String, Instant> { // // private final DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT; // // @Override // public Instant unmarshal(String value) throws Exception { // return value != null ? formatter.parse(value, Instant::from) : null; // } // // @Override // public String marshal(Instant value) throws Exception { // return value != null ? formatter.format(value) : null; // } // // }
import de.jeha.s3srv.xml.InstantXmlAdapter; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.time.Instant; import java.util.ArrayList; import java.util.List;
@XmlElement(name = "CommonPrefixes") private List<CommonPrefix> commonPrefixes = new ArrayList<>(); public ListBucketResult() { } public ListBucketResult(String name, Integer keyCount, Integer maxKeys, List<ContentsEntry> objects) { this.name = name; this.keyCount = keyCount; this.maxKeys = maxKeys; this.objects = objects; } public ListBucketResult(String name, Integer keyCount, Integer maxKeys, List<ContentsEntry> objects, List<CommonPrefix> commonPrefixes) { this.name = name; this.keyCount = keyCount; this.maxKeys = maxKeys; this.objects = objects; this.commonPrefixes = commonPrefixes; } public static class ContentsEntry { private static final String STORAGE_CLASS_STANDARD = "STANDARD"; private static final String STORAGE_CLASS_REDUCED_REDUNDANCY = "REDUCED_REDUNDANCY"; @XmlElement(name = "Key") private String key;
// Path: src/main/java/de/jeha/s3srv/xml/InstantXmlAdapter.java // public class InstantXmlAdapter extends XmlAdapter<String, Instant> { // // private final DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT; // // @Override // public Instant unmarshal(String value) throws Exception { // return value != null ? formatter.parse(value, Instant::from) : null; // } // // @Override // public String marshal(Instant value) throws Exception { // return value != null ? formatter.format(value) : null; // } // // } // Path: src/main/java/de/jeha/s3srv/api/ListBucketResult.java import de.jeha.s3srv.xml.InstantXmlAdapter; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.time.Instant; import java.util.ArrayList; import java.util.List; @XmlElement(name = "CommonPrefixes") private List<CommonPrefix> commonPrefixes = new ArrayList<>(); public ListBucketResult() { } public ListBucketResult(String name, Integer keyCount, Integer maxKeys, List<ContentsEntry> objects) { this.name = name; this.keyCount = keyCount; this.maxKeys = maxKeys; this.objects = objects; } public ListBucketResult(String name, Integer keyCount, Integer maxKeys, List<ContentsEntry> objects, List<CommonPrefix> commonPrefixes) { this.name = name; this.keyCount = keyCount; this.maxKeys = maxKeys; this.objects = objects; this.commonPrefixes = commonPrefixes; } public static class ContentsEntry { private static final String STORAGE_CLASS_STANDARD = "STANDARD"; private static final String STORAGE_CLASS_REDUCED_REDUNDANCY = "REDUCED_REDUNDANCY"; @XmlElement(name = "Key") private String key;
@XmlJavaTypeAdapter(InstantXmlAdapter.class)
jenshadlich/s3srv
src/main/java/de/jeha/s3srv/model/S3User.java
// Path: src/main/java/de/jeha/s3srv/common/security/Credentials.java // public class Credentials { // // private final static String ACCESS_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // private final static int ACCESS_KEY_LENGTH = 20; // // private final static String SECRET_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // private final static String SECRET_KEY_CHARS_WITH_SPECIAL_CHARS = SECRET_KEY_CHARS + "/+"; // private final static int SECRET_KEY_LENGTH = 40; // // private final String accessKey; // private final String secretKey; // // public Credentials(String accessKey, String secretKey) { // this.accessKey = accessKey; // this.secretKey = secretKey; // } // // public String getAccessKey() { // return accessKey; // } // // public String getSecretKey() { // return secretKey; // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @return randomly generated credentials // */ // public static Credentials generateRandom() { // return generateRandom(true); // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @param includeSpecialChars include special chars ('/' and '+') for secret keys // * @return randomly generated credentials // */ // public static Credentials generateRandom(boolean includeSpecialChars) { // String accessKey = RandomStringUtils.random(ACCESS_KEY_LENGTH, ACCESS_KEY_CHARS); // String secretKey = RandomStringUtils.random( // SECRET_KEY_LENGTH, // includeSpecialChars ? SECRET_KEY_CHARS_WITH_SPECIAL_CHARS : SECRET_KEY_CHARS // ); // // return new Credentials(accessKey, secretKey); // } // // public void print() { // System.out.println(); // System.out.println("accessKey: " + accessKey); // System.out.println("secretKey: " + secretKey); // System.out.println(); // } // // }
import de.jeha.s3srv.common.security.Credentials;
package de.jeha.s3srv.model; /** * @author jenshadlich@googlemail.com */ public class S3User { private final String id; private final String displayName;
// Path: src/main/java/de/jeha/s3srv/common/security/Credentials.java // public class Credentials { // // private final static String ACCESS_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // private final static int ACCESS_KEY_LENGTH = 20; // // private final static String SECRET_KEY_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; // private final static String SECRET_KEY_CHARS_WITH_SPECIAL_CHARS = SECRET_KEY_CHARS + "/+"; // private final static int SECRET_KEY_LENGTH = 40; // // private final String accessKey; // private final String secretKey; // // public Credentials(String accessKey, String secretKey) { // this.accessKey = accessKey; // this.secretKey = secretKey; // } // // public String getAccessKey() { // return accessKey; // } // // public String getSecretKey() { // return secretKey; // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @return randomly generated credentials // */ // public static Credentials generateRandom() { // return generateRandom(true); // } // // /** // * Generates a random pair of access key and secret key in a pretty naive way. // * // * @param includeSpecialChars include special chars ('/' and '+') for secret keys // * @return randomly generated credentials // */ // public static Credentials generateRandom(boolean includeSpecialChars) { // String accessKey = RandomStringUtils.random(ACCESS_KEY_LENGTH, ACCESS_KEY_CHARS); // String secretKey = RandomStringUtils.random( // SECRET_KEY_LENGTH, // includeSpecialChars ? SECRET_KEY_CHARS_WITH_SPECIAL_CHARS : SECRET_KEY_CHARS // ); // // return new Credentials(accessKey, secretKey); // } // // public void print() { // System.out.println(); // System.out.println("accessKey: " + accessKey); // System.out.println("secretKey: " + secretKey); // System.out.println(); // } // // } // Path: src/main/java/de/jeha/s3srv/model/S3User.java import de.jeha.s3srv.common.security.Credentials; package de.jeha.s3srv.model; /** * @author jenshadlich@googlemail.com */ public class S3User { private final String id; private final String displayName;
private final Credentials credentials;
AlexanderMisel/gnubridge
src/main/java/org/gnubridge/core/Deal.java
// Path: src/main/java/org/gnubridge/core/deck/Suit.java // public abstract class Suit extends Trump { // // //note, DO NOT USE statics from Trump here, ie SPADES instead of Spades.i() // public static final Suit[] list = { Spades.i(), Hearts.i(), Diamonds.i(), Clubs.i() }; // public static final Suit[] reverseList = { Clubs.i(), Diamonds.i(), Hearts.i(), Spades.i(), }; // public static final Suit[] mmList = { Hearts.i(), Spades.i(), Clubs.i(), Diamonds.i() }; // // public static int getIndex(Suit denomination) { // int result = -1; // for (Suit suit : reverseList) { // result++; // if (suit.equals(denomination)) { // break; // } // } // return result; // } // // @Override // public abstract String toDebugString(); // // public boolean isLowerRankThan(Trump other) { // if (other.isNoTrump()) { // return true; // } // return getIndex(this) < getIndex(other.asSuit()); // } // // public static Suit get(String s) { // if ("S".equals(s)) { // return Spades.i(); // } else if ("H".equals(s)) { // return Hearts.i(); // } else if ("D".equals(s)) { // return Diamonds.i(); // } else if ("C".equals(s)) { // return Clubs.i(); // } else { // throw new RuntimeException("do not know how to translate string '" + s // + "' to a suit (need one of: S,H,D,C)"); // } // } // } // // Path: src/main/java/org/gnubridge/core/deck/Trump.java // public abstract class Trump { // // public static final Suit CLUBS = Clubs.i(); // public static final Suit DIAMONDS = Diamonds.i(); // public static final Suit HEARTS = Hearts.i(); // public static final Suit SPADES = Spades.i(); // public static final Trump NOTRUMP = NoTrump.i(); // // @Override // public abstract String toString(); // // public static Trump instance(String s) { // Trump result = null; // if (NoTrump.i().toString().equalsIgnoreCase(s)) { // result = NoTrump.i(); // } else if (Spades.i().toString().equalsIgnoreCase(s)) { // result = Spades.i(); // } else if (Hearts.i().toString().equalsIgnoreCase(s)) { // result = Hearts.i(); // } else if (Diamonds.i().toString().equalsIgnoreCase(s)) { // result = Diamonds.i(); // } else if (Clubs.i().toString().equalsIgnoreCase(s)) { // result = Clubs.i(); // } // return result; // } // // public abstract String toDebugString(); // // public boolean isMajorSuit() { // return Spades.i().equals(this) || Hearts.i().equals(this); // } // // public Suit asSuit() { // if (this instanceof Suit) { // return (Suit) this; // } else { // throw new RuntimeException("Trying to treat " + this + " as suit."); // } // } // // public boolean isMinorSuit() { // return Diamonds.i().equals(this) || Clubs.i().equals(this); // } // // public boolean isSuit() { // return isMajorSuit() || isMinorSuit(); // } // // public boolean isNoTrump() { // return NoTrump.i().equals(this); // } // }
import java.util.ArrayList; import java.util.List; import org.gnubridge.core.deck.Suit; import org.gnubridge.core.deck.Trump; import org.gnubridge.presentation.GameUtils;
package org.gnubridge.core; public class Deal { private static Deal preInitializedGame; private final Player[] players; int nextToPlay; Trick currentTrick; protected boolean done;
// Path: src/main/java/org/gnubridge/core/deck/Suit.java // public abstract class Suit extends Trump { // // //note, DO NOT USE statics from Trump here, ie SPADES instead of Spades.i() // public static final Suit[] list = { Spades.i(), Hearts.i(), Diamonds.i(), Clubs.i() }; // public static final Suit[] reverseList = { Clubs.i(), Diamonds.i(), Hearts.i(), Spades.i(), }; // public static final Suit[] mmList = { Hearts.i(), Spades.i(), Clubs.i(), Diamonds.i() }; // // public static int getIndex(Suit denomination) { // int result = -1; // for (Suit suit : reverseList) { // result++; // if (suit.equals(denomination)) { // break; // } // } // return result; // } // // @Override // public abstract String toDebugString(); // // public boolean isLowerRankThan(Trump other) { // if (other.isNoTrump()) { // return true; // } // return getIndex(this) < getIndex(other.asSuit()); // } // // public static Suit get(String s) { // if ("S".equals(s)) { // return Spades.i(); // } else if ("H".equals(s)) { // return Hearts.i(); // } else if ("D".equals(s)) { // return Diamonds.i(); // } else if ("C".equals(s)) { // return Clubs.i(); // } else { // throw new RuntimeException("do not know how to translate string '" + s // + "' to a suit (need one of: S,H,D,C)"); // } // } // } // // Path: src/main/java/org/gnubridge/core/deck/Trump.java // public abstract class Trump { // // public static final Suit CLUBS = Clubs.i(); // public static final Suit DIAMONDS = Diamonds.i(); // public static final Suit HEARTS = Hearts.i(); // public static final Suit SPADES = Spades.i(); // public static final Trump NOTRUMP = NoTrump.i(); // // @Override // public abstract String toString(); // // public static Trump instance(String s) { // Trump result = null; // if (NoTrump.i().toString().equalsIgnoreCase(s)) { // result = NoTrump.i(); // } else if (Spades.i().toString().equalsIgnoreCase(s)) { // result = Spades.i(); // } else if (Hearts.i().toString().equalsIgnoreCase(s)) { // result = Hearts.i(); // } else if (Diamonds.i().toString().equalsIgnoreCase(s)) { // result = Diamonds.i(); // } else if (Clubs.i().toString().equalsIgnoreCase(s)) { // result = Clubs.i(); // } // return result; // } // // public abstract String toDebugString(); // // public boolean isMajorSuit() { // return Spades.i().equals(this) || Hearts.i().equals(this); // } // // public Suit asSuit() { // if (this instanceof Suit) { // return (Suit) this; // } else { // throw new RuntimeException("Trying to treat " + this + " as suit."); // } // } // // public boolean isMinorSuit() { // return Diamonds.i().equals(this) || Clubs.i().equals(this); // } // // public boolean isSuit() { // return isMajorSuit() || isMinorSuit(); // } // // public boolean isNoTrump() { // return NoTrump.i().equals(this); // } // } // Path: src/main/java/org/gnubridge/core/Deal.java import java.util.ArrayList; import java.util.List; import org.gnubridge.core.deck.Suit; import org.gnubridge.core.deck.Trump; import org.gnubridge.presentation.GameUtils; package org.gnubridge.core; public class Deal { private static Deal preInitializedGame; private final Player[] players; int nextToPlay; Trick currentTrick; protected boolean done;
private Trump trump;
AlexanderMisel/gnubridge
src/main/java/org/gnubridge/core/Deal.java
// Path: src/main/java/org/gnubridge/core/deck/Suit.java // public abstract class Suit extends Trump { // // //note, DO NOT USE statics from Trump here, ie SPADES instead of Spades.i() // public static final Suit[] list = { Spades.i(), Hearts.i(), Diamonds.i(), Clubs.i() }; // public static final Suit[] reverseList = { Clubs.i(), Diamonds.i(), Hearts.i(), Spades.i(), }; // public static final Suit[] mmList = { Hearts.i(), Spades.i(), Clubs.i(), Diamonds.i() }; // // public static int getIndex(Suit denomination) { // int result = -1; // for (Suit suit : reverseList) { // result++; // if (suit.equals(denomination)) { // break; // } // } // return result; // } // // @Override // public abstract String toDebugString(); // // public boolean isLowerRankThan(Trump other) { // if (other.isNoTrump()) { // return true; // } // return getIndex(this) < getIndex(other.asSuit()); // } // // public static Suit get(String s) { // if ("S".equals(s)) { // return Spades.i(); // } else if ("H".equals(s)) { // return Hearts.i(); // } else if ("D".equals(s)) { // return Diamonds.i(); // } else if ("C".equals(s)) { // return Clubs.i(); // } else { // throw new RuntimeException("do not know how to translate string '" + s // + "' to a suit (need one of: S,H,D,C)"); // } // } // } // // Path: src/main/java/org/gnubridge/core/deck/Trump.java // public abstract class Trump { // // public static final Suit CLUBS = Clubs.i(); // public static final Suit DIAMONDS = Diamonds.i(); // public static final Suit HEARTS = Hearts.i(); // public static final Suit SPADES = Spades.i(); // public static final Trump NOTRUMP = NoTrump.i(); // // @Override // public abstract String toString(); // // public static Trump instance(String s) { // Trump result = null; // if (NoTrump.i().toString().equalsIgnoreCase(s)) { // result = NoTrump.i(); // } else if (Spades.i().toString().equalsIgnoreCase(s)) { // result = Spades.i(); // } else if (Hearts.i().toString().equalsIgnoreCase(s)) { // result = Hearts.i(); // } else if (Diamonds.i().toString().equalsIgnoreCase(s)) { // result = Diamonds.i(); // } else if (Clubs.i().toString().equalsIgnoreCase(s)) { // result = Clubs.i(); // } // return result; // } // // public abstract String toDebugString(); // // public boolean isMajorSuit() { // return Spades.i().equals(this) || Hearts.i().equals(this); // } // // public Suit asSuit() { // if (this instanceof Suit) { // return (Suit) this; // } else { // throw new RuntimeException("Trying to treat " + this + " as suit."); // } // } // // public boolean isMinorSuit() { // return Diamonds.i().equals(this) || Clubs.i().equals(this); // } // // public boolean isSuit() { // return isMajorSuit() || isMinorSuit(); // } // // public boolean isNoTrump() { // return NoTrump.i().equals(this); // } // }
import java.util.ArrayList; import java.util.List; import org.gnubridge.core.deck.Suit; import org.gnubridge.core.deck.Trump; import org.gnubridge.presentation.GameUtils;
public Player getPlayer(int i) { return players[i]; } public Player getWest() { return players[Direction.WEST_DEPRECATED]; } public Player getNorth() { return players[Direction.NORTH_DEPRECATED]; } public Player getEast() { return players[Direction.EAST_DEPRECATED]; } public Player getSouth() { return players[Direction.SOUTH_DEPRECATED]; } public void setPlayer(int i, Player p) { players[i] = p; } public void doNextCard() { doNextCard(players[nextToPlay].getPossibleMoves(currentTrick).get(0)); } // TODO: test how it interacts with play()
// Path: src/main/java/org/gnubridge/core/deck/Suit.java // public abstract class Suit extends Trump { // // //note, DO NOT USE statics from Trump here, ie SPADES instead of Spades.i() // public static final Suit[] list = { Spades.i(), Hearts.i(), Diamonds.i(), Clubs.i() }; // public static final Suit[] reverseList = { Clubs.i(), Diamonds.i(), Hearts.i(), Spades.i(), }; // public static final Suit[] mmList = { Hearts.i(), Spades.i(), Clubs.i(), Diamonds.i() }; // // public static int getIndex(Suit denomination) { // int result = -1; // for (Suit suit : reverseList) { // result++; // if (suit.equals(denomination)) { // break; // } // } // return result; // } // // @Override // public abstract String toDebugString(); // // public boolean isLowerRankThan(Trump other) { // if (other.isNoTrump()) { // return true; // } // return getIndex(this) < getIndex(other.asSuit()); // } // // public static Suit get(String s) { // if ("S".equals(s)) { // return Spades.i(); // } else if ("H".equals(s)) { // return Hearts.i(); // } else if ("D".equals(s)) { // return Diamonds.i(); // } else if ("C".equals(s)) { // return Clubs.i(); // } else { // throw new RuntimeException("do not know how to translate string '" + s // + "' to a suit (need one of: S,H,D,C)"); // } // } // } // // Path: src/main/java/org/gnubridge/core/deck/Trump.java // public abstract class Trump { // // public static final Suit CLUBS = Clubs.i(); // public static final Suit DIAMONDS = Diamonds.i(); // public static final Suit HEARTS = Hearts.i(); // public static final Suit SPADES = Spades.i(); // public static final Trump NOTRUMP = NoTrump.i(); // // @Override // public abstract String toString(); // // public static Trump instance(String s) { // Trump result = null; // if (NoTrump.i().toString().equalsIgnoreCase(s)) { // result = NoTrump.i(); // } else if (Spades.i().toString().equalsIgnoreCase(s)) { // result = Spades.i(); // } else if (Hearts.i().toString().equalsIgnoreCase(s)) { // result = Hearts.i(); // } else if (Diamonds.i().toString().equalsIgnoreCase(s)) { // result = Diamonds.i(); // } else if (Clubs.i().toString().equalsIgnoreCase(s)) { // result = Clubs.i(); // } // return result; // } // // public abstract String toDebugString(); // // public boolean isMajorSuit() { // return Spades.i().equals(this) || Hearts.i().equals(this); // } // // public Suit asSuit() { // if (this instanceof Suit) { // return (Suit) this; // } else { // throw new RuntimeException("Trying to treat " + this + " as suit."); // } // } // // public boolean isMinorSuit() { // return Diamonds.i().equals(this) || Clubs.i().equals(this); // } // // public boolean isSuit() { // return isMajorSuit() || isMinorSuit(); // } // // public boolean isNoTrump() { // return NoTrump.i().equals(this); // } // } // Path: src/main/java/org/gnubridge/core/Deal.java import java.util.ArrayList; import java.util.List; import org.gnubridge.core.deck.Suit; import org.gnubridge.core.deck.Trump; import org.gnubridge.presentation.GameUtils; public Player getPlayer(int i) { return players[i]; } public Player getWest() { return players[Direction.WEST_DEPRECATED]; } public Player getNorth() { return players[Direction.NORTH_DEPRECATED]; } public Player getEast() { return players[Direction.EAST_DEPRECATED]; } public Player getSouth() { return players[Direction.SOUTH_DEPRECATED]; } public void setPlayer(int i, Player p) { players[i] = p; } public void doNextCard() { doNextCard(players[nextToPlay].getPossibleMoves(currentTrick).get(0)); } // TODO: test how it interacts with play()
public List<Card> getPlayedCardsHiToLow(Suit color) {
AlexanderMisel/gnubridge
src/main/java/org/gnubridge/core/Player.java
// Path: src/main/java/org/gnubridge/core/deck/Suit.java // public abstract class Suit extends Trump { // // //note, DO NOT USE statics from Trump here, ie SPADES instead of Spades.i() // public static final Suit[] list = { Spades.i(), Hearts.i(), Diamonds.i(), Clubs.i() }; // public static final Suit[] reverseList = { Clubs.i(), Diamonds.i(), Hearts.i(), Spades.i(), }; // public static final Suit[] mmList = { Hearts.i(), Spades.i(), Clubs.i(), Diamonds.i() }; // // public static int getIndex(Suit denomination) { // int result = -1; // for (Suit suit : reverseList) { // result++; // if (suit.equals(denomination)) { // break; // } // } // return result; // } // // @Override // public abstract String toDebugString(); // // public boolean isLowerRankThan(Trump other) { // if (other.isNoTrump()) { // return true; // } // return getIndex(this) < getIndex(other.asSuit()); // } // // public static Suit get(String s) { // if ("S".equals(s)) { // return Spades.i(); // } else if ("H".equals(s)) { // return Hearts.i(); // } else if ("D".equals(s)) { // return Diamonds.i(); // } else if ("C".equals(s)) { // return Clubs.i(); // } else { // throw new RuntimeException("do not know how to translate string '" + s // + "' to a suit (need one of: S,H,D,C)"); // } // } // }
import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import org.gnubridge.core.deck.Suit;
package org.gnubridge.core; public class Player { public static final int WEST_EAST = 0; public static final int NORTH_SOUTH = 1; private final int direction; private final List<Card> hand; private final List<Card> played; private final List<Trick> tricks; public Player(int i) { hand = new LinkedList<Card>(); played = new ArrayList<Card>(); tricks = new ArrayList<Trick>(); direction = i; } public Player(Direction d) { this(d.getValue()); } public void hand(String... suits) { init(new Hand(suits).getCardsHighToLow()); } public void init(String[]... valueSuits) { for (int i = 0; i < valueSuits.length; i++) { String[] values = valueSuits[i]; for (int j = 0; j < values.length; j++) {
// Path: src/main/java/org/gnubridge/core/deck/Suit.java // public abstract class Suit extends Trump { // // //note, DO NOT USE statics from Trump here, ie SPADES instead of Spades.i() // public static final Suit[] list = { Spades.i(), Hearts.i(), Diamonds.i(), Clubs.i() }; // public static final Suit[] reverseList = { Clubs.i(), Diamonds.i(), Hearts.i(), Spades.i(), }; // public static final Suit[] mmList = { Hearts.i(), Spades.i(), Clubs.i(), Diamonds.i() }; // // public static int getIndex(Suit denomination) { // int result = -1; // for (Suit suit : reverseList) { // result++; // if (suit.equals(denomination)) { // break; // } // } // return result; // } // // @Override // public abstract String toDebugString(); // // public boolean isLowerRankThan(Trump other) { // if (other.isNoTrump()) { // return true; // } // return getIndex(this) < getIndex(other.asSuit()); // } // // public static Suit get(String s) { // if ("S".equals(s)) { // return Spades.i(); // } else if ("H".equals(s)) { // return Hearts.i(); // } else if ("D".equals(s)) { // return Diamonds.i(); // } else if ("C".equals(s)) { // return Clubs.i(); // } else { // throw new RuntimeException("do not know how to translate string '" + s // + "' to a suit (need one of: S,H,D,C)"); // } // } // } // Path: src/main/java/org/gnubridge/core/Player.java import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import org.gnubridge.core.deck.Suit; package org.gnubridge.core; public class Player { public static final int WEST_EAST = 0; public static final int NORTH_SOUTH = 1; private final int direction; private final List<Card> hand; private final List<Card> played; private final List<Trick> tricks; public Player(int i) { hand = new LinkedList<Card>(); played = new ArrayList<Card>(); tricks = new ArrayList<Trick>(); direction = i; } public Player(Direction d) { this(d.getValue()); } public void hand(String... suits) { init(new Hand(suits).getCardsHighToLow()); } public void init(String[]... valueSuits) { for (int i = 0; i < valueSuits.length; i++) { String[] values = valueSuits[i]; for (int j = 0; j < values.length; j++) {
hand.add(new Card(values[j], Suit.list[i]));
AlexanderMisel/gnubridge
acceptance/org/gnubridge/search/DDRegressionTest.java
// Path: src/main/java/org/gnubridge/core/deck/Trump.java // public abstract class Trump { // // public static final Suit CLUBS = Clubs.i(); // public static final Suit DIAMONDS = Diamonds.i(); // public static final Suit HEARTS = Hearts.i(); // public static final Suit SPADES = Spades.i(); // public static final Trump NOTRUMP = NoTrump.i(); // // @Override // public abstract String toString(); // // public static Trump instance(String s) { // Trump result = null; // if (NoTrump.i().toString().equalsIgnoreCase(s)) { // result = NoTrump.i(); // } else if (Spades.i().toString().equalsIgnoreCase(s)) { // result = Spades.i(); // } else if (Hearts.i().toString().equalsIgnoreCase(s)) { // result = Hearts.i(); // } else if (Diamonds.i().toString().equalsIgnoreCase(s)) { // result = Diamonds.i(); // } else if (Clubs.i().toString().equalsIgnoreCase(s)) { // result = Clubs.i(); // } // return result; // } // // public abstract String toDebugString(); // // public boolean isMajorSuit() { // return Spades.i().equals(this) || Hearts.i().equals(this); // } // // public Suit asSuit() { // if (this instanceof Suit) { // return (Suit) this; // } else { // throw new RuntimeException("Trying to treat " + this + " as suit."); // } // } // // public boolean isMinorSuit() { // return Diamonds.i().equals(this) || Clubs.i().equals(this); // } // // public boolean isSuit() { // return isMajorSuit() || isMinorSuit(); // } // // public boolean isNoTrump() { // return NoTrump.i().equals(this); // } // } // // Path: src/main/java/org/gnubridge/core/deck/Seven.java // public class Seven { // public static Card of(Suit denomination) { // return new Card("7", denomination); // } // }
import static org.gnubridge.core.Direction.*; import static org.gnubridge.core.deck.Trump.*; import org.gnubridge.core.deck.Four; import org.gnubridge.core.deck.King; import org.gnubridge.core.deck.Seven;
} public void testSidneyLenzMiniature() { given(SOUTH, "A,3", "", "", "A"); given(WEST, "J,2", "A", "", ""); given(NORTH, "Q,8", "", "", "7"); given(EAST, "K,10", "", "A", ""); givenTrump(SPADES); whenLeadBy(SOUTH); shouldWinTricks(2); } public void testTedMullerFittingEndMiniature() { given(SOUTH, "Q", "", "A,Q", ""); given(WEST, "K", "", "", "J,10"); given(NORTH, "", "K,J", "", "A"); given(EAST, "", "A", "9", "7"); givenTrump(SPADES); whenLeadBy(EAST); shouldWinTricks(2); } //source - generated by gnubridge stochastic tests public void testAlphaBetaBugGivingUpTrick() { given(SOUTH, "Q,2", "", "9", ""); given(WEST, "J,7", "", "", "3"); given(NORTH, "4,3", "", "5", ""); given(EAST, "K,5", "", "Q", ""); givenTrump(CLUBS);
// Path: src/main/java/org/gnubridge/core/deck/Trump.java // public abstract class Trump { // // public static final Suit CLUBS = Clubs.i(); // public static final Suit DIAMONDS = Diamonds.i(); // public static final Suit HEARTS = Hearts.i(); // public static final Suit SPADES = Spades.i(); // public static final Trump NOTRUMP = NoTrump.i(); // // @Override // public abstract String toString(); // // public static Trump instance(String s) { // Trump result = null; // if (NoTrump.i().toString().equalsIgnoreCase(s)) { // result = NoTrump.i(); // } else if (Spades.i().toString().equalsIgnoreCase(s)) { // result = Spades.i(); // } else if (Hearts.i().toString().equalsIgnoreCase(s)) { // result = Hearts.i(); // } else if (Diamonds.i().toString().equalsIgnoreCase(s)) { // result = Diamonds.i(); // } else if (Clubs.i().toString().equalsIgnoreCase(s)) { // result = Clubs.i(); // } // return result; // } // // public abstract String toDebugString(); // // public boolean isMajorSuit() { // return Spades.i().equals(this) || Hearts.i().equals(this); // } // // public Suit asSuit() { // if (this instanceof Suit) { // return (Suit) this; // } else { // throw new RuntimeException("Trying to treat " + this + " as suit."); // } // } // // public boolean isMinorSuit() { // return Diamonds.i().equals(this) || Clubs.i().equals(this); // } // // public boolean isSuit() { // return isMajorSuit() || isMinorSuit(); // } // // public boolean isNoTrump() { // return NoTrump.i().equals(this); // } // } // // Path: src/main/java/org/gnubridge/core/deck/Seven.java // public class Seven { // public static Card of(Suit denomination) { // return new Card("7", denomination); // } // } // Path: acceptance/org/gnubridge/search/DDRegressionTest.java import static org.gnubridge.core.Direction.*; import static org.gnubridge.core.deck.Trump.*; import org.gnubridge.core.deck.Four; import org.gnubridge.core.deck.King; import org.gnubridge.core.deck.Seven; } public void testSidneyLenzMiniature() { given(SOUTH, "A,3", "", "", "A"); given(WEST, "J,2", "A", "", ""); given(NORTH, "Q,8", "", "", "7"); given(EAST, "K,10", "", "A", ""); givenTrump(SPADES); whenLeadBy(SOUTH); shouldWinTricks(2); } public void testTedMullerFittingEndMiniature() { given(SOUTH, "Q", "", "A,Q", ""); given(WEST, "K", "", "", "J,10"); given(NORTH, "", "K,J", "", "A"); given(EAST, "", "A", "9", "7"); givenTrump(SPADES); whenLeadBy(EAST); shouldWinTricks(2); } //source - generated by gnubridge stochastic tests public void testAlphaBetaBugGivingUpTrick() { given(SOUTH, "Q,2", "", "9", ""); given(WEST, "J,7", "", "", "3"); given(NORTH, "4,3", "", "5", ""); given(EAST, "K,5", "", "Q", ""); givenTrump(CLUBS);
whenLeadBy(WEST, Seven.of(SPADES));
AlexanderMisel/gnubridge
src/main/java/org/gnubridge/core/Trick.java
// Path: src/main/java/org/gnubridge/core/deck/Suit.java // public abstract class Suit extends Trump { // // //note, DO NOT USE statics from Trump here, ie SPADES instead of Spades.i() // public static final Suit[] list = { Spades.i(), Hearts.i(), Diamonds.i(), Clubs.i() }; // public static final Suit[] reverseList = { Clubs.i(), Diamonds.i(), Hearts.i(), Spades.i(), }; // public static final Suit[] mmList = { Hearts.i(), Spades.i(), Clubs.i(), Diamonds.i() }; // // public static int getIndex(Suit denomination) { // int result = -1; // for (Suit suit : reverseList) { // result++; // if (suit.equals(denomination)) { // break; // } // } // return result; // } // // @Override // public abstract String toDebugString(); // // public boolean isLowerRankThan(Trump other) { // if (other.isNoTrump()) { // return true; // } // return getIndex(this) < getIndex(other.asSuit()); // } // // public static Suit get(String s) { // if ("S".equals(s)) { // return Spades.i(); // } else if ("H".equals(s)) { // return Hearts.i(); // } else if ("D".equals(s)) { // return Diamonds.i(); // } else if ("C".equals(s)) { // return Clubs.i(); // } else { // throw new RuntimeException("do not know how to translate string '" + s // + "' to a suit (need one of: S,H,D,C)"); // } // } // } // // Path: src/main/java/org/gnubridge/core/deck/Trump.java // public abstract class Trump { // // public static final Suit CLUBS = Clubs.i(); // public static final Suit DIAMONDS = Diamonds.i(); // public static final Suit HEARTS = Hearts.i(); // public static final Suit SPADES = Spades.i(); // public static final Trump NOTRUMP = NoTrump.i(); // // @Override // public abstract String toString(); // // public static Trump instance(String s) { // Trump result = null; // if (NoTrump.i().toString().equalsIgnoreCase(s)) { // result = NoTrump.i(); // } else if (Spades.i().toString().equalsIgnoreCase(s)) { // result = Spades.i(); // } else if (Hearts.i().toString().equalsIgnoreCase(s)) { // result = Hearts.i(); // } else if (Diamonds.i().toString().equalsIgnoreCase(s)) { // result = Diamonds.i(); // } else if (Clubs.i().toString().equalsIgnoreCase(s)) { // result = Clubs.i(); // } // return result; // } // // public abstract String toDebugString(); // // public boolean isMajorSuit() { // return Spades.i().equals(this) || Hearts.i().equals(this); // } // // public Suit asSuit() { // if (this instanceof Suit) { // return (Suit) this; // } else { // throw new RuntimeException("Trying to treat " + this + " as suit."); // } // } // // public boolean isMinorSuit() { // return Diamonds.i().equals(this) || Clubs.i().equals(this); // } // // public boolean isSuit() { // return isMajorSuit() || isMinorSuit(); // } // // public boolean isNoTrump() { // return NoTrump.i().equals(this); // } // }
import java.util.ArrayList; import java.util.List; import org.gnubridge.core.deck.Suit; import org.gnubridge.core.deck.Trump;
package org.gnubridge.core; public class Trick { private final List<Card> cards;
// Path: src/main/java/org/gnubridge/core/deck/Suit.java // public abstract class Suit extends Trump { // // //note, DO NOT USE statics from Trump here, ie SPADES instead of Spades.i() // public static final Suit[] list = { Spades.i(), Hearts.i(), Diamonds.i(), Clubs.i() }; // public static final Suit[] reverseList = { Clubs.i(), Diamonds.i(), Hearts.i(), Spades.i(), }; // public static final Suit[] mmList = { Hearts.i(), Spades.i(), Clubs.i(), Diamonds.i() }; // // public static int getIndex(Suit denomination) { // int result = -1; // for (Suit suit : reverseList) { // result++; // if (suit.equals(denomination)) { // break; // } // } // return result; // } // // @Override // public abstract String toDebugString(); // // public boolean isLowerRankThan(Trump other) { // if (other.isNoTrump()) { // return true; // } // return getIndex(this) < getIndex(other.asSuit()); // } // // public static Suit get(String s) { // if ("S".equals(s)) { // return Spades.i(); // } else if ("H".equals(s)) { // return Hearts.i(); // } else if ("D".equals(s)) { // return Diamonds.i(); // } else if ("C".equals(s)) { // return Clubs.i(); // } else { // throw new RuntimeException("do not know how to translate string '" + s // + "' to a suit (need one of: S,H,D,C)"); // } // } // } // // Path: src/main/java/org/gnubridge/core/deck/Trump.java // public abstract class Trump { // // public static final Suit CLUBS = Clubs.i(); // public static final Suit DIAMONDS = Diamonds.i(); // public static final Suit HEARTS = Hearts.i(); // public static final Suit SPADES = Spades.i(); // public static final Trump NOTRUMP = NoTrump.i(); // // @Override // public abstract String toString(); // // public static Trump instance(String s) { // Trump result = null; // if (NoTrump.i().toString().equalsIgnoreCase(s)) { // result = NoTrump.i(); // } else if (Spades.i().toString().equalsIgnoreCase(s)) { // result = Spades.i(); // } else if (Hearts.i().toString().equalsIgnoreCase(s)) { // result = Hearts.i(); // } else if (Diamonds.i().toString().equalsIgnoreCase(s)) { // result = Diamonds.i(); // } else if (Clubs.i().toString().equalsIgnoreCase(s)) { // result = Clubs.i(); // } // return result; // } // // public abstract String toDebugString(); // // public boolean isMajorSuit() { // return Spades.i().equals(this) || Hearts.i().equals(this); // } // // public Suit asSuit() { // if (this instanceof Suit) { // return (Suit) this; // } else { // throw new RuntimeException("Trying to treat " + this + " as suit."); // } // } // // public boolean isMinorSuit() { // return Diamonds.i().equals(this) || Clubs.i().equals(this); // } // // public boolean isSuit() { // return isMajorSuit() || isMinorSuit(); // } // // public boolean isNoTrump() { // return NoTrump.i().equals(this); // } // } // Path: src/main/java/org/gnubridge/core/Trick.java import java.util.ArrayList; import java.util.List; import org.gnubridge.core.deck.Suit; import org.gnubridge.core.deck.Trump; package org.gnubridge.core; public class Trick { private final List<Card> cards;
private Trump trump;
AlexanderMisel/gnubridge
src/main/java/org/gnubridge/core/Trick.java
// Path: src/main/java/org/gnubridge/core/deck/Suit.java // public abstract class Suit extends Trump { // // //note, DO NOT USE statics from Trump here, ie SPADES instead of Spades.i() // public static final Suit[] list = { Spades.i(), Hearts.i(), Diamonds.i(), Clubs.i() }; // public static final Suit[] reverseList = { Clubs.i(), Diamonds.i(), Hearts.i(), Spades.i(), }; // public static final Suit[] mmList = { Hearts.i(), Spades.i(), Clubs.i(), Diamonds.i() }; // // public static int getIndex(Suit denomination) { // int result = -1; // for (Suit suit : reverseList) { // result++; // if (suit.equals(denomination)) { // break; // } // } // return result; // } // // @Override // public abstract String toDebugString(); // // public boolean isLowerRankThan(Trump other) { // if (other.isNoTrump()) { // return true; // } // return getIndex(this) < getIndex(other.asSuit()); // } // // public static Suit get(String s) { // if ("S".equals(s)) { // return Spades.i(); // } else if ("H".equals(s)) { // return Hearts.i(); // } else if ("D".equals(s)) { // return Diamonds.i(); // } else if ("C".equals(s)) { // return Clubs.i(); // } else { // throw new RuntimeException("do not know how to translate string '" + s // + "' to a suit (need one of: S,H,D,C)"); // } // } // } // // Path: src/main/java/org/gnubridge/core/deck/Trump.java // public abstract class Trump { // // public static final Suit CLUBS = Clubs.i(); // public static final Suit DIAMONDS = Diamonds.i(); // public static final Suit HEARTS = Hearts.i(); // public static final Suit SPADES = Spades.i(); // public static final Trump NOTRUMP = NoTrump.i(); // // @Override // public abstract String toString(); // // public static Trump instance(String s) { // Trump result = null; // if (NoTrump.i().toString().equalsIgnoreCase(s)) { // result = NoTrump.i(); // } else if (Spades.i().toString().equalsIgnoreCase(s)) { // result = Spades.i(); // } else if (Hearts.i().toString().equalsIgnoreCase(s)) { // result = Hearts.i(); // } else if (Diamonds.i().toString().equalsIgnoreCase(s)) { // result = Diamonds.i(); // } else if (Clubs.i().toString().equalsIgnoreCase(s)) { // result = Clubs.i(); // } // return result; // } // // public abstract String toDebugString(); // // public boolean isMajorSuit() { // return Spades.i().equals(this) || Hearts.i().equals(this); // } // // public Suit asSuit() { // if (this instanceof Suit) { // return (Suit) this; // } else { // throw new RuntimeException("Trying to treat " + this + " as suit."); // } // } // // public boolean isMinorSuit() { // return Diamonds.i().equals(this) || Clubs.i().equals(this); // } // // public boolean isSuit() { // return isMajorSuit() || isMinorSuit(); // } // // public boolean isNoTrump() { // return NoTrump.i().equals(this); // } // }
import java.util.ArrayList; import java.util.List; import org.gnubridge.core.deck.Suit; import org.gnubridge.core.deck.Trump;
cards.add(card); players.add(p); } public boolean isStart() { return cards.size() == 0; } public boolean isDone() { return cards.size() == 4; } public Card getHighestCard() { Card highest = null; for (Card card : cards) { if (highest == null) { highest = card; } else if (card.trumps(highest, trump)) { highest = card; } else if (card.hasSameColorAs(highest) && card.hasGreaterValueThan(highest)) { highest = card; } } return highest; } public void setTrump(Trump trump) { this.trump = trump; }
// Path: src/main/java/org/gnubridge/core/deck/Suit.java // public abstract class Suit extends Trump { // // //note, DO NOT USE statics from Trump here, ie SPADES instead of Spades.i() // public static final Suit[] list = { Spades.i(), Hearts.i(), Diamonds.i(), Clubs.i() }; // public static final Suit[] reverseList = { Clubs.i(), Diamonds.i(), Hearts.i(), Spades.i(), }; // public static final Suit[] mmList = { Hearts.i(), Spades.i(), Clubs.i(), Diamonds.i() }; // // public static int getIndex(Suit denomination) { // int result = -1; // for (Suit suit : reverseList) { // result++; // if (suit.equals(denomination)) { // break; // } // } // return result; // } // // @Override // public abstract String toDebugString(); // // public boolean isLowerRankThan(Trump other) { // if (other.isNoTrump()) { // return true; // } // return getIndex(this) < getIndex(other.asSuit()); // } // // public static Suit get(String s) { // if ("S".equals(s)) { // return Spades.i(); // } else if ("H".equals(s)) { // return Hearts.i(); // } else if ("D".equals(s)) { // return Diamonds.i(); // } else if ("C".equals(s)) { // return Clubs.i(); // } else { // throw new RuntimeException("do not know how to translate string '" + s // + "' to a suit (need one of: S,H,D,C)"); // } // } // } // // Path: src/main/java/org/gnubridge/core/deck/Trump.java // public abstract class Trump { // // public static final Suit CLUBS = Clubs.i(); // public static final Suit DIAMONDS = Diamonds.i(); // public static final Suit HEARTS = Hearts.i(); // public static final Suit SPADES = Spades.i(); // public static final Trump NOTRUMP = NoTrump.i(); // // @Override // public abstract String toString(); // // public static Trump instance(String s) { // Trump result = null; // if (NoTrump.i().toString().equalsIgnoreCase(s)) { // result = NoTrump.i(); // } else if (Spades.i().toString().equalsIgnoreCase(s)) { // result = Spades.i(); // } else if (Hearts.i().toString().equalsIgnoreCase(s)) { // result = Hearts.i(); // } else if (Diamonds.i().toString().equalsIgnoreCase(s)) { // result = Diamonds.i(); // } else if (Clubs.i().toString().equalsIgnoreCase(s)) { // result = Clubs.i(); // } // return result; // } // // public abstract String toDebugString(); // // public boolean isMajorSuit() { // return Spades.i().equals(this) || Hearts.i().equals(this); // } // // public Suit asSuit() { // if (this instanceof Suit) { // return (Suit) this; // } else { // throw new RuntimeException("Trying to treat " + this + " as suit."); // } // } // // public boolean isMinorSuit() { // return Diamonds.i().equals(this) || Clubs.i().equals(this); // } // // public boolean isSuit() { // return isMajorSuit() || isMinorSuit(); // } // // public boolean isNoTrump() { // return NoTrump.i().equals(this); // } // } // Path: src/main/java/org/gnubridge/core/Trick.java import java.util.ArrayList; import java.util.List; import org.gnubridge.core.deck.Suit; import org.gnubridge.core.deck.Trump; cards.add(card); players.add(p); } public boolean isStart() { return cards.size() == 0; } public boolean isDone() { return cards.size() == 4; } public Card getHighestCard() { Card highest = null; for (Card card : cards) { if (highest == null) { highest = card; } else if (card.trumps(highest, trump)) { highest = card; } else if (card.hasSameColorAs(highest) && card.hasGreaterValueThan(highest)) { highest = card; } } return highest; } public void setTrump(Trump trump) { this.trump = trump; }
public Suit getDenomination() {
AlexanderMisel/gnubridge
src/test/java/org/gnubridge/core/HandTest.java
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // }
import java.util.List; import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.King; import org.gnubridge.core.deck.Three; import org.gnubridge.core.deck.Two;
package org.gnubridge.core; public class HandTest extends TestCase { public void testGetColorLength() { Hand h = new Hand("", "", "4,3,2", "A,K");
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // } // Path: src/test/java/org/gnubridge/core/HandTest.java import java.util.List; import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.King; import org.gnubridge.core.deck.Three; import org.gnubridge.core.deck.Two; package org.gnubridge.core; public class HandTest extends TestCase { public void testGetColorLength() { Hand h = new Hand("", "", "4,3,2", "A,K");
assertEquals(0, h.getSuitLength(Hearts.i()));
AlexanderMisel/gnubridge
src/test/java/org/gnubridge/core/HandTest.java
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // }
import java.util.List; import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.King; import org.gnubridge.core.deck.Three; import org.gnubridge.core.deck.Two;
package org.gnubridge.core; public class HandTest extends TestCase { public void testGetColorLength() { Hand h = new Hand("", "", "4,3,2", "A,K"); assertEquals(0, h.getSuitLength(Hearts.i())); assertEquals(3, h.getSuitLength(Diamonds.i())); } public void testGetColor() {
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // } // Path: src/test/java/org/gnubridge/core/HandTest.java import java.util.List; import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.King; import org.gnubridge.core.deck.Three; import org.gnubridge.core.deck.Two; package org.gnubridge.core; public class HandTest extends TestCase { public void testGetColorLength() { Hand h = new Hand("", "", "4,3,2", "A,K"); assertEquals(0, h.getSuitLength(Hearts.i())); assertEquals(3, h.getSuitLength(Diamonds.i())); } public void testGetColor() {
Hand h = new Hand(King.of(Hearts.i()), Two.of(Diamonds.i()), Ace.of(Diamonds.i()), Three.of(Clubs.i()), Three.of(Diamonds.i()));
AlexanderMisel/gnubridge
src/test/java/org/gnubridge/core/TrickTest.java
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Five.java // public class Five { // public static Card of(Suit denomination) { // return new Card("5", denomination); // } // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/NoTrump.java // public class NoTrump extends Trump { // // private static NoTrump instance = new NoTrump(); // // private NoTrump() { // super(); // } // // public static NoTrump i() { // return instance ; // } // // @Override // public String toString() { // return "NT"; // } // // @Override // public String toDebugString() { // return "NoTrump.i()"; // } // // }
import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Five; import org.gnubridge.core.deck.Four; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.NoTrump; import org.gnubridge.core.deck.Spades; import org.gnubridge.core.deck.Three; import org.gnubridge.core.deck.Two;
package org.gnubridge.core; public class TrickTest extends TestCase { Trick tr; protected void setUp() {
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Five.java // public class Five { // public static Card of(Suit denomination) { // return new Card("5", denomination); // } // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/NoTrump.java // public class NoTrump extends Trump { // // private static NoTrump instance = new NoTrump(); // // private NoTrump() { // super(); // } // // public static NoTrump i() { // return instance ; // } // // @Override // public String toString() { // return "NT"; // } // // @Override // public String toDebugString() { // return "NoTrump.i()"; // } // // } // Path: src/test/java/org/gnubridge/core/TrickTest.java import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Five; import org.gnubridge.core.deck.Four; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.NoTrump; import org.gnubridge.core.deck.Spades; import org.gnubridge.core.deck.Three; import org.gnubridge.core.deck.Two; package org.gnubridge.core; public class TrickTest extends TestCase { Trick tr; protected void setUp() {
tr = new Trick(NoTrump.i());
AlexanderMisel/gnubridge
src/test/java/org/gnubridge/core/TrickTest.java
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Five.java // public class Five { // public static Card of(Suit denomination) { // return new Card("5", denomination); // } // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/NoTrump.java // public class NoTrump extends Trump { // // private static NoTrump instance = new NoTrump(); // // private NoTrump() { // super(); // } // // public static NoTrump i() { // return instance ; // } // // @Override // public String toString() { // return "NT"; // } // // @Override // public String toDebugString() { // return "NoTrump.i()"; // } // // }
import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Five; import org.gnubridge.core.deck.Four; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.NoTrump; import org.gnubridge.core.deck.Spades; import org.gnubridge.core.deck.Three; import org.gnubridge.core.deck.Two;
package org.gnubridge.core; public class TrickTest extends TestCase { Trick tr; protected void setUp() { tr = new Trick(NoTrump.i()); } public void testGetHighestCardSameColor() { tr.addCard(Four.of(Spades.i()), null); tr.addCard(Two.of(Spades.i()), null);
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Five.java // public class Five { // public static Card of(Suit denomination) { // return new Card("5", denomination); // } // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/NoTrump.java // public class NoTrump extends Trump { // // private static NoTrump instance = new NoTrump(); // // private NoTrump() { // super(); // } // // public static NoTrump i() { // return instance ; // } // // @Override // public String toString() { // return "NT"; // } // // @Override // public String toDebugString() { // return "NoTrump.i()"; // } // // } // Path: src/test/java/org/gnubridge/core/TrickTest.java import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Five; import org.gnubridge.core.deck.Four; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.NoTrump; import org.gnubridge.core.deck.Spades; import org.gnubridge.core.deck.Three; import org.gnubridge.core.deck.Two; package org.gnubridge.core; public class TrickTest extends TestCase { Trick tr; protected void setUp() { tr = new Trick(NoTrump.i()); } public void testGetHighestCardSameColor() { tr.addCard(Four.of(Spades.i()), null); tr.addCard(Two.of(Spades.i()), null);
Card expected = Ace.of(Spades.i());
AlexanderMisel/gnubridge
src/test/java/org/gnubridge/core/TrickTest.java
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Five.java // public class Five { // public static Card of(Suit denomination) { // return new Card("5", denomination); // } // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/NoTrump.java // public class NoTrump extends Trump { // // private static NoTrump instance = new NoTrump(); // // private NoTrump() { // super(); // } // // public static NoTrump i() { // return instance ; // } // // @Override // public String toString() { // return "NT"; // } // // @Override // public String toDebugString() { // return "NoTrump.i()"; // } // // }
import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Five; import org.gnubridge.core.deck.Four; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.NoTrump; import org.gnubridge.core.deck.Spades; import org.gnubridge.core.deck.Three; import org.gnubridge.core.deck.Two;
package org.gnubridge.core; public class TrickTest extends TestCase { Trick tr; protected void setUp() { tr = new Trick(NoTrump.i()); } public void testGetHighestCardSameColor() { tr.addCard(Four.of(Spades.i()), null); tr.addCard(Two.of(Spades.i()), null); Card expected = Ace.of(Spades.i()); tr.addCard(expected, null); tr.addCard(Three.of(Spades.i()), null); assertEquals(expected, tr.getHighestCard()); } public void testGetHighestUnmatchedColor() { tr.addCard(Two.of(Spades.i()), null);
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Five.java // public class Five { // public static Card of(Suit denomination) { // return new Card("5", denomination); // } // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/NoTrump.java // public class NoTrump extends Trump { // // private static NoTrump instance = new NoTrump(); // // private NoTrump() { // super(); // } // // public static NoTrump i() { // return instance ; // } // // @Override // public String toString() { // return "NT"; // } // // @Override // public String toDebugString() { // return "NoTrump.i()"; // } // // } // Path: src/test/java/org/gnubridge/core/TrickTest.java import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Five; import org.gnubridge.core.deck.Four; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.NoTrump; import org.gnubridge.core.deck.Spades; import org.gnubridge.core.deck.Three; import org.gnubridge.core.deck.Two; package org.gnubridge.core; public class TrickTest extends TestCase { Trick tr; protected void setUp() { tr = new Trick(NoTrump.i()); } public void testGetHighestCardSameColor() { tr.addCard(Four.of(Spades.i()), null); tr.addCard(Two.of(Spades.i()), null); Card expected = Ace.of(Spades.i()); tr.addCard(expected, null); tr.addCard(Three.of(Spades.i()), null); assertEquals(expected, tr.getHighestCard()); } public void testGetHighestUnmatchedColor() { tr.addCard(Two.of(Spades.i()), null);
tr.addCard(Ace.of(Hearts.i()), null);
AlexanderMisel/gnubridge
src/test/java/org/gnubridge/core/TrickTest.java
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Five.java // public class Five { // public static Card of(Suit denomination) { // return new Card("5", denomination); // } // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/NoTrump.java // public class NoTrump extends Trump { // // private static NoTrump instance = new NoTrump(); // // private NoTrump() { // super(); // } // // public static NoTrump i() { // return instance ; // } // // @Override // public String toString() { // return "NT"; // } // // @Override // public String toDebugString() { // return "NoTrump.i()"; // } // // }
import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Five; import org.gnubridge.core.deck.Four; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.NoTrump; import org.gnubridge.core.deck.Spades; import org.gnubridge.core.deck.Three; import org.gnubridge.core.deck.Two;
public void testGetHighestTrumpMoreThanOneTrump() { tr.setTrump(Spades.i()); tr.addCard(Two.of(Spades.i()), null); Card expected = Four.of(Spades.i()); tr.addCard(expected, null); tr.addCard(Ace.of(Clubs.i()), null); tr.addCard(Three.of(Diamonds.i()), null); assertEquals(expected, tr.getHighestCard()); } public void testGetHighestTrumpMoreThanOneTrump2() { tr.setTrump(Spades.i()); Card expected = Four.of(Spades.i()); tr.addCard(expected, null); tr.addCard(Two.of(Spades.i()), null); tr.addCard(Ace.of(Clubs.i()), null); tr.addCard(Three.of(Diamonds.i()), null); assertEquals(expected, tr.getHighestCard()); } public void testWhoPlayedOneCard() { Player p = new Player(East.i()); Card card = Four.of(Spades.i()); tr.addCard(card, p); assertEquals(p, tr.whoPlayed(card)); } public void testWhoPlayedTwoCards() { Player p = new Player(East.i()); Player p2 = new Player(North.i()); Card card = Four.of(Spades.i());
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Five.java // public class Five { // public static Card of(Suit denomination) { // return new Card("5", denomination); // } // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/NoTrump.java // public class NoTrump extends Trump { // // private static NoTrump instance = new NoTrump(); // // private NoTrump() { // super(); // } // // public static NoTrump i() { // return instance ; // } // // @Override // public String toString() { // return "NT"; // } // // @Override // public String toDebugString() { // return "NoTrump.i()"; // } // // } // Path: src/test/java/org/gnubridge/core/TrickTest.java import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Five; import org.gnubridge.core.deck.Four; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.NoTrump; import org.gnubridge.core.deck.Spades; import org.gnubridge.core.deck.Three; import org.gnubridge.core.deck.Two; public void testGetHighestTrumpMoreThanOneTrump() { tr.setTrump(Spades.i()); tr.addCard(Two.of(Spades.i()), null); Card expected = Four.of(Spades.i()); tr.addCard(expected, null); tr.addCard(Ace.of(Clubs.i()), null); tr.addCard(Three.of(Diamonds.i()), null); assertEquals(expected, tr.getHighestCard()); } public void testGetHighestTrumpMoreThanOneTrump2() { tr.setTrump(Spades.i()); Card expected = Four.of(Spades.i()); tr.addCard(expected, null); tr.addCard(Two.of(Spades.i()), null); tr.addCard(Ace.of(Clubs.i()), null); tr.addCard(Three.of(Diamonds.i()), null); assertEquals(expected, tr.getHighestCard()); } public void testWhoPlayedOneCard() { Player p = new Player(East.i()); Card card = Four.of(Spades.i()); tr.addCard(card, p); assertEquals(p, tr.whoPlayed(card)); } public void testWhoPlayedTwoCards() { Player p = new Player(East.i()); Player p2 = new Player(North.i()); Card card = Four.of(Spades.i());
Card card2 = Five.of(Spades.i());
AlexanderMisel/gnubridge
src/main/java/org/gnubridge/core/Hand.java
// Path: src/main/java/org/gnubridge/core/deck/Suit.java // public abstract class Suit extends Trump { // // //note, DO NOT USE statics from Trump here, ie SPADES instead of Spades.i() // public static final Suit[] list = { Spades.i(), Hearts.i(), Diamonds.i(), Clubs.i() }; // public static final Suit[] reverseList = { Clubs.i(), Diamonds.i(), Hearts.i(), Spades.i(), }; // public static final Suit[] mmList = { Hearts.i(), Spades.i(), Clubs.i(), Diamonds.i() }; // // public static int getIndex(Suit denomination) { // int result = -1; // for (Suit suit : reverseList) { // result++; // if (suit.equals(denomination)) { // break; // } // } // return result; // } // // @Override // public abstract String toDebugString(); // // public boolean isLowerRankThan(Trump other) { // if (other.isNoTrump()) { // return true; // } // return getIndex(this) < getIndex(other.asSuit()); // } // // public static Suit get(String s) { // if ("S".equals(s)) { // return Spades.i(); // } else if ("H".equals(s)) { // return Hearts.i(); // } else if ("D".equals(s)) { // return Diamonds.i(); // } else if ("C".equals(s)) { // return Clubs.i(); // } else { // throw new RuntimeException("do not know how to translate string '" + s // + "' to a suit (need one of: S,H,D,C)"); // } // } // }
import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import org.gnubridge.core.deck.Suit;
package org.gnubridge.core; public class Hand { List<Card> cards; /** * Caching optimization for pruning played cards * and perhaps others */ List<Card> orderedCards;
// Path: src/main/java/org/gnubridge/core/deck/Suit.java // public abstract class Suit extends Trump { // // //note, DO NOT USE statics from Trump here, ie SPADES instead of Spades.i() // public static final Suit[] list = { Spades.i(), Hearts.i(), Diamonds.i(), Clubs.i() }; // public static final Suit[] reverseList = { Clubs.i(), Diamonds.i(), Hearts.i(), Spades.i(), }; // public static final Suit[] mmList = { Hearts.i(), Spades.i(), Clubs.i(), Diamonds.i() }; // // public static int getIndex(Suit denomination) { // int result = -1; // for (Suit suit : reverseList) { // result++; // if (suit.equals(denomination)) { // break; // } // } // return result; // } // // @Override // public abstract String toDebugString(); // // public boolean isLowerRankThan(Trump other) { // if (other.isNoTrump()) { // return true; // } // return getIndex(this) < getIndex(other.asSuit()); // } // // public static Suit get(String s) { // if ("S".equals(s)) { // return Spades.i(); // } else if ("H".equals(s)) { // return Hearts.i(); // } else if ("D".equals(s)) { // return Diamonds.i(); // } else if ("C".equals(s)) { // return Clubs.i(); // } else { // throw new RuntimeException("do not know how to translate string '" + s // + "' to a suit (need one of: S,H,D,C)"); // } // } // } // Path: src/main/java/org/gnubridge/core/Hand.java import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import org.gnubridge.core.deck.Suit; package org.gnubridge.core; public class Hand { List<Card> cards; /** * Caching optimization for pruning played cards * and perhaps others */ List<Card> orderedCards;
Suit color;
AlexanderMisel/gnubridge
src/test/java/org/gnubridge/core/DealTest.java
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/NoTrump.java // public class NoTrump extends Trump { // // private static NoTrump instance = new NoTrump(); // // private NoTrump() { // super(); // } // // public static NoTrump i() { // return instance ; // } // // @Override // public String toString() { // return "NT"; // } // // @Override // public String toDebugString() { // return "NoTrump.i()"; // } // // }
import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.NoTrump; import org.gnubridge.core.deck.Spades; import org.gnubridge.core.deck.Two; import org.gnubridge.presentation.GameUtils;
package org.gnubridge.core; public class DealTest extends TestCase { Deal game; @Override protected void setUp() {
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/NoTrump.java // public class NoTrump extends Trump { // // private static NoTrump instance = new NoTrump(); // // private NoTrump() { // super(); // } // // public static NoTrump i() { // return instance ; // } // // @Override // public String toString() { // return "NT"; // } // // @Override // public String toDebugString() { // return "NoTrump.i()"; // } // // } // Path: src/test/java/org/gnubridge/core/DealTest.java import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.NoTrump; import org.gnubridge.core.deck.Spades; import org.gnubridge.core.deck.Two; import org.gnubridge.presentation.GameUtils; package org.gnubridge.core; public class DealTest extends TestCase { Deal game; @Override protected void setUp() {
game = new Deal(NoTrump.i());
AlexanderMisel/gnubridge
src/test/java/org/gnubridge/core/DealTest.java
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/NoTrump.java // public class NoTrump extends Trump { // // private static NoTrump instance = new NoTrump(); // // private NoTrump() { // super(); // } // // public static NoTrump i() { // return instance ; // } // // @Override // public String toString() { // return "NT"; // } // // @Override // public String toDebugString() { // return "NoTrump.i()"; // } // // }
import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.NoTrump; import org.gnubridge.core.deck.Spades; import org.gnubridge.core.deck.Two; import org.gnubridge.presentation.GameUtils;
GameUtils.initializeSingleColorSuits(game); game.doNextCard(); assertEquals(12, game.getPlayer(Direction.WEST_DEPRECATED).getUnplayedCardsCount()); assertEquals(13, game.getPlayer(Direction.NORTH_DEPRECATED).getUnplayedCardsCount()); assertEquals(13, game.getPlayer(Direction.EAST_DEPRECATED).getUnplayedCardsCount()); assertEquals(13, game.getPlayer(Direction.SOUTH_DEPRECATED).getUnplayedCardsCount()); game.doNextCard(); assertEquals(12, game.getPlayer(Direction.WEST_DEPRECATED).getUnplayedCardsCount()); assertEquals(12, game.getPlayer(Direction.NORTH_DEPRECATED).getUnplayedCardsCount()); assertEquals(13, game.getPlayer(Direction.EAST_DEPRECATED).getUnplayedCardsCount()); assertEquals(13, game.getPlayer(Direction.SOUTH_DEPRECATED).getUnplayedCardsCount()); game.doNextCard(); assertEquals(12, game.getPlayer(Direction.WEST_DEPRECATED).getUnplayedCardsCount()); assertEquals(12, game.getPlayer(Direction.NORTH_DEPRECATED).getUnplayedCardsCount()); assertEquals(12, game.getPlayer(Direction.EAST_DEPRECATED).getUnplayedCardsCount()); assertEquals(13, game.getPlayer(Direction.SOUTH_DEPRECATED).getUnplayedCardsCount()); game.doNextCard(); assertEquals(12, game.getPlayer(Direction.WEST_DEPRECATED).getUnplayedCardsCount()); assertEquals(12, game.getPlayer(Direction.NORTH_DEPRECATED).getUnplayedCardsCount()); assertEquals(12, game.getPlayer(Direction.EAST_DEPRECATED).getUnplayedCardsCount()); assertEquals(12, game.getPlayer(Direction.SOUTH_DEPRECATED).getUnplayedCardsCount()); game.doNextCard(); assertEquals(11, game.getPlayer(Direction.WEST_DEPRECATED).getUnplayedCardsCount()); assertEquals(12, game.getPlayer(Direction.NORTH_DEPRECATED).getUnplayedCardsCount()); assertEquals(12, game.getPlayer(Direction.EAST_DEPRECATED).getUnplayedCardsCount()); assertEquals(12, game.getPlayer(Direction.SOUTH_DEPRECATED).getUnplayedCardsCount()); } public void testGameEndsWhenPlayersRunOutOfCards() { game.getPlayer(Direction.WEST_DEPRECATED).init(new Card[] { Two.of(Spades.i()) });
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/NoTrump.java // public class NoTrump extends Trump { // // private static NoTrump instance = new NoTrump(); // // private NoTrump() { // super(); // } // // public static NoTrump i() { // return instance ; // } // // @Override // public String toString() { // return "NT"; // } // // @Override // public String toDebugString() { // return "NoTrump.i()"; // } // // } // Path: src/test/java/org/gnubridge/core/DealTest.java import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.NoTrump; import org.gnubridge.core.deck.Spades; import org.gnubridge.core.deck.Two; import org.gnubridge.presentation.GameUtils; GameUtils.initializeSingleColorSuits(game); game.doNextCard(); assertEquals(12, game.getPlayer(Direction.WEST_DEPRECATED).getUnplayedCardsCount()); assertEquals(13, game.getPlayer(Direction.NORTH_DEPRECATED).getUnplayedCardsCount()); assertEquals(13, game.getPlayer(Direction.EAST_DEPRECATED).getUnplayedCardsCount()); assertEquals(13, game.getPlayer(Direction.SOUTH_DEPRECATED).getUnplayedCardsCount()); game.doNextCard(); assertEquals(12, game.getPlayer(Direction.WEST_DEPRECATED).getUnplayedCardsCount()); assertEquals(12, game.getPlayer(Direction.NORTH_DEPRECATED).getUnplayedCardsCount()); assertEquals(13, game.getPlayer(Direction.EAST_DEPRECATED).getUnplayedCardsCount()); assertEquals(13, game.getPlayer(Direction.SOUTH_DEPRECATED).getUnplayedCardsCount()); game.doNextCard(); assertEquals(12, game.getPlayer(Direction.WEST_DEPRECATED).getUnplayedCardsCount()); assertEquals(12, game.getPlayer(Direction.NORTH_DEPRECATED).getUnplayedCardsCount()); assertEquals(12, game.getPlayer(Direction.EAST_DEPRECATED).getUnplayedCardsCount()); assertEquals(13, game.getPlayer(Direction.SOUTH_DEPRECATED).getUnplayedCardsCount()); game.doNextCard(); assertEquals(12, game.getPlayer(Direction.WEST_DEPRECATED).getUnplayedCardsCount()); assertEquals(12, game.getPlayer(Direction.NORTH_DEPRECATED).getUnplayedCardsCount()); assertEquals(12, game.getPlayer(Direction.EAST_DEPRECATED).getUnplayedCardsCount()); assertEquals(12, game.getPlayer(Direction.SOUTH_DEPRECATED).getUnplayedCardsCount()); game.doNextCard(); assertEquals(11, game.getPlayer(Direction.WEST_DEPRECATED).getUnplayedCardsCount()); assertEquals(12, game.getPlayer(Direction.NORTH_DEPRECATED).getUnplayedCardsCount()); assertEquals(12, game.getPlayer(Direction.EAST_DEPRECATED).getUnplayedCardsCount()); assertEquals(12, game.getPlayer(Direction.SOUTH_DEPRECATED).getUnplayedCardsCount()); } public void testGameEndsWhenPlayersRunOutOfCards() { game.getPlayer(Direction.WEST_DEPRECATED).init(new Card[] { Two.of(Spades.i()) });
game.getPlayer(Direction.NORTH_DEPRECATED).init(new Card[] { Two.of(Hearts.i()) });
AlexanderMisel/gnubridge
src/test/java/org/gnubridge/core/DealTest.java
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/NoTrump.java // public class NoTrump extends Trump { // // private static NoTrump instance = new NoTrump(); // // private NoTrump() { // super(); // } // // public static NoTrump i() { // return instance ; // } // // @Override // public String toString() { // return "NT"; // } // // @Override // public String toDebugString() { // return "NoTrump.i()"; // } // // }
import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.NoTrump; import org.gnubridge.core.deck.Spades; import org.gnubridge.core.deck.Two; import org.gnubridge.presentation.GameUtils;
assertEquals(12, game.getPlayer(Direction.NORTH_DEPRECATED).getUnplayedCardsCount()); assertEquals(12, game.getPlayer(Direction.EAST_DEPRECATED).getUnplayedCardsCount()); assertEquals(12, game.getPlayer(Direction.SOUTH_DEPRECATED).getUnplayedCardsCount()); } public void testGameEndsWhenPlayersRunOutOfCards() { game.getPlayer(Direction.WEST_DEPRECATED).init(new Card[] { Two.of(Spades.i()) }); game.getPlayer(Direction.NORTH_DEPRECATED).init(new Card[] { Two.of(Hearts.i()) }); game.getPlayer(Direction.SOUTH_DEPRECATED).init(new Card[] { Two.of(Diamonds.i()) }); game.getPlayer(Direction.EAST_DEPRECATED).init(new Card[] { Two.of(Clubs.i()) }); for (int i = 0; i < 4; i++) { assertFalse("game ended before all cards were played", game.isDone()); game.doNextCard(); } assertTrue("not ended, but all cards have been played", game.isDone()); } public void testGameEndsWhen52CardsPlayed() { GameUtils.initializeSingleColorSuits(game); int cardCount = 0; while (!game.isDone()) { assertNotSame("Ran out of cards, but game not finished", 52, cardCount); game.doNextCard(); cardCount++; } assertEquals(52, cardCount); } public void testPreviousTrickTakerFirstToPlay() {
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/NoTrump.java // public class NoTrump extends Trump { // // private static NoTrump instance = new NoTrump(); // // private NoTrump() { // super(); // } // // public static NoTrump i() { // return instance ; // } // // @Override // public String toString() { // return "NT"; // } // // @Override // public String toDebugString() { // return "NoTrump.i()"; // } // // } // Path: src/test/java/org/gnubridge/core/DealTest.java import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.NoTrump; import org.gnubridge.core.deck.Spades; import org.gnubridge.core.deck.Two; import org.gnubridge.presentation.GameUtils; assertEquals(12, game.getPlayer(Direction.NORTH_DEPRECATED).getUnplayedCardsCount()); assertEquals(12, game.getPlayer(Direction.EAST_DEPRECATED).getUnplayedCardsCount()); assertEquals(12, game.getPlayer(Direction.SOUTH_DEPRECATED).getUnplayedCardsCount()); } public void testGameEndsWhenPlayersRunOutOfCards() { game.getPlayer(Direction.WEST_DEPRECATED).init(new Card[] { Two.of(Spades.i()) }); game.getPlayer(Direction.NORTH_DEPRECATED).init(new Card[] { Two.of(Hearts.i()) }); game.getPlayer(Direction.SOUTH_DEPRECATED).init(new Card[] { Two.of(Diamonds.i()) }); game.getPlayer(Direction.EAST_DEPRECATED).init(new Card[] { Two.of(Clubs.i()) }); for (int i = 0; i < 4; i++) { assertFalse("game ended before all cards were played", game.isDone()); game.doNextCard(); } assertTrue("not ended, but all cards have been played", game.isDone()); } public void testGameEndsWhen52CardsPlayed() { GameUtils.initializeSingleColorSuits(game); int cardCount = 0; while (!game.isDone()) { assertNotSame("Ran out of cards, but game not finished", 52, cardCount); game.doNextCard(); cardCount++; } assertEquals(52, cardCount); } public void testPreviousTrickTakerFirstToPlay() {
game.getPlayer(Direction.WEST_DEPRECATED).init(Ace.of(Hearts.i()), Two.of(Spades.i()));
AlexanderMisel/gnubridge
src/test/java/org/gnubridge/core/PlayerTest.java
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Suit.java // public abstract class Suit extends Trump { // // //note, DO NOT USE statics from Trump here, ie SPADES instead of Spades.i() // public static final Suit[] list = { Spades.i(), Hearts.i(), Diamonds.i(), Clubs.i() }; // public static final Suit[] reverseList = { Clubs.i(), Diamonds.i(), Hearts.i(), Spades.i(), }; // public static final Suit[] mmList = { Hearts.i(), Spades.i(), Clubs.i(), Diamonds.i() }; // // public static int getIndex(Suit denomination) { // int result = -1; // for (Suit suit : reverseList) { // result++; // if (suit.equals(denomination)) { // break; // } // } // return result; // } // // @Override // public abstract String toDebugString(); // // public boolean isLowerRankThan(Trump other) { // if (other.isNoTrump()) { // return true; // } // return getIndex(this) < getIndex(other.asSuit()); // } // // public static Suit get(String s) { // if ("S".equals(s)) { // return Spades.i(); // } else if ("H".equals(s)) { // return Hearts.i(); // } else if ("D".equals(s)) { // return Diamonds.i(); // } else if ("C".equals(s)) { // return Clubs.i(); // } else { // throw new RuntimeException("do not know how to translate string '" + s // + "' to a suit (need one of: S,H,D,C)"); // } // } // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/NoTrump.java // public class NoTrump extends Trump { // // private static NoTrump instance = new NoTrump(); // // private NoTrump() { // super(); // } // // public static NoTrump i() { // return instance ; // } // // @Override // public String toString() { // return "NT"; // } // // @Override // public String toDebugString() { // return "NoTrump.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Queen.java // public class Queen { // public static Card of(Suit denomination) { // return new Card("Q", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("Q"); // } // } // // Path: src/main/java/org/gnubridge/core/deck/Ten.java // public class Ten { // public static Card of(Suit denomination) { // return new Card("10", denomination); // } // }
import java.util.List; import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Suit; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.Jack; import org.gnubridge.core.deck.King; import org.gnubridge.core.deck.NoTrump; import org.gnubridge.core.deck.Queen; import org.gnubridge.core.deck.Spades; import org.gnubridge.core.deck.Ten; import org.gnubridge.core.deck.Three; import org.gnubridge.core.deck.Two;
package org.gnubridge.core; public class PlayerTest extends TestCase { public void testOnePlayerInitialization() { String[] westSpades = Card.FullSuit; String[] westHearts = {}; String[] westDiamonds = {}; String[] westClubs = {}; Player west = new Player(Direction.WEST_DEPRECATED); west.init(westSpades, westHearts, westDiamonds, westClubs); for (int i = 0; i < westSpades.length; i++) { assertTrue(west.hasUnplayedCard(new Card(westSpades[i], Spades.i()))); }
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Suit.java // public abstract class Suit extends Trump { // // //note, DO NOT USE statics from Trump here, ie SPADES instead of Spades.i() // public static final Suit[] list = { Spades.i(), Hearts.i(), Diamonds.i(), Clubs.i() }; // public static final Suit[] reverseList = { Clubs.i(), Diamonds.i(), Hearts.i(), Spades.i(), }; // public static final Suit[] mmList = { Hearts.i(), Spades.i(), Clubs.i(), Diamonds.i() }; // // public static int getIndex(Suit denomination) { // int result = -1; // for (Suit suit : reverseList) { // result++; // if (suit.equals(denomination)) { // break; // } // } // return result; // } // // @Override // public abstract String toDebugString(); // // public boolean isLowerRankThan(Trump other) { // if (other.isNoTrump()) { // return true; // } // return getIndex(this) < getIndex(other.asSuit()); // } // // public static Suit get(String s) { // if ("S".equals(s)) { // return Spades.i(); // } else if ("H".equals(s)) { // return Hearts.i(); // } else if ("D".equals(s)) { // return Diamonds.i(); // } else if ("C".equals(s)) { // return Clubs.i(); // } else { // throw new RuntimeException("do not know how to translate string '" + s // + "' to a suit (need one of: S,H,D,C)"); // } // } // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/NoTrump.java // public class NoTrump extends Trump { // // private static NoTrump instance = new NoTrump(); // // private NoTrump() { // super(); // } // // public static NoTrump i() { // return instance ; // } // // @Override // public String toString() { // return "NT"; // } // // @Override // public String toDebugString() { // return "NoTrump.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Queen.java // public class Queen { // public static Card of(Suit denomination) { // return new Card("Q", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("Q"); // } // } // // Path: src/main/java/org/gnubridge/core/deck/Ten.java // public class Ten { // public static Card of(Suit denomination) { // return new Card("10", denomination); // } // } // Path: src/test/java/org/gnubridge/core/PlayerTest.java import java.util.List; import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Suit; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.Jack; import org.gnubridge.core.deck.King; import org.gnubridge.core.deck.NoTrump; import org.gnubridge.core.deck.Queen; import org.gnubridge.core.deck.Spades; import org.gnubridge.core.deck.Ten; import org.gnubridge.core.deck.Three; import org.gnubridge.core.deck.Two; package org.gnubridge.core; public class PlayerTest extends TestCase { public void testOnePlayerInitialization() { String[] westSpades = Card.FullSuit; String[] westHearts = {}; String[] westDiamonds = {}; String[] westClubs = {}; Player west = new Player(Direction.WEST_DEPRECATED); west.init(westSpades, westHearts, westDiamonds, westClubs); for (int i = 0; i < westSpades.length; i++) { assertTrue(west.hasUnplayedCard(new Card(westSpades[i], Spades.i()))); }
for (int j = 1; j < Suit.list.length; j++) {
AlexanderMisel/gnubridge
src/test/java/org/gnubridge/core/PlayerTest.java
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Suit.java // public abstract class Suit extends Trump { // // //note, DO NOT USE statics from Trump here, ie SPADES instead of Spades.i() // public static final Suit[] list = { Spades.i(), Hearts.i(), Diamonds.i(), Clubs.i() }; // public static final Suit[] reverseList = { Clubs.i(), Diamonds.i(), Hearts.i(), Spades.i(), }; // public static final Suit[] mmList = { Hearts.i(), Spades.i(), Clubs.i(), Diamonds.i() }; // // public static int getIndex(Suit denomination) { // int result = -1; // for (Suit suit : reverseList) { // result++; // if (suit.equals(denomination)) { // break; // } // } // return result; // } // // @Override // public abstract String toDebugString(); // // public boolean isLowerRankThan(Trump other) { // if (other.isNoTrump()) { // return true; // } // return getIndex(this) < getIndex(other.asSuit()); // } // // public static Suit get(String s) { // if ("S".equals(s)) { // return Spades.i(); // } else if ("H".equals(s)) { // return Hearts.i(); // } else if ("D".equals(s)) { // return Diamonds.i(); // } else if ("C".equals(s)) { // return Clubs.i(); // } else { // throw new RuntimeException("do not know how to translate string '" + s // + "' to a suit (need one of: S,H,D,C)"); // } // } // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/NoTrump.java // public class NoTrump extends Trump { // // private static NoTrump instance = new NoTrump(); // // private NoTrump() { // super(); // } // // public static NoTrump i() { // return instance ; // } // // @Override // public String toString() { // return "NT"; // } // // @Override // public String toDebugString() { // return "NoTrump.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Queen.java // public class Queen { // public static Card of(Suit denomination) { // return new Card("Q", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("Q"); // } // } // // Path: src/main/java/org/gnubridge/core/deck/Ten.java // public class Ten { // public static Card of(Suit denomination) { // return new Card("10", denomination); // } // }
import java.util.List; import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Suit; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.Jack; import org.gnubridge.core.deck.King; import org.gnubridge.core.deck.NoTrump; import org.gnubridge.core.deck.Queen; import org.gnubridge.core.deck.Spades; import org.gnubridge.core.deck.Ten; import org.gnubridge.core.deck.Three; import org.gnubridge.core.deck.Two;
for (int i = 0; i < westSpades.length; i++) { assertTrue(west.hasUnplayedCard(new Card(westSpades[i], Spades.i()))); } for (int j = 1; j < Suit.list.length; j++) { for (int i = 0; i < Card.FullSuit.length; i++) { assertFalse(west.hasUnplayedCard(new Card(Card.FullSuit[i], Suit.list[j]))); } } } public void testInitializationNotByReference() { String[] westSpades = { "2" }; String[] westHearts = {}; String[] westDiamonds = {}; String[] westClubs = {}; Player west = new Player(Direction.WEST_DEPRECATED); west.init(westSpades, westHearts, westDiamonds, westClubs); westSpades[0] = "3"; assertFalse(west.hasUnplayedCard(new Card("3", Spades.i()))); } public void testGetLegalMovesHasMatchingColor() { String[] westSpades = { "2", "3", "A" }; String[] westHearts = { "J", "Q" }; String[] westDiamonds = {}; String[] westClubs = { "10", "K" }; Player west = new Player(Direction.WEST_DEPRECATED); west.init(westSpades, westHearts, westDiamonds, westClubs);
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Suit.java // public abstract class Suit extends Trump { // // //note, DO NOT USE statics from Trump here, ie SPADES instead of Spades.i() // public static final Suit[] list = { Spades.i(), Hearts.i(), Diamonds.i(), Clubs.i() }; // public static final Suit[] reverseList = { Clubs.i(), Diamonds.i(), Hearts.i(), Spades.i(), }; // public static final Suit[] mmList = { Hearts.i(), Spades.i(), Clubs.i(), Diamonds.i() }; // // public static int getIndex(Suit denomination) { // int result = -1; // for (Suit suit : reverseList) { // result++; // if (suit.equals(denomination)) { // break; // } // } // return result; // } // // @Override // public abstract String toDebugString(); // // public boolean isLowerRankThan(Trump other) { // if (other.isNoTrump()) { // return true; // } // return getIndex(this) < getIndex(other.asSuit()); // } // // public static Suit get(String s) { // if ("S".equals(s)) { // return Spades.i(); // } else if ("H".equals(s)) { // return Hearts.i(); // } else if ("D".equals(s)) { // return Diamonds.i(); // } else if ("C".equals(s)) { // return Clubs.i(); // } else { // throw new RuntimeException("do not know how to translate string '" + s // + "' to a suit (need one of: S,H,D,C)"); // } // } // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/NoTrump.java // public class NoTrump extends Trump { // // private static NoTrump instance = new NoTrump(); // // private NoTrump() { // super(); // } // // public static NoTrump i() { // return instance ; // } // // @Override // public String toString() { // return "NT"; // } // // @Override // public String toDebugString() { // return "NoTrump.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Queen.java // public class Queen { // public static Card of(Suit denomination) { // return new Card("Q", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("Q"); // } // } // // Path: src/main/java/org/gnubridge/core/deck/Ten.java // public class Ten { // public static Card of(Suit denomination) { // return new Card("10", denomination); // } // } // Path: src/test/java/org/gnubridge/core/PlayerTest.java import java.util.List; import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Suit; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.Jack; import org.gnubridge.core.deck.King; import org.gnubridge.core.deck.NoTrump; import org.gnubridge.core.deck.Queen; import org.gnubridge.core.deck.Spades; import org.gnubridge.core.deck.Ten; import org.gnubridge.core.deck.Three; import org.gnubridge.core.deck.Two; for (int i = 0; i < westSpades.length; i++) { assertTrue(west.hasUnplayedCard(new Card(westSpades[i], Spades.i()))); } for (int j = 1; j < Suit.list.length; j++) { for (int i = 0; i < Card.FullSuit.length; i++) { assertFalse(west.hasUnplayedCard(new Card(Card.FullSuit[i], Suit.list[j]))); } } } public void testInitializationNotByReference() { String[] westSpades = { "2" }; String[] westHearts = {}; String[] westDiamonds = {}; String[] westClubs = {}; Player west = new Player(Direction.WEST_DEPRECATED); west.init(westSpades, westHearts, westDiamonds, westClubs); westSpades[0] = "3"; assertFalse(west.hasUnplayedCard(new Card("3", Spades.i()))); } public void testGetLegalMovesHasMatchingColor() { String[] westSpades = { "2", "3", "A" }; String[] westHearts = { "J", "Q" }; String[] westDiamonds = {}; String[] westClubs = { "10", "K" }; Player west = new Player(Direction.WEST_DEPRECATED); west.init(westSpades, westHearts, westDiamonds, westClubs);
Trick trick = new Trick(NoTrump.i());
AlexanderMisel/gnubridge
src/test/java/org/gnubridge/core/PlayerTest.java
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Suit.java // public abstract class Suit extends Trump { // // //note, DO NOT USE statics from Trump here, ie SPADES instead of Spades.i() // public static final Suit[] list = { Spades.i(), Hearts.i(), Diamonds.i(), Clubs.i() }; // public static final Suit[] reverseList = { Clubs.i(), Diamonds.i(), Hearts.i(), Spades.i(), }; // public static final Suit[] mmList = { Hearts.i(), Spades.i(), Clubs.i(), Diamonds.i() }; // // public static int getIndex(Suit denomination) { // int result = -1; // for (Suit suit : reverseList) { // result++; // if (suit.equals(denomination)) { // break; // } // } // return result; // } // // @Override // public abstract String toDebugString(); // // public boolean isLowerRankThan(Trump other) { // if (other.isNoTrump()) { // return true; // } // return getIndex(this) < getIndex(other.asSuit()); // } // // public static Suit get(String s) { // if ("S".equals(s)) { // return Spades.i(); // } else if ("H".equals(s)) { // return Hearts.i(); // } else if ("D".equals(s)) { // return Diamonds.i(); // } else if ("C".equals(s)) { // return Clubs.i(); // } else { // throw new RuntimeException("do not know how to translate string '" + s // + "' to a suit (need one of: S,H,D,C)"); // } // } // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/NoTrump.java // public class NoTrump extends Trump { // // private static NoTrump instance = new NoTrump(); // // private NoTrump() { // super(); // } // // public static NoTrump i() { // return instance ; // } // // @Override // public String toString() { // return "NT"; // } // // @Override // public String toDebugString() { // return "NoTrump.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Queen.java // public class Queen { // public static Card of(Suit denomination) { // return new Card("Q", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("Q"); // } // } // // Path: src/main/java/org/gnubridge/core/deck/Ten.java // public class Ten { // public static Card of(Suit denomination) { // return new Card("10", denomination); // } // }
import java.util.List; import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Suit; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.Jack; import org.gnubridge.core.deck.King; import org.gnubridge.core.deck.NoTrump; import org.gnubridge.core.deck.Queen; import org.gnubridge.core.deck.Spades; import org.gnubridge.core.deck.Ten; import org.gnubridge.core.deck.Three; import org.gnubridge.core.deck.Two;
assertTrue(west.hasUnplayedCard(new Card(westSpades[i], Spades.i()))); } for (int j = 1; j < Suit.list.length; j++) { for (int i = 0; i < Card.FullSuit.length; i++) { assertFalse(west.hasUnplayedCard(new Card(Card.FullSuit[i], Suit.list[j]))); } } } public void testInitializationNotByReference() { String[] westSpades = { "2" }; String[] westHearts = {}; String[] westDiamonds = {}; String[] westClubs = {}; Player west = new Player(Direction.WEST_DEPRECATED); west.init(westSpades, westHearts, westDiamonds, westClubs); westSpades[0] = "3"; assertFalse(west.hasUnplayedCard(new Card("3", Spades.i()))); } public void testGetLegalMovesHasMatchingColor() { String[] westSpades = { "2", "3", "A" }; String[] westHearts = { "J", "Q" }; String[] westDiamonds = {}; String[] westClubs = { "10", "K" }; Player west = new Player(Direction.WEST_DEPRECATED); west.init(westSpades, westHearts, westDiamonds, westClubs); Trick trick = new Trick(NoTrump.i());
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Suit.java // public abstract class Suit extends Trump { // // //note, DO NOT USE statics from Trump here, ie SPADES instead of Spades.i() // public static final Suit[] list = { Spades.i(), Hearts.i(), Diamonds.i(), Clubs.i() }; // public static final Suit[] reverseList = { Clubs.i(), Diamonds.i(), Hearts.i(), Spades.i(), }; // public static final Suit[] mmList = { Hearts.i(), Spades.i(), Clubs.i(), Diamonds.i() }; // // public static int getIndex(Suit denomination) { // int result = -1; // for (Suit suit : reverseList) { // result++; // if (suit.equals(denomination)) { // break; // } // } // return result; // } // // @Override // public abstract String toDebugString(); // // public boolean isLowerRankThan(Trump other) { // if (other.isNoTrump()) { // return true; // } // return getIndex(this) < getIndex(other.asSuit()); // } // // public static Suit get(String s) { // if ("S".equals(s)) { // return Spades.i(); // } else if ("H".equals(s)) { // return Hearts.i(); // } else if ("D".equals(s)) { // return Diamonds.i(); // } else if ("C".equals(s)) { // return Clubs.i(); // } else { // throw new RuntimeException("do not know how to translate string '" + s // + "' to a suit (need one of: S,H,D,C)"); // } // } // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/NoTrump.java // public class NoTrump extends Trump { // // private static NoTrump instance = new NoTrump(); // // private NoTrump() { // super(); // } // // public static NoTrump i() { // return instance ; // } // // @Override // public String toString() { // return "NT"; // } // // @Override // public String toDebugString() { // return "NoTrump.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Queen.java // public class Queen { // public static Card of(Suit denomination) { // return new Card("Q", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("Q"); // } // } // // Path: src/main/java/org/gnubridge/core/deck/Ten.java // public class Ten { // public static Card of(Suit denomination) { // return new Card("10", denomination); // } // } // Path: src/test/java/org/gnubridge/core/PlayerTest.java import java.util.List; import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Suit; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.Jack; import org.gnubridge.core.deck.King; import org.gnubridge.core.deck.NoTrump; import org.gnubridge.core.deck.Queen; import org.gnubridge.core.deck.Spades; import org.gnubridge.core.deck.Ten; import org.gnubridge.core.deck.Three; import org.gnubridge.core.deck.Two; assertTrue(west.hasUnplayedCard(new Card(westSpades[i], Spades.i()))); } for (int j = 1; j < Suit.list.length; j++) { for (int i = 0; i < Card.FullSuit.length; i++) { assertFalse(west.hasUnplayedCard(new Card(Card.FullSuit[i], Suit.list[j]))); } } } public void testInitializationNotByReference() { String[] westSpades = { "2" }; String[] westHearts = {}; String[] westDiamonds = {}; String[] westClubs = {}; Player west = new Player(Direction.WEST_DEPRECATED); west.init(westSpades, westHearts, westDiamonds, westClubs); westSpades[0] = "3"; assertFalse(west.hasUnplayedCard(new Card("3", Spades.i()))); } public void testGetLegalMovesHasMatchingColor() { String[] westSpades = { "2", "3", "A" }; String[] westHearts = { "J", "Q" }; String[] westDiamonds = {}; String[] westClubs = { "10", "K" }; Player west = new Player(Direction.WEST_DEPRECATED); west.init(westSpades, westHearts, westDiamonds, westClubs); Trick trick = new Trick(NoTrump.i());
trick.addCard(Three.of(Hearts.i()), null);
AlexanderMisel/gnubridge
src/test/java/org/gnubridge/core/PlayerTest.java
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Suit.java // public abstract class Suit extends Trump { // // //note, DO NOT USE statics from Trump here, ie SPADES instead of Spades.i() // public static final Suit[] list = { Spades.i(), Hearts.i(), Diamonds.i(), Clubs.i() }; // public static final Suit[] reverseList = { Clubs.i(), Diamonds.i(), Hearts.i(), Spades.i(), }; // public static final Suit[] mmList = { Hearts.i(), Spades.i(), Clubs.i(), Diamonds.i() }; // // public static int getIndex(Suit denomination) { // int result = -1; // for (Suit suit : reverseList) { // result++; // if (suit.equals(denomination)) { // break; // } // } // return result; // } // // @Override // public abstract String toDebugString(); // // public boolean isLowerRankThan(Trump other) { // if (other.isNoTrump()) { // return true; // } // return getIndex(this) < getIndex(other.asSuit()); // } // // public static Suit get(String s) { // if ("S".equals(s)) { // return Spades.i(); // } else if ("H".equals(s)) { // return Hearts.i(); // } else if ("D".equals(s)) { // return Diamonds.i(); // } else if ("C".equals(s)) { // return Clubs.i(); // } else { // throw new RuntimeException("do not know how to translate string '" + s // + "' to a suit (need one of: S,H,D,C)"); // } // } // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/NoTrump.java // public class NoTrump extends Trump { // // private static NoTrump instance = new NoTrump(); // // private NoTrump() { // super(); // } // // public static NoTrump i() { // return instance ; // } // // @Override // public String toString() { // return "NT"; // } // // @Override // public String toDebugString() { // return "NoTrump.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Queen.java // public class Queen { // public static Card of(Suit denomination) { // return new Card("Q", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("Q"); // } // } // // Path: src/main/java/org/gnubridge/core/deck/Ten.java // public class Ten { // public static Card of(Suit denomination) { // return new Card("10", denomination); // } // }
import java.util.List; import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Suit; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.Jack; import org.gnubridge.core.deck.King; import org.gnubridge.core.deck.NoTrump; import org.gnubridge.core.deck.Queen; import org.gnubridge.core.deck.Spades; import org.gnubridge.core.deck.Ten; import org.gnubridge.core.deck.Three; import org.gnubridge.core.deck.Two;
} for (int j = 1; j < Suit.list.length; j++) { for (int i = 0; i < Card.FullSuit.length; i++) { assertFalse(west.hasUnplayedCard(new Card(Card.FullSuit[i], Suit.list[j]))); } } } public void testInitializationNotByReference() { String[] westSpades = { "2" }; String[] westHearts = {}; String[] westDiamonds = {}; String[] westClubs = {}; Player west = new Player(Direction.WEST_DEPRECATED); west.init(westSpades, westHearts, westDiamonds, westClubs); westSpades[0] = "3"; assertFalse(west.hasUnplayedCard(new Card("3", Spades.i()))); } public void testGetLegalMovesHasMatchingColor() { String[] westSpades = { "2", "3", "A" }; String[] westHearts = { "J", "Q" }; String[] westDiamonds = {}; String[] westClubs = { "10", "K" }; Player west = new Player(Direction.WEST_DEPRECATED); west.init(westSpades, westHearts, westDiamonds, westClubs); Trick trick = new Trick(NoTrump.i()); trick.addCard(Three.of(Hearts.i()), null);
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Suit.java // public abstract class Suit extends Trump { // // //note, DO NOT USE statics from Trump here, ie SPADES instead of Spades.i() // public static final Suit[] list = { Spades.i(), Hearts.i(), Diamonds.i(), Clubs.i() }; // public static final Suit[] reverseList = { Clubs.i(), Diamonds.i(), Hearts.i(), Spades.i(), }; // public static final Suit[] mmList = { Hearts.i(), Spades.i(), Clubs.i(), Diamonds.i() }; // // public static int getIndex(Suit denomination) { // int result = -1; // for (Suit suit : reverseList) { // result++; // if (suit.equals(denomination)) { // break; // } // } // return result; // } // // @Override // public abstract String toDebugString(); // // public boolean isLowerRankThan(Trump other) { // if (other.isNoTrump()) { // return true; // } // return getIndex(this) < getIndex(other.asSuit()); // } // // public static Suit get(String s) { // if ("S".equals(s)) { // return Spades.i(); // } else if ("H".equals(s)) { // return Hearts.i(); // } else if ("D".equals(s)) { // return Diamonds.i(); // } else if ("C".equals(s)) { // return Clubs.i(); // } else { // throw new RuntimeException("do not know how to translate string '" + s // + "' to a suit (need one of: S,H,D,C)"); // } // } // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/NoTrump.java // public class NoTrump extends Trump { // // private static NoTrump instance = new NoTrump(); // // private NoTrump() { // super(); // } // // public static NoTrump i() { // return instance ; // } // // @Override // public String toString() { // return "NT"; // } // // @Override // public String toDebugString() { // return "NoTrump.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Queen.java // public class Queen { // public static Card of(Suit denomination) { // return new Card("Q", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("Q"); // } // } // // Path: src/main/java/org/gnubridge/core/deck/Ten.java // public class Ten { // public static Card of(Suit denomination) { // return new Card("10", denomination); // } // } // Path: src/test/java/org/gnubridge/core/PlayerTest.java import java.util.List; import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Suit; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.Jack; import org.gnubridge.core.deck.King; import org.gnubridge.core.deck.NoTrump; import org.gnubridge.core.deck.Queen; import org.gnubridge.core.deck.Spades; import org.gnubridge.core.deck.Ten; import org.gnubridge.core.deck.Three; import org.gnubridge.core.deck.Two; } for (int j = 1; j < Suit.list.length; j++) { for (int i = 0; i < Card.FullSuit.length; i++) { assertFalse(west.hasUnplayedCard(new Card(Card.FullSuit[i], Suit.list[j]))); } } } public void testInitializationNotByReference() { String[] westSpades = { "2" }; String[] westHearts = {}; String[] westDiamonds = {}; String[] westClubs = {}; Player west = new Player(Direction.WEST_DEPRECATED); west.init(westSpades, westHearts, westDiamonds, westClubs); westSpades[0] = "3"; assertFalse(west.hasUnplayedCard(new Card("3", Spades.i()))); } public void testGetLegalMovesHasMatchingColor() { String[] westSpades = { "2", "3", "A" }; String[] westHearts = { "J", "Q" }; String[] westDiamonds = {}; String[] westClubs = { "10", "K" }; Player west = new Player(Direction.WEST_DEPRECATED); west.init(westSpades, westHearts, westDiamonds, westClubs); Trick trick = new Trick(NoTrump.i()); trick.addCard(Three.of(Hearts.i()), null);
trick.addCard(Ace.of(Clubs.i()), null);
AlexanderMisel/gnubridge
src/test/java/org/gnubridge/core/PlayerTest.java
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Suit.java // public abstract class Suit extends Trump { // // //note, DO NOT USE statics from Trump here, ie SPADES instead of Spades.i() // public static final Suit[] list = { Spades.i(), Hearts.i(), Diamonds.i(), Clubs.i() }; // public static final Suit[] reverseList = { Clubs.i(), Diamonds.i(), Hearts.i(), Spades.i(), }; // public static final Suit[] mmList = { Hearts.i(), Spades.i(), Clubs.i(), Diamonds.i() }; // // public static int getIndex(Suit denomination) { // int result = -1; // for (Suit suit : reverseList) { // result++; // if (suit.equals(denomination)) { // break; // } // } // return result; // } // // @Override // public abstract String toDebugString(); // // public boolean isLowerRankThan(Trump other) { // if (other.isNoTrump()) { // return true; // } // return getIndex(this) < getIndex(other.asSuit()); // } // // public static Suit get(String s) { // if ("S".equals(s)) { // return Spades.i(); // } else if ("H".equals(s)) { // return Hearts.i(); // } else if ("D".equals(s)) { // return Diamonds.i(); // } else if ("C".equals(s)) { // return Clubs.i(); // } else { // throw new RuntimeException("do not know how to translate string '" + s // + "' to a suit (need one of: S,H,D,C)"); // } // } // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/NoTrump.java // public class NoTrump extends Trump { // // private static NoTrump instance = new NoTrump(); // // private NoTrump() { // super(); // } // // public static NoTrump i() { // return instance ; // } // // @Override // public String toString() { // return "NT"; // } // // @Override // public String toDebugString() { // return "NoTrump.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Queen.java // public class Queen { // public static Card of(Suit denomination) { // return new Card("Q", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("Q"); // } // } // // Path: src/main/java/org/gnubridge/core/deck/Ten.java // public class Ten { // public static Card of(Suit denomination) { // return new Card("10", denomination); // } // }
import java.util.List; import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Suit; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.Jack; import org.gnubridge.core.deck.King; import org.gnubridge.core.deck.NoTrump; import org.gnubridge.core.deck.Queen; import org.gnubridge.core.deck.Spades; import org.gnubridge.core.deck.Ten; import org.gnubridge.core.deck.Three; import org.gnubridge.core.deck.Two;
assertFalse(west.hasUnplayedCard(new Card(Card.FullSuit[i], Suit.list[j]))); } } } public void testInitializationNotByReference() { String[] westSpades = { "2" }; String[] westHearts = {}; String[] westDiamonds = {}; String[] westClubs = {}; Player west = new Player(Direction.WEST_DEPRECATED); west.init(westSpades, westHearts, westDiamonds, westClubs); westSpades[0] = "3"; assertFalse(west.hasUnplayedCard(new Card("3", Spades.i()))); } public void testGetLegalMovesHasMatchingColor() { String[] westSpades = { "2", "3", "A" }; String[] westHearts = { "J", "Q" }; String[] westDiamonds = {}; String[] westClubs = { "10", "K" }; Player west = new Player(Direction.WEST_DEPRECATED); west.init(westSpades, westHearts, westDiamonds, westClubs); Trick trick = new Trick(NoTrump.i()); trick.addCard(Three.of(Hearts.i()), null); trick.addCard(Ace.of(Clubs.i()), null); List<Card> moves = west.getPossibleMoves(trick); assertEquals(2, moves.size()); assertEquals(Jack.of(Hearts.i()), moves.get(0));
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Suit.java // public abstract class Suit extends Trump { // // //note, DO NOT USE statics from Trump here, ie SPADES instead of Spades.i() // public static final Suit[] list = { Spades.i(), Hearts.i(), Diamonds.i(), Clubs.i() }; // public static final Suit[] reverseList = { Clubs.i(), Diamonds.i(), Hearts.i(), Spades.i(), }; // public static final Suit[] mmList = { Hearts.i(), Spades.i(), Clubs.i(), Diamonds.i() }; // // public static int getIndex(Suit denomination) { // int result = -1; // for (Suit suit : reverseList) { // result++; // if (suit.equals(denomination)) { // break; // } // } // return result; // } // // @Override // public abstract String toDebugString(); // // public boolean isLowerRankThan(Trump other) { // if (other.isNoTrump()) { // return true; // } // return getIndex(this) < getIndex(other.asSuit()); // } // // public static Suit get(String s) { // if ("S".equals(s)) { // return Spades.i(); // } else if ("H".equals(s)) { // return Hearts.i(); // } else if ("D".equals(s)) { // return Diamonds.i(); // } else if ("C".equals(s)) { // return Clubs.i(); // } else { // throw new RuntimeException("do not know how to translate string '" + s // + "' to a suit (need one of: S,H,D,C)"); // } // } // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/NoTrump.java // public class NoTrump extends Trump { // // private static NoTrump instance = new NoTrump(); // // private NoTrump() { // super(); // } // // public static NoTrump i() { // return instance ; // } // // @Override // public String toString() { // return "NT"; // } // // @Override // public String toDebugString() { // return "NoTrump.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Queen.java // public class Queen { // public static Card of(Suit denomination) { // return new Card("Q", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("Q"); // } // } // // Path: src/main/java/org/gnubridge/core/deck/Ten.java // public class Ten { // public static Card of(Suit denomination) { // return new Card("10", denomination); // } // } // Path: src/test/java/org/gnubridge/core/PlayerTest.java import java.util.List; import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Suit; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.Jack; import org.gnubridge.core.deck.King; import org.gnubridge.core.deck.NoTrump; import org.gnubridge.core.deck.Queen; import org.gnubridge.core.deck.Spades; import org.gnubridge.core.deck.Ten; import org.gnubridge.core.deck.Three; import org.gnubridge.core.deck.Two; assertFalse(west.hasUnplayedCard(new Card(Card.FullSuit[i], Suit.list[j]))); } } } public void testInitializationNotByReference() { String[] westSpades = { "2" }; String[] westHearts = {}; String[] westDiamonds = {}; String[] westClubs = {}; Player west = new Player(Direction.WEST_DEPRECATED); west.init(westSpades, westHearts, westDiamonds, westClubs); westSpades[0] = "3"; assertFalse(west.hasUnplayedCard(new Card("3", Spades.i()))); } public void testGetLegalMovesHasMatchingColor() { String[] westSpades = { "2", "3", "A" }; String[] westHearts = { "J", "Q" }; String[] westDiamonds = {}; String[] westClubs = { "10", "K" }; Player west = new Player(Direction.WEST_DEPRECATED); west.init(westSpades, westHearts, westDiamonds, westClubs); Trick trick = new Trick(NoTrump.i()); trick.addCard(Three.of(Hearts.i()), null); trick.addCard(Ace.of(Clubs.i()), null); List<Card> moves = west.getPossibleMoves(trick); assertEquals(2, moves.size()); assertEquals(Jack.of(Hearts.i()), moves.get(0));
assertEquals(Queen.of(Hearts.i()), moves.get(1));
AlexanderMisel/gnubridge
src/test/java/org/gnubridge/core/PlayerTest.java
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Suit.java // public abstract class Suit extends Trump { // // //note, DO NOT USE statics from Trump here, ie SPADES instead of Spades.i() // public static final Suit[] list = { Spades.i(), Hearts.i(), Diamonds.i(), Clubs.i() }; // public static final Suit[] reverseList = { Clubs.i(), Diamonds.i(), Hearts.i(), Spades.i(), }; // public static final Suit[] mmList = { Hearts.i(), Spades.i(), Clubs.i(), Diamonds.i() }; // // public static int getIndex(Suit denomination) { // int result = -1; // for (Suit suit : reverseList) { // result++; // if (suit.equals(denomination)) { // break; // } // } // return result; // } // // @Override // public abstract String toDebugString(); // // public boolean isLowerRankThan(Trump other) { // if (other.isNoTrump()) { // return true; // } // return getIndex(this) < getIndex(other.asSuit()); // } // // public static Suit get(String s) { // if ("S".equals(s)) { // return Spades.i(); // } else if ("H".equals(s)) { // return Hearts.i(); // } else if ("D".equals(s)) { // return Diamonds.i(); // } else if ("C".equals(s)) { // return Clubs.i(); // } else { // throw new RuntimeException("do not know how to translate string '" + s // + "' to a suit (need one of: S,H,D,C)"); // } // } // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/NoTrump.java // public class NoTrump extends Trump { // // private static NoTrump instance = new NoTrump(); // // private NoTrump() { // super(); // } // // public static NoTrump i() { // return instance ; // } // // @Override // public String toString() { // return "NT"; // } // // @Override // public String toDebugString() { // return "NoTrump.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Queen.java // public class Queen { // public static Card of(Suit denomination) { // return new Card("Q", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("Q"); // } // } // // Path: src/main/java/org/gnubridge/core/deck/Ten.java // public class Ten { // public static Card of(Suit denomination) { // return new Card("10", denomination); // } // }
import java.util.List; import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Suit; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.Jack; import org.gnubridge.core.deck.King; import org.gnubridge.core.deck.NoTrump; import org.gnubridge.core.deck.Queen; import org.gnubridge.core.deck.Spades; import org.gnubridge.core.deck.Ten; import org.gnubridge.core.deck.Three; import org.gnubridge.core.deck.Two;
String[] westClubs = { "10", "K" }; Player west = new Player(Direction.WEST_DEPRECATED); west.init(westSpades, westHearts, westDiamonds, westClubs); Trick trick = new Trick(NoTrump.i()); trick.addCard(Three.of(Hearts.i()), null); trick.addCard(Ace.of(Clubs.i()), null); List<Card> moves = west.getPossibleMoves(trick); assertEquals(2, moves.size()); assertEquals(Jack.of(Hearts.i()), moves.get(0)); assertEquals(Queen.of(Hearts.i()), moves.get(1)); } public void testGetLegalMovesNoMatchingColor() { String[] westSpades = { "2", "3", "A" }; String[] westHearts = { "J", "Q" }; String[] westDiamonds = {}; String[] westClubs = { "10", "K" }; Player west = new Player(Direction.WEST_DEPRECATED); west.init(westSpades, westHearts, westDiamonds, westClubs); Trick trick = new Trick(NoTrump.i()); trick.addCard(Three.of(Diamonds.i()), null); trick.addCard(Ace.of(Clubs.i()), null); List<Card> moves = west.getPossibleMoves(trick); assertEquals(7, moves.size()); assertTrue(moves.contains(Two.of(Spades.i()))); assertTrue(moves.contains(Three.of(Spades.i()))); assertTrue(moves.contains(Ace.of(Spades.i()))); assertTrue(moves.contains(Jack.of(Hearts.i()))); assertTrue(moves.contains(Queen.of(Hearts.i())));
// Path: src/main/java/org/gnubridge/core/deck/Ace.java // public class Ace { // public static Card of(Suit denomination) { // return new Card("A", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("A"); // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Suit.java // public abstract class Suit extends Trump { // // //note, DO NOT USE statics from Trump here, ie SPADES instead of Spades.i() // public static final Suit[] list = { Spades.i(), Hearts.i(), Diamonds.i(), Clubs.i() }; // public static final Suit[] reverseList = { Clubs.i(), Diamonds.i(), Hearts.i(), Spades.i(), }; // public static final Suit[] mmList = { Hearts.i(), Spades.i(), Clubs.i(), Diamonds.i() }; // // public static int getIndex(Suit denomination) { // int result = -1; // for (Suit suit : reverseList) { // result++; // if (suit.equals(denomination)) { // break; // } // } // return result; // } // // @Override // public abstract String toDebugString(); // // public boolean isLowerRankThan(Trump other) { // if (other.isNoTrump()) { // return true; // } // return getIndex(this) < getIndex(other.asSuit()); // } // // public static Suit get(String s) { // if ("S".equals(s)) { // return Spades.i(); // } else if ("H".equals(s)) { // return Hearts.i(); // } else if ("D".equals(s)) { // return Diamonds.i(); // } else if ("C".equals(s)) { // return Clubs.i(); // } else { // throw new RuntimeException("do not know how to translate string '" + s // + "' to a suit (need one of: S,H,D,C)"); // } // } // } // // Path: src/main/java/org/gnubridge/core/deck/Hearts.java // public class Hearts extends Suit { // // private static Hearts instance; // // private Hearts() { // super(); // } // // public static Hearts i() { // if (instance == null) { // instance = new Hearts(); // } // return instance ; // } // // @Override // public String toString() { // return "HEARTS"; // } // // @Override // public String toDebugString() { // return "Hearts.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/NoTrump.java // public class NoTrump extends Trump { // // private static NoTrump instance = new NoTrump(); // // private NoTrump() { // super(); // } // // public static NoTrump i() { // return instance ; // } // // @Override // public String toString() { // return "NT"; // } // // @Override // public String toDebugString() { // return "NoTrump.i()"; // } // // } // // Path: src/main/java/org/gnubridge/core/deck/Queen.java // public class Queen { // public static Card of(Suit denomination) { // return new Card("Q", denomination); // } // // public static boolean isValueOf(Card card) { // return card.getValue() == Card.strToIntValue("Q"); // } // } // // Path: src/main/java/org/gnubridge/core/deck/Ten.java // public class Ten { // public static Card of(Suit denomination) { // return new Card("10", denomination); // } // } // Path: src/test/java/org/gnubridge/core/PlayerTest.java import java.util.List; import junit.framework.TestCase; import org.gnubridge.core.deck.Ace; import org.gnubridge.core.deck.Clubs; import org.gnubridge.core.deck.Suit; import org.gnubridge.core.deck.Diamonds; import org.gnubridge.core.deck.Hearts; import org.gnubridge.core.deck.Jack; import org.gnubridge.core.deck.King; import org.gnubridge.core.deck.NoTrump; import org.gnubridge.core.deck.Queen; import org.gnubridge.core.deck.Spades; import org.gnubridge.core.deck.Ten; import org.gnubridge.core.deck.Three; import org.gnubridge.core.deck.Two; String[] westClubs = { "10", "K" }; Player west = new Player(Direction.WEST_DEPRECATED); west.init(westSpades, westHearts, westDiamonds, westClubs); Trick trick = new Trick(NoTrump.i()); trick.addCard(Three.of(Hearts.i()), null); trick.addCard(Ace.of(Clubs.i()), null); List<Card> moves = west.getPossibleMoves(trick); assertEquals(2, moves.size()); assertEquals(Jack.of(Hearts.i()), moves.get(0)); assertEquals(Queen.of(Hearts.i()), moves.get(1)); } public void testGetLegalMovesNoMatchingColor() { String[] westSpades = { "2", "3", "A" }; String[] westHearts = { "J", "Q" }; String[] westDiamonds = {}; String[] westClubs = { "10", "K" }; Player west = new Player(Direction.WEST_DEPRECATED); west.init(westSpades, westHearts, westDiamonds, westClubs); Trick trick = new Trick(NoTrump.i()); trick.addCard(Three.of(Diamonds.i()), null); trick.addCard(Ace.of(Clubs.i()), null); List<Card> moves = west.getPossibleMoves(trick); assertEquals(7, moves.size()); assertTrue(moves.contains(Two.of(Spades.i()))); assertTrue(moves.contains(Three.of(Spades.i()))); assertTrue(moves.contains(Ace.of(Spades.i()))); assertTrue(moves.contains(Jack.of(Hearts.i()))); assertTrue(moves.contains(Queen.of(Hearts.i())));
assertTrue(moves.contains(Ten.of(Clubs.i())));
AlexanderMisel/gnubridge
src/test/java/org/gnubridge/search/DoubleDummySolverDeepAlphaBetaPruningTest.java
// Path: src/main/java/org/gnubridge/core/Player.java // public class Player { // // public static final int WEST_EAST = 0; // public static final int NORTH_SOUTH = 1; // // private final int direction; // // private final List<Card> hand; // // private final List<Card> played; // // private final List<Trick> tricks; // // public Player(int i) { // hand = new LinkedList<Card>(); // played = new ArrayList<Card>(); // tricks = new ArrayList<Trick>(); // direction = i; // } // // public Player(Direction d) { // this(d.getValue()); // } // // // public void hand(String... suits) { // init(new Hand(suits).getCardsHighToLow()); // // } // // public void init(String[]... valueSuits) { // for (int i = 0; i < valueSuits.length; i++) { // String[] values = valueSuits[i]; // for (int j = 0; j < values.length; j++) { // hand.add(new Card(values[j], Suit.list[i])); // // } // } // // } // // @Override // public String toString() { // return getDirection2().toString(); // // } // // public void init(Card... cards) { // for (int i = 0; i < cards.length; i++) { // hand.add(cards[i]); // } // // } // // public void init(List<Card> cards) { // for (Card card : cards) { // hand.add(card); // } // // } // // public void init(Player other) { // init(other.getHand()); // for (Card card : other.getPlayedCards()) { // played.add(card); // } // } // // private List<Card> getPlayedCards() { // return played; // } // // public boolean hasUnplayedCard(Card c) { // return contains(hand, c); // // } // // private boolean contains(List<Card> list, Card c) { // for (Card current : list) { // if (current.equals(c)) { // return true; // } // } // return false; // } // // public int getUnplayedCardsCount() { // return hand.size(); // } // // public int getDirection() { // return direction; // } // // public boolean hasPlayedCard(Card c) { // return contains(played, c); // } // // public int countTricksTaken() { // return tricks.size(); // } // // public void addTrickTaken(Trick trick) { // tricks.add(trick); // // } // // public List<Card> getPossibleMoves(Trick trick) { // List<Card> matching = new ArrayList<Card>(); // for (Card card : hand) { // if (card.getDenomination().equals(trick.getDenomination())) { // matching.add(card); // } // } // if (matching.size() == 0) { // return hand; // } else { // return matching; // } // } // // public void play(Card c) { // played.add(c); // hand.remove(hand.indexOf(c)); // } // // public List<Card> getHand() { // return hand; // } // // public int pair() { // return matchPair(direction); // } // // public static int matchPair(int player) { // int result; // switch (player) { // case Direction.WEST_DEPRECATED: // case Direction.EAST_DEPRECATED: // result = Player.WEST_EAST; // break; // case Direction.NORTH_DEPRECATED: // case Direction.SOUTH_DEPRECATED: // result = Player.NORTH_SOUTH; // break; // default: // throw new RuntimeException("Unknown player: " + player); // } // return result; // } // // public int otherPair() { // return matchPair((direction + 1) % 4); // } // // public Direction getDirection2() { // return Direction.instance(direction); // } // // public void init(Hand aHand) { // init(aHand.cards); // // } // // public boolean isPartnerWith(Player other) { // return pair() == other.pair(); // // } // // }
import junit.framework.TestCase; import org.gnubridge.core.Direction; import org.gnubridge.core.Player;
package org.gnubridge.search; public class DoubleDummySolverDeepAlphaBetaPruningTest extends TestCase { public void testAllTestsTemporarilyDisabled() { assertTrue(true); } /** * root W * \ * 00 W * / \ * (2 ) 0 1 W * / \ * 1_0 1_1 N <- prune alpha * / \ * (0 ) 1_1_0 1_1_1 W */ public void zzztestDeepAlphaPrune1() { Node root = new Node(null, Direction.WEST_DEPRECATED); Node node_00 = new Node(root, Direction.WEST_DEPRECATED); Node node_0 = new Node(node_00, Direction.NORTH_DEPRECATED);
// Path: src/main/java/org/gnubridge/core/Player.java // public class Player { // // public static final int WEST_EAST = 0; // public static final int NORTH_SOUTH = 1; // // private final int direction; // // private final List<Card> hand; // // private final List<Card> played; // // private final List<Trick> tricks; // // public Player(int i) { // hand = new LinkedList<Card>(); // played = new ArrayList<Card>(); // tricks = new ArrayList<Trick>(); // direction = i; // } // // public Player(Direction d) { // this(d.getValue()); // } // // // public void hand(String... suits) { // init(new Hand(suits).getCardsHighToLow()); // // } // // public void init(String[]... valueSuits) { // for (int i = 0; i < valueSuits.length; i++) { // String[] values = valueSuits[i]; // for (int j = 0; j < values.length; j++) { // hand.add(new Card(values[j], Suit.list[i])); // // } // } // // } // // @Override // public String toString() { // return getDirection2().toString(); // // } // // public void init(Card... cards) { // for (int i = 0; i < cards.length; i++) { // hand.add(cards[i]); // } // // } // // public void init(List<Card> cards) { // for (Card card : cards) { // hand.add(card); // } // // } // // public void init(Player other) { // init(other.getHand()); // for (Card card : other.getPlayedCards()) { // played.add(card); // } // } // // private List<Card> getPlayedCards() { // return played; // } // // public boolean hasUnplayedCard(Card c) { // return contains(hand, c); // // } // // private boolean contains(List<Card> list, Card c) { // for (Card current : list) { // if (current.equals(c)) { // return true; // } // } // return false; // } // // public int getUnplayedCardsCount() { // return hand.size(); // } // // public int getDirection() { // return direction; // } // // public boolean hasPlayedCard(Card c) { // return contains(played, c); // } // // public int countTricksTaken() { // return tricks.size(); // } // // public void addTrickTaken(Trick trick) { // tricks.add(trick); // // } // // public List<Card> getPossibleMoves(Trick trick) { // List<Card> matching = new ArrayList<Card>(); // for (Card card : hand) { // if (card.getDenomination().equals(trick.getDenomination())) { // matching.add(card); // } // } // if (matching.size() == 0) { // return hand; // } else { // return matching; // } // } // // public void play(Card c) { // played.add(c); // hand.remove(hand.indexOf(c)); // } // // public List<Card> getHand() { // return hand; // } // // public int pair() { // return matchPair(direction); // } // // public static int matchPair(int player) { // int result; // switch (player) { // case Direction.WEST_DEPRECATED: // case Direction.EAST_DEPRECATED: // result = Player.WEST_EAST; // break; // case Direction.NORTH_DEPRECATED: // case Direction.SOUTH_DEPRECATED: // result = Player.NORTH_SOUTH; // break; // default: // throw new RuntimeException("Unknown player: " + player); // } // return result; // } // // public int otherPair() { // return matchPair((direction + 1) % 4); // } // // public Direction getDirection2() { // return Direction.instance(direction); // } // // public void init(Hand aHand) { // init(aHand.cards); // // } // // public boolean isPartnerWith(Player other) { // return pair() == other.pair(); // // } // // } // Path: src/test/java/org/gnubridge/search/DoubleDummySolverDeepAlphaBetaPruningTest.java import junit.framework.TestCase; import org.gnubridge.core.Direction; import org.gnubridge.core.Player; package org.gnubridge.search; public class DoubleDummySolverDeepAlphaBetaPruningTest extends TestCase { public void testAllTestsTemporarilyDisabled() { assertTrue(true); } /** * root W * \ * 00 W * / \ * (2 ) 0 1 W * / \ * 1_0 1_1 N <- prune alpha * / \ * (0 ) 1_1_0 1_1_1 W */ public void zzztestDeepAlphaPrune1() { Node root = new Node(null, Direction.WEST_DEPRECATED); Node node_00 = new Node(root, Direction.WEST_DEPRECATED); Node node_0 = new Node(node_00, Direction.NORTH_DEPRECATED);
node_0.setTricksTaken(Player.WEST_EAST, 2);
baby2431/renovate2
rx-renovate/src/main/java/renovate/rxjava/subscribe/BodyOnSubscribe.java
// Path: renovate/src/main/java/renovate/HttpException.java // public class HttpException extends RuntimeException { // private static String getMessage(Response<?> response) { // checkNotNull(response, "response == null"); // return "HTTP " + response.code() + " " + response.message(); // } // // private final int code; // private final String message; // private final transient Response<?> response; // // public HttpException(Response<?> response) { // super(getMessage(response)); // this.code = response.code(); // this.message = response.message(); // this.response = response; // } // // /** HTTP status code. */ // public int code() { // return code; // } // // /** HTTP status message. */ // public String message() { // return message; // } // // /** // * The full HTTP response. This may be null if the exception was serialized. // */ // public Response<?> response() { // return response; // } // } // // Path: renovate/src/main/java/renovate/Response.java // public final class Response<T> { // private final okhttp3.Response rawResponse; // private final T body; // private final ResponseBody errorBody; // // private Response(okhttp3.Response rawResponse, T body, ResponseBody errorBody) { // this.rawResponse = rawResponse; // this.body = body; // this.errorBody = errorBody; // } // // public static <T> Response<T> success(T body) { // return success(body, new okhttp3.Response.Builder() // // .code(200) // .message("OK") // .protocol(Protocol.HTTP_1_1) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> success(T body, Headers headers) { // if (headers == null) throw new NullPointerException("headers == null"); // return success(body, new okhttp3.Response.Builder() // // .code(200) // .message("OK") // .protocol(Protocol.HTTP_1_1) // .headers(headers) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> success(T body, okhttp3.Response rawResponse) { // if (rawResponse == null) throw new NullPointerException("rawResponse == null"); // if (!rawResponse.isSuccessful()) { // throw new IllegalArgumentException("rawResponse must be successful response"); // } // return new Response<>(rawResponse, body, null); // } // // public static <T> Response<T> error(int code, ResponseBody body) { // if (code < 400) throw new IllegalArgumentException("code < 400: " + code); // return error(body, new okhttp3.Response.Builder() // // .code(code) // .protocol(Protocol.HTTP_1_1) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> error(ResponseBody body, okhttp3.Response rawResponse) { // if (body == null) throw new NullPointerException("body == null"); // if (rawResponse == null) throw new NullPointerException("rawResponse == null"); // if (rawResponse.isSuccessful()) { // throw new IllegalArgumentException("rawResponse should not be successful response"); // } // return new Response<>(rawResponse, null, body); // } // // public okhttp3.Response raw() { // return rawResponse; // } // // public int code() { // return rawResponse.code(); // } // // public String message() { // return rawResponse.message(); // } // // public Headers headers() { // return rawResponse.headers(); // } // // public boolean isSuccessful() { // return rawResponse.isSuccessful(); // } // // public T body() { // return body; // } // // public ResponseBody errorBody() { // return errorBody; // } // // @Override public String toString() { // return rawResponse.toString(); // } // }
import renovate.HttpException; import renovate.Response; import rx.Observable.OnSubscribe; import rx.Subscriber; import rx.exceptions.*; import rx.plugins.RxJavaHooks;
/* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava.subscribe; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:16/9/11 * 描 述: * 修订历史: * ================================================ */ public final class BodyOnSubscribe<T> implements OnSubscribe<T> { private final OnSubscribe<Response<T>> upstream; public BodyOnSubscribe(OnSubscribe<Response<T>> upstream) { this.upstream = upstream; } @Override public void call(Subscriber<? super T> subscriber) { upstream.call(new BodySubscriber<>(subscriber)); } private static class BodySubscriber<R> extends Subscriber<Response<R>> { private final Subscriber<? super R> subscriber; private boolean subscriberTerminated; BodySubscriber(Subscriber<? super R> subscriber) { super(subscriber); this.subscriber = subscriber; } @Override public void onNext(Response<R> response) { if (response.isSuccessful()) { subscriber.onNext(response.body()); } else { subscriberTerminated = true;
// Path: renovate/src/main/java/renovate/HttpException.java // public class HttpException extends RuntimeException { // private static String getMessage(Response<?> response) { // checkNotNull(response, "response == null"); // return "HTTP " + response.code() + " " + response.message(); // } // // private final int code; // private final String message; // private final transient Response<?> response; // // public HttpException(Response<?> response) { // super(getMessage(response)); // this.code = response.code(); // this.message = response.message(); // this.response = response; // } // // /** HTTP status code. */ // public int code() { // return code; // } // // /** HTTP status message. */ // public String message() { // return message; // } // // /** // * The full HTTP response. This may be null if the exception was serialized. // */ // public Response<?> response() { // return response; // } // } // // Path: renovate/src/main/java/renovate/Response.java // public final class Response<T> { // private final okhttp3.Response rawResponse; // private final T body; // private final ResponseBody errorBody; // // private Response(okhttp3.Response rawResponse, T body, ResponseBody errorBody) { // this.rawResponse = rawResponse; // this.body = body; // this.errorBody = errorBody; // } // // public static <T> Response<T> success(T body) { // return success(body, new okhttp3.Response.Builder() // // .code(200) // .message("OK") // .protocol(Protocol.HTTP_1_1) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> success(T body, Headers headers) { // if (headers == null) throw new NullPointerException("headers == null"); // return success(body, new okhttp3.Response.Builder() // // .code(200) // .message("OK") // .protocol(Protocol.HTTP_1_1) // .headers(headers) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> success(T body, okhttp3.Response rawResponse) { // if (rawResponse == null) throw new NullPointerException("rawResponse == null"); // if (!rawResponse.isSuccessful()) { // throw new IllegalArgumentException("rawResponse must be successful response"); // } // return new Response<>(rawResponse, body, null); // } // // public static <T> Response<T> error(int code, ResponseBody body) { // if (code < 400) throw new IllegalArgumentException("code < 400: " + code); // return error(body, new okhttp3.Response.Builder() // // .code(code) // .protocol(Protocol.HTTP_1_1) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> error(ResponseBody body, okhttp3.Response rawResponse) { // if (body == null) throw new NullPointerException("body == null"); // if (rawResponse == null) throw new NullPointerException("rawResponse == null"); // if (rawResponse.isSuccessful()) { // throw new IllegalArgumentException("rawResponse should not be successful response"); // } // return new Response<>(rawResponse, null, body); // } // // public okhttp3.Response raw() { // return rawResponse; // } // // public int code() { // return rawResponse.code(); // } // // public String message() { // return rawResponse.message(); // } // // public Headers headers() { // return rawResponse.headers(); // } // // public boolean isSuccessful() { // return rawResponse.isSuccessful(); // } // // public T body() { // return body; // } // // public ResponseBody errorBody() { // return errorBody; // } // // @Override public String toString() { // return rawResponse.toString(); // } // } // Path: rx-renovate/src/main/java/renovate/rxjava/subscribe/BodyOnSubscribe.java import renovate.HttpException; import renovate.Response; import rx.Observable.OnSubscribe; import rx.Subscriber; import rx.exceptions.*; import rx.plugins.RxJavaHooks; /* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava.subscribe; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:16/9/11 * 描 述: * 修订历史: * ================================================ */ public final class BodyOnSubscribe<T> implements OnSubscribe<T> { private final OnSubscribe<Response<T>> upstream; public BodyOnSubscribe(OnSubscribe<Response<T>> upstream) { this.upstream = upstream; } @Override public void call(Subscriber<? super T> subscriber) { upstream.call(new BodySubscriber<>(subscriber)); } private static class BodySubscriber<R> extends Subscriber<Response<R>> { private final Subscriber<? super R> subscriber; private boolean subscriberTerminated; BodySubscriber(Subscriber<? super R> subscriber) { super(subscriber); this.subscriber = subscriber; } @Override public void onNext(Response<R> response) { if (response.isSuccessful()) { subscriber.onNext(response.body()); } else { subscriberTerminated = true;
Throwable t = new HttpException(response);
baby2431/renovate2
rx-renovate2/src/main/java/renovate/rxjava2/adapter/FlowableResult.java
// Path: renovate/src/main/java/renovate/AdapterParam.java // public class AdapterParam { // public boolean isAsync; // // public AdapterParam() { // isAsync = true; // } // } // // Path: renovate/src/main/java/renovate/Call.java // public interface Call<T> extends Cloneable { // Response<T> execute() throws IOException; // // void enqueue(Callback<T> callback); // // boolean isExecuted(); // // void cancel(); // // boolean isCanceled(); // // Call<T> clone(); // // Request request(); // } // // Path: renovate/src/main/java/renovate/CallAdapter.java // public interface CallAdapter<T, R> { // // /** call执行的代理方法 */ // R adapt(Call<T> call, AdapterParam param); // } // // Path: renovate/src/main/java/renovate/Result.java // public final class Result<T> { // @SuppressWarnings("ConstantConditions") // Guarding public API nullability. // public static <T> Result<T> error(Throwable error) { // if (error == null) throw new NullPointerException("error == null"); // return new Result<>(null, error); // } // // @SuppressWarnings("ConstantConditions") // Guarding public API nullability. // public static <T> Result<T> response(Response<T> response) { // if (response == null) throw new NullPointerException("response == null"); // return new Result<>(response, null); // } // // private final Response<T> response; // private final Throwable error; // // private Result(Response<T> response, Throwable error) { // this.response = response; // this.error = error; // } // // /** // * The response received from executing an HTTP request. Only present when {@link #isError()} is // * false, null otherwise. // */ // // public Response<T> response() { // return response; // } // // /** // * The error experienced while attempting to execute an HTTP request. Only present when {@link // * #isError()} is true, null otherwise. // * If the error is an {@link IOException} then there was a problem with the transport to the // * remote server. Any other exception type indicates an unexpected failure and should be // * considered fatal (configuration error, programming error, etc.). // */ // // public Throwable error() { // return error; // } // // /** {@code true} if the request resulted in an error. See {@link #error()} for the cause. */ // public boolean isError() { // return error != null; // } // // @Override // public String toString() { // if (error != null) { // return "Result{isError=true, error=\"" + error + "\"}"; // } // return "Result{isError=false, response=" + response + '}'; // } // }
import io.reactivex.BackpressureStrategy; import io.reactivex.Flowable; import renovate.AdapterParam; import renovate.Call; import renovate.CallAdapter; import renovate.Result;
/* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava2.adapter; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:2017/5/27 * 描 述: * 修订历史: * ================================================ */ public class FlowableResult<T> implements CallAdapter<T, Flowable<Result<T>>> { @Override
// Path: renovate/src/main/java/renovate/AdapterParam.java // public class AdapterParam { // public boolean isAsync; // // public AdapterParam() { // isAsync = true; // } // } // // Path: renovate/src/main/java/renovate/Call.java // public interface Call<T> extends Cloneable { // Response<T> execute() throws IOException; // // void enqueue(Callback<T> callback); // // boolean isExecuted(); // // void cancel(); // // boolean isCanceled(); // // Call<T> clone(); // // Request request(); // } // // Path: renovate/src/main/java/renovate/CallAdapter.java // public interface CallAdapter<T, R> { // // /** call执行的代理方法 */ // R adapt(Call<T> call, AdapterParam param); // } // // Path: renovate/src/main/java/renovate/Result.java // public final class Result<T> { // @SuppressWarnings("ConstantConditions") // Guarding public API nullability. // public static <T> Result<T> error(Throwable error) { // if (error == null) throw new NullPointerException("error == null"); // return new Result<>(null, error); // } // // @SuppressWarnings("ConstantConditions") // Guarding public API nullability. // public static <T> Result<T> response(Response<T> response) { // if (response == null) throw new NullPointerException("response == null"); // return new Result<>(response, null); // } // // private final Response<T> response; // private final Throwable error; // // private Result(Response<T> response, Throwable error) { // this.response = response; // this.error = error; // } // // /** // * The response received from executing an HTTP request. Only present when {@link #isError()} is // * false, null otherwise. // */ // // public Response<T> response() { // return response; // } // // /** // * The error experienced while attempting to execute an HTTP request. Only present when {@link // * #isError()} is true, null otherwise. // * If the error is an {@link IOException} then there was a problem with the transport to the // * remote server. Any other exception type indicates an unexpected failure and should be // * considered fatal (configuration error, programming error, etc.). // */ // // public Throwable error() { // return error; // } // // /** {@code true} if the request resulted in an error. See {@link #error()} for the cause. */ // public boolean isError() { // return error != null; // } // // @Override // public String toString() { // if (error != null) { // return "Result{isError=true, error=\"" + error + "\"}"; // } // return "Result{isError=false, response=" + response + '}'; // } // } // Path: rx-renovate2/src/main/java/renovate/rxjava2/adapter/FlowableResult.java import io.reactivex.BackpressureStrategy; import io.reactivex.Flowable; import renovate.AdapterParam; import renovate.Call; import renovate.CallAdapter; import renovate.Result; /* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava2.adapter; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:2017/5/27 * 描 述: * 修订历史: * ================================================ */ public class FlowableResult<T> implements CallAdapter<T, Flowable<Result<T>>> { @Override
public Flowable<Result<T>> adapt(Call<T> call, AdapterParam param) {
baby2431/renovate2
rx-renovate2/src/main/java/renovate/rxjava2/adapter/FlowableResult.java
// Path: renovate/src/main/java/renovate/AdapterParam.java // public class AdapterParam { // public boolean isAsync; // // public AdapterParam() { // isAsync = true; // } // } // // Path: renovate/src/main/java/renovate/Call.java // public interface Call<T> extends Cloneable { // Response<T> execute() throws IOException; // // void enqueue(Callback<T> callback); // // boolean isExecuted(); // // void cancel(); // // boolean isCanceled(); // // Call<T> clone(); // // Request request(); // } // // Path: renovate/src/main/java/renovate/CallAdapter.java // public interface CallAdapter<T, R> { // // /** call执行的代理方法 */ // R adapt(Call<T> call, AdapterParam param); // } // // Path: renovate/src/main/java/renovate/Result.java // public final class Result<T> { // @SuppressWarnings("ConstantConditions") // Guarding public API nullability. // public static <T> Result<T> error(Throwable error) { // if (error == null) throw new NullPointerException("error == null"); // return new Result<>(null, error); // } // // @SuppressWarnings("ConstantConditions") // Guarding public API nullability. // public static <T> Result<T> response(Response<T> response) { // if (response == null) throw new NullPointerException("response == null"); // return new Result<>(response, null); // } // // private final Response<T> response; // private final Throwable error; // // private Result(Response<T> response, Throwable error) { // this.response = response; // this.error = error; // } // // /** // * The response received from executing an HTTP request. Only present when {@link #isError()} is // * false, null otherwise. // */ // // public Response<T> response() { // return response; // } // // /** // * The error experienced while attempting to execute an HTTP request. Only present when {@link // * #isError()} is true, null otherwise. // * If the error is an {@link IOException} then there was a problem with the transport to the // * remote server. Any other exception type indicates an unexpected failure and should be // * considered fatal (configuration error, programming error, etc.). // */ // // public Throwable error() { // return error; // } // // /** {@code true} if the request resulted in an error. See {@link #error()} for the cause. */ // public boolean isError() { // return error != null; // } // // @Override // public String toString() { // if (error != null) { // return "Result{isError=true, error=\"" + error + "\"}"; // } // return "Result{isError=false, response=" + response + '}'; // } // }
import io.reactivex.BackpressureStrategy; import io.reactivex.Flowable; import renovate.AdapterParam; import renovate.Call; import renovate.CallAdapter; import renovate.Result;
/* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava2.adapter; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:2017/5/27 * 描 述: * 修订历史: * ================================================ */ public class FlowableResult<T> implements CallAdapter<T, Flowable<Result<T>>> { @Override
// Path: renovate/src/main/java/renovate/AdapterParam.java // public class AdapterParam { // public boolean isAsync; // // public AdapterParam() { // isAsync = true; // } // } // // Path: renovate/src/main/java/renovate/Call.java // public interface Call<T> extends Cloneable { // Response<T> execute() throws IOException; // // void enqueue(Callback<T> callback); // // boolean isExecuted(); // // void cancel(); // // boolean isCanceled(); // // Call<T> clone(); // // Request request(); // } // // Path: renovate/src/main/java/renovate/CallAdapter.java // public interface CallAdapter<T, R> { // // /** call执行的代理方法 */ // R adapt(Call<T> call, AdapterParam param); // } // // Path: renovate/src/main/java/renovate/Result.java // public final class Result<T> { // @SuppressWarnings("ConstantConditions") // Guarding public API nullability. // public static <T> Result<T> error(Throwable error) { // if (error == null) throw new NullPointerException("error == null"); // return new Result<>(null, error); // } // // @SuppressWarnings("ConstantConditions") // Guarding public API nullability. // public static <T> Result<T> response(Response<T> response) { // if (response == null) throw new NullPointerException("response == null"); // return new Result<>(response, null); // } // // private final Response<T> response; // private final Throwable error; // // private Result(Response<T> response, Throwable error) { // this.response = response; // this.error = error; // } // // /** // * The response received from executing an HTTP request. Only present when {@link #isError()} is // * false, null otherwise. // */ // // public Response<T> response() { // return response; // } // // /** // * The error experienced while attempting to execute an HTTP request. Only present when {@link // * #isError()} is true, null otherwise. // * If the error is an {@link IOException} then there was a problem with the transport to the // * remote server. Any other exception type indicates an unexpected failure and should be // * considered fatal (configuration error, programming error, etc.). // */ // // public Throwable error() { // return error; // } // // /** {@code true} if the request resulted in an error. See {@link #error()} for the cause. */ // public boolean isError() { // return error != null; // } // // @Override // public String toString() { // if (error != null) { // return "Result{isError=true, error=\"" + error + "\"}"; // } // return "Result{isError=false, response=" + response + '}'; // } // } // Path: rx-renovate2/src/main/java/renovate/rxjava2/adapter/FlowableResult.java import io.reactivex.BackpressureStrategy; import io.reactivex.Flowable; import renovate.AdapterParam; import renovate.Call; import renovate.CallAdapter; import renovate.Result; /* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava2.adapter; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:2017/5/27 * 描 述: * 修订历史: * ================================================ */ public class FlowableResult<T> implements CallAdapter<T, Flowable<Result<T>>> { @Override
public Flowable<Result<T>> adapt(Call<T> call, AdapterParam param) {
baby2431/renovate2
rx-renovate2/src/main/java/renovate/rxjava2/adapter/MaybeBody.java
// Path: renovate/src/main/java/renovate/AdapterParam.java // public class AdapterParam { // public boolean isAsync; // // public AdapterParam() { // isAsync = true; // } // } // // Path: renovate/src/main/java/renovate/Call.java // public interface Call<T> extends Cloneable { // Response<T> execute() throws IOException; // // void enqueue(Callback<T> callback); // // boolean isExecuted(); // // void cancel(); // // boolean isCanceled(); // // Call<T> clone(); // // Request request(); // } // // Path: renovate/src/main/java/renovate/CallAdapter.java // public interface CallAdapter<T, R> { // // /** call执行的代理方法 */ // R adapt(Call<T> call, AdapterParam param); // }
import io.reactivex.Maybe; import renovate.AdapterParam; import renovate.Call; import renovate.CallAdapter;
/* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava2.adapter; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:2017/5/27 * 描 述: * 修订历史: * ================================================ */ public class MaybeBody<T> implements CallAdapter<T, Maybe<T>> { @Override
// Path: renovate/src/main/java/renovate/AdapterParam.java // public class AdapterParam { // public boolean isAsync; // // public AdapterParam() { // isAsync = true; // } // } // // Path: renovate/src/main/java/renovate/Call.java // public interface Call<T> extends Cloneable { // Response<T> execute() throws IOException; // // void enqueue(Callback<T> callback); // // boolean isExecuted(); // // void cancel(); // // boolean isCanceled(); // // Call<T> clone(); // // Request request(); // } // // Path: renovate/src/main/java/renovate/CallAdapter.java // public interface CallAdapter<T, R> { // // /** call执行的代理方法 */ // R adapt(Call<T> call, AdapterParam param); // } // Path: rx-renovate2/src/main/java/renovate/rxjava2/adapter/MaybeBody.java import io.reactivex.Maybe; import renovate.AdapterParam; import renovate.Call; import renovate.CallAdapter; /* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava2.adapter; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:2017/5/27 * 描 述: * 修订历史: * ================================================ */ public class MaybeBody<T> implements CallAdapter<T, Maybe<T>> { @Override
public Maybe<T> adapt(Call<T> call, AdapterParam param) {
baby2431/renovate2
rx-renovate2/src/main/java/renovate/rxjava2/adapter/MaybeBody.java
// Path: renovate/src/main/java/renovate/AdapterParam.java // public class AdapterParam { // public boolean isAsync; // // public AdapterParam() { // isAsync = true; // } // } // // Path: renovate/src/main/java/renovate/Call.java // public interface Call<T> extends Cloneable { // Response<T> execute() throws IOException; // // void enqueue(Callback<T> callback); // // boolean isExecuted(); // // void cancel(); // // boolean isCanceled(); // // Call<T> clone(); // // Request request(); // } // // Path: renovate/src/main/java/renovate/CallAdapter.java // public interface CallAdapter<T, R> { // // /** call执行的代理方法 */ // R adapt(Call<T> call, AdapterParam param); // }
import io.reactivex.Maybe; import renovate.AdapterParam; import renovate.Call; import renovate.CallAdapter;
/* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava2.adapter; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:2017/5/27 * 描 述: * 修订历史: * ================================================ */ public class MaybeBody<T> implements CallAdapter<T, Maybe<T>> { @Override
// Path: renovate/src/main/java/renovate/AdapterParam.java // public class AdapterParam { // public boolean isAsync; // // public AdapterParam() { // isAsync = true; // } // } // // Path: renovate/src/main/java/renovate/Call.java // public interface Call<T> extends Cloneable { // Response<T> execute() throws IOException; // // void enqueue(Callback<T> callback); // // boolean isExecuted(); // // void cancel(); // // boolean isCanceled(); // // Call<T> clone(); // // Request request(); // } // // Path: renovate/src/main/java/renovate/CallAdapter.java // public interface CallAdapter<T, R> { // // /** call执行的代理方法 */ // R adapt(Call<T> call, AdapterParam param); // } // Path: rx-renovate2/src/main/java/renovate/rxjava2/adapter/MaybeBody.java import io.reactivex.Maybe; import renovate.AdapterParam; import renovate.Call; import renovate.CallAdapter; /* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava2.adapter; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:2017/5/27 * 描 述: * 修订历史: * ================================================ */ public class MaybeBody<T> implements CallAdapter<T, Maybe<T>> { @Override
public Maybe<T> adapt(Call<T> call, AdapterParam param) {
baby2431/renovate2
rx-renovate2/src/main/java/renovate/rxjava2/adapter/SingleResult.java
// Path: renovate/src/main/java/renovate/AdapterParam.java // public class AdapterParam { // public boolean isAsync; // // public AdapterParam() { // isAsync = true; // } // } // // Path: renovate/src/main/java/renovate/Call.java // public interface Call<T> extends Cloneable { // Response<T> execute() throws IOException; // // void enqueue(Callback<T> callback); // // boolean isExecuted(); // // void cancel(); // // boolean isCanceled(); // // Call<T> clone(); // // Request request(); // } // // Path: renovate/src/main/java/renovate/CallAdapter.java // public interface CallAdapter<T, R> { // // /** call执行的代理方法 */ // R adapt(Call<T> call, AdapterParam param); // } // // Path: renovate/src/main/java/renovate/Result.java // public final class Result<T> { // @SuppressWarnings("ConstantConditions") // Guarding public API nullability. // public static <T> Result<T> error(Throwable error) { // if (error == null) throw new NullPointerException("error == null"); // return new Result<>(null, error); // } // // @SuppressWarnings("ConstantConditions") // Guarding public API nullability. // public static <T> Result<T> response(Response<T> response) { // if (response == null) throw new NullPointerException("response == null"); // return new Result<>(response, null); // } // // private final Response<T> response; // private final Throwable error; // // private Result(Response<T> response, Throwable error) { // this.response = response; // this.error = error; // } // // /** // * The response received from executing an HTTP request. Only present when {@link #isError()} is // * false, null otherwise. // */ // // public Response<T> response() { // return response; // } // // /** // * The error experienced while attempting to execute an HTTP request. Only present when {@link // * #isError()} is true, null otherwise. // * If the error is an {@link IOException} then there was a problem with the transport to the // * remote server. Any other exception type indicates an unexpected failure and should be // * considered fatal (configuration error, programming error, etc.). // */ // // public Throwable error() { // return error; // } // // /** {@code true} if the request resulted in an error. See {@link #error()} for the cause. */ // public boolean isError() { // return error != null; // } // // @Override // public String toString() { // if (error != null) { // return "Result{isError=true, error=\"" + error + "\"}"; // } // return "Result{isError=false, response=" + response + '}'; // } // }
import io.reactivex.Single; import renovate.AdapterParam; import renovate.Call; import renovate.CallAdapter; import renovate.Result;
/* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava2.adapter; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:2017/5/27 * 描 述: * 修订历史: * ================================================ */ public class SingleResult<T> implements CallAdapter<T, Single<Result<T>>> { @Override
// Path: renovate/src/main/java/renovate/AdapterParam.java // public class AdapterParam { // public boolean isAsync; // // public AdapterParam() { // isAsync = true; // } // } // // Path: renovate/src/main/java/renovate/Call.java // public interface Call<T> extends Cloneable { // Response<T> execute() throws IOException; // // void enqueue(Callback<T> callback); // // boolean isExecuted(); // // void cancel(); // // boolean isCanceled(); // // Call<T> clone(); // // Request request(); // } // // Path: renovate/src/main/java/renovate/CallAdapter.java // public interface CallAdapter<T, R> { // // /** call执行的代理方法 */ // R adapt(Call<T> call, AdapterParam param); // } // // Path: renovate/src/main/java/renovate/Result.java // public final class Result<T> { // @SuppressWarnings("ConstantConditions") // Guarding public API nullability. // public static <T> Result<T> error(Throwable error) { // if (error == null) throw new NullPointerException("error == null"); // return new Result<>(null, error); // } // // @SuppressWarnings("ConstantConditions") // Guarding public API nullability. // public static <T> Result<T> response(Response<T> response) { // if (response == null) throw new NullPointerException("response == null"); // return new Result<>(response, null); // } // // private final Response<T> response; // private final Throwable error; // // private Result(Response<T> response, Throwable error) { // this.response = response; // this.error = error; // } // // /** // * The response received from executing an HTTP request. Only present when {@link #isError()} is // * false, null otherwise. // */ // // public Response<T> response() { // return response; // } // // /** // * The error experienced while attempting to execute an HTTP request. Only present when {@link // * #isError()} is true, null otherwise. // * If the error is an {@link IOException} then there was a problem with the transport to the // * remote server. Any other exception type indicates an unexpected failure and should be // * considered fatal (configuration error, programming error, etc.). // */ // // public Throwable error() { // return error; // } // // /** {@code true} if the request resulted in an error. See {@link #error()} for the cause. */ // public boolean isError() { // return error != null; // } // // @Override // public String toString() { // if (error != null) { // return "Result{isError=true, error=\"" + error + "\"}"; // } // return "Result{isError=false, response=" + response + '}'; // } // } // Path: rx-renovate2/src/main/java/renovate/rxjava2/adapter/SingleResult.java import io.reactivex.Single; import renovate.AdapterParam; import renovate.Call; import renovate.CallAdapter; import renovate.Result; /* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava2.adapter; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:2017/5/27 * 描 述: * 修订历史: * ================================================ */ public class SingleResult<T> implements CallAdapter<T, Single<Result<T>>> { @Override
public Single<Result<T>> adapt(Call<T> call, AdapterParam param) {
baby2431/renovate2
rx-renovate2/src/main/java/renovate/rxjava2/adapter/SingleResult.java
// Path: renovate/src/main/java/renovate/AdapterParam.java // public class AdapterParam { // public boolean isAsync; // // public AdapterParam() { // isAsync = true; // } // } // // Path: renovate/src/main/java/renovate/Call.java // public interface Call<T> extends Cloneable { // Response<T> execute() throws IOException; // // void enqueue(Callback<T> callback); // // boolean isExecuted(); // // void cancel(); // // boolean isCanceled(); // // Call<T> clone(); // // Request request(); // } // // Path: renovate/src/main/java/renovate/CallAdapter.java // public interface CallAdapter<T, R> { // // /** call执行的代理方法 */ // R adapt(Call<T> call, AdapterParam param); // } // // Path: renovate/src/main/java/renovate/Result.java // public final class Result<T> { // @SuppressWarnings("ConstantConditions") // Guarding public API nullability. // public static <T> Result<T> error(Throwable error) { // if (error == null) throw new NullPointerException("error == null"); // return new Result<>(null, error); // } // // @SuppressWarnings("ConstantConditions") // Guarding public API nullability. // public static <T> Result<T> response(Response<T> response) { // if (response == null) throw new NullPointerException("response == null"); // return new Result<>(response, null); // } // // private final Response<T> response; // private final Throwable error; // // private Result(Response<T> response, Throwable error) { // this.response = response; // this.error = error; // } // // /** // * The response received from executing an HTTP request. Only present when {@link #isError()} is // * false, null otherwise. // */ // // public Response<T> response() { // return response; // } // // /** // * The error experienced while attempting to execute an HTTP request. Only present when {@link // * #isError()} is true, null otherwise. // * If the error is an {@link IOException} then there was a problem with the transport to the // * remote server. Any other exception type indicates an unexpected failure and should be // * considered fatal (configuration error, programming error, etc.). // */ // // public Throwable error() { // return error; // } // // /** {@code true} if the request resulted in an error. See {@link #error()} for the cause. */ // public boolean isError() { // return error != null; // } // // @Override // public String toString() { // if (error != null) { // return "Result{isError=true, error=\"" + error + "\"}"; // } // return "Result{isError=false, response=" + response + '}'; // } // }
import io.reactivex.Single; import renovate.AdapterParam; import renovate.Call; import renovate.CallAdapter; import renovate.Result;
/* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava2.adapter; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:2017/5/27 * 描 述: * 修订历史: * ================================================ */ public class SingleResult<T> implements CallAdapter<T, Single<Result<T>>> { @Override
// Path: renovate/src/main/java/renovate/AdapterParam.java // public class AdapterParam { // public boolean isAsync; // // public AdapterParam() { // isAsync = true; // } // } // // Path: renovate/src/main/java/renovate/Call.java // public interface Call<T> extends Cloneable { // Response<T> execute() throws IOException; // // void enqueue(Callback<T> callback); // // boolean isExecuted(); // // void cancel(); // // boolean isCanceled(); // // Call<T> clone(); // // Request request(); // } // // Path: renovate/src/main/java/renovate/CallAdapter.java // public interface CallAdapter<T, R> { // // /** call执行的代理方法 */ // R adapt(Call<T> call, AdapterParam param); // } // // Path: renovate/src/main/java/renovate/Result.java // public final class Result<T> { // @SuppressWarnings("ConstantConditions") // Guarding public API nullability. // public static <T> Result<T> error(Throwable error) { // if (error == null) throw new NullPointerException("error == null"); // return new Result<>(null, error); // } // // @SuppressWarnings("ConstantConditions") // Guarding public API nullability. // public static <T> Result<T> response(Response<T> response) { // if (response == null) throw new NullPointerException("response == null"); // return new Result<>(response, null); // } // // private final Response<T> response; // private final Throwable error; // // private Result(Response<T> response, Throwable error) { // this.response = response; // this.error = error; // } // // /** // * The response received from executing an HTTP request. Only present when {@link #isError()} is // * false, null otherwise. // */ // // public Response<T> response() { // return response; // } // // /** // * The error experienced while attempting to execute an HTTP request. Only present when {@link // * #isError()} is true, null otherwise. // * If the error is an {@link IOException} then there was a problem with the transport to the // * remote server. Any other exception type indicates an unexpected failure and should be // * considered fatal (configuration error, programming error, etc.). // */ // // public Throwable error() { // return error; // } // // /** {@code true} if the request resulted in an error. See {@link #error()} for the cause. */ // public boolean isError() { // return error != null; // } // // @Override // public String toString() { // if (error != null) { // return "Result{isError=true, error=\"" + error + "\"}"; // } // return "Result{isError=false, response=" + response + '}'; // } // } // Path: rx-renovate2/src/main/java/renovate/rxjava2/adapter/SingleResult.java import io.reactivex.Single; import renovate.AdapterParam; import renovate.Call; import renovate.CallAdapter; import renovate.Result; /* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava2.adapter; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:2017/5/27 * 描 述: * 修订历史: * ================================================ */ public class SingleResult<T> implements CallAdapter<T, Single<Result<T>>> { @Override
public Single<Result<T>> adapt(Call<T> call, AdapterParam param) {
baby2431/renovate2
rx-renovate2/src/main/java/renovate/rxjava2/observable/BodyObservable.java
// Path: renovate/src/main/java/renovate/HttpException.java // public class HttpException extends RuntimeException { // private static String getMessage(Response<?> response) { // checkNotNull(response, "response == null"); // return "HTTP " + response.code() + " " + response.message(); // } // // private final int code; // private final String message; // private final transient Response<?> response; // // public HttpException(Response<?> response) { // super(getMessage(response)); // this.code = response.code(); // this.message = response.message(); // this.response = response; // } // // /** HTTP status code. */ // public int code() { // return code; // } // // /** HTTP status message. */ // public String message() { // return message; // } // // /** // * The full HTTP response. This may be null if the exception was serialized. // */ // public Response<?> response() { // return response; // } // } // // Path: renovate/src/main/java/renovate/Response.java // public final class Response<T> { // private final okhttp3.Response rawResponse; // private final T body; // private final ResponseBody errorBody; // // private Response(okhttp3.Response rawResponse, T body, ResponseBody errorBody) { // this.rawResponse = rawResponse; // this.body = body; // this.errorBody = errorBody; // } // // public static <T> Response<T> success(T body) { // return success(body, new okhttp3.Response.Builder() // // .code(200) // .message("OK") // .protocol(Protocol.HTTP_1_1) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> success(T body, Headers headers) { // if (headers == null) throw new NullPointerException("headers == null"); // return success(body, new okhttp3.Response.Builder() // // .code(200) // .message("OK") // .protocol(Protocol.HTTP_1_1) // .headers(headers) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> success(T body, okhttp3.Response rawResponse) { // if (rawResponse == null) throw new NullPointerException("rawResponse == null"); // if (!rawResponse.isSuccessful()) { // throw new IllegalArgumentException("rawResponse must be successful response"); // } // return new Response<>(rawResponse, body, null); // } // // public static <T> Response<T> error(int code, ResponseBody body) { // if (code < 400) throw new IllegalArgumentException("code < 400: " + code); // return error(body, new okhttp3.Response.Builder() // // .code(code) // .protocol(Protocol.HTTP_1_1) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> error(ResponseBody body, okhttp3.Response rawResponse) { // if (body == null) throw new NullPointerException("body == null"); // if (rawResponse == null) throw new NullPointerException("rawResponse == null"); // if (rawResponse.isSuccessful()) { // throw new IllegalArgumentException("rawResponse should not be successful response"); // } // return new Response<>(rawResponse, null, body); // } // // public okhttp3.Response raw() { // return rawResponse; // } // // public int code() { // return rawResponse.code(); // } // // public String message() { // return rawResponse.message(); // } // // public Headers headers() { // return rawResponse.headers(); // } // // public boolean isSuccessful() { // return rawResponse.isSuccessful(); // } // // public T body() { // return body; // } // // public ResponseBody errorBody() { // return errorBody; // } // // @Override public String toString() { // return rawResponse.toString(); // } // }
import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.CompositeException; import io.reactivex.exceptions.Exceptions; import io.reactivex.plugins.RxJavaPlugins; import renovate.HttpException; import renovate.Response;
/* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava2.observable; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:16/9/11 * 描 述: * 修订历史: * ================================================ */ public final class BodyObservable<T> extends Observable<T> { private final Observable<Response<T>> upstream; public BodyObservable(Observable<Response<T>> upstream) { this.upstream = upstream; } @Override protected void subscribeActual(Observer<? super T> observer) { upstream.subscribe(new BodyObserver<T>(observer)); } private static class BodyObserver<R> implements Observer<Response<R>> { private final Observer<? super R> observer; private boolean terminated; BodyObserver(Observer<? super R> observer) { this.observer = observer; } @Override public void onSubscribe(Disposable disposable) { observer.onSubscribe(disposable); } @Override public void onNext(Response<R> response) { if (response.isSuccessful()) { observer.onNext(response.body()); } else { terminated = true;
// Path: renovate/src/main/java/renovate/HttpException.java // public class HttpException extends RuntimeException { // private static String getMessage(Response<?> response) { // checkNotNull(response, "response == null"); // return "HTTP " + response.code() + " " + response.message(); // } // // private final int code; // private final String message; // private final transient Response<?> response; // // public HttpException(Response<?> response) { // super(getMessage(response)); // this.code = response.code(); // this.message = response.message(); // this.response = response; // } // // /** HTTP status code. */ // public int code() { // return code; // } // // /** HTTP status message. */ // public String message() { // return message; // } // // /** // * The full HTTP response. This may be null if the exception was serialized. // */ // public Response<?> response() { // return response; // } // } // // Path: renovate/src/main/java/renovate/Response.java // public final class Response<T> { // private final okhttp3.Response rawResponse; // private final T body; // private final ResponseBody errorBody; // // private Response(okhttp3.Response rawResponse, T body, ResponseBody errorBody) { // this.rawResponse = rawResponse; // this.body = body; // this.errorBody = errorBody; // } // // public static <T> Response<T> success(T body) { // return success(body, new okhttp3.Response.Builder() // // .code(200) // .message("OK") // .protocol(Protocol.HTTP_1_1) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> success(T body, Headers headers) { // if (headers == null) throw new NullPointerException("headers == null"); // return success(body, new okhttp3.Response.Builder() // // .code(200) // .message("OK") // .protocol(Protocol.HTTP_1_1) // .headers(headers) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> success(T body, okhttp3.Response rawResponse) { // if (rawResponse == null) throw new NullPointerException("rawResponse == null"); // if (!rawResponse.isSuccessful()) { // throw new IllegalArgumentException("rawResponse must be successful response"); // } // return new Response<>(rawResponse, body, null); // } // // public static <T> Response<T> error(int code, ResponseBody body) { // if (code < 400) throw new IllegalArgumentException("code < 400: " + code); // return error(body, new okhttp3.Response.Builder() // // .code(code) // .protocol(Protocol.HTTP_1_1) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> error(ResponseBody body, okhttp3.Response rawResponse) { // if (body == null) throw new NullPointerException("body == null"); // if (rawResponse == null) throw new NullPointerException("rawResponse == null"); // if (rawResponse.isSuccessful()) { // throw new IllegalArgumentException("rawResponse should not be successful response"); // } // return new Response<>(rawResponse, null, body); // } // // public okhttp3.Response raw() { // return rawResponse; // } // // public int code() { // return rawResponse.code(); // } // // public String message() { // return rawResponse.message(); // } // // public Headers headers() { // return rawResponse.headers(); // } // // public boolean isSuccessful() { // return rawResponse.isSuccessful(); // } // // public T body() { // return body; // } // // public ResponseBody errorBody() { // return errorBody; // } // // @Override public String toString() { // return rawResponse.toString(); // } // } // Path: rx-renovate2/src/main/java/renovate/rxjava2/observable/BodyObservable.java import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.CompositeException; import io.reactivex.exceptions.Exceptions; import io.reactivex.plugins.RxJavaPlugins; import renovate.HttpException; import renovate.Response; /* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava2.observable; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:16/9/11 * 描 述: * 修订历史: * ================================================ */ public final class BodyObservable<T> extends Observable<T> { private final Observable<Response<T>> upstream; public BodyObservable(Observable<Response<T>> upstream) { this.upstream = upstream; } @Override protected void subscribeActual(Observer<? super T> observer) { upstream.subscribe(new BodyObserver<T>(observer)); } private static class BodyObserver<R> implements Observer<Response<R>> { private final Observer<? super R> observer; private boolean terminated; BodyObserver(Observer<? super R> observer) { this.observer = observer; } @Override public void onSubscribe(Disposable disposable) { observer.onSubscribe(disposable); } @Override public void onNext(Response<R> response) { if (response.isSuccessful()) { observer.onNext(response.body()); } else { terminated = true;
Throwable t = new HttpException(response);
baby2431/renovate2
rx-renovate/src/main/java/renovate/rxjava/subscribe/CallEnqueueOnSubscribe.java
// Path: renovate/src/main/java/renovate/Call.java // public interface Call<T> extends Cloneable { // Response<T> execute() throws IOException; // // void enqueue(Callback<T> callback); // // boolean isExecuted(); // // void cancel(); // // boolean isCanceled(); // // Call<T> clone(); // // Request request(); // } // // Path: renovate/src/main/java/renovate/Callback.java // public interface Callback<T> { // // void onResponse(Call<T> call, Response<T> response); // // void onFailure(Call<T> call, Throwable t); // } // // Path: renovate/src/main/java/renovate/Response.java // public final class Response<T> { // private final okhttp3.Response rawResponse; // private final T body; // private final ResponseBody errorBody; // // private Response(okhttp3.Response rawResponse, T body, ResponseBody errorBody) { // this.rawResponse = rawResponse; // this.body = body; // this.errorBody = errorBody; // } // // public static <T> Response<T> success(T body) { // return success(body, new okhttp3.Response.Builder() // // .code(200) // .message("OK") // .protocol(Protocol.HTTP_1_1) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> success(T body, Headers headers) { // if (headers == null) throw new NullPointerException("headers == null"); // return success(body, new okhttp3.Response.Builder() // // .code(200) // .message("OK") // .protocol(Protocol.HTTP_1_1) // .headers(headers) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> success(T body, okhttp3.Response rawResponse) { // if (rawResponse == null) throw new NullPointerException("rawResponse == null"); // if (!rawResponse.isSuccessful()) { // throw new IllegalArgumentException("rawResponse must be successful response"); // } // return new Response<>(rawResponse, body, null); // } // // public static <T> Response<T> error(int code, ResponseBody body) { // if (code < 400) throw new IllegalArgumentException("code < 400: " + code); // return error(body, new okhttp3.Response.Builder() // // .code(code) // .protocol(Protocol.HTTP_1_1) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> error(ResponseBody body, okhttp3.Response rawResponse) { // if (body == null) throw new NullPointerException("body == null"); // if (rawResponse == null) throw new NullPointerException("rawResponse == null"); // if (rawResponse.isSuccessful()) { // throw new IllegalArgumentException("rawResponse should not be successful response"); // } // return new Response<>(rawResponse, null, body); // } // // public okhttp3.Response raw() { // return rawResponse; // } // // public int code() { // return rawResponse.code(); // } // // public String message() { // return rawResponse.message(); // } // // public Headers headers() { // return rawResponse.headers(); // } // // public boolean isSuccessful() { // return rawResponse.isSuccessful(); // } // // public T body() { // return body; // } // // public ResponseBody errorBody() { // return errorBody; // } // // @Override public String toString() { // return rawResponse.toString(); // } // }
import renovate.Call; import renovate.Callback; import renovate.Response; import rx.Observable.OnSubscribe; import rx.Subscriber; import rx.exceptions.Exceptions;
/* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava.subscribe; public final class CallEnqueueOnSubscribe<T> implements OnSubscribe<Response<T>> { private final Call<T> originalCall; public CallEnqueueOnSubscribe(Call<T> originalCall) { this.originalCall = originalCall; } @Override public void call(final Subscriber<? super Response<T>> subscriber) { // Since Call is a one-shot type, clone it for each new subscriber. Call<T> call = originalCall.clone(); final CallArbiter<T> arbiter = new CallArbiter<>(call, subscriber); subscriber.add(arbiter); subscriber.setProducer(arbiter);
// Path: renovate/src/main/java/renovate/Call.java // public interface Call<T> extends Cloneable { // Response<T> execute() throws IOException; // // void enqueue(Callback<T> callback); // // boolean isExecuted(); // // void cancel(); // // boolean isCanceled(); // // Call<T> clone(); // // Request request(); // } // // Path: renovate/src/main/java/renovate/Callback.java // public interface Callback<T> { // // void onResponse(Call<T> call, Response<T> response); // // void onFailure(Call<T> call, Throwable t); // } // // Path: renovate/src/main/java/renovate/Response.java // public final class Response<T> { // private final okhttp3.Response rawResponse; // private final T body; // private final ResponseBody errorBody; // // private Response(okhttp3.Response rawResponse, T body, ResponseBody errorBody) { // this.rawResponse = rawResponse; // this.body = body; // this.errorBody = errorBody; // } // // public static <T> Response<T> success(T body) { // return success(body, new okhttp3.Response.Builder() // // .code(200) // .message("OK") // .protocol(Protocol.HTTP_1_1) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> success(T body, Headers headers) { // if (headers == null) throw new NullPointerException("headers == null"); // return success(body, new okhttp3.Response.Builder() // // .code(200) // .message("OK") // .protocol(Protocol.HTTP_1_1) // .headers(headers) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> success(T body, okhttp3.Response rawResponse) { // if (rawResponse == null) throw new NullPointerException("rawResponse == null"); // if (!rawResponse.isSuccessful()) { // throw new IllegalArgumentException("rawResponse must be successful response"); // } // return new Response<>(rawResponse, body, null); // } // // public static <T> Response<T> error(int code, ResponseBody body) { // if (code < 400) throw new IllegalArgumentException("code < 400: " + code); // return error(body, new okhttp3.Response.Builder() // // .code(code) // .protocol(Protocol.HTTP_1_1) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> error(ResponseBody body, okhttp3.Response rawResponse) { // if (body == null) throw new NullPointerException("body == null"); // if (rawResponse == null) throw new NullPointerException("rawResponse == null"); // if (rawResponse.isSuccessful()) { // throw new IllegalArgumentException("rawResponse should not be successful response"); // } // return new Response<>(rawResponse, null, body); // } // // public okhttp3.Response raw() { // return rawResponse; // } // // public int code() { // return rawResponse.code(); // } // // public String message() { // return rawResponse.message(); // } // // public Headers headers() { // return rawResponse.headers(); // } // // public boolean isSuccessful() { // return rawResponse.isSuccessful(); // } // // public T body() { // return body; // } // // public ResponseBody errorBody() { // return errorBody; // } // // @Override public String toString() { // return rawResponse.toString(); // } // } // Path: rx-renovate/src/main/java/renovate/rxjava/subscribe/CallEnqueueOnSubscribe.java import renovate.Call; import renovate.Callback; import renovate.Response; import rx.Observable.OnSubscribe; import rx.Subscriber; import rx.exceptions.Exceptions; /* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava.subscribe; public final class CallEnqueueOnSubscribe<T> implements OnSubscribe<Response<T>> { private final Call<T> originalCall; public CallEnqueueOnSubscribe(Call<T> originalCall) { this.originalCall = originalCall; } @Override public void call(final Subscriber<? super Response<T>> subscriber) { // Since Call is a one-shot type, clone it for each new subscriber. Call<T> call = originalCall.clone(); final CallArbiter<T> arbiter = new CallArbiter<>(call, subscriber); subscriber.add(arbiter); subscriber.setProducer(arbiter);
call.enqueue(new Callback<T>() {
baby2431/renovate2
rx-renovate2/src/main/java/renovate/rxjava2/adapter/CompletableResponse.java
// Path: renovate/src/main/java/renovate/AdapterParam.java // public class AdapterParam { // public boolean isAsync; // // public AdapterParam() { // isAsync = true; // } // } // // Path: renovate/src/main/java/renovate/Call.java // public interface Call<T> extends Cloneable { // Response<T> execute() throws IOException; // // void enqueue(Callback<T> callback); // // boolean isExecuted(); // // void cancel(); // // boolean isCanceled(); // // Call<T> clone(); // // Request request(); // } // // Path: renovate/src/main/java/renovate/CallAdapter.java // public interface CallAdapter<T, R> { // // /** call执行的代理方法 */ // R adapt(Call<T> call, AdapterParam param); // }
import io.reactivex.Completable; import renovate.AdapterParam; import renovate.Call; import renovate.CallAdapter;
/* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava2.adapter; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:2017/5/27 * 描 述: * 修订历史: * ================================================ */ public class CompletableResponse<T> implements CallAdapter<T, Completable> { @Override
// Path: renovate/src/main/java/renovate/AdapterParam.java // public class AdapterParam { // public boolean isAsync; // // public AdapterParam() { // isAsync = true; // } // } // // Path: renovate/src/main/java/renovate/Call.java // public interface Call<T> extends Cloneable { // Response<T> execute() throws IOException; // // void enqueue(Callback<T> callback); // // boolean isExecuted(); // // void cancel(); // // boolean isCanceled(); // // Call<T> clone(); // // Request request(); // } // // Path: renovate/src/main/java/renovate/CallAdapter.java // public interface CallAdapter<T, R> { // // /** call执行的代理方法 */ // R adapt(Call<T> call, AdapterParam param); // } // Path: rx-renovate2/src/main/java/renovate/rxjava2/adapter/CompletableResponse.java import io.reactivex.Completable; import renovate.AdapterParam; import renovate.Call; import renovate.CallAdapter; /* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava2.adapter; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:2017/5/27 * 描 述: * 修订历史: * ================================================ */ public class CompletableResponse<T> implements CallAdapter<T, Completable> { @Override
public Completable adapt(Call<T> call, AdapterParam param) {
baby2431/renovate2
rx-renovate2/src/main/java/renovate/rxjava2/adapter/CompletableResponse.java
// Path: renovate/src/main/java/renovate/AdapterParam.java // public class AdapterParam { // public boolean isAsync; // // public AdapterParam() { // isAsync = true; // } // } // // Path: renovate/src/main/java/renovate/Call.java // public interface Call<T> extends Cloneable { // Response<T> execute() throws IOException; // // void enqueue(Callback<T> callback); // // boolean isExecuted(); // // void cancel(); // // boolean isCanceled(); // // Call<T> clone(); // // Request request(); // } // // Path: renovate/src/main/java/renovate/CallAdapter.java // public interface CallAdapter<T, R> { // // /** call执行的代理方法 */ // R adapt(Call<T> call, AdapterParam param); // }
import io.reactivex.Completable; import renovate.AdapterParam; import renovate.Call; import renovate.CallAdapter;
/* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava2.adapter; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:2017/5/27 * 描 述: * 修订历史: * ================================================ */ public class CompletableResponse<T> implements CallAdapter<T, Completable> { @Override
// Path: renovate/src/main/java/renovate/AdapterParam.java // public class AdapterParam { // public boolean isAsync; // // public AdapterParam() { // isAsync = true; // } // } // // Path: renovate/src/main/java/renovate/Call.java // public interface Call<T> extends Cloneable { // Response<T> execute() throws IOException; // // void enqueue(Callback<T> callback); // // boolean isExecuted(); // // void cancel(); // // boolean isCanceled(); // // Call<T> clone(); // // Request request(); // } // // Path: renovate/src/main/java/renovate/CallAdapter.java // public interface CallAdapter<T, R> { // // /** call执行的代理方法 */ // R adapt(Call<T> call, AdapterParam param); // } // Path: rx-renovate2/src/main/java/renovate/rxjava2/adapter/CompletableResponse.java import io.reactivex.Completable; import renovate.AdapterParam; import renovate.Call; import renovate.CallAdapter; /* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava2.adapter; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:2017/5/27 * 描 述: * 修订历史: * ================================================ */ public class CompletableResponse<T> implements CallAdapter<T, Completable> { @Override
public Completable adapt(Call<T> call, AdapterParam param) {
baby2431/renovate2
rx-renovate2/src/main/java/renovate/rxjava2/adapter/MaybeResult.java
// Path: renovate/src/main/java/renovate/AdapterParam.java // public class AdapterParam { // public boolean isAsync; // // public AdapterParam() { // isAsync = true; // } // } // // Path: renovate/src/main/java/renovate/Call.java // public interface Call<T> extends Cloneable { // Response<T> execute() throws IOException; // // void enqueue(Callback<T> callback); // // boolean isExecuted(); // // void cancel(); // // boolean isCanceled(); // // Call<T> clone(); // // Request request(); // } // // Path: renovate/src/main/java/renovate/CallAdapter.java // public interface CallAdapter<T, R> { // // /** call执行的代理方法 */ // R adapt(Call<T> call, AdapterParam param); // } // // Path: renovate/src/main/java/renovate/Result.java // public final class Result<T> { // @SuppressWarnings("ConstantConditions") // Guarding public API nullability. // public static <T> Result<T> error(Throwable error) { // if (error == null) throw new NullPointerException("error == null"); // return new Result<>(null, error); // } // // @SuppressWarnings("ConstantConditions") // Guarding public API nullability. // public static <T> Result<T> response(Response<T> response) { // if (response == null) throw new NullPointerException("response == null"); // return new Result<>(response, null); // } // // private final Response<T> response; // private final Throwable error; // // private Result(Response<T> response, Throwable error) { // this.response = response; // this.error = error; // } // // /** // * The response received from executing an HTTP request. Only present when {@link #isError()} is // * false, null otherwise. // */ // // public Response<T> response() { // return response; // } // // /** // * The error experienced while attempting to execute an HTTP request. Only present when {@link // * #isError()} is true, null otherwise. // * If the error is an {@link IOException} then there was a problem with the transport to the // * remote server. Any other exception type indicates an unexpected failure and should be // * considered fatal (configuration error, programming error, etc.). // */ // // public Throwable error() { // return error; // } // // /** {@code true} if the request resulted in an error. See {@link #error()} for the cause. */ // public boolean isError() { // return error != null; // } // // @Override // public String toString() { // if (error != null) { // return "Result{isError=true, error=\"" + error + "\"}"; // } // return "Result{isError=false, response=" + response + '}'; // } // }
import io.reactivex.Maybe; import renovate.AdapterParam; import renovate.Call; import renovate.CallAdapter; import renovate.Result;
/* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava2.adapter; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:2017/5/27 * 描 述: * 修订历史: * ================================================ */ public class MaybeResult<T> implements CallAdapter<T, Maybe<Result<T>>> { @Override
// Path: renovate/src/main/java/renovate/AdapterParam.java // public class AdapterParam { // public boolean isAsync; // // public AdapterParam() { // isAsync = true; // } // } // // Path: renovate/src/main/java/renovate/Call.java // public interface Call<T> extends Cloneable { // Response<T> execute() throws IOException; // // void enqueue(Callback<T> callback); // // boolean isExecuted(); // // void cancel(); // // boolean isCanceled(); // // Call<T> clone(); // // Request request(); // } // // Path: renovate/src/main/java/renovate/CallAdapter.java // public interface CallAdapter<T, R> { // // /** call执行的代理方法 */ // R adapt(Call<T> call, AdapterParam param); // } // // Path: renovate/src/main/java/renovate/Result.java // public final class Result<T> { // @SuppressWarnings("ConstantConditions") // Guarding public API nullability. // public static <T> Result<T> error(Throwable error) { // if (error == null) throw new NullPointerException("error == null"); // return new Result<>(null, error); // } // // @SuppressWarnings("ConstantConditions") // Guarding public API nullability. // public static <T> Result<T> response(Response<T> response) { // if (response == null) throw new NullPointerException("response == null"); // return new Result<>(response, null); // } // // private final Response<T> response; // private final Throwable error; // // private Result(Response<T> response, Throwable error) { // this.response = response; // this.error = error; // } // // /** // * The response received from executing an HTTP request. Only present when {@link #isError()} is // * false, null otherwise. // */ // // public Response<T> response() { // return response; // } // // /** // * The error experienced while attempting to execute an HTTP request. Only present when {@link // * #isError()} is true, null otherwise. // * If the error is an {@link IOException} then there was a problem with the transport to the // * remote server. Any other exception type indicates an unexpected failure and should be // * considered fatal (configuration error, programming error, etc.). // */ // // public Throwable error() { // return error; // } // // /** {@code true} if the request resulted in an error. See {@link #error()} for the cause. */ // public boolean isError() { // return error != null; // } // // @Override // public String toString() { // if (error != null) { // return "Result{isError=true, error=\"" + error + "\"}"; // } // return "Result{isError=false, response=" + response + '}'; // } // } // Path: rx-renovate2/src/main/java/renovate/rxjava2/adapter/MaybeResult.java import io.reactivex.Maybe; import renovate.AdapterParam; import renovate.Call; import renovate.CallAdapter; import renovate.Result; /* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava2.adapter; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:2017/5/27 * 描 述: * 修订历史: * ================================================ */ public class MaybeResult<T> implements CallAdapter<T, Maybe<Result<T>>> { @Override
public Maybe<Result<T>> adapt(Call<T> call, AdapterParam param) {
baby2431/renovate2
rx-renovate2/src/main/java/renovate/rxjava2/adapter/MaybeResult.java
// Path: renovate/src/main/java/renovate/AdapterParam.java // public class AdapterParam { // public boolean isAsync; // // public AdapterParam() { // isAsync = true; // } // } // // Path: renovate/src/main/java/renovate/Call.java // public interface Call<T> extends Cloneable { // Response<T> execute() throws IOException; // // void enqueue(Callback<T> callback); // // boolean isExecuted(); // // void cancel(); // // boolean isCanceled(); // // Call<T> clone(); // // Request request(); // } // // Path: renovate/src/main/java/renovate/CallAdapter.java // public interface CallAdapter<T, R> { // // /** call执行的代理方法 */ // R adapt(Call<T> call, AdapterParam param); // } // // Path: renovate/src/main/java/renovate/Result.java // public final class Result<T> { // @SuppressWarnings("ConstantConditions") // Guarding public API nullability. // public static <T> Result<T> error(Throwable error) { // if (error == null) throw new NullPointerException("error == null"); // return new Result<>(null, error); // } // // @SuppressWarnings("ConstantConditions") // Guarding public API nullability. // public static <T> Result<T> response(Response<T> response) { // if (response == null) throw new NullPointerException("response == null"); // return new Result<>(response, null); // } // // private final Response<T> response; // private final Throwable error; // // private Result(Response<T> response, Throwable error) { // this.response = response; // this.error = error; // } // // /** // * The response received from executing an HTTP request. Only present when {@link #isError()} is // * false, null otherwise. // */ // // public Response<T> response() { // return response; // } // // /** // * The error experienced while attempting to execute an HTTP request. Only present when {@link // * #isError()} is true, null otherwise. // * If the error is an {@link IOException} then there was a problem with the transport to the // * remote server. Any other exception type indicates an unexpected failure and should be // * considered fatal (configuration error, programming error, etc.). // */ // // public Throwable error() { // return error; // } // // /** {@code true} if the request resulted in an error. See {@link #error()} for the cause. */ // public boolean isError() { // return error != null; // } // // @Override // public String toString() { // if (error != null) { // return "Result{isError=true, error=\"" + error + "\"}"; // } // return "Result{isError=false, response=" + response + '}'; // } // }
import io.reactivex.Maybe; import renovate.AdapterParam; import renovate.Call; import renovate.CallAdapter; import renovate.Result;
/* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava2.adapter; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:2017/5/27 * 描 述: * 修订历史: * ================================================ */ public class MaybeResult<T> implements CallAdapter<T, Maybe<Result<T>>> { @Override
// Path: renovate/src/main/java/renovate/AdapterParam.java // public class AdapterParam { // public boolean isAsync; // // public AdapterParam() { // isAsync = true; // } // } // // Path: renovate/src/main/java/renovate/Call.java // public interface Call<T> extends Cloneable { // Response<T> execute() throws IOException; // // void enqueue(Callback<T> callback); // // boolean isExecuted(); // // void cancel(); // // boolean isCanceled(); // // Call<T> clone(); // // Request request(); // } // // Path: renovate/src/main/java/renovate/CallAdapter.java // public interface CallAdapter<T, R> { // // /** call执行的代理方法 */ // R adapt(Call<T> call, AdapterParam param); // } // // Path: renovate/src/main/java/renovate/Result.java // public final class Result<T> { // @SuppressWarnings("ConstantConditions") // Guarding public API nullability. // public static <T> Result<T> error(Throwable error) { // if (error == null) throw new NullPointerException("error == null"); // return new Result<>(null, error); // } // // @SuppressWarnings("ConstantConditions") // Guarding public API nullability. // public static <T> Result<T> response(Response<T> response) { // if (response == null) throw new NullPointerException("response == null"); // return new Result<>(response, null); // } // // private final Response<T> response; // private final Throwable error; // // private Result(Response<T> response, Throwable error) { // this.response = response; // this.error = error; // } // // /** // * The response received from executing an HTTP request. Only present when {@link #isError()} is // * false, null otherwise. // */ // // public Response<T> response() { // return response; // } // // /** // * The error experienced while attempting to execute an HTTP request. Only present when {@link // * #isError()} is true, null otherwise. // * If the error is an {@link IOException} then there was a problem with the transport to the // * remote server. Any other exception type indicates an unexpected failure and should be // * considered fatal (configuration error, programming error, etc.). // */ // // public Throwable error() { // return error; // } // // /** {@code true} if the request resulted in an error. See {@link #error()} for the cause. */ // public boolean isError() { // return error != null; // } // // @Override // public String toString() { // if (error != null) { // return "Result{isError=true, error=\"" + error + "\"}"; // } // return "Result{isError=false, response=" + response + '}'; // } // } // Path: rx-renovate2/src/main/java/renovate/rxjava2/adapter/MaybeResult.java import io.reactivex.Maybe; import renovate.AdapterParam; import renovate.Call; import renovate.CallAdapter; import renovate.Result; /* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava2.adapter; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:2017/5/27 * 描 述: * 修订历史: * ================================================ */ public class MaybeResult<T> implements CallAdapter<T, Maybe<Result<T>>> { @Override
public Maybe<Result<T>> adapt(Call<T> call, AdapterParam param) {
baby2431/renovate2
rx-renovate2/src/main/java/renovate/rxjava2/adapter/FlowableResponse.java
// Path: renovate/src/main/java/renovate/AdapterParam.java // public class AdapterParam { // public boolean isAsync; // // public AdapterParam() { // isAsync = true; // } // } // // Path: renovate/src/main/java/renovate/Call.java // public interface Call<T> extends Cloneable { // Response<T> execute() throws IOException; // // void enqueue(Callback<T> callback); // // boolean isExecuted(); // // void cancel(); // // boolean isCanceled(); // // Call<T> clone(); // // Request request(); // } // // Path: renovate/src/main/java/renovate/CallAdapter.java // public interface CallAdapter<T, R> { // // /** call执行的代理方法 */ // R adapt(Call<T> call, AdapterParam param); // } // // Path: renovate/src/main/java/renovate/Response.java // public final class Response<T> { // private final okhttp3.Response rawResponse; // private final T body; // private final ResponseBody errorBody; // // private Response(okhttp3.Response rawResponse, T body, ResponseBody errorBody) { // this.rawResponse = rawResponse; // this.body = body; // this.errorBody = errorBody; // } // // public static <T> Response<T> success(T body) { // return success(body, new okhttp3.Response.Builder() // // .code(200) // .message("OK") // .protocol(Protocol.HTTP_1_1) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> success(T body, Headers headers) { // if (headers == null) throw new NullPointerException("headers == null"); // return success(body, new okhttp3.Response.Builder() // // .code(200) // .message("OK") // .protocol(Protocol.HTTP_1_1) // .headers(headers) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> success(T body, okhttp3.Response rawResponse) { // if (rawResponse == null) throw new NullPointerException("rawResponse == null"); // if (!rawResponse.isSuccessful()) { // throw new IllegalArgumentException("rawResponse must be successful response"); // } // return new Response<>(rawResponse, body, null); // } // // public static <T> Response<T> error(int code, ResponseBody body) { // if (code < 400) throw new IllegalArgumentException("code < 400: " + code); // return error(body, new okhttp3.Response.Builder() // // .code(code) // .protocol(Protocol.HTTP_1_1) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> error(ResponseBody body, okhttp3.Response rawResponse) { // if (body == null) throw new NullPointerException("body == null"); // if (rawResponse == null) throw new NullPointerException("rawResponse == null"); // if (rawResponse.isSuccessful()) { // throw new IllegalArgumentException("rawResponse should not be successful response"); // } // return new Response<>(rawResponse, null, body); // } // // public okhttp3.Response raw() { // return rawResponse; // } // // public int code() { // return rawResponse.code(); // } // // public String message() { // return rawResponse.message(); // } // // public Headers headers() { // return rawResponse.headers(); // } // // public boolean isSuccessful() { // return rawResponse.isSuccessful(); // } // // public T body() { // return body; // } // // public ResponseBody errorBody() { // return errorBody; // } // // @Override public String toString() { // return rawResponse.toString(); // } // }
import io.reactivex.BackpressureStrategy; import io.reactivex.Flowable; import renovate.AdapterParam; import renovate.Call; import renovate.CallAdapter; import renovate.Response;
/* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava2.adapter; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:2017/5/27 * 描 述: * 修订历史: * ================================================ */ public class FlowableResponse<T> implements CallAdapter<T, Flowable<Response<T>>> { @Override
// Path: renovate/src/main/java/renovate/AdapterParam.java // public class AdapterParam { // public boolean isAsync; // // public AdapterParam() { // isAsync = true; // } // } // // Path: renovate/src/main/java/renovate/Call.java // public interface Call<T> extends Cloneable { // Response<T> execute() throws IOException; // // void enqueue(Callback<T> callback); // // boolean isExecuted(); // // void cancel(); // // boolean isCanceled(); // // Call<T> clone(); // // Request request(); // } // // Path: renovate/src/main/java/renovate/CallAdapter.java // public interface CallAdapter<T, R> { // // /** call执行的代理方法 */ // R adapt(Call<T> call, AdapterParam param); // } // // Path: renovate/src/main/java/renovate/Response.java // public final class Response<T> { // private final okhttp3.Response rawResponse; // private final T body; // private final ResponseBody errorBody; // // private Response(okhttp3.Response rawResponse, T body, ResponseBody errorBody) { // this.rawResponse = rawResponse; // this.body = body; // this.errorBody = errorBody; // } // // public static <T> Response<T> success(T body) { // return success(body, new okhttp3.Response.Builder() // // .code(200) // .message("OK") // .protocol(Protocol.HTTP_1_1) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> success(T body, Headers headers) { // if (headers == null) throw new NullPointerException("headers == null"); // return success(body, new okhttp3.Response.Builder() // // .code(200) // .message("OK") // .protocol(Protocol.HTTP_1_1) // .headers(headers) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> success(T body, okhttp3.Response rawResponse) { // if (rawResponse == null) throw new NullPointerException("rawResponse == null"); // if (!rawResponse.isSuccessful()) { // throw new IllegalArgumentException("rawResponse must be successful response"); // } // return new Response<>(rawResponse, body, null); // } // // public static <T> Response<T> error(int code, ResponseBody body) { // if (code < 400) throw new IllegalArgumentException("code < 400: " + code); // return error(body, new okhttp3.Response.Builder() // // .code(code) // .protocol(Protocol.HTTP_1_1) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> error(ResponseBody body, okhttp3.Response rawResponse) { // if (body == null) throw new NullPointerException("body == null"); // if (rawResponse == null) throw new NullPointerException("rawResponse == null"); // if (rawResponse.isSuccessful()) { // throw new IllegalArgumentException("rawResponse should not be successful response"); // } // return new Response<>(rawResponse, null, body); // } // // public okhttp3.Response raw() { // return rawResponse; // } // // public int code() { // return rawResponse.code(); // } // // public String message() { // return rawResponse.message(); // } // // public Headers headers() { // return rawResponse.headers(); // } // // public boolean isSuccessful() { // return rawResponse.isSuccessful(); // } // // public T body() { // return body; // } // // public ResponseBody errorBody() { // return errorBody; // } // // @Override public String toString() { // return rawResponse.toString(); // } // } // Path: rx-renovate2/src/main/java/renovate/rxjava2/adapter/FlowableResponse.java import io.reactivex.BackpressureStrategy; import io.reactivex.Flowable; import renovate.AdapterParam; import renovate.Call; import renovate.CallAdapter; import renovate.Response; /* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava2.adapter; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:2017/5/27 * 描 述: * 修订历史: * ================================================ */ public class FlowableResponse<T> implements CallAdapter<T, Flowable<Response<T>>> { @Override
public Flowable<Response<T>> adapt(Call<T> call, AdapterParam param) {
baby2431/renovate2
rx-renovate2/src/main/java/renovate/rxjava2/adapter/FlowableResponse.java
// Path: renovate/src/main/java/renovate/AdapterParam.java // public class AdapterParam { // public boolean isAsync; // // public AdapterParam() { // isAsync = true; // } // } // // Path: renovate/src/main/java/renovate/Call.java // public interface Call<T> extends Cloneable { // Response<T> execute() throws IOException; // // void enqueue(Callback<T> callback); // // boolean isExecuted(); // // void cancel(); // // boolean isCanceled(); // // Call<T> clone(); // // Request request(); // } // // Path: renovate/src/main/java/renovate/CallAdapter.java // public interface CallAdapter<T, R> { // // /** call执行的代理方法 */ // R adapt(Call<T> call, AdapterParam param); // } // // Path: renovate/src/main/java/renovate/Response.java // public final class Response<T> { // private final okhttp3.Response rawResponse; // private final T body; // private final ResponseBody errorBody; // // private Response(okhttp3.Response rawResponse, T body, ResponseBody errorBody) { // this.rawResponse = rawResponse; // this.body = body; // this.errorBody = errorBody; // } // // public static <T> Response<T> success(T body) { // return success(body, new okhttp3.Response.Builder() // // .code(200) // .message("OK") // .protocol(Protocol.HTTP_1_1) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> success(T body, Headers headers) { // if (headers == null) throw new NullPointerException("headers == null"); // return success(body, new okhttp3.Response.Builder() // // .code(200) // .message("OK") // .protocol(Protocol.HTTP_1_1) // .headers(headers) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> success(T body, okhttp3.Response rawResponse) { // if (rawResponse == null) throw new NullPointerException("rawResponse == null"); // if (!rawResponse.isSuccessful()) { // throw new IllegalArgumentException("rawResponse must be successful response"); // } // return new Response<>(rawResponse, body, null); // } // // public static <T> Response<T> error(int code, ResponseBody body) { // if (code < 400) throw new IllegalArgumentException("code < 400: " + code); // return error(body, new okhttp3.Response.Builder() // // .code(code) // .protocol(Protocol.HTTP_1_1) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> error(ResponseBody body, okhttp3.Response rawResponse) { // if (body == null) throw new NullPointerException("body == null"); // if (rawResponse == null) throw new NullPointerException("rawResponse == null"); // if (rawResponse.isSuccessful()) { // throw new IllegalArgumentException("rawResponse should not be successful response"); // } // return new Response<>(rawResponse, null, body); // } // // public okhttp3.Response raw() { // return rawResponse; // } // // public int code() { // return rawResponse.code(); // } // // public String message() { // return rawResponse.message(); // } // // public Headers headers() { // return rawResponse.headers(); // } // // public boolean isSuccessful() { // return rawResponse.isSuccessful(); // } // // public T body() { // return body; // } // // public ResponseBody errorBody() { // return errorBody; // } // // @Override public String toString() { // return rawResponse.toString(); // } // }
import io.reactivex.BackpressureStrategy; import io.reactivex.Flowable; import renovate.AdapterParam; import renovate.Call; import renovate.CallAdapter; import renovate.Response;
/* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava2.adapter; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:2017/5/27 * 描 述: * 修订历史: * ================================================ */ public class FlowableResponse<T> implements CallAdapter<T, Flowable<Response<T>>> { @Override
// Path: renovate/src/main/java/renovate/AdapterParam.java // public class AdapterParam { // public boolean isAsync; // // public AdapterParam() { // isAsync = true; // } // } // // Path: renovate/src/main/java/renovate/Call.java // public interface Call<T> extends Cloneable { // Response<T> execute() throws IOException; // // void enqueue(Callback<T> callback); // // boolean isExecuted(); // // void cancel(); // // boolean isCanceled(); // // Call<T> clone(); // // Request request(); // } // // Path: renovate/src/main/java/renovate/CallAdapter.java // public interface CallAdapter<T, R> { // // /** call执行的代理方法 */ // R adapt(Call<T> call, AdapterParam param); // } // // Path: renovate/src/main/java/renovate/Response.java // public final class Response<T> { // private final okhttp3.Response rawResponse; // private final T body; // private final ResponseBody errorBody; // // private Response(okhttp3.Response rawResponse, T body, ResponseBody errorBody) { // this.rawResponse = rawResponse; // this.body = body; // this.errorBody = errorBody; // } // // public static <T> Response<T> success(T body) { // return success(body, new okhttp3.Response.Builder() // // .code(200) // .message("OK") // .protocol(Protocol.HTTP_1_1) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> success(T body, Headers headers) { // if (headers == null) throw new NullPointerException("headers == null"); // return success(body, new okhttp3.Response.Builder() // // .code(200) // .message("OK") // .protocol(Protocol.HTTP_1_1) // .headers(headers) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> success(T body, okhttp3.Response rawResponse) { // if (rawResponse == null) throw new NullPointerException("rawResponse == null"); // if (!rawResponse.isSuccessful()) { // throw new IllegalArgumentException("rawResponse must be successful response"); // } // return new Response<>(rawResponse, body, null); // } // // public static <T> Response<T> error(int code, ResponseBody body) { // if (code < 400) throw new IllegalArgumentException("code < 400: " + code); // return error(body, new okhttp3.Response.Builder() // // .code(code) // .protocol(Protocol.HTTP_1_1) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> error(ResponseBody body, okhttp3.Response rawResponse) { // if (body == null) throw new NullPointerException("body == null"); // if (rawResponse == null) throw new NullPointerException("rawResponse == null"); // if (rawResponse.isSuccessful()) { // throw new IllegalArgumentException("rawResponse should not be successful response"); // } // return new Response<>(rawResponse, null, body); // } // // public okhttp3.Response raw() { // return rawResponse; // } // // public int code() { // return rawResponse.code(); // } // // public String message() { // return rawResponse.message(); // } // // public Headers headers() { // return rawResponse.headers(); // } // // public boolean isSuccessful() { // return rawResponse.isSuccessful(); // } // // public T body() { // return body; // } // // public ResponseBody errorBody() { // return errorBody; // } // // @Override public String toString() { // return rawResponse.toString(); // } // } // Path: rx-renovate2/src/main/java/renovate/rxjava2/adapter/FlowableResponse.java import io.reactivex.BackpressureStrategy; import io.reactivex.Flowable; import renovate.AdapterParam; import renovate.Call; import renovate.CallAdapter; import renovate.Response; /* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava2.adapter; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:2017/5/27 * 描 述: * 修订历史: * ================================================ */ public class FlowableResponse<T> implements CallAdapter<T, Flowable<Response<T>>> { @Override
public Flowable<Response<T>> adapt(Call<T> call, AdapterParam param) {
baby2431/renovate2
renovate/src/main/java/renovate/Renovate.java
// Path: renovate/src/main/java/renovate/Utils.java // static <T> T checkNotNull(T object, String message) { // if (object == null) { // throw new NullPointerException(message); // } // return object; // }
import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.RequestBody; import okhttp3.ResponseBody; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.*; import java.util.concurrent.Executor; import static java.util.Collections.unmodifiableList; import static renovate.Utils.checkNotNull;
if (clazzOP.containsKey(object.getClass())) { return clazzOP.get(object.getClass()); } else { clazzOP.put(object.getClass(), new ObjectParser.Builder(Renovate.this, object).build()); } return clazzOP.get(object.getClass()); } public Request request(Object object) { ObjectParser objectParser = initObject(object); return new Request(this, objectParser, object); } public Request request() { return new Request(this); } public List<Converter.Factory> converterFactories() { return converterFactories; } <T> Converter<ResponseBody, T> responseBodyConverter(Type type, Annotation[] annotations) { return nextResponseBodyConverter(type, annotations); } <T> Converter<ResponseBody, T> nextResponseBodyConverter( Type type, Annotation[] annotations) {
// Path: renovate/src/main/java/renovate/Utils.java // static <T> T checkNotNull(T object, String message) { // if (object == null) { // throw new NullPointerException(message); // } // return object; // } // Path: renovate/src/main/java/renovate/Renovate.java import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.RequestBody; import okhttp3.ResponseBody; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.*; import java.util.concurrent.Executor; import static java.util.Collections.unmodifiableList; import static renovate.Utils.checkNotNull; if (clazzOP.containsKey(object.getClass())) { return clazzOP.get(object.getClass()); } else { clazzOP.put(object.getClass(), new ObjectParser.Builder(Renovate.this, object).build()); } return clazzOP.get(object.getClass()); } public Request request(Object object) { ObjectParser objectParser = initObject(object); return new Request(this, objectParser, object); } public Request request() { return new Request(this); } public List<Converter.Factory> converterFactories() { return converterFactories; } <T> Converter<ResponseBody, T> responseBodyConverter(Type type, Annotation[] annotations) { return nextResponseBodyConverter(type, annotations); } <T> Converter<ResponseBody, T> nextResponseBodyConverter( Type type, Annotation[] annotations) {
checkNotNull(type, "type == null");
baby2431/renovate2
rx-renovate2/src/main/java/renovate/rxjava2/observable/CallEnqueueObservable.java
// Path: renovate/src/main/java/renovate/Call.java // public interface Call<T> extends Cloneable { // Response<T> execute() throws IOException; // // void enqueue(Callback<T> callback); // // boolean isExecuted(); // // void cancel(); // // boolean isCanceled(); // // Call<T> clone(); // // Request request(); // } // // Path: renovate/src/main/java/renovate/Callback.java // public interface Callback<T> { // // void onResponse(Call<T> call, Response<T> response); // // void onFailure(Call<T> call, Throwable t); // } // // Path: renovate/src/main/java/renovate/Response.java // public final class Response<T> { // private final okhttp3.Response rawResponse; // private final T body; // private final ResponseBody errorBody; // // private Response(okhttp3.Response rawResponse, T body, ResponseBody errorBody) { // this.rawResponse = rawResponse; // this.body = body; // this.errorBody = errorBody; // } // // public static <T> Response<T> success(T body) { // return success(body, new okhttp3.Response.Builder() // // .code(200) // .message("OK") // .protocol(Protocol.HTTP_1_1) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> success(T body, Headers headers) { // if (headers == null) throw new NullPointerException("headers == null"); // return success(body, new okhttp3.Response.Builder() // // .code(200) // .message("OK") // .protocol(Protocol.HTTP_1_1) // .headers(headers) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> success(T body, okhttp3.Response rawResponse) { // if (rawResponse == null) throw new NullPointerException("rawResponse == null"); // if (!rawResponse.isSuccessful()) { // throw new IllegalArgumentException("rawResponse must be successful response"); // } // return new Response<>(rawResponse, body, null); // } // // public static <T> Response<T> error(int code, ResponseBody body) { // if (code < 400) throw new IllegalArgumentException("code < 400: " + code); // return error(body, new okhttp3.Response.Builder() // // .code(code) // .protocol(Protocol.HTTP_1_1) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> error(ResponseBody body, okhttp3.Response rawResponse) { // if (body == null) throw new NullPointerException("body == null"); // if (rawResponse == null) throw new NullPointerException("rawResponse == null"); // if (rawResponse.isSuccessful()) { // throw new IllegalArgumentException("rawResponse should not be successful response"); // } // return new Response<>(rawResponse, null, body); // } // // public okhttp3.Response raw() { // return rawResponse; // } // // public int code() { // return rawResponse.code(); // } // // public String message() { // return rawResponse.message(); // } // // public Headers headers() { // return rawResponse.headers(); // } // // public boolean isSuccessful() { // return rawResponse.isSuccessful(); // } // // public T body() { // return body; // } // // public ResponseBody errorBody() { // return errorBody; // } // // @Override public String toString() { // return rawResponse.toString(); // } // }
import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.CompositeException; import io.reactivex.exceptions.Exceptions; import io.reactivex.plugins.RxJavaPlugins; import renovate.Call; import renovate.Callback; import renovate.Response;
/* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava2.observable; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:16/9/11 * 描 述: * 修订历史: * ================================================ */ public class CallEnqueueObservable<T> extends Observable<Response<T>> { private final Call<T> originalCall; public CallEnqueueObservable(Call<T> originalCall) { this.originalCall = originalCall; } @Override protected void subscribeActual(Observer<? super Response<T>> observer) { // Since Call is a one-shot type, clone it for each new observer. Call<T> call = originalCall.clone(); CallCallback<T> callback = new CallCallback<>(call, observer); observer.onSubscribe(callback); call.enqueue(callback); }
// Path: renovate/src/main/java/renovate/Call.java // public interface Call<T> extends Cloneable { // Response<T> execute() throws IOException; // // void enqueue(Callback<T> callback); // // boolean isExecuted(); // // void cancel(); // // boolean isCanceled(); // // Call<T> clone(); // // Request request(); // } // // Path: renovate/src/main/java/renovate/Callback.java // public interface Callback<T> { // // void onResponse(Call<T> call, Response<T> response); // // void onFailure(Call<T> call, Throwable t); // } // // Path: renovate/src/main/java/renovate/Response.java // public final class Response<T> { // private final okhttp3.Response rawResponse; // private final T body; // private final ResponseBody errorBody; // // private Response(okhttp3.Response rawResponse, T body, ResponseBody errorBody) { // this.rawResponse = rawResponse; // this.body = body; // this.errorBody = errorBody; // } // // public static <T> Response<T> success(T body) { // return success(body, new okhttp3.Response.Builder() // // .code(200) // .message("OK") // .protocol(Protocol.HTTP_1_1) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> success(T body, Headers headers) { // if (headers == null) throw new NullPointerException("headers == null"); // return success(body, new okhttp3.Response.Builder() // // .code(200) // .message("OK") // .protocol(Protocol.HTTP_1_1) // .headers(headers) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> success(T body, okhttp3.Response rawResponse) { // if (rawResponse == null) throw new NullPointerException("rawResponse == null"); // if (!rawResponse.isSuccessful()) { // throw new IllegalArgumentException("rawResponse must be successful response"); // } // return new Response<>(rawResponse, body, null); // } // // public static <T> Response<T> error(int code, ResponseBody body) { // if (code < 400) throw new IllegalArgumentException("code < 400: " + code); // return error(body, new okhttp3.Response.Builder() // // .code(code) // .protocol(Protocol.HTTP_1_1) // .request(new Request.Builder().url("http://localhost/").build()) // .build()); // } // // public static <T> Response<T> error(ResponseBody body, okhttp3.Response rawResponse) { // if (body == null) throw new NullPointerException("body == null"); // if (rawResponse == null) throw new NullPointerException("rawResponse == null"); // if (rawResponse.isSuccessful()) { // throw new IllegalArgumentException("rawResponse should not be successful response"); // } // return new Response<>(rawResponse, null, body); // } // // public okhttp3.Response raw() { // return rawResponse; // } // // public int code() { // return rawResponse.code(); // } // // public String message() { // return rawResponse.message(); // } // // public Headers headers() { // return rawResponse.headers(); // } // // public boolean isSuccessful() { // return rawResponse.isSuccessful(); // } // // public T body() { // return body; // } // // public ResponseBody errorBody() { // return errorBody; // } // // @Override public String toString() { // return rawResponse.toString(); // } // } // Path: rx-renovate2/src/main/java/renovate/rxjava2/observable/CallEnqueueObservable.java import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.disposables.Disposable; import io.reactivex.exceptions.CompositeException; import io.reactivex.exceptions.Exceptions; import io.reactivex.plugins.RxJavaPlugins; import renovate.Call; import renovate.Callback; import renovate.Response; /* * Copyright 2016 jeasonlzy(廖子尧) * * 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 renovate.rxjava2.observable; /** * ================================================ * 作 者:jeasonlzy(廖子尧)Github地址:https://github.com/jeasonlzy * 版 本:1.0 * 创建日期:16/9/11 * 描 述: * 修订历史: * ================================================ */ public class CallEnqueueObservable<T> extends Observable<Response<T>> { private final Call<T> originalCall; public CallEnqueueObservable(Call<T> originalCall) { this.originalCall = originalCall; } @Override protected void subscribeActual(Observer<? super Response<T>> observer) { // Since Call is a one-shot type, clone it for each new observer. Call<T> call = originalCall.clone(); CallCallback<T> callback = new CallCallback<>(call, observer); observer.onSubscribe(callback); call.enqueue(callback); }
private static final class CallCallback<T> implements Disposable, Callback<T> {
baby2431/renovate2
renovate/src/main/java/renovate/ParameterHandler.java
// Path: renovate/src/main/java/renovate/Utils.java // static <T> T checkNotNull(T object, String message) { // if (object == null) { // throw new NullPointerException(message); // } // return object; // }
import okhttp3.Headers; import okhttp3.MultipartBody; import okhttp3.RequestBody; import java.io.IOException; import java.lang.reflect.Array; import java.util.Map; import static renovate.Utils.checkNotNull;
ParameterHandler.this.apply(builder, value); } } }; } final ParameterHandler<Object> array() { return new ParameterHandler<Object>() { @Override void apply(OKHttpRequestBuilder builder, Object values) throws IOException { if (values == null) return; // Skip null values. for (int i = 0, size = Array.getLength(values); i < size; i++) { //noinspection unchecked ParameterHandler.this.apply(builder, (T) Array.get(values, i)); } } }; } static final class RelativeUrl extends ParameterHandler<Object> { @Override void apply(OKHttpRequestBuilder builder, Object value) { builder.setRelativeUrl(value); } } static final class Header<T> extends ParameterHandler<T> { private final String name; private final Converter<T, String> valueConverter; Header(String name, Converter<T, String> valueConverter) {
// Path: renovate/src/main/java/renovate/Utils.java // static <T> T checkNotNull(T object, String message) { // if (object == null) { // throw new NullPointerException(message); // } // return object; // } // Path: renovate/src/main/java/renovate/ParameterHandler.java import okhttp3.Headers; import okhttp3.MultipartBody; import okhttp3.RequestBody; import java.io.IOException; import java.lang.reflect.Array; import java.util.Map; import static renovate.Utils.checkNotNull; ParameterHandler.this.apply(builder, value); } } }; } final ParameterHandler<Object> array() { return new ParameterHandler<Object>() { @Override void apply(OKHttpRequestBuilder builder, Object values) throws IOException { if (values == null) return; // Skip null values. for (int i = 0, size = Array.getLength(values); i < size; i++) { //noinspection unchecked ParameterHandler.this.apply(builder, (T) Array.get(values, i)); } } }; } static final class RelativeUrl extends ParameterHandler<Object> { @Override void apply(OKHttpRequestBuilder builder, Object value) { builder.setRelativeUrl(value); } } static final class Header<T> extends ParameterHandler<T> { private final String name; private final Converter<T, String> valueConverter; Header(String name, Converter<T, String> valueConverter) {
this.name = checkNotNull(name, "name == null");