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
osuWorks/osu-api-Java-Client
Common/src/main/java/de/maxikg/osuapi/model/MatchDetails.java
// Path: Common/src/main/java/de/maxikg/osuapi/jackson/OsuDateDeserializer.java // public class OsuDateDeserializer extends JsonDeserializer<Date> { // // @Override // public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { // String value = jsonParser.getValueAsString(); // // return value != null ? DateUtils.parseDate(value) : null; // } // } // // Path: Common/src/main/java/de/maxikg/osuapi/jackson/OsuDateSerializer.java // public class OsuDateSerializer extends JsonSerializer<Date> { // // @Override // public void serialize(Date value, JsonGenerator generator, SerializerProvider provider) throws IOException { // if (value != null) // generator.writeString(DateUtils.formatDate(value)); // else // generator.writeNull(); // } // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import de.maxikg.osuapi.jackson.OsuDateDeserializer; import de.maxikg.osuapi.jackson.OsuDateSerializer; import lombok.Data; import java.util.Date;
package de.maxikg.osuapi.model; /** * @author maxikg * @since 1.0 */ @Data public class MatchDetails { @JsonProperty("match_id") private int matchId; @JsonProperty("name") private String name; @JsonProperty("start_time")
// Path: Common/src/main/java/de/maxikg/osuapi/jackson/OsuDateDeserializer.java // public class OsuDateDeserializer extends JsonDeserializer<Date> { // // @Override // public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { // String value = jsonParser.getValueAsString(); // // return value != null ? DateUtils.parseDate(value) : null; // } // } // // Path: Common/src/main/java/de/maxikg/osuapi/jackson/OsuDateSerializer.java // public class OsuDateSerializer extends JsonSerializer<Date> { // // @Override // public void serialize(Date value, JsonGenerator generator, SerializerProvider provider) throws IOException { // if (value != null) // generator.writeString(DateUtils.formatDate(value)); // else // generator.writeNull(); // } // } // Path: Common/src/main/java/de/maxikg/osuapi/model/MatchDetails.java import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import de.maxikg.osuapi.jackson.OsuDateDeserializer; import de.maxikg.osuapi.jackson.OsuDateSerializer; import lombok.Data; import java.util.Date; package de.maxikg.osuapi.model; /** * @author maxikg * @since 1.0 */ @Data public class MatchDetails { @JsonProperty("match_id") private int matchId; @JsonProperty("name") private String name; @JsonProperty("start_time")
@JsonSerialize(using = OsuDateSerializer.class)
osuWorks/osu-api-Java-Client
Common/src/main/java/de/maxikg/osuapi/model/MatchDetails.java
// Path: Common/src/main/java/de/maxikg/osuapi/jackson/OsuDateDeserializer.java // public class OsuDateDeserializer extends JsonDeserializer<Date> { // // @Override // public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { // String value = jsonParser.getValueAsString(); // // return value != null ? DateUtils.parseDate(value) : null; // } // } // // Path: Common/src/main/java/de/maxikg/osuapi/jackson/OsuDateSerializer.java // public class OsuDateSerializer extends JsonSerializer<Date> { // // @Override // public void serialize(Date value, JsonGenerator generator, SerializerProvider provider) throws IOException { // if (value != null) // generator.writeString(DateUtils.formatDate(value)); // else // generator.writeNull(); // } // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import de.maxikg.osuapi.jackson.OsuDateDeserializer; import de.maxikg.osuapi.jackson.OsuDateSerializer; import lombok.Data; import java.util.Date;
package de.maxikg.osuapi.model; /** * @author maxikg * @since 1.0 */ @Data public class MatchDetails { @JsonProperty("match_id") private int matchId; @JsonProperty("name") private String name; @JsonProperty("start_time") @JsonSerialize(using = OsuDateSerializer.class)
// Path: Common/src/main/java/de/maxikg/osuapi/jackson/OsuDateDeserializer.java // public class OsuDateDeserializer extends JsonDeserializer<Date> { // // @Override // public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { // String value = jsonParser.getValueAsString(); // // return value != null ? DateUtils.parseDate(value) : null; // } // } // // Path: Common/src/main/java/de/maxikg/osuapi/jackson/OsuDateSerializer.java // public class OsuDateSerializer extends JsonSerializer<Date> { // // @Override // public void serialize(Date value, JsonGenerator generator, SerializerProvider provider) throws IOException { // if (value != null) // generator.writeString(DateUtils.formatDate(value)); // else // generator.writeNull(); // } // } // Path: Common/src/main/java/de/maxikg/osuapi/model/MatchDetails.java import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import de.maxikg.osuapi.jackson.OsuDateDeserializer; import de.maxikg.osuapi.jackson.OsuDateSerializer; import lombok.Data; import java.util.Date; package de.maxikg.osuapi.model; /** * @author maxikg * @since 1.0 */ @Data public class MatchDetails { @JsonProperty("match_id") private int matchId; @JsonProperty("name") private String name; @JsonProperty("start_time") @JsonSerialize(using = OsuDateSerializer.class)
@JsonDeserialize(using = OsuDateDeserializer.class)
osuWorks/osu-api-Java-Client
Client/src/main/java/de/maxikg/osuapi/client/request/builder/GetScoresRequestBuilder.java
// Path: Common/src/main/java/de/maxikg/osuapi/model/BeatmapScore.java // @Data // public class BeatmapScore { // // @JsonProperty("score") // private int score; // // @JsonProperty("username") // private String username; // // @JsonProperty("count300") // private int count300; // // @JsonProperty("count100") // private int count100; // // @JsonProperty("count50") // private int count50; // // @JsonProperty("countmiss") // private int countMiss; // // @JsonProperty("maxcombo") // private int maxCombo; // // @JsonProperty("countkatu") // private int countKatu; // // @JsonProperty("countgeki") // private int countGeki; // // @JsonProperty("perfect") // @JsonSerialize(using = OsuBooleanSerializer.class) // @JsonDeserialize(using = OsuBooleanDeserializer.class) // private boolean perfect; // // @JsonProperty("enabled_mods") // @JsonSerialize(using = OsuModSerializer.class) // @JsonDeserialize(using = OsuModDeserializer.class) // private Set<Mod> enabledMods; // // @JsonProperty("user_id") // private int userId; // // @JsonProperty("date") // @JsonSerialize(using = OsuDateSerializer.class) // @JsonDeserialize(using = OsuDateDeserializer.class) // private Date date; // // @JsonProperty("rank") // private String rank; // // @JsonProperty("pp") // private float pp; // } // // Path: Common/src/main/java/de/maxikg/osuapi/model/GameMode.java // @RequiredArgsConstructor // public enum GameMode implements Valuable<Integer> { // // /** // * It represents the default osu! game mode. See: https://osu.ppy.sh/wiki/Standard // */ // STANDARD(0), // // /** // * It represents the game mode on which you must hit the drum. See: https://osu.ppy.sh/wiki/Taiko // */ // TAIKO(1), // // /** // * It represents the game mode on which you must catch the falling fruits. See: // * https://osu.ppy.sh/wiki/Catch_The_Beat // */ // CTB(2), // // /** // * It represents the game mode on which you must hit the right beat note in the right moment. See: // * https://osu.ppy.sh/wiki/Osu!mania // */ // OSU_MANIA(3); // // @NonNull // private final Integer value; // // /** // * {@inheritDoc} // */ // @JsonValue // public Integer getValue() { // return value; // } // // /** // * Returns the {@code GameMode} by it's number value. // * // * @param value The value. // * @return An {@link Optional}. Absent if an unknown value was given. // */ // @JsonCreator // public static Optional<GameMode> byValue(int value) { // return ValuableUtils.getByValue(GameMode.class, value); // } // }
import de.maxikg.osuapi.model.BeatmapScore; import de.maxikg.osuapi.model.GameMode; import java.util.Collection;
package de.maxikg.osuapi.client.request.builder; /** * @author maxikg */ public interface GetScoresRequestBuilder extends RequestBuilder<Collection<BeatmapScore>> { GetScoresRequestBuilder username(String username); GetScoresRequestBuilder userId(int id); GetScoresRequestBuilder unsetUser();
// Path: Common/src/main/java/de/maxikg/osuapi/model/BeatmapScore.java // @Data // public class BeatmapScore { // // @JsonProperty("score") // private int score; // // @JsonProperty("username") // private String username; // // @JsonProperty("count300") // private int count300; // // @JsonProperty("count100") // private int count100; // // @JsonProperty("count50") // private int count50; // // @JsonProperty("countmiss") // private int countMiss; // // @JsonProperty("maxcombo") // private int maxCombo; // // @JsonProperty("countkatu") // private int countKatu; // // @JsonProperty("countgeki") // private int countGeki; // // @JsonProperty("perfect") // @JsonSerialize(using = OsuBooleanSerializer.class) // @JsonDeserialize(using = OsuBooleanDeserializer.class) // private boolean perfect; // // @JsonProperty("enabled_mods") // @JsonSerialize(using = OsuModSerializer.class) // @JsonDeserialize(using = OsuModDeserializer.class) // private Set<Mod> enabledMods; // // @JsonProperty("user_id") // private int userId; // // @JsonProperty("date") // @JsonSerialize(using = OsuDateSerializer.class) // @JsonDeserialize(using = OsuDateDeserializer.class) // private Date date; // // @JsonProperty("rank") // private String rank; // // @JsonProperty("pp") // private float pp; // } // // Path: Common/src/main/java/de/maxikg/osuapi/model/GameMode.java // @RequiredArgsConstructor // public enum GameMode implements Valuable<Integer> { // // /** // * It represents the default osu! game mode. See: https://osu.ppy.sh/wiki/Standard // */ // STANDARD(0), // // /** // * It represents the game mode on which you must hit the drum. See: https://osu.ppy.sh/wiki/Taiko // */ // TAIKO(1), // // /** // * It represents the game mode on which you must catch the falling fruits. See: // * https://osu.ppy.sh/wiki/Catch_The_Beat // */ // CTB(2), // // /** // * It represents the game mode on which you must hit the right beat note in the right moment. See: // * https://osu.ppy.sh/wiki/Osu!mania // */ // OSU_MANIA(3); // // @NonNull // private final Integer value; // // /** // * {@inheritDoc} // */ // @JsonValue // public Integer getValue() { // return value; // } // // /** // * Returns the {@code GameMode} by it's number value. // * // * @param value The value. // * @return An {@link Optional}. Absent if an unknown value was given. // */ // @JsonCreator // public static Optional<GameMode> byValue(int value) { // return ValuableUtils.getByValue(GameMode.class, value); // } // } // Path: Client/src/main/java/de/maxikg/osuapi/client/request/builder/GetScoresRequestBuilder.java import de.maxikg.osuapi.model.BeatmapScore; import de.maxikg.osuapi.model.GameMode; import java.util.Collection; package de.maxikg.osuapi.client.request.builder; /** * @author maxikg */ public interface GetScoresRequestBuilder extends RequestBuilder<Collection<BeatmapScore>> { GetScoresRequestBuilder username(String username); GetScoresRequestBuilder userId(int id); GetScoresRequestBuilder unsetUser();
GetScoresRequestBuilder mode(GameMode mode);
osuWorks/osu-api-Java-Client
Common/src/main/java/de/maxikg/osuapi/model/GameMode.java
// Path: Common/src/main/java/de/maxikg/osuapi/utils/Valuable.java // public interface Valuable<T> { // // /** // * Returns the representative and unique value. // * // * @return The value // */ // T getValue(); // } // // Path: Common/src/main/java/de/maxikg/osuapi/utils/ValuableUtils.java // @NoArgsConstructor(access = AccessLevel.PRIVATE) // public class ValuableUtils { // // /** // * Identifies a enum value based on value returned by {@link Valuable#getValue()}. // * // * @param enumClass The class of the enumeration type. // * @param value The value to search for (it can be null). // * @param <T> The value type. // * @param <U> The enum entry type. // * @return A {@link Optional} value. Absent if no enum entry matches given value. // */ // public static <T, U extends Enum<U> & Valuable<T>> Optional<U> getByValue(Class<U> enumClass, T value) { // for (U enumerationValue : enumClass.getEnumConstants()) { // T currentValue = enumerationValue.getValue(); // // if ((currentValue == null && value == null) || (value != null && value.equals(currentValue))) // return Optional.fromNullable(enumerationValue); // } // // return Optional.absent(); // } // }
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import com.google.common.base.Optional; import de.maxikg.osuapi.utils.Valuable; import de.maxikg.osuapi.utils.ValuableUtils; import lombok.NonNull; import lombok.RequiredArgsConstructor;
package de.maxikg.osuapi.model; /** * Represents the osu! game mode. * * @since 1.0 * @author maxikg */ @RequiredArgsConstructor public enum GameMode implements Valuable<Integer> { /** * It represents the default osu! game mode. See: https://osu.ppy.sh/wiki/Standard */ STANDARD(0), /** * It represents the game mode on which you must hit the drum. See: https://osu.ppy.sh/wiki/Taiko */ TAIKO(1), /** * It represents the game mode on which you must catch the falling fruits. See: * https://osu.ppy.sh/wiki/Catch_The_Beat */ CTB(2), /** * It represents the game mode on which you must hit the right beat note in the right moment. See: * https://osu.ppy.sh/wiki/Osu!mania */ OSU_MANIA(3); @NonNull private final Integer value; /** * {@inheritDoc} */ @JsonValue public Integer getValue() { return value; } /** * Returns the {@code GameMode} by it's number value. * * @param value The value. * @return An {@link Optional}. Absent if an unknown value was given. */ @JsonCreator public static Optional<GameMode> byValue(int value) {
// Path: Common/src/main/java/de/maxikg/osuapi/utils/Valuable.java // public interface Valuable<T> { // // /** // * Returns the representative and unique value. // * // * @return The value // */ // T getValue(); // } // // Path: Common/src/main/java/de/maxikg/osuapi/utils/ValuableUtils.java // @NoArgsConstructor(access = AccessLevel.PRIVATE) // public class ValuableUtils { // // /** // * Identifies a enum value based on value returned by {@link Valuable#getValue()}. // * // * @param enumClass The class of the enumeration type. // * @param value The value to search for (it can be null). // * @param <T> The value type. // * @param <U> The enum entry type. // * @return A {@link Optional} value. Absent if no enum entry matches given value. // */ // public static <T, U extends Enum<U> & Valuable<T>> Optional<U> getByValue(Class<U> enumClass, T value) { // for (U enumerationValue : enumClass.getEnumConstants()) { // T currentValue = enumerationValue.getValue(); // // if ((currentValue == null && value == null) || (value != null && value.equals(currentValue))) // return Optional.fromNullable(enumerationValue); // } // // return Optional.absent(); // } // } // Path: Common/src/main/java/de/maxikg/osuapi/model/GameMode.java import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import com.google.common.base.Optional; import de.maxikg.osuapi.utils.Valuable; import de.maxikg.osuapi.utils.ValuableUtils; import lombok.NonNull; import lombok.RequiredArgsConstructor; package de.maxikg.osuapi.model; /** * Represents the osu! game mode. * * @since 1.0 * @author maxikg */ @RequiredArgsConstructor public enum GameMode implements Valuable<Integer> { /** * It represents the default osu! game mode. See: https://osu.ppy.sh/wiki/Standard */ STANDARD(0), /** * It represents the game mode on which you must hit the drum. See: https://osu.ppy.sh/wiki/Taiko */ TAIKO(1), /** * It represents the game mode on which you must catch the falling fruits. See: * https://osu.ppy.sh/wiki/Catch_The_Beat */ CTB(2), /** * It represents the game mode on which you must hit the right beat note in the right moment. See: * https://osu.ppy.sh/wiki/Osu!mania */ OSU_MANIA(3); @NonNull private final Integer value; /** * {@inheritDoc} */ @JsonValue public Integer getValue() { return value; } /** * Returns the {@code GameMode} by it's number value. * * @param value The value. * @return An {@link Optional}. Absent if an unknown value was given. */ @JsonCreator public static Optional<GameMode> byValue(int value) {
return ValuableUtils.getByValue(GameMode.class, value);
osuWorks/osu-api-Java-Client
Common/src/main/java/de/maxikg/osuapi/model/TeamType.java
// Path: Common/src/main/java/de/maxikg/osuapi/utils/Valuable.java // public interface Valuable<T> { // // /** // * Returns the representative and unique value. // * // * @return The value // */ // T getValue(); // } // // Path: Common/src/main/java/de/maxikg/osuapi/utils/ValuableUtils.java // @NoArgsConstructor(access = AccessLevel.PRIVATE) // public class ValuableUtils { // // /** // * Identifies a enum value based on value returned by {@link Valuable#getValue()}. // * // * @param enumClass The class of the enumeration type. // * @param value The value to search for (it can be null). // * @param <T> The value type. // * @param <U> The enum entry type. // * @return A {@link Optional} value. Absent if no enum entry matches given value. // */ // public static <T, U extends Enum<U> & Valuable<T>> Optional<U> getByValue(Class<U> enumClass, T value) { // for (U enumerationValue : enumClass.getEnumConstants()) { // T currentValue = enumerationValue.getValue(); // // if ((currentValue == null && value == null) || (value != null && value.equals(currentValue))) // return Optional.fromNullable(enumerationValue); // } // // return Optional.absent(); // } // }
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import com.google.common.base.Optional; import de.maxikg.osuapi.utils.Valuable; import de.maxikg.osuapi.utils.ValuableUtils; import lombok.RequiredArgsConstructor;
package de.maxikg.osuapi.model; /** * @author maxikg * @since 1.0 */ @RequiredArgsConstructor public enum TeamType implements Valuable<Integer> { HEAD_TO_HEAD(0), TAG_COOP(1), TEAM_VS(2), TAG_TEAM_VS(3); private final Integer value; @JsonValue public Integer getValue() { return value; } @JsonCreator public static Optional<TeamType> byValue(int value) {
// Path: Common/src/main/java/de/maxikg/osuapi/utils/Valuable.java // public interface Valuable<T> { // // /** // * Returns the representative and unique value. // * // * @return The value // */ // T getValue(); // } // // Path: Common/src/main/java/de/maxikg/osuapi/utils/ValuableUtils.java // @NoArgsConstructor(access = AccessLevel.PRIVATE) // public class ValuableUtils { // // /** // * Identifies a enum value based on value returned by {@link Valuable#getValue()}. // * // * @param enumClass The class of the enumeration type. // * @param value The value to search for (it can be null). // * @param <T> The value type. // * @param <U> The enum entry type. // * @return A {@link Optional} value. Absent if no enum entry matches given value. // */ // public static <T, U extends Enum<U> & Valuable<T>> Optional<U> getByValue(Class<U> enumClass, T value) { // for (U enumerationValue : enumClass.getEnumConstants()) { // T currentValue = enumerationValue.getValue(); // // if ((currentValue == null && value == null) || (value != null && value.equals(currentValue))) // return Optional.fromNullable(enumerationValue); // } // // return Optional.absent(); // } // } // Path: Common/src/main/java/de/maxikg/osuapi/model/TeamType.java import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import com.google.common.base.Optional; import de.maxikg.osuapi.utils.Valuable; import de.maxikg.osuapi.utils.ValuableUtils; import lombok.RequiredArgsConstructor; package de.maxikg.osuapi.model; /** * @author maxikg * @since 1.0 */ @RequiredArgsConstructor public enum TeamType implements Valuable<Integer> { HEAD_TO_HEAD(0), TAG_COOP(1), TEAM_VS(2), TAG_TEAM_VS(3); private final Integer value; @JsonValue public Integer getValue() { return value; } @JsonCreator public static Optional<TeamType> byValue(int value) {
return ValuableUtils.getByValue(TeamType.class, value);
osuWorks/osu-api-Java-Client
Common/src/test/java/de/maxikg/osuapi/model/MatchTest.java
// Path: Common/src/main/java/de/maxikg/osuapi/utils/DateUtils.java // @NoArgsConstructor(access = AccessLevel.NONE) // public class DateUtils { // // private static final DateFormat OSU_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // // static { // OSU_DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC+8")); // } // // public static Date parseDate(String input) { // try { // synchronized (OSU_DATE_FORMAT) { // return OSU_DATE_FORMAT.parse(input); // } // } catch (ParseException e) { // throw Throwables.propagate(e); // } // } // // public static String formatDate(Date date) { // synchronized (OSU_DATE_FORMAT) { // return OSU_DATE_FORMAT.format(date); // } // } // }
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import de.maxikg.osuapi.utils.DateUtils; import org.junit.Test; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*;
package de.maxikg.osuapi.model; /** * @author maxikg */ public class MatchTest { @Test public void testFromFile() throws Throwable { ObjectMapper mapper = new ObjectMapper(); List<Match> matches = mapper.readValue(getClass().getResourceAsStream("/api/responses/get_match.json"), new TypeReference<List<Match>>() { }); assertThat(matches.size(), equalTo(1)); Match first = matches.get(0); MatchDetails firstDetails = first.getDetails(); assertThat(firstDetails.getMatchId(), equalTo(1936471)); assertThat(firstDetails.getName(), equalTo("Marcin's game"));
// Path: Common/src/main/java/de/maxikg/osuapi/utils/DateUtils.java // @NoArgsConstructor(access = AccessLevel.NONE) // public class DateUtils { // // private static final DateFormat OSU_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // // static { // OSU_DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC+8")); // } // // public static Date parseDate(String input) { // try { // synchronized (OSU_DATE_FORMAT) { // return OSU_DATE_FORMAT.parse(input); // } // } catch (ParseException e) { // throw Throwables.propagate(e); // } // } // // public static String formatDate(Date date) { // synchronized (OSU_DATE_FORMAT) { // return OSU_DATE_FORMAT.format(date); // } // } // } // Path: Common/src/test/java/de/maxikg/osuapi/model/MatchTest.java import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import de.maxikg.osuapi.utils.DateUtils; import org.junit.Test; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; package de.maxikg.osuapi.model; /** * @author maxikg */ public class MatchTest { @Test public void testFromFile() throws Throwable { ObjectMapper mapper = new ObjectMapper(); List<Match> matches = mapper.readValue(getClass().getResourceAsStream("/api/responses/get_match.json"), new TypeReference<List<Match>>() { }); assertThat(matches.size(), equalTo(1)); Match first = matches.get(0); MatchDetails firstDetails = first.getDetails(); assertThat(firstDetails.getMatchId(), equalTo(1936471)); assertThat(firstDetails.getName(), equalTo("Marcin's game"));
assertThat(firstDetails.getStartTime(), equalTo(DateUtils.parseDate("2013-10-06 03:34:54")));
osuWorks/osu-api-Java-Client
Common/src/test/java/de/maxikg/osuapi/jackson/OsuModSerializationTest.java
// Path: Common/src/main/java/de/maxikg/osuapi/model/Mod.java // @RequiredArgsConstructor // public enum Mod { // // NO_FAIL(1), // EASY(2), // HIDDEN(8), // HARD_ROCK(16), // SUDDEN_DEATH(32), // DOUBLE_TIME(64), // RELAX(128), // HALF_TIME(256), // NIGHTCORE(512), // FLASHLIGHT(1024), // AUTOPLAY(2048), // SPUN_OUT(4096), // RELAX_2(8192), // PERFECT(16384), // KEY_4(32768), // KEY_5(65536), // KEY_6(131072), // KEY_7(262144), // KEY_8(524288), // KEY_MOD(KEY_4.getFlag() | KEY_5.getFlag() | KEY_6.getFlag() | KEY_7.getFlag() | KEY_8.getFlag()), // FADE_IN(1048576), // RANDOM(2097152), // LAST_MOD(4194304), // FREE_MOD_ALLOWED(NO_FAIL.getFlag() | EASY.getFlag() | HIDDEN.getFlag() | HARD_ROCK.getFlag() | SUDDEN_DEATH.getFlag() | FLASHLIGHT.getFlag() | FADE_IN.getFlag() | RELAX.getFlag() | RELAX_2.getFlag() | SPUN_OUT.getFlag() | KEY_MOD.getFlag()), // KEY_9(16777216), // KEY_10(33554432), // KEY_1(67108864), // KEY_3(134217728), // KEY_2(268435456); // // @Getter // private final int flag; // // public boolean isEnabled(int flagSum) { // int flag = getFlag(); // // return (flagSum & flag) == flag; // } // // public static Set<Mod> parseFlagSum(int flagSum) { // ImmutableSet.Builder<Mod> builder = ImmutableSet.builder(); // // for (Mod mod : values()) { // if (mod.isEnabled(flagSum)) // builder.add(mod); // } // // return builder.build(); // } // // public static int createSum(Iterable<Mod> mods) { // int sum = 0; // // for (Mod mod : mods) // sum |= mod.getFlag(); // // return sum; // } // }
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import de.maxikg.osuapi.model.Mod; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.junit.Test; import java.util.Set; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*;
package de.maxikg.osuapi.jackson; /** * @author maxikg */ public class OsuModSerializationTest { @Test public void testSerializationProcess() throws Throwable { ObjectMapper mapper = new ObjectMapper();
// Path: Common/src/main/java/de/maxikg/osuapi/model/Mod.java // @RequiredArgsConstructor // public enum Mod { // // NO_FAIL(1), // EASY(2), // HIDDEN(8), // HARD_ROCK(16), // SUDDEN_DEATH(32), // DOUBLE_TIME(64), // RELAX(128), // HALF_TIME(256), // NIGHTCORE(512), // FLASHLIGHT(1024), // AUTOPLAY(2048), // SPUN_OUT(4096), // RELAX_2(8192), // PERFECT(16384), // KEY_4(32768), // KEY_5(65536), // KEY_6(131072), // KEY_7(262144), // KEY_8(524288), // KEY_MOD(KEY_4.getFlag() | KEY_5.getFlag() | KEY_6.getFlag() | KEY_7.getFlag() | KEY_8.getFlag()), // FADE_IN(1048576), // RANDOM(2097152), // LAST_MOD(4194304), // FREE_MOD_ALLOWED(NO_FAIL.getFlag() | EASY.getFlag() | HIDDEN.getFlag() | HARD_ROCK.getFlag() | SUDDEN_DEATH.getFlag() | FLASHLIGHT.getFlag() | FADE_IN.getFlag() | RELAX.getFlag() | RELAX_2.getFlag() | SPUN_OUT.getFlag() | KEY_MOD.getFlag()), // KEY_9(16777216), // KEY_10(33554432), // KEY_1(67108864), // KEY_3(134217728), // KEY_2(268435456); // // @Getter // private final int flag; // // public boolean isEnabled(int flagSum) { // int flag = getFlag(); // // return (flagSum & flag) == flag; // } // // public static Set<Mod> parseFlagSum(int flagSum) { // ImmutableSet.Builder<Mod> builder = ImmutableSet.builder(); // // for (Mod mod : values()) { // if (mod.isEnabled(flagSum)) // builder.add(mod); // } // // return builder.build(); // } // // public static int createSum(Iterable<Mod> mods) { // int sum = 0; // // for (Mod mod : mods) // sum |= mod.getFlag(); // // return sum; // } // } // Path: Common/src/test/java/de/maxikg/osuapi/jackson/OsuModSerializationTest.java import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import de.maxikg.osuapi.model.Mod; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.junit.Test; import java.util.Set; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; package de.maxikg.osuapi.jackson; /** * @author maxikg */ public class OsuModSerializationTest { @Test public void testSerializationProcess() throws Throwable { ObjectMapper mapper = new ObjectMapper();
TestClass allMods = new TestClass(Sets.newHashSet(Mod.values()));
osuWorks/osu-api-Java-Client
Client/src/main/java/de/maxikg/osuapi/client/request/builder/GetBeatmapsRequestBuilder.java
// Path: Common/src/main/java/de/maxikg/osuapi/model/Beatmap.java // @Data // public class Beatmap { // // @JsonProperty("approved") // private BeatmapState approved; // // @JsonProperty("approved_date") // @JsonSerialize(using = OsuDateSerializer.class) // @JsonDeserialize(using = OsuDateDeserializer.class) // private Date approvedDate; // // @JsonProperty("last_update") // @JsonSerialize(using = OsuDateSerializer.class) // @JsonDeserialize(using = OsuDateDeserializer.class) // private Date lastUpdate; // // @JsonProperty("artist") // private String artist; // // @JsonProperty("beatmap_id") // private int beatmapId; // // @JsonProperty("beatmapset_id") // private int beatmapSetId; // // @JsonProperty("bpm") // private float bpm; // // @JsonProperty("creator") // private String creator; // // @JsonProperty("difficultyrating") // private float difficultyRating; // // @JsonProperty("diff_size") // private int difficultySize; // // @JsonProperty("diff_overall") // private int difficultyOverall; // // @JsonProperty("diff_approach") // private int difficultyApproach; // // @JsonProperty("diff_drain") // private int difficultyDrain; // // @JsonProperty("hit_length") // private int hitLength; // // @JsonProperty("source") // private String source; // // @JsonProperty("title") // private String title; // // @JsonProperty("total_length") // private long totalLength; // // @JsonProperty("version") // private String version; // // @JsonProperty("mode") // private GameMode mode; // } // // Path: Common/src/main/java/de/maxikg/osuapi/model/GameMode.java // @RequiredArgsConstructor // public enum GameMode implements Valuable<Integer> { // // /** // * It represents the default osu! game mode. See: https://osu.ppy.sh/wiki/Standard // */ // STANDARD(0), // // /** // * It represents the game mode on which you must hit the drum. See: https://osu.ppy.sh/wiki/Taiko // */ // TAIKO(1), // // /** // * It represents the game mode on which you must catch the falling fruits. See: // * https://osu.ppy.sh/wiki/Catch_The_Beat // */ // CTB(2), // // /** // * It represents the game mode on which you must hit the right beat note in the right moment. See: // * https://osu.ppy.sh/wiki/Osu!mania // */ // OSU_MANIA(3); // // @NonNull // private final Integer value; // // /** // * {@inheritDoc} // */ // @JsonValue // public Integer getValue() { // return value; // } // // /** // * Returns the {@code GameMode} by it's number value. // * // * @param value The value. // * @return An {@link Optional}. Absent if an unknown value was given. // */ // @JsonCreator // public static Optional<GameMode> byValue(int value) { // return ValuableUtils.getByValue(GameMode.class, value); // } // }
import de.maxikg.osuapi.model.Beatmap; import de.maxikg.osuapi.model.GameMode; import java.util.Collection; import java.util.Date;
package de.maxikg.osuapi.client.request.builder; /** * @author maxikg */ public interface GetBeatmapsRequestBuilder extends RequestBuilder<Collection<Beatmap>> { GetBeatmapsRequestBuilder since(Date date); GetBeatmapsRequestBuilder unsetSince(); GetBeatmapsRequestBuilder beatmapSetId(int id); GetBeatmapsRequestBuilder unsetBeatmapSetId(); GetBeatmapsRequestBuilder beatmapId(int id); GetBeatmapsRequestBuilder unsetBeatmapId(); GetBeatmapsRequestBuilder username(String username); GetBeatmapsRequestBuilder userId(int id); GetBeatmapsRequestBuilder unsetUser();
// Path: Common/src/main/java/de/maxikg/osuapi/model/Beatmap.java // @Data // public class Beatmap { // // @JsonProperty("approved") // private BeatmapState approved; // // @JsonProperty("approved_date") // @JsonSerialize(using = OsuDateSerializer.class) // @JsonDeserialize(using = OsuDateDeserializer.class) // private Date approvedDate; // // @JsonProperty("last_update") // @JsonSerialize(using = OsuDateSerializer.class) // @JsonDeserialize(using = OsuDateDeserializer.class) // private Date lastUpdate; // // @JsonProperty("artist") // private String artist; // // @JsonProperty("beatmap_id") // private int beatmapId; // // @JsonProperty("beatmapset_id") // private int beatmapSetId; // // @JsonProperty("bpm") // private float bpm; // // @JsonProperty("creator") // private String creator; // // @JsonProperty("difficultyrating") // private float difficultyRating; // // @JsonProperty("diff_size") // private int difficultySize; // // @JsonProperty("diff_overall") // private int difficultyOverall; // // @JsonProperty("diff_approach") // private int difficultyApproach; // // @JsonProperty("diff_drain") // private int difficultyDrain; // // @JsonProperty("hit_length") // private int hitLength; // // @JsonProperty("source") // private String source; // // @JsonProperty("title") // private String title; // // @JsonProperty("total_length") // private long totalLength; // // @JsonProperty("version") // private String version; // // @JsonProperty("mode") // private GameMode mode; // } // // Path: Common/src/main/java/de/maxikg/osuapi/model/GameMode.java // @RequiredArgsConstructor // public enum GameMode implements Valuable<Integer> { // // /** // * It represents the default osu! game mode. See: https://osu.ppy.sh/wiki/Standard // */ // STANDARD(0), // // /** // * It represents the game mode on which you must hit the drum. See: https://osu.ppy.sh/wiki/Taiko // */ // TAIKO(1), // // /** // * It represents the game mode on which you must catch the falling fruits. See: // * https://osu.ppy.sh/wiki/Catch_The_Beat // */ // CTB(2), // // /** // * It represents the game mode on which you must hit the right beat note in the right moment. See: // * https://osu.ppy.sh/wiki/Osu!mania // */ // OSU_MANIA(3); // // @NonNull // private final Integer value; // // /** // * {@inheritDoc} // */ // @JsonValue // public Integer getValue() { // return value; // } // // /** // * Returns the {@code GameMode} by it's number value. // * // * @param value The value. // * @return An {@link Optional}. Absent if an unknown value was given. // */ // @JsonCreator // public static Optional<GameMode> byValue(int value) { // return ValuableUtils.getByValue(GameMode.class, value); // } // } // Path: Client/src/main/java/de/maxikg/osuapi/client/request/builder/GetBeatmapsRequestBuilder.java import de.maxikg.osuapi.model.Beatmap; import de.maxikg.osuapi.model.GameMode; import java.util.Collection; import java.util.Date; package de.maxikg.osuapi.client.request.builder; /** * @author maxikg */ public interface GetBeatmapsRequestBuilder extends RequestBuilder<Collection<Beatmap>> { GetBeatmapsRequestBuilder since(Date date); GetBeatmapsRequestBuilder unsetSince(); GetBeatmapsRequestBuilder beatmapSetId(int id); GetBeatmapsRequestBuilder unsetBeatmapSetId(); GetBeatmapsRequestBuilder beatmapId(int id); GetBeatmapsRequestBuilder unsetBeatmapId(); GetBeatmapsRequestBuilder username(String username); GetBeatmapsRequestBuilder userId(int id); GetBeatmapsRequestBuilder unsetUser();
GetBeatmapsRequestBuilder mode(GameMode mode);
cattaka/CatHandsGendroid
cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/RawQueryTest.java
// Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/StringKvModel.java // @DataModel(find="key", autoincrement=false, // query= { // "Distinct:select distinct value from stringKvModel", // "QueryKey:select value from stringKvModel where key=?", // "QueryValue:select key as value from stringKvModel where value=?" // } // ) // public class StringKvModel { // @DataModelAttrs(primaryKey=true) // private String key; // private String value; // // public StringKvModel() { // } // // public StringKvModel(String key, String value) { // super(); // this.key = key; // this.value = value; // } // // public String getKey() { // return key; // } // public void setKey(String key) { // this.key = key; // } // public String getValue() { // return value; // } // public void setValue(String value) { // this.value = value; // } // }
import java.util.HashSet; import java.util.List; import java.util.Set; import net.cattaka.util.cathandsgendroid.test.model.StringKvModel; import net.cattaka.util.cathandsgendroid.test.model.StringKvModelCatHands; import static org.junit.Assert.*; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import android.database.sqlite.SQLiteDatabase; import org.robolectric.annotation.Config;
package net.cattaka.util.cathandsgendroid.test; @RunWith(RobolectricTestRunner.class) public class RawQueryTest { @Test public void testRawQuery() { SQLiteDatabase db = SQLiteDatabase.create(null); db.execSQL(StringKvModelCatHands.SQL_CREATE_TABLE); {
// Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/StringKvModel.java // @DataModel(find="key", autoincrement=false, // query= { // "Distinct:select distinct value from stringKvModel", // "QueryKey:select value from stringKvModel where key=?", // "QueryValue:select key as value from stringKvModel where value=?" // } // ) // public class StringKvModel { // @DataModelAttrs(primaryKey=true) // private String key; // private String value; // // public StringKvModel() { // } // // public StringKvModel(String key, String value) { // super(); // this.key = key; // this.value = value; // } // // public String getKey() { // return key; // } // public void setKey(String key) { // this.key = key; // } // public String getValue() { // return value; // } // public void setValue(String value) { // this.value = value; // } // } // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/RawQueryTest.java import java.util.HashSet; import java.util.List; import java.util.Set; import net.cattaka.util.cathandsgendroid.test.model.StringKvModel; import net.cattaka.util.cathandsgendroid.test.model.StringKvModelCatHands; import static org.junit.Assert.*; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import android.database.sqlite.SQLiteDatabase; import org.robolectric.annotation.Config; package net.cattaka.util.cathandsgendroid.test; @RunWith(RobolectricTestRunner.class) public class RawQueryTest { @Test public void testRawQuery() { SQLiteDatabase db = SQLiteDatabase.create(null); db.execSQL(StringKvModelCatHands.SQL_CREATE_TABLE); {
StringKvModelCatHands.insert(db, new StringKvModel("key1", "apple"));
cattaka/CatHandsGendroid
cathandsgendroid-core/src/main/java/net/cattaka/util/cathandsgendroid/accessor/SerializableAccessor.java
// Path: cathandsgendroid-core/src/main/java/net/cattaka/util/cathandsgendroid/accessor/Accessors.java // public static class BlobAccessor implements IAccessor<byte[]> { // static BlobAccessor instance; // // public static IAccessor<byte[]> createAccessor(Class<byte[]> clazz) { // if (instance == null) { // instance = new BlobAccessor(); // } // return instance; // } // // @Override // public byte[] readFromStream(DataInputStream in) throws IOException { // int n = in.readInt(); // if (n >= 0) { // byte[] bs = new byte[n]; // in.read(bs, 0, n); // return bs; // } else { // return null; // } // } // // @Override // public void writeToStream(DataOutputStream out, byte[] value) throws IOException { // if (value != null) { // out.writeInt(value.length); // out.write(value); // } else { // out.writeInt(-1); // } // } // // @Override // public byte[] readFromParcel(Parcel p) { // int n = p.readInt(); // if (n >= 0) { // byte[] bs = new byte[n]; // p.readByteArray(bs); // return bs; // } else { // return null; // } // } // // @Override // public void writeToParcel(Parcel p, byte[] value) { // if (value != null) { // p.writeInt(value.length); // p.writeByteArray(value); // } else { // p.writeInt(-1); // } // } // // @Override // public byte[] readFromCursor(Cursor c, int idx) { // return (c.isNull(idx) ? null : (c.getBlob(idx))); // } // // @Override // public void putToContentValues(ContentValues values, String columnName, byte[] value) { // values.put(columnName, value); // } // // @Override // public String stringValue(byte[] value) { // if (value == null) { // return null; // } else { // StringBuilder sb = new StringBuilder(); // for (byte b : value) { // if (0 <= b && b < 0x10) { // sb.append('0'); // } // sb.append(Integer.toHexString(b)); // } // return sb.toString(); // } // }; // };
import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import net.cattaka.util.cathandsgendroid.accessor.Accessors.BlobAccessor; import android.content.ContentValues; import android.database.Cursor; import android.os.Parcel;
oout.writeObject(value); oout.flush(); } else { out.writeBoolean(false); } } @Override public T readFromParcel(Parcel p) { if (p.readByte() != 0) { Object obj = p.readSerializable(); if (clazz.isInstance(obj)) { @SuppressWarnings("unchecked") T t = (T)obj; return t; } } return null; } @Override public void writeToParcel(Parcel p, Serializable value) { p.writeByte(value != null ? (byte)1 : 0); if (value != null) { p.writeSerializable(value); } } @Override public T readFromCursor(Cursor c, int idx) {
// Path: cathandsgendroid-core/src/main/java/net/cattaka/util/cathandsgendroid/accessor/Accessors.java // public static class BlobAccessor implements IAccessor<byte[]> { // static BlobAccessor instance; // // public static IAccessor<byte[]> createAccessor(Class<byte[]> clazz) { // if (instance == null) { // instance = new BlobAccessor(); // } // return instance; // } // // @Override // public byte[] readFromStream(DataInputStream in) throws IOException { // int n = in.readInt(); // if (n >= 0) { // byte[] bs = new byte[n]; // in.read(bs, 0, n); // return bs; // } else { // return null; // } // } // // @Override // public void writeToStream(DataOutputStream out, byte[] value) throws IOException { // if (value != null) { // out.writeInt(value.length); // out.write(value); // } else { // out.writeInt(-1); // } // } // // @Override // public byte[] readFromParcel(Parcel p) { // int n = p.readInt(); // if (n >= 0) { // byte[] bs = new byte[n]; // p.readByteArray(bs); // return bs; // } else { // return null; // } // } // // @Override // public void writeToParcel(Parcel p, byte[] value) { // if (value != null) { // p.writeInt(value.length); // p.writeByteArray(value); // } else { // p.writeInt(-1); // } // } // // @Override // public byte[] readFromCursor(Cursor c, int idx) { // return (c.isNull(idx) ? null : (c.getBlob(idx))); // } // // @Override // public void putToContentValues(ContentValues values, String columnName, byte[] value) { // values.put(columnName, value); // } // // @Override // public String stringValue(byte[] value) { // if (value == null) { // return null; // } else { // StringBuilder sb = new StringBuilder(); // for (byte b : value) { // if (0 <= b && b < 0x10) { // sb.append('0'); // } // sb.append(Integer.toHexString(b)); // } // return sb.toString(); // } // }; // }; // Path: cathandsgendroid-core/src/main/java/net/cattaka/util/cathandsgendroid/accessor/SerializableAccessor.java import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import net.cattaka.util.cathandsgendroid.accessor.Accessors.BlobAccessor; import android.content.ContentValues; import android.database.Cursor; import android.os.Parcel; oout.writeObject(value); oout.flush(); } else { out.writeBoolean(false); } } @Override public T readFromParcel(Parcel p) { if (p.readByte() != 0) { Object obj = p.readSerializable(); if (clazz.isInstance(obj)) { @SuppressWarnings("unchecked") T t = (T)obj; return t; } } return null; } @Override public void writeToParcel(Parcel p, Serializable value) { p.writeByte(value != null ? (byte)1 : 0); if (value != null) { p.writeSerializable(value); } } @Override public T readFromCursor(Cursor c, int idx) {
byte[] bs = BlobAccessor.createAccessor(byte[].class).readFromCursor(c, idx);
cattaka/CatHandsGendroid
cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/FullModel.java
// Path: cathandsgendroid-core/src/main/java/net/cattaka/util/cathandsgendroid/accessor/EnumOrderAccessor.java // @AccessorAttrs(dbDataType="INTEGER") // public class EnumOrderAccessor<T extends Enum<T>> implements IAccessor<T> { // // /** // * Create the accessor for enum. // * // * @param child accessor for inherited datatype. // * @return created accessor // */ // public static <T extends Enum<T>> IAccessor<T> createAccessor(Class<T> clazz) { // return new EnumOrderAccessor<T>(clazz); // } // // private Class<T> enumType; // // private EnumOrderAccessor(Class<T> enumType) { // super(); // this.enumType = enumType; // } // // @Override // public T readFromStream(DataInputStream in) throws IOException { // int order = (in.readBoolean()) ? in.readInt() : -1; // T[] values = enumType.getEnumConstants(); // if (0 <= order && order <= values.length) { // return values[order]; // } // return null; // } // // @Override // public void writeToStream(DataOutputStream out, T value) throws IOException { // out.writeBoolean(value != null); // if (value != null) { // out.writeInt(value.ordinal()); // } // } // // @Override // public T readFromParcel(Parcel p) { // int order = (p.readByte() != 0) ? p.readInt() : -1; // T[] values = enumType.getEnumConstants(); // if (0 <= order && order <= values.length) { // return values[order]; // } // return null; // } // // @Override // public void writeToParcel(Parcel p, T value) { // p.writeByte(value != null ? (byte)1 : 0); // if (value != null) { // p.writeInt(value.ordinal()); // } // } // // @Override // public T readFromCursor(Cursor c, int idx) { // if (!c.isNull(idx)) { // int order = c.getInt(idx); // T[] values = enumType.getEnumConstants(); // if (0 <= order && order <= values.length) { // return values[order]; // } // } // return null; // } // // @Override // public void putToContentValues(ContentValues values, String columnName, T value) { // values.put(columnName, (value != null) ? value.ordinal() : null); // } // // @Override // public String stringValue(T value) { // return (value != null) ? String.valueOf(value.ordinal()) : null; // } // }
import java.util.Date; import java.util.Set; import net.cattaka.util.cathandsgendroid.accessor.EnumOrderAccessor; import net.cattaka.util.cathandsgendroid.annotation.DataModel; import net.cattaka.util.cathandsgendroid.annotation.DataModelAttrs; import android.os.Parcel; import android.os.Parcelable;
public void writeToParcel(Parcel dest, int flags) { FullModelCatHands.writeToParcel(this, dest, flags); } public static final Parcelable.Creator<FullModel> CREATOR = FullModelCatHands.CREATOR; public FullModel() { } public enum TinyEnum { A, B, C } @DataModelAttrs(primaryKey = true) private long key; private byte[] blobValue; private Boolean booleanValue; private Byte byteValue; private Character characterValue; private Date dateValue; private Double doubleValue; private TinyEnum tinyEnum;
// Path: cathandsgendroid-core/src/main/java/net/cattaka/util/cathandsgendroid/accessor/EnumOrderAccessor.java // @AccessorAttrs(dbDataType="INTEGER") // public class EnumOrderAccessor<T extends Enum<T>> implements IAccessor<T> { // // /** // * Create the accessor for enum. // * // * @param child accessor for inherited datatype. // * @return created accessor // */ // public static <T extends Enum<T>> IAccessor<T> createAccessor(Class<T> clazz) { // return new EnumOrderAccessor<T>(clazz); // } // // private Class<T> enumType; // // private EnumOrderAccessor(Class<T> enumType) { // super(); // this.enumType = enumType; // } // // @Override // public T readFromStream(DataInputStream in) throws IOException { // int order = (in.readBoolean()) ? in.readInt() : -1; // T[] values = enumType.getEnumConstants(); // if (0 <= order && order <= values.length) { // return values[order]; // } // return null; // } // // @Override // public void writeToStream(DataOutputStream out, T value) throws IOException { // out.writeBoolean(value != null); // if (value != null) { // out.writeInt(value.ordinal()); // } // } // // @Override // public T readFromParcel(Parcel p) { // int order = (p.readByte() != 0) ? p.readInt() : -1; // T[] values = enumType.getEnumConstants(); // if (0 <= order && order <= values.length) { // return values[order]; // } // return null; // } // // @Override // public void writeToParcel(Parcel p, T value) { // p.writeByte(value != null ? (byte)1 : 0); // if (value != null) { // p.writeInt(value.ordinal()); // } // } // // @Override // public T readFromCursor(Cursor c, int idx) { // if (!c.isNull(idx)) { // int order = c.getInt(idx); // T[] values = enumType.getEnumConstants(); // if (0 <= order && order <= values.length) { // return values[order]; // } // } // return null; // } // // @Override // public void putToContentValues(ContentValues values, String columnName, T value) { // values.put(columnName, (value != null) ? value.ordinal() : null); // } // // @Override // public String stringValue(T value) { // return (value != null) ? String.valueOf(value.ordinal()) : null; // } // } // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/FullModel.java import java.util.Date; import java.util.Set; import net.cattaka.util.cathandsgendroid.accessor.EnumOrderAccessor; import net.cattaka.util.cathandsgendroid.annotation.DataModel; import net.cattaka.util.cathandsgendroid.annotation.DataModelAttrs; import android.os.Parcel; import android.os.Parcelable; public void writeToParcel(Parcel dest, int flags) { FullModelCatHands.writeToParcel(this, dest, flags); } public static final Parcelable.Creator<FullModel> CREATOR = FullModelCatHands.CREATOR; public FullModel() { } public enum TinyEnum { A, B, C } @DataModelAttrs(primaryKey = true) private long key; private byte[] blobValue; private Boolean booleanValue; private Byte byteValue; private Character characterValue; private Date dateValue; private Double doubleValue; private TinyEnum tinyEnum;
@DataModelAttrs(accessor=EnumOrderAccessor.class)
cattaka/CatHandsGendroid
cathandsgendroid-core/src/main/java/net/cattaka/util/cathandsgendroid/annotation/DataModelAttrs.java
// Path: cathandsgendroid-core/src/main/java/net/cattaka/util/cathandsgendroid/accessor/IAccessor.java // public interface IAccessor<T> { // /** // * The way to read from DataInputStream. // * // * @param in datasource // * @return result of read. // * @throws IOException if an I/O error occurs. // */ // public T readFromStream(DataInputStream in) throws IOException; // // /** // * The way to write to DataInputStream. // * // * @param out destination // * @param value the value to write // * @throws IOException if an I/O error occurs. // */ // public void writeToStream(DataOutputStream out, T value) throws IOException; // // /** // * The way to read from Parcel. // * // * @param p datasource // * @return result of read. // */ // public T readFromParcel(Parcel p); // // /** // * The way to write to Parcel. // * // * @param p destination // * @param value the value to write // */ // public void writeToParcel(Parcel p, T value); // // /** // * The way to read from Cursor. // * // * @param c datasource // * @param idx the zero-based index of the target column. // * @return result of read. // */ // public T readFromCursor(Cursor c, int idx); // // /** // * The way to put to ContentValues. // * // * @param values destination // * @param columnName the name of the value to put // * @param value the data for the value to put // */ // public void putToContentValues(ContentValues values, String columnName, T value); // // /** // * Make string representation of given value. this method is used in WHERE // * phrase of find of DB. // * // * @param value input value // * @return string representation. // */ // public String stringValue(T value); // }
import java.io.DataInputStream; import java.io.DataOutputStream; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import net.cattaka.util.cathandsgendroid.accessor.IAccessor;
package net.cattaka.util.cathandsgendroid.annotation; /** * An annotation for fields of DataModel. * * @see DataModel * @author cattaka */ @Retention(RetentionPolicy.SOURCE) @Target(ElementType.FIELD) public @interface DataModelAttrs { /** * Specify whether this field is ignored. * * @return If true this is ignored. */ boolean ignore() default false; /** * Specify whether this field is used for DB. * * @return If true this is used for DB. */ boolean forDb() default true; /** * Specify whether this field is used for Parcel. * * @return If true this is used for Parcel. */ boolean forParcel() default true; /** * Specify whether this field is used for ContentResolver. * * @return If true this is used for ContentResolver. */ boolean forContentResolver() default true; /** * Specify whether this field is used for {@link DataOutputStream} and {@link DataInputStream}. * * @return If true this is used for DB. */ boolean forDs() default true; /** * Specify whether or not the primary key. * * @return If true this is used as primary key. */ boolean primaryKey() default false; /** * Specify DB version when this field added. * * @return DB version when this field added. */ long version() default 1; /** * Indicate Custom accessor for this field. * * @return Custom accessor for this field */ @SuppressWarnings("rawtypes")
// Path: cathandsgendroid-core/src/main/java/net/cattaka/util/cathandsgendroid/accessor/IAccessor.java // public interface IAccessor<T> { // /** // * The way to read from DataInputStream. // * // * @param in datasource // * @return result of read. // * @throws IOException if an I/O error occurs. // */ // public T readFromStream(DataInputStream in) throws IOException; // // /** // * The way to write to DataInputStream. // * // * @param out destination // * @param value the value to write // * @throws IOException if an I/O error occurs. // */ // public void writeToStream(DataOutputStream out, T value) throws IOException; // // /** // * The way to read from Parcel. // * // * @param p datasource // * @return result of read. // */ // public T readFromParcel(Parcel p); // // /** // * The way to write to Parcel. // * // * @param p destination // * @param value the value to write // */ // public void writeToParcel(Parcel p, T value); // // /** // * The way to read from Cursor. // * // * @param c datasource // * @param idx the zero-based index of the target column. // * @return result of read. // */ // public T readFromCursor(Cursor c, int idx); // // /** // * The way to put to ContentValues. // * // * @param values destination // * @param columnName the name of the value to put // * @param value the data for the value to put // */ // public void putToContentValues(ContentValues values, String columnName, T value); // // /** // * Make string representation of given value. this method is used in WHERE // * phrase of find of DB. // * // * @param value input value // * @return string representation. // */ // public String stringValue(T value); // } // Path: cathandsgendroid-core/src/main/java/net/cattaka/util/cathandsgendroid/annotation/DataModelAttrs.java import java.io.DataInputStream; import java.io.DataOutputStream; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import net.cattaka.util.cathandsgendroid.accessor.IAccessor; package net.cattaka.util.cathandsgendroid.annotation; /** * An annotation for fields of DataModel. * * @see DataModel * @author cattaka */ @Retention(RetentionPolicy.SOURCE) @Target(ElementType.FIELD) public @interface DataModelAttrs { /** * Specify whether this field is ignored. * * @return If true this is ignored. */ boolean ignore() default false; /** * Specify whether this field is used for DB. * * @return If true this is used for DB. */ boolean forDb() default true; /** * Specify whether this field is used for Parcel. * * @return If true this is used for Parcel. */ boolean forParcel() default true; /** * Specify whether this field is used for ContentResolver. * * @return If true this is used for ContentResolver. */ boolean forContentResolver() default true; /** * Specify whether this field is used for {@link DataOutputStream} and {@link DataInputStream}. * * @return If true this is used for DB. */ boolean forDs() default true; /** * Specify whether or not the primary key. * * @return If true this is used as primary key. */ boolean primaryKey() default false; /** * Specify DB version when this field added. * * @return DB version when this field added. */ long version() default 1; /** * Indicate Custom accessor for this field. * * @return Custom accessor for this field */ @SuppressWarnings("rawtypes")
Class<? extends IAccessor> accessor() default IAccessor.class;
cattaka/CatHandsGendroid
cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/UserModel.java
// Path: cathandsgendroid-core/src/main/java/net/cattaka/util/cathandsgendroid/accessor/EnumOrderAccessor.java // @AccessorAttrs(dbDataType="INTEGER") // public class EnumOrderAccessor<T extends Enum<T>> implements IAccessor<T> { // // /** // * Create the accessor for enum. // * // * @param child accessor for inherited datatype. // * @return created accessor // */ // public static <T extends Enum<T>> IAccessor<T> createAccessor(Class<T> clazz) { // return new EnumOrderAccessor<T>(clazz); // } // // private Class<T> enumType; // // private EnumOrderAccessor(Class<T> enumType) { // super(); // this.enumType = enumType; // } // // @Override // public T readFromStream(DataInputStream in) throws IOException { // int order = (in.readBoolean()) ? in.readInt() : -1; // T[] values = enumType.getEnumConstants(); // if (0 <= order && order <= values.length) { // return values[order]; // } // return null; // } // // @Override // public void writeToStream(DataOutputStream out, T value) throws IOException { // out.writeBoolean(value != null); // if (value != null) { // out.writeInt(value.ordinal()); // } // } // // @Override // public T readFromParcel(Parcel p) { // int order = (p.readByte() != 0) ? p.readInt() : -1; // T[] values = enumType.getEnumConstants(); // if (0 <= order && order <= values.length) { // return values[order]; // } // return null; // } // // @Override // public void writeToParcel(Parcel p, T value) { // p.writeByte(value != null ? (byte)1 : 0); // if (value != null) { // p.writeInt(value.ordinal()); // } // } // // @Override // public T readFromCursor(Cursor c, int idx) { // if (!c.isNull(idx)) { // int order = c.getInt(idx); // T[] values = enumType.getEnumConstants(); // if (0 <= order && order <= values.length) { // return values[order]; // } // } // return null; // } // // @Override // public void putToContentValues(ContentValues values, String columnName, T value) { // values.put(columnName, (value != null) ? value.ordinal() : null); // } // // @Override // public String stringValue(T value) { // return (value != null) ? String.valueOf(value.ordinal()) : null; // } // }
import java.util.Date; import java.util.List; import net.cattaka.util.cathandsgendroid.accessor.EnumOrderAccessor; import net.cattaka.util.cathandsgendroid.annotation.DataModel; import net.cattaka.util.cathandsgendroid.annotation.DataModelAttrs;
package net.cattaka.util.cathandsgendroid.test.model; @DataModel(find = { "id", "username", "team:role+,id", "team:id-", ":id", "authority:id+" }, unique = { "username" }) public class UserModel { public enum Role { PROGRAMMER, DESIGNNER, MANAGER } public enum Authority { USER, ADMIN } @DataModelAttrs(primaryKey = true) private Long id; private String username; @DataModelAttrs(version = 2) private String nickname; @DataModelAttrs(version = 2) private String team; private Role role; private Date createdAt; private List<String> tags;
// Path: cathandsgendroid-core/src/main/java/net/cattaka/util/cathandsgendroid/accessor/EnumOrderAccessor.java // @AccessorAttrs(dbDataType="INTEGER") // public class EnumOrderAccessor<T extends Enum<T>> implements IAccessor<T> { // // /** // * Create the accessor for enum. // * // * @param child accessor for inherited datatype. // * @return created accessor // */ // public static <T extends Enum<T>> IAccessor<T> createAccessor(Class<T> clazz) { // return new EnumOrderAccessor<T>(clazz); // } // // private Class<T> enumType; // // private EnumOrderAccessor(Class<T> enumType) { // super(); // this.enumType = enumType; // } // // @Override // public T readFromStream(DataInputStream in) throws IOException { // int order = (in.readBoolean()) ? in.readInt() : -1; // T[] values = enumType.getEnumConstants(); // if (0 <= order && order <= values.length) { // return values[order]; // } // return null; // } // // @Override // public void writeToStream(DataOutputStream out, T value) throws IOException { // out.writeBoolean(value != null); // if (value != null) { // out.writeInt(value.ordinal()); // } // } // // @Override // public T readFromParcel(Parcel p) { // int order = (p.readByte() != 0) ? p.readInt() : -1; // T[] values = enumType.getEnumConstants(); // if (0 <= order && order <= values.length) { // return values[order]; // } // return null; // } // // @Override // public void writeToParcel(Parcel p, T value) { // p.writeByte(value != null ? (byte)1 : 0); // if (value != null) { // p.writeInt(value.ordinal()); // } // } // // @Override // public T readFromCursor(Cursor c, int idx) { // if (!c.isNull(idx)) { // int order = c.getInt(idx); // T[] values = enumType.getEnumConstants(); // if (0 <= order && order <= values.length) { // return values[order]; // } // } // return null; // } // // @Override // public void putToContentValues(ContentValues values, String columnName, T value) { // values.put(columnName, (value != null) ? value.ordinal() : null); // } // // @Override // public String stringValue(T value) { // return (value != null) ? String.valueOf(value.ordinal()) : null; // } // } // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/UserModel.java import java.util.Date; import java.util.List; import net.cattaka.util.cathandsgendroid.accessor.EnumOrderAccessor; import net.cattaka.util.cathandsgendroid.annotation.DataModel; import net.cattaka.util.cathandsgendroid.annotation.DataModelAttrs; package net.cattaka.util.cathandsgendroid.test.model; @DataModel(find = { "id", "username", "team:role+,id", "team:id-", ":id", "authority:id+" }, unique = { "username" }) public class UserModel { public enum Role { PROGRAMMER, DESIGNNER, MANAGER } public enum Authority { USER, ADMIN } @DataModelAttrs(primaryKey = true) private Long id; private String username; @DataModelAttrs(version = 2) private String nickname; @DataModelAttrs(version = 2) private String team; private Role role; private Date createdAt; private List<String> tags;
@DataModelAttrs(version = 3, accessor = EnumOrderAccessor.class)
cattaka/CatHandsGendroid
cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/SimpleInterfaceTest.java
// Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/asyncif/SimpleInterface.java // @AsyncInterface // public interface SimpleInterface { // public void run(); // public int add(int a, int b); // public List<Integer> runLists(List<Integer> args); // } // // Path: cathandsgendroid-apt/tmp/net/cattaka/util/cathandsgendroid/test/asyncif/SimpleInterfaceAsync.java // public class SimpleInterfaceAsync implements SimpleInterface { // private static final int WORK_SIZE = 6; // private static final int POOL_SIZE = 10; // private static final int EVENT_START = 1; // // // private static final int EVENT_METHOD_0_run = EVENT_START + 1; // private static final int EVENT_METHOD_1_add = EVENT_START + 2; // // private static Callback sCallback = new Callback() { // // @Override // public boolean handleMessage(Message msg) { // switch (msg.what) { // // case EVENT_METHOD_0_run: { // Object[] work = (Object[]) msg.obj; // // SimpleInterfaceAsync me = (SimpleInterfaceAsync) work[0]; // SimpleInterface orig = (SimpleInterface) work[1]; // // // orig.run(); // me.recycle(work); // return true; // // } // // case EVENT_METHOD_1_add: { // Object[] work = (Object[]) msg.obj; // // SimpleInterface orig = (SimpleInterface) work[1]; // // Integer arg0 = (Integer) (work[0+2]); // Integer arg1 = (Integer) (work[1+2]); // // try { // // Object result = // orig.add(arg0 ,arg1); // // work[WORK_SIZE - 2] = result; // } catch (Exception e) { // work[WORK_SIZE - 1] = e; // } // synchronized (work) { // work.notify(); // } // return true; // // } // // } // return false; // } // }; // private static Map<Looper, Handler> sHandlerMap = new HashMap<Looper, Handler>(); // private Handler mHandler; // private Object[][] sOwnedPool = new Object[POOL_SIZE][WORK_SIZE]; // private SimpleInterface orig; // // public SimpleInterfaceAsync(SimpleInterface orig, Looper looper) { // super(); // this.orig = orig; // synchronized (sHandlerMap) { // mHandler = sHandlerMap.get(looper); // if (mHandler == null) { // mHandler = new Handler(looper, sCallback); // sHandlerMap.put(looper, mHandler); // } // } // } // // public SimpleInterfaceAsync(SimpleInterface orig) { // this(orig, Looper.getMainLooper()); // } // // // // @Override // public void run() // // { // if (Looper.myLooper() == mHandler.getLooper()) { // // orig.run(); // return; // // } // Object[] work = obtain(); // work[0] = this; // work[1] = orig; // // // mHandler.obtainMessage(EVENT_METHOD_0_run, work).sendToTarget(); // // } // // @Override // public int add(int arg0, int arg1) // // { // if (Looper.myLooper() == mHandler.getLooper()) { // // return orig.add(arg0, arg1); // // } // Object[] work = obtain(); // work[0] = this; // work[1] = orig; // // work[0+2] = arg0; // work[1+2] = arg1; // // synchronized (work) { // mHandler.obtainMessage(EVENT_METHOD_1_add, work) // .sendToTarget(); // try { // work.wait(); // } catch (InterruptedException e) { // throw new AsyncInterfaceException(e); // } // } // if (work[WORK_SIZE - 1] != null) { // // throw new AsyncInterfaceException((Exception) work[WORK_SIZE - 1]); // // } // // // int result = (Integer) work[WORK_SIZE - 2]; // recycle(work); // // // return result; // // // } // // // private Object[] obtain() { // final Object[][] pool = sOwnedPool; // synchronized (pool) { // Object[] p; // for (int i = 0; i < POOL_SIZE; i++) { // p = pool[i]; // if (p != null) { // pool[i] = null; // return p; // } // } // } // return new Object[WORK_SIZE]; // } // // private void recycle(Object[] p) { // for (int i=0;i<p.length;i++) { // p[i] = null; // } // final Object[][] pool = sOwnedPool; // synchronized (pool) { // for (int i = 0; i < POOL_SIZE; i++) { // if (pool[i] == null) { // pool[i] = p; // return; // } // } // } // } // }
import java.util.Arrays; import java.util.List; import net.cattaka.util.cathandsgendroid.test.asyncif.SimpleInterface; import net.cattaka.util.cathandsgendroid.test.asyncif.SimpleInterfaceAsync; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.Shadows; import org.robolectric.annotation.Config; import org.robolectric.shadow.api.Shadow; import org.robolectric.shadows.ShadowLooper; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import static org.junit.Assert.*;
package net.cattaka.util.cathandsgendroid.test; @RunWith(RobolectricTestRunner.class) public class SimpleInterfaceTest {
// Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/asyncif/SimpleInterface.java // @AsyncInterface // public interface SimpleInterface { // public void run(); // public int add(int a, int b); // public List<Integer> runLists(List<Integer> args); // } // // Path: cathandsgendroid-apt/tmp/net/cattaka/util/cathandsgendroid/test/asyncif/SimpleInterfaceAsync.java // public class SimpleInterfaceAsync implements SimpleInterface { // private static final int WORK_SIZE = 6; // private static final int POOL_SIZE = 10; // private static final int EVENT_START = 1; // // // private static final int EVENT_METHOD_0_run = EVENT_START + 1; // private static final int EVENT_METHOD_1_add = EVENT_START + 2; // // private static Callback sCallback = new Callback() { // // @Override // public boolean handleMessage(Message msg) { // switch (msg.what) { // // case EVENT_METHOD_0_run: { // Object[] work = (Object[]) msg.obj; // // SimpleInterfaceAsync me = (SimpleInterfaceAsync) work[0]; // SimpleInterface orig = (SimpleInterface) work[1]; // // // orig.run(); // me.recycle(work); // return true; // // } // // case EVENT_METHOD_1_add: { // Object[] work = (Object[]) msg.obj; // // SimpleInterface orig = (SimpleInterface) work[1]; // // Integer arg0 = (Integer) (work[0+2]); // Integer arg1 = (Integer) (work[1+2]); // // try { // // Object result = // orig.add(arg0 ,arg1); // // work[WORK_SIZE - 2] = result; // } catch (Exception e) { // work[WORK_SIZE - 1] = e; // } // synchronized (work) { // work.notify(); // } // return true; // // } // // } // return false; // } // }; // private static Map<Looper, Handler> sHandlerMap = new HashMap<Looper, Handler>(); // private Handler mHandler; // private Object[][] sOwnedPool = new Object[POOL_SIZE][WORK_SIZE]; // private SimpleInterface orig; // // public SimpleInterfaceAsync(SimpleInterface orig, Looper looper) { // super(); // this.orig = orig; // synchronized (sHandlerMap) { // mHandler = sHandlerMap.get(looper); // if (mHandler == null) { // mHandler = new Handler(looper, sCallback); // sHandlerMap.put(looper, mHandler); // } // } // } // // public SimpleInterfaceAsync(SimpleInterface orig) { // this(orig, Looper.getMainLooper()); // } // // // // @Override // public void run() // // { // if (Looper.myLooper() == mHandler.getLooper()) { // // orig.run(); // return; // // } // Object[] work = obtain(); // work[0] = this; // work[1] = orig; // // // mHandler.obtainMessage(EVENT_METHOD_0_run, work).sendToTarget(); // // } // // @Override // public int add(int arg0, int arg1) // // { // if (Looper.myLooper() == mHandler.getLooper()) { // // return orig.add(arg0, arg1); // // } // Object[] work = obtain(); // work[0] = this; // work[1] = orig; // // work[0+2] = arg0; // work[1+2] = arg1; // // synchronized (work) { // mHandler.obtainMessage(EVENT_METHOD_1_add, work) // .sendToTarget(); // try { // work.wait(); // } catch (InterruptedException e) { // throw new AsyncInterfaceException(e); // } // } // if (work[WORK_SIZE - 1] != null) { // // throw new AsyncInterfaceException((Exception) work[WORK_SIZE - 1]); // // } // // // int result = (Integer) work[WORK_SIZE - 2]; // recycle(work); // // // return result; // // // } // // // private Object[] obtain() { // final Object[][] pool = sOwnedPool; // synchronized (pool) { // Object[] p; // for (int i = 0; i < POOL_SIZE; i++) { // p = pool[i]; // if (p != null) { // pool[i] = null; // return p; // } // } // } // return new Object[WORK_SIZE]; // } // // private void recycle(Object[] p) { // for (int i=0;i<p.length;i++) { // p[i] = null; // } // final Object[][] pool = sOwnedPool; // synchronized (pool) { // for (int i = 0; i < POOL_SIZE; i++) { // if (pool[i] == null) { // pool[i] = p; // return; // } // } // } // } // } // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/SimpleInterfaceTest.java import java.util.Arrays; import java.util.List; import net.cattaka.util.cathandsgendroid.test.asyncif.SimpleInterface; import net.cattaka.util.cathandsgendroid.test.asyncif.SimpleInterfaceAsync; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.Shadows; import org.robolectric.annotation.Config; import org.robolectric.shadow.api.Shadow; import org.robolectric.shadows.ShadowLooper; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import static org.junit.Assert.*; package net.cattaka.util.cathandsgendroid.test; @RunWith(RobolectricTestRunner.class) public class SimpleInterfaceTest {
static class SimpleInterfaceImpl implements SimpleInterface {
cattaka/CatHandsGendroid
cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/GenericsCallbackTest.java
// Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/asyncif/GenericsCallback.java // @AsyncInterface // public interface GenericsCallback<T extends Number> { // public T add(T a, T b); // // public T mod(T a, T b) throws ArithmeticException; // // public void put(String key, T number); // // public T get(String key); // }
import java.util.HashMap; import java.util.Map; import net.cattaka.util.cathandsgendroid.test.asyncif.GenericsCallback; import net.cattaka.util.cathandsgendroid.test.asyncif.GenericsCallbackAsync; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import android.os.Handler; import org.robolectric.annotation.Config; import org.robolectric.shadow.api.Shadow; import static org.junit.Assert.*;
package net.cattaka.util.cathandsgendroid.test; @RunWith(RobolectricTestRunner.class) public class GenericsCallbackTest {
// Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/asyncif/GenericsCallback.java // @AsyncInterface // public interface GenericsCallback<T extends Number> { // public T add(T a, T b); // // public T mod(T a, T b) throws ArithmeticException; // // public void put(String key, T number); // // public T get(String key); // } // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/GenericsCallbackTest.java import java.util.HashMap; import java.util.Map; import net.cattaka.util.cathandsgendroid.test.asyncif.GenericsCallback; import net.cattaka.util.cathandsgendroid.test.asyncif.GenericsCallbackAsync; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import android.os.Handler; import org.robolectric.annotation.Config; import org.robolectric.shadow.api.Shadow; import static org.junit.Assert.*; package net.cattaka.util.cathandsgendroid.test; @RunWith(RobolectricTestRunner.class) public class GenericsCallbackTest {
static class GenericsCallbackImpl implements GenericsCallback<Integer> {
cattaka/CatHandsGendroid
cathandsgendroid-apt/src/main/java/net/cattaka/util/cathandsgendroid/apt/AsycInterfaceProcessor.java
// Path: cathandsgendroid-apt/src/main/java/net/cattaka/util/cathandsgendroid/apt/util/ResourceUtil.java // public class ResourceUtil { // public static String getResourceAsString(String resourceName) throws IOException { // InputStream in = null; // try { // in = ResourceUtil.class.getClassLoader().getResourceAsStream(resourceName); // Reader reader = new InputStreamReader(in, "UTF-8"); // StringBuilder sb = new StringBuilder(); // char[] cbuf = new char[1 << 12]; // int r; // while ((r = reader.read(cbuf)) > 0) { // sb.append(cbuf, 0, r); // } // // return sb.toString(); // } finally { // if (in != null) { // try { // in.close(); // } catch (IOException e2) { // // ignore // } // } // } // } // }
import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import javax.annotation.processing.Filer; import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.annotation.processing.SupportedSourceVersion; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.TypeParameterElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.ArrayType; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.PrimitiveType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.type.TypeVariable; import javax.lang.model.util.ElementFilter; import javax.tools.Diagnostic.Kind; import javax.tools.JavaFileObject; import org.mvel2.templates.TemplateRuntime; import net.cattaka.util.cathandsgendroid.annotation.AsyncInterface; import net.cattaka.util.cathandsgendroid.annotation.AsyncInterfaceAttrs; import net.cattaka.util.cathandsgendroid.apt.util.ResourceUtil;
if (obj == null) return false; if (getClass() != obj.getClass()) return false; MethodInfo other = (MethodInfo)obj; if (argTypes == null) { if (other.argTypes != null) return false; } else if (!argTypes.equals(other.argTypes)) return false; if (methodName == null) { if (other.methodName != null) return false; } else if (!methodName.equals(other.methodName)) return false; return true; } } private ProcessingEnvironment processingEnv; private String mTemplate; public AsycInterfaceProcessor(ProcessingEnvironment processingEnv) { this.processingEnv = processingEnv; String templateResource = getClass().getPackage().getName().replace('.', '/') + "/AsyncInterfaceTemplate.java.mvel"; try {
// Path: cathandsgendroid-apt/src/main/java/net/cattaka/util/cathandsgendroid/apt/util/ResourceUtil.java // public class ResourceUtil { // public static String getResourceAsString(String resourceName) throws IOException { // InputStream in = null; // try { // in = ResourceUtil.class.getClassLoader().getResourceAsStream(resourceName); // Reader reader = new InputStreamReader(in, "UTF-8"); // StringBuilder sb = new StringBuilder(); // char[] cbuf = new char[1 << 12]; // int r; // while ((r = reader.read(cbuf)) > 0) { // sb.append(cbuf, 0, r); // } // // return sb.toString(); // } finally { // if (in != null) { // try { // in.close(); // } catch (IOException e2) { // // ignore // } // } // } // } // } // Path: cathandsgendroid-apt/src/main/java/net/cattaka/util/cathandsgendroid/apt/AsycInterfaceProcessor.java import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import javax.annotation.processing.Filer; import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.annotation.processing.SupportedSourceVersion; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.TypeParameterElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.ArrayType; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.PrimitiveType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.type.TypeVariable; import javax.lang.model.util.ElementFilter; import javax.tools.Diagnostic.Kind; import javax.tools.JavaFileObject; import org.mvel2.templates.TemplateRuntime; import net.cattaka.util.cathandsgendroid.annotation.AsyncInterface; import net.cattaka.util.cathandsgendroid.annotation.AsyncInterfaceAttrs; import net.cattaka.util.cathandsgendroid.apt.util.ResourceUtil; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MethodInfo other = (MethodInfo)obj; if (argTypes == null) { if (other.argTypes != null) return false; } else if (!argTypes.equals(other.argTypes)) return false; if (methodName == null) { if (other.methodName != null) return false; } else if (!methodName.equals(other.methodName)) return false; return true; } } private ProcessingEnvironment processingEnv; private String mTemplate; public AsycInterfaceProcessor(ProcessingEnvironment processingEnv) { this.processingEnv = processingEnv; String templateResource = getClass().getPackage().getName().replace('.', '/') + "/AsyncInterfaceTemplate.java.mvel"; try {
mTemplate = ResourceUtil.getResourceAsString(templateResource);
cattaka/CatHandsGendroid
cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/GenDbHandlerTest.java
// Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/UserModel.java // @DataModel(find = { // "id", "username", "team:role+,id", "team:id-", ":id", "authority:id+" // }, unique = { // "username" // }) // public class UserModel { // public enum Role { // PROGRAMMER, DESIGNNER, MANAGER // } // // public enum Authority { // USER, ADMIN // } // // @DataModelAttrs(primaryKey = true) // private Long id; // // private String username; // // @DataModelAttrs(version = 2) // private String nickname; // // @DataModelAttrs(version = 2) // private String team; // // private Role role; // // private Date createdAt; // // private List<String> tags; // // @DataModelAttrs(version = 3, accessor = EnumOrderAccessor.class) // private Authority authority; // // @DataModelAttrs(ignore = true) // private Object userData; // // private byte[] blob; // // private Boolean booleanData; // // private Byte byteData; // // private Character charData; // // public UserModel() { // } // // public UserModel(Long id, String username, String nickname, String team, Role role, // Date createdAt, List<String> tags, Authority authority) { // super(); // this.id = id; // this.username = username; // this.nickname = nickname; // this.team = team; // this.role = role; // this.createdAt = createdAt; // this.tags = tags; // this.authority = authority; // } // // public UserModel(Long id, String username, String nickname, String team, Role role, // Date createdAt, List<String> tags, Authority authority, byte[] blob, // Boolean booleanData, Byte byteData, Character charData) { // super(); // this.id = id; // this.username = username; // this.nickname = nickname; // this.team = team; // this.role = role; // this.createdAt = createdAt; // this.tags = tags; // this.authority = authority; // this.blob = blob; // this.booleanData = booleanData; // this.byteData = byteData; // this.charData = charData; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getNickname() { // return nickname; // } // // public void setNickname(String nickname) { // this.nickname = nickname; // } // // public String getTeam() { // return team; // } // // public void setTeam(String team) { // this.team = team; // } // // public Role getRole() { // return role; // } // // public void setRole(Role role) { // this.role = role; // } // // public Date getCreatedAt() { // return createdAt; // } // // public void setCreatedAt(Date createdAt) { // this.createdAt = createdAt; // } // // public List<String> getTags() { // return tags; // } // // public void setTags(List<String> tags) { // this.tags = tags; // } // // public Object getUserData() { // return userData; // } // // public void setUserData(Object userData) { // this.userData = userData; // } // // public Authority getAuthority() { // return authority; // } // // public void setAuthority(Authority authority) { // this.authority = authority; // } // // public byte[] getBlob() { // return blob; // } // // public void setBlob(byte[] blob) { // this.blob = blob; // } // // public Boolean getBooleanData() { // return booleanData; // } // // public void setBooleanData(Boolean booleanData) { // this.booleanData = booleanData; // } // // public Byte getByteData() { // return byteData; // } // // public void setByteData(Byte byteData) { // this.byteData = byteData; // } // // public Character getCharData() { // return charData; // } // // public void setCharData(Character charData) { // this.charData = charData; // } // // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/UserModel.java // public enum Authority { // USER, ADMIN // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/UserModel.java // public enum Role { // PROGRAMMER, DESIGNNER, MANAGER // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.util.ArrayList; import java.util.Date; import java.util.List; import net.cattaka.util.cathandsgendroid.test.model.UserModel; import net.cattaka.util.cathandsgendroid.test.model.UserModel.Authority; import net.cattaka.util.cathandsgendroid.test.model.UserModel.Role; import net.cattaka.util.cathandsgendroid.test.model.UserModelCatHands; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import android.database.sqlite.SQLiteDatabase; import org.robolectric.annotation.Config;
package net.cattaka.util.cathandsgendroid.test; @RunWith(RobolectricTestRunner.class) public class GenDbHandlerTest { @Test public void testDml() { SQLiteDatabase db = SQLiteDatabase.create(null); db.execSQL(UserModelCatHands.SQL_CREATE_TABLE); { // Insert
// Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/UserModel.java // @DataModel(find = { // "id", "username", "team:role+,id", "team:id-", ":id", "authority:id+" // }, unique = { // "username" // }) // public class UserModel { // public enum Role { // PROGRAMMER, DESIGNNER, MANAGER // } // // public enum Authority { // USER, ADMIN // } // // @DataModelAttrs(primaryKey = true) // private Long id; // // private String username; // // @DataModelAttrs(version = 2) // private String nickname; // // @DataModelAttrs(version = 2) // private String team; // // private Role role; // // private Date createdAt; // // private List<String> tags; // // @DataModelAttrs(version = 3, accessor = EnumOrderAccessor.class) // private Authority authority; // // @DataModelAttrs(ignore = true) // private Object userData; // // private byte[] blob; // // private Boolean booleanData; // // private Byte byteData; // // private Character charData; // // public UserModel() { // } // // public UserModel(Long id, String username, String nickname, String team, Role role, // Date createdAt, List<String> tags, Authority authority) { // super(); // this.id = id; // this.username = username; // this.nickname = nickname; // this.team = team; // this.role = role; // this.createdAt = createdAt; // this.tags = tags; // this.authority = authority; // } // // public UserModel(Long id, String username, String nickname, String team, Role role, // Date createdAt, List<String> tags, Authority authority, byte[] blob, // Boolean booleanData, Byte byteData, Character charData) { // super(); // this.id = id; // this.username = username; // this.nickname = nickname; // this.team = team; // this.role = role; // this.createdAt = createdAt; // this.tags = tags; // this.authority = authority; // this.blob = blob; // this.booleanData = booleanData; // this.byteData = byteData; // this.charData = charData; // } // // public Long getId() { // return id; // } // // public void setId(Long id) { // this.id = id; // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getNickname() { // return nickname; // } // // public void setNickname(String nickname) { // this.nickname = nickname; // } // // public String getTeam() { // return team; // } // // public void setTeam(String team) { // this.team = team; // } // // public Role getRole() { // return role; // } // // public void setRole(Role role) { // this.role = role; // } // // public Date getCreatedAt() { // return createdAt; // } // // public void setCreatedAt(Date createdAt) { // this.createdAt = createdAt; // } // // public List<String> getTags() { // return tags; // } // // public void setTags(List<String> tags) { // this.tags = tags; // } // // public Object getUserData() { // return userData; // } // // public void setUserData(Object userData) { // this.userData = userData; // } // // public Authority getAuthority() { // return authority; // } // // public void setAuthority(Authority authority) { // this.authority = authority; // } // // public byte[] getBlob() { // return blob; // } // // public void setBlob(byte[] blob) { // this.blob = blob; // } // // public Boolean getBooleanData() { // return booleanData; // } // // public void setBooleanData(Boolean booleanData) { // this.booleanData = booleanData; // } // // public Byte getByteData() { // return byteData; // } // // public void setByteData(Byte byteData) { // this.byteData = byteData; // } // // public Character getCharData() { // return charData; // } // // public void setCharData(Character charData) { // this.charData = charData; // } // // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/UserModel.java // public enum Authority { // USER, ADMIN // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/UserModel.java // public enum Role { // PROGRAMMER, DESIGNNER, MANAGER // } // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/GenDbHandlerTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.util.ArrayList; import java.util.Date; import java.util.List; import net.cattaka.util.cathandsgendroid.test.model.UserModel; import net.cattaka.util.cathandsgendroid.test.model.UserModel.Authority; import net.cattaka.util.cathandsgendroid.test.model.UserModel.Role; import net.cattaka.util.cathandsgendroid.test.model.UserModelCatHands; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import android.database.sqlite.SQLiteDatabase; import org.robolectric.annotation.Config; package net.cattaka.util.cathandsgendroid.test; @RunWith(RobolectricTestRunner.class) public class GenDbHandlerTest { @Test public void testDml() { SQLiteDatabase db = SQLiteDatabase.create(null); db.execSQL(UserModelCatHands.SQL_CREATE_TABLE); { // Insert
UserModel model;
cattaka/CatHandsGendroid
cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/StringKvModelTest.java
// Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/StringKvModel.java // @DataModel(find="key", autoincrement=false, // query= { // "Distinct:select distinct value from stringKvModel", // "QueryKey:select value from stringKvModel where key=?", // "QueryValue:select key as value from stringKvModel where value=?" // } // ) // public class StringKvModel { // @DataModelAttrs(primaryKey=true) // private String key; // private String value; // // public StringKvModel() { // } // // public StringKvModel(String key, String value) { // super(); // this.key = key; // this.value = value; // } // // public String getKey() { // return key; // } // public void setKey(String key) { // this.key = key; // } // public String getValue() { // return value; // } // public void setValue(String value) { // this.value = value; // } // }
import net.cattaka.util.cathandsgendroid.test.model.StringKvModel; import net.cattaka.util.cathandsgendroid.test.model.StringKvModelCatHands; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import android.database.sqlite.SQLiteDatabase; import org.robolectric.annotation.Config; import static org.junit.Assert.*;
package net.cattaka.util.cathandsgendroid.test; @RunWith(RobolectricTestRunner.class) public class StringKvModelTest { @Test public void testRun() { SQLiteDatabase db = SQLiteDatabase.create(null); db.execSQL(StringKvModelCatHands.SQL_CREATE_TABLE);
// Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/StringKvModel.java // @DataModel(find="key", autoincrement=false, // query= { // "Distinct:select distinct value from stringKvModel", // "QueryKey:select value from stringKvModel where key=?", // "QueryValue:select key as value from stringKvModel where value=?" // } // ) // public class StringKvModel { // @DataModelAttrs(primaryKey=true) // private String key; // private String value; // // public StringKvModel() { // } // // public StringKvModel(String key, String value) { // super(); // this.key = key; // this.value = value; // } // // public String getKey() { // return key; // } // public void setKey(String key) { // this.key = key; // } // public String getValue() { // return value; // } // public void setValue(String value) { // this.value = value; // } // } // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/StringKvModelTest.java import net.cattaka.util.cathandsgendroid.test.model.StringKvModel; import net.cattaka.util.cathandsgendroid.test.model.StringKvModelCatHands; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import android.database.sqlite.SQLiteDatabase; import org.robolectric.annotation.Config; import static org.junit.Assert.*; package net.cattaka.util.cathandsgendroid.test; @RunWith(RobolectricTestRunner.class) public class StringKvModelTest { @Test public void testRun() { SQLiteDatabase db = SQLiteDatabase.create(null); db.execSQL(StringKvModelCatHands.SQL_CREATE_TABLE);
StringKvModelCatHands.insert(db, new StringKvModel("Cat","Fish"));
cattaka/CatHandsGendroid
cathandsgendroid-apt/tmp/net/cattaka/util/cathandsgendroid/test/asyncif/IGenericsCallbackAsync.java
// Path: cathandsgendroid-core/src/main/java/net/cattaka/util/cathandsgendroid/exception/AsyncInterfaceException.java // public class AsyncInterfaceException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public AsyncInterfaceException() { // super(); // } // // public AsyncInterfaceException(String message, Throwable cause) { // super(message, cause); // } // // public AsyncInterfaceException(String message) { // super(message); // } // // public AsyncInterfaceException(Throwable cause) { // super(cause); // } // // }
import java.util.HashMap; import java.util.Map; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.Handler.Callback; import net.cattaka.util.cathandsgendroid.exception.AsyncInterfaceException; import net.cattaka.util.cathandsgendroid.test.asyncif.IGenericsCallback;
} public IGenericsCallbackAsync(IGenericsCallback<T> orig) { this(orig, Looper.getMainLooper()); } @Override public T add(T arg0, T arg1) { if (Looper.myLooper() == mHandler.getLooper()) { return orig.add(arg0, arg1); } Object[] work = obtain(); work[0] = this; work[1] = orig; work[0+2] = arg0; work[1+2] = arg1; synchronized (work) { mHandler.obtainMessage(EVENT_METHOD_0_add, work) .sendToTarget(); try { work.wait(); } catch (InterruptedException e) {
// Path: cathandsgendroid-core/src/main/java/net/cattaka/util/cathandsgendroid/exception/AsyncInterfaceException.java // public class AsyncInterfaceException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public AsyncInterfaceException() { // super(); // } // // public AsyncInterfaceException(String message, Throwable cause) { // super(message, cause); // } // // public AsyncInterfaceException(String message) { // super(message); // } // // public AsyncInterfaceException(Throwable cause) { // super(cause); // } // // } // Path: cathandsgendroid-apt/tmp/net/cattaka/util/cathandsgendroid/test/asyncif/IGenericsCallbackAsync.java import java.util.HashMap; import java.util.Map; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.Handler.Callback; import net.cattaka.util.cathandsgendroid.exception.AsyncInterfaceException; import net.cattaka.util.cathandsgendroid.test.asyncif.IGenericsCallback; } public IGenericsCallbackAsync(IGenericsCallback<T> orig) { this(orig, Looper.getMainLooper()); } @Override public T add(T arg0, T arg1) { if (Looper.myLooper() == mHandler.getLooper()) { return orig.add(arg0, arg1); } Object[] work = obtain(); work[0] = this; work[1] = orig; work[0+2] = arg0; work[1+2] = arg1; synchronized (work) { mHandler.obtainMessage(EVENT_METHOD_0_add, work) .sendToTarget(); try { work.wait(); } catch (InterruptedException e) {
throw new AsyncInterfaceException(e);
cattaka/CatHandsGendroid
cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/AutoIncrementTest.java
// Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/IntKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class IntKeyAiModel { // @DataModelAttrs(primaryKey=true) // private Integer key; // // public Integer getKey() { // return key; // } // // public void setKey(Integer key) { // this.key = key; // } // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/LongKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class LongKeyAiModel { // @DataModelAttrs(primaryKey=true) // private Long key; // // public Long getKey() { // return key; // } // // public void setKey(Long key) { // this.key = key; // } // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/PintKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class PintKeyAiModel { // @DataModelAttrs(primaryKey=true) // private int key; // // public int getKey() { // return key; // } // // public void setKey(int key) { // this.key = key; // } // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/PlongKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class PlongKeyAiModel { // @DataModelAttrs(primaryKey=true) // private long key; // // public long getKey() { // return key; // } // // public void setKey(long key) { // this.key = key; // } // }
import android.content.ContentValues; import net.cattaka.util.cathandsgendroid.test.model.IntKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.IntKeyAiModelCatHands; import net.cattaka.util.cathandsgendroid.test.model.LongKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.LongKeyAiModelCatHands; import net.cattaka.util.cathandsgendroid.test.model.PintKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.PintKeyAiModelCatHands; import net.cattaka.util.cathandsgendroid.test.model.PlongKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.PlongKeyAiModelCatHands; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import org.robolectric.RobolectricTestRunner; import android.database.sqlite.SQLiteDatabase; import org.robolectric.annotation.Config; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.doReturn;
package net.cattaka.util.cathandsgendroid.test; @RunWith(RobolectricTestRunner.class) public class AutoIncrementTest { @Test public void testPint() { SQLiteDatabase db = Mockito.spy(SQLiteDatabase.create(null)); db.execSQL(PintKeyAiModelCatHands.SQL_CREATE_TABLE);
// Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/IntKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class IntKeyAiModel { // @DataModelAttrs(primaryKey=true) // private Integer key; // // public Integer getKey() { // return key; // } // // public void setKey(Integer key) { // this.key = key; // } // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/LongKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class LongKeyAiModel { // @DataModelAttrs(primaryKey=true) // private Long key; // // public Long getKey() { // return key; // } // // public void setKey(Long key) { // this.key = key; // } // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/PintKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class PintKeyAiModel { // @DataModelAttrs(primaryKey=true) // private int key; // // public int getKey() { // return key; // } // // public void setKey(int key) { // this.key = key; // } // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/PlongKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class PlongKeyAiModel { // @DataModelAttrs(primaryKey=true) // private long key; // // public long getKey() { // return key; // } // // public void setKey(long key) { // this.key = key; // } // } // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/AutoIncrementTest.java import android.content.ContentValues; import net.cattaka.util.cathandsgendroid.test.model.IntKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.IntKeyAiModelCatHands; import net.cattaka.util.cathandsgendroid.test.model.LongKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.LongKeyAiModelCatHands; import net.cattaka.util.cathandsgendroid.test.model.PintKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.PintKeyAiModelCatHands; import net.cattaka.util.cathandsgendroid.test.model.PlongKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.PlongKeyAiModelCatHands; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import org.robolectric.RobolectricTestRunner; import android.database.sqlite.SQLiteDatabase; import org.robolectric.annotation.Config; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.doReturn; package net.cattaka.util.cathandsgendroid.test; @RunWith(RobolectricTestRunner.class) public class AutoIncrementTest { @Test public void testPint() { SQLiteDatabase db = Mockito.spy(SQLiteDatabase.create(null)); db.execSQL(PintKeyAiModelCatHands.SQL_CREATE_TABLE);
PintKeyAiModel m1 = new PintKeyAiModel();
cattaka/CatHandsGendroid
cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/AutoIncrementTest.java
// Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/IntKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class IntKeyAiModel { // @DataModelAttrs(primaryKey=true) // private Integer key; // // public Integer getKey() { // return key; // } // // public void setKey(Integer key) { // this.key = key; // } // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/LongKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class LongKeyAiModel { // @DataModelAttrs(primaryKey=true) // private Long key; // // public Long getKey() { // return key; // } // // public void setKey(Long key) { // this.key = key; // } // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/PintKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class PintKeyAiModel { // @DataModelAttrs(primaryKey=true) // private int key; // // public int getKey() { // return key; // } // // public void setKey(int key) { // this.key = key; // } // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/PlongKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class PlongKeyAiModel { // @DataModelAttrs(primaryKey=true) // private long key; // // public long getKey() { // return key; // } // // public void setKey(long key) { // this.key = key; // } // }
import android.content.ContentValues; import net.cattaka.util.cathandsgendroid.test.model.IntKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.IntKeyAiModelCatHands; import net.cattaka.util.cathandsgendroid.test.model.LongKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.LongKeyAiModelCatHands; import net.cattaka.util.cathandsgendroid.test.model.PintKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.PintKeyAiModelCatHands; import net.cattaka.util.cathandsgendroid.test.model.PlongKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.PlongKeyAiModelCatHands; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import org.robolectric.RobolectricTestRunner; import android.database.sqlite.SQLiteDatabase; import org.robolectric.annotation.Config; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.doReturn;
package net.cattaka.util.cathandsgendroid.test; @RunWith(RobolectricTestRunner.class) public class AutoIncrementTest { @Test public void testPint() { SQLiteDatabase db = Mockito.spy(SQLiteDatabase.create(null)); db.execSQL(PintKeyAiModelCatHands.SQL_CREATE_TABLE); PintKeyAiModel m1 = new PintKeyAiModel(); PintKeyAiModel m2 = new PintKeyAiModel(); doReturn(1L).when(db).insert(anyString(), isNull(), any(ContentValues.class)); PintKeyAiModelCatHands.insert(db, m1); doReturn(2L).when(db).insert(anyString(), isNull(), any(ContentValues.class)); PintKeyAiModelCatHands.insert(db, m2); assertEquals(1, m1.getKey()); assertEquals(2, m2.getKey()); } @Test public void testPlong() { SQLiteDatabase db = Mockito.spy(SQLiteDatabase.create(null)); db.execSQL(PlongKeyAiModelCatHands.SQL_CREATE_TABLE);
// Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/IntKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class IntKeyAiModel { // @DataModelAttrs(primaryKey=true) // private Integer key; // // public Integer getKey() { // return key; // } // // public void setKey(Integer key) { // this.key = key; // } // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/LongKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class LongKeyAiModel { // @DataModelAttrs(primaryKey=true) // private Long key; // // public Long getKey() { // return key; // } // // public void setKey(Long key) { // this.key = key; // } // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/PintKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class PintKeyAiModel { // @DataModelAttrs(primaryKey=true) // private int key; // // public int getKey() { // return key; // } // // public void setKey(int key) { // this.key = key; // } // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/PlongKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class PlongKeyAiModel { // @DataModelAttrs(primaryKey=true) // private long key; // // public long getKey() { // return key; // } // // public void setKey(long key) { // this.key = key; // } // } // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/AutoIncrementTest.java import android.content.ContentValues; import net.cattaka.util.cathandsgendroid.test.model.IntKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.IntKeyAiModelCatHands; import net.cattaka.util.cathandsgendroid.test.model.LongKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.LongKeyAiModelCatHands; import net.cattaka.util.cathandsgendroid.test.model.PintKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.PintKeyAiModelCatHands; import net.cattaka.util.cathandsgendroid.test.model.PlongKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.PlongKeyAiModelCatHands; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import org.robolectric.RobolectricTestRunner; import android.database.sqlite.SQLiteDatabase; import org.robolectric.annotation.Config; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.doReturn; package net.cattaka.util.cathandsgendroid.test; @RunWith(RobolectricTestRunner.class) public class AutoIncrementTest { @Test public void testPint() { SQLiteDatabase db = Mockito.spy(SQLiteDatabase.create(null)); db.execSQL(PintKeyAiModelCatHands.SQL_CREATE_TABLE); PintKeyAiModel m1 = new PintKeyAiModel(); PintKeyAiModel m2 = new PintKeyAiModel(); doReturn(1L).when(db).insert(anyString(), isNull(), any(ContentValues.class)); PintKeyAiModelCatHands.insert(db, m1); doReturn(2L).when(db).insert(anyString(), isNull(), any(ContentValues.class)); PintKeyAiModelCatHands.insert(db, m2); assertEquals(1, m1.getKey()); assertEquals(2, m2.getKey()); } @Test public void testPlong() { SQLiteDatabase db = Mockito.spy(SQLiteDatabase.create(null)); db.execSQL(PlongKeyAiModelCatHands.SQL_CREATE_TABLE);
PlongKeyAiModel m1 = new PlongKeyAiModel();
cattaka/CatHandsGendroid
cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/AutoIncrementTest.java
// Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/IntKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class IntKeyAiModel { // @DataModelAttrs(primaryKey=true) // private Integer key; // // public Integer getKey() { // return key; // } // // public void setKey(Integer key) { // this.key = key; // } // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/LongKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class LongKeyAiModel { // @DataModelAttrs(primaryKey=true) // private Long key; // // public Long getKey() { // return key; // } // // public void setKey(Long key) { // this.key = key; // } // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/PintKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class PintKeyAiModel { // @DataModelAttrs(primaryKey=true) // private int key; // // public int getKey() { // return key; // } // // public void setKey(int key) { // this.key = key; // } // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/PlongKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class PlongKeyAiModel { // @DataModelAttrs(primaryKey=true) // private long key; // // public long getKey() { // return key; // } // // public void setKey(long key) { // this.key = key; // } // }
import android.content.ContentValues; import net.cattaka.util.cathandsgendroid.test.model.IntKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.IntKeyAiModelCatHands; import net.cattaka.util.cathandsgendroid.test.model.LongKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.LongKeyAiModelCatHands; import net.cattaka.util.cathandsgendroid.test.model.PintKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.PintKeyAiModelCatHands; import net.cattaka.util.cathandsgendroid.test.model.PlongKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.PlongKeyAiModelCatHands; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import org.robolectric.RobolectricTestRunner; import android.database.sqlite.SQLiteDatabase; import org.robolectric.annotation.Config; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.doReturn;
PintKeyAiModelCatHands.insert(db, m1); doReturn(2L).when(db).insert(anyString(), isNull(), any(ContentValues.class)); PintKeyAiModelCatHands.insert(db, m2); assertEquals(1, m1.getKey()); assertEquals(2, m2.getKey()); } @Test public void testPlong() { SQLiteDatabase db = Mockito.spy(SQLiteDatabase.create(null)); db.execSQL(PlongKeyAiModelCatHands.SQL_CREATE_TABLE); PlongKeyAiModel m1 = new PlongKeyAiModel(); PlongKeyAiModel m2 = new PlongKeyAiModel(); doReturn(1L).when(db).insert(anyString(), isNull(), any(ContentValues.class)); PlongKeyAiModelCatHands.insert(db, m1); doReturn(2L).when(db).insert(anyString(), isNull(), any(ContentValues.class)); PlongKeyAiModelCatHands.insert(db, m2); assertEquals(1, m1.getKey()); assertEquals(2, m2.getKey()); } @Test public void testInt() { SQLiteDatabase db = Mockito.spy(SQLiteDatabase.create(null)); db.execSQL(IntKeyAiModelCatHands.SQL_CREATE_TABLE);
// Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/IntKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class IntKeyAiModel { // @DataModelAttrs(primaryKey=true) // private Integer key; // // public Integer getKey() { // return key; // } // // public void setKey(Integer key) { // this.key = key; // } // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/LongKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class LongKeyAiModel { // @DataModelAttrs(primaryKey=true) // private Long key; // // public Long getKey() { // return key; // } // // public void setKey(Long key) { // this.key = key; // } // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/PintKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class PintKeyAiModel { // @DataModelAttrs(primaryKey=true) // private int key; // // public int getKey() { // return key; // } // // public void setKey(int key) { // this.key = key; // } // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/PlongKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class PlongKeyAiModel { // @DataModelAttrs(primaryKey=true) // private long key; // // public long getKey() { // return key; // } // // public void setKey(long key) { // this.key = key; // } // } // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/AutoIncrementTest.java import android.content.ContentValues; import net.cattaka.util.cathandsgendroid.test.model.IntKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.IntKeyAiModelCatHands; import net.cattaka.util.cathandsgendroid.test.model.LongKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.LongKeyAiModelCatHands; import net.cattaka.util.cathandsgendroid.test.model.PintKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.PintKeyAiModelCatHands; import net.cattaka.util.cathandsgendroid.test.model.PlongKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.PlongKeyAiModelCatHands; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import org.robolectric.RobolectricTestRunner; import android.database.sqlite.SQLiteDatabase; import org.robolectric.annotation.Config; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.doReturn; PintKeyAiModelCatHands.insert(db, m1); doReturn(2L).when(db).insert(anyString(), isNull(), any(ContentValues.class)); PintKeyAiModelCatHands.insert(db, m2); assertEquals(1, m1.getKey()); assertEquals(2, m2.getKey()); } @Test public void testPlong() { SQLiteDatabase db = Mockito.spy(SQLiteDatabase.create(null)); db.execSQL(PlongKeyAiModelCatHands.SQL_CREATE_TABLE); PlongKeyAiModel m1 = new PlongKeyAiModel(); PlongKeyAiModel m2 = new PlongKeyAiModel(); doReturn(1L).when(db).insert(anyString(), isNull(), any(ContentValues.class)); PlongKeyAiModelCatHands.insert(db, m1); doReturn(2L).when(db).insert(anyString(), isNull(), any(ContentValues.class)); PlongKeyAiModelCatHands.insert(db, m2); assertEquals(1, m1.getKey()); assertEquals(2, m2.getKey()); } @Test public void testInt() { SQLiteDatabase db = Mockito.spy(SQLiteDatabase.create(null)); db.execSQL(IntKeyAiModelCatHands.SQL_CREATE_TABLE);
IntKeyAiModel m1 = new IntKeyAiModel();
cattaka/CatHandsGendroid
cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/AutoIncrementTest.java
// Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/IntKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class IntKeyAiModel { // @DataModelAttrs(primaryKey=true) // private Integer key; // // public Integer getKey() { // return key; // } // // public void setKey(Integer key) { // this.key = key; // } // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/LongKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class LongKeyAiModel { // @DataModelAttrs(primaryKey=true) // private Long key; // // public Long getKey() { // return key; // } // // public void setKey(Long key) { // this.key = key; // } // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/PintKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class PintKeyAiModel { // @DataModelAttrs(primaryKey=true) // private int key; // // public int getKey() { // return key; // } // // public void setKey(int key) { // this.key = key; // } // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/PlongKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class PlongKeyAiModel { // @DataModelAttrs(primaryKey=true) // private long key; // // public long getKey() { // return key; // } // // public void setKey(long key) { // this.key = key; // } // }
import android.content.ContentValues; import net.cattaka.util.cathandsgendroid.test.model.IntKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.IntKeyAiModelCatHands; import net.cattaka.util.cathandsgendroid.test.model.LongKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.LongKeyAiModelCatHands; import net.cattaka.util.cathandsgendroid.test.model.PintKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.PintKeyAiModelCatHands; import net.cattaka.util.cathandsgendroid.test.model.PlongKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.PlongKeyAiModelCatHands; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import org.robolectric.RobolectricTestRunner; import android.database.sqlite.SQLiteDatabase; import org.robolectric.annotation.Config; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.doReturn;
PlongKeyAiModelCatHands.insert(db, m1); doReturn(2L).when(db).insert(anyString(), isNull(), any(ContentValues.class)); PlongKeyAiModelCatHands.insert(db, m2); assertEquals(1, m1.getKey()); assertEquals(2, m2.getKey()); } @Test public void testInt() { SQLiteDatabase db = Mockito.spy(SQLiteDatabase.create(null)); db.execSQL(IntKeyAiModelCatHands.SQL_CREATE_TABLE); IntKeyAiModel m1 = new IntKeyAiModel(); IntKeyAiModel m2 = new IntKeyAiModel(); doReturn(1L).when(db).insert(anyString(), isNull(), any(ContentValues.class)); IntKeyAiModelCatHands.insert(db, m1); doReturn(2L).when(db).insert(anyString(), isNull(), any(ContentValues.class)); IntKeyAiModelCatHands.insert(db, m2); assertEquals(Integer.valueOf(1), m1.getKey()); assertEquals(Integer.valueOf(2), m2.getKey()); } @Test public void testLong() { SQLiteDatabase db = Mockito.spy(SQLiteDatabase.create(null)); db.execSQL(LongKeyAiModelCatHands.SQL_CREATE_TABLE);
// Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/IntKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class IntKeyAiModel { // @DataModelAttrs(primaryKey=true) // private Integer key; // // public Integer getKey() { // return key; // } // // public void setKey(Integer key) { // this.key = key; // } // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/LongKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class LongKeyAiModel { // @DataModelAttrs(primaryKey=true) // private Long key; // // public Long getKey() { // return key; // } // // public void setKey(Long key) { // this.key = key; // } // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/PintKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class PintKeyAiModel { // @DataModelAttrs(primaryKey=true) // private int key; // // public int getKey() { // return key; // } // // public void setKey(int key) { // this.key = key; // } // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/model/PlongKeyAiModel.java // @DataModel(find = "key", genDbFunc = true, autoincrement = true) // public class PlongKeyAiModel { // @DataModelAttrs(primaryKey=true) // private long key; // // public long getKey() { // return key; // } // // public void setKey(long key) { // this.key = key; // } // } // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/AutoIncrementTest.java import android.content.ContentValues; import net.cattaka.util.cathandsgendroid.test.model.IntKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.IntKeyAiModelCatHands; import net.cattaka.util.cathandsgendroid.test.model.LongKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.LongKeyAiModelCatHands; import net.cattaka.util.cathandsgendroid.test.model.PintKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.PintKeyAiModelCatHands; import net.cattaka.util.cathandsgendroid.test.model.PlongKeyAiModel; import net.cattaka.util.cathandsgendroid.test.model.PlongKeyAiModelCatHands; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import org.robolectric.RobolectricTestRunner; import android.database.sqlite.SQLiteDatabase; import org.robolectric.annotation.Config; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.doReturn; PlongKeyAiModelCatHands.insert(db, m1); doReturn(2L).when(db).insert(anyString(), isNull(), any(ContentValues.class)); PlongKeyAiModelCatHands.insert(db, m2); assertEquals(1, m1.getKey()); assertEquals(2, m2.getKey()); } @Test public void testInt() { SQLiteDatabase db = Mockito.spy(SQLiteDatabase.create(null)); db.execSQL(IntKeyAiModelCatHands.SQL_CREATE_TABLE); IntKeyAiModel m1 = new IntKeyAiModel(); IntKeyAiModel m2 = new IntKeyAiModel(); doReturn(1L).when(db).insert(anyString(), isNull(), any(ContentValues.class)); IntKeyAiModelCatHands.insert(db, m1); doReturn(2L).when(db).insert(anyString(), isNull(), any(ContentValues.class)); IntKeyAiModelCatHands.insert(db, m2); assertEquals(Integer.valueOf(1), m1.getKey()); assertEquals(Integer.valueOf(2), m2.getKey()); } @Test public void testLong() { SQLiteDatabase db = Mockito.spy(SQLiteDatabase.create(null)); db.execSQL(LongKeyAiModelCatHands.SQL_CREATE_TABLE);
LongKeyAiModel m1 = new LongKeyAiModel();
cattaka/CatHandsGendroid
cathandsgendroid-core/src/main/java/net/cattaka/util/cathandsgendroid/accessor/ParcelableAccessor.java
// Path: cathandsgendroid-core/src/main/java/net/cattaka/util/cathandsgendroid/accessor/Accessors.java // public static class BlobAccessor implements IAccessor<byte[]> { // static BlobAccessor instance; // // public static IAccessor<byte[]> createAccessor(Class<byte[]> clazz) { // if (instance == null) { // instance = new BlobAccessor(); // } // return instance; // } // // @Override // public byte[] readFromStream(DataInputStream in) throws IOException { // int n = in.readInt(); // if (n >= 0) { // byte[] bs = new byte[n]; // in.read(bs, 0, n); // return bs; // } else { // return null; // } // } // // @Override // public void writeToStream(DataOutputStream out, byte[] value) throws IOException { // if (value != null) { // out.writeInt(value.length); // out.write(value); // } else { // out.writeInt(-1); // } // } // // @Override // public byte[] readFromParcel(Parcel p) { // int n = p.readInt(); // if (n >= 0) { // byte[] bs = new byte[n]; // p.readByteArray(bs); // return bs; // } else { // return null; // } // } // // @Override // public void writeToParcel(Parcel p, byte[] value) { // if (value != null) { // p.writeInt(value.length); // p.writeByteArray(value); // } else { // p.writeInt(-1); // } // } // // @Override // public byte[] readFromCursor(Cursor c, int idx) { // return (c.isNull(idx) ? null : (c.getBlob(idx))); // } // // @Override // public void putToContentValues(ContentValues values, String columnName, byte[] value) { // values.put(columnName, value); // } // // @Override // public String stringValue(byte[] value) { // if (value == null) { // return null; // } else { // StringBuilder sb = new StringBuilder(); // for (byte b : value) { // if (0 <= b && b < 0x10) { // sb.append('0'); // } // sb.append(Integer.toHexString(b)); // } // return sb.toString(); // } // }; // };
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import net.cattaka.util.cathandsgendroid.accessor.Accessors.BlobAccessor; import android.content.ContentValues; import android.database.Cursor; import android.os.Parcel; import android.os.Parcelable;
package net.cattaka.util.cathandsgendroid.accessor; public class ParcelableAccessor<T extends Parcelable> implements IAccessor<T> { private Class<T> clazz; public static <T extends Parcelable> IAccessor<T> createAccessor(Class<T> clazz) { return new ParcelableAccessor<T>(clazz); } public ParcelableAccessor(Class<T> clazz) { super(); this.clazz = clazz; } @Override public T readFromStream(DataInputStream in) throws IOException {
// Path: cathandsgendroid-core/src/main/java/net/cattaka/util/cathandsgendroid/accessor/Accessors.java // public static class BlobAccessor implements IAccessor<byte[]> { // static BlobAccessor instance; // // public static IAccessor<byte[]> createAccessor(Class<byte[]> clazz) { // if (instance == null) { // instance = new BlobAccessor(); // } // return instance; // } // // @Override // public byte[] readFromStream(DataInputStream in) throws IOException { // int n = in.readInt(); // if (n >= 0) { // byte[] bs = new byte[n]; // in.read(bs, 0, n); // return bs; // } else { // return null; // } // } // // @Override // public void writeToStream(DataOutputStream out, byte[] value) throws IOException { // if (value != null) { // out.writeInt(value.length); // out.write(value); // } else { // out.writeInt(-1); // } // } // // @Override // public byte[] readFromParcel(Parcel p) { // int n = p.readInt(); // if (n >= 0) { // byte[] bs = new byte[n]; // p.readByteArray(bs); // return bs; // } else { // return null; // } // } // // @Override // public void writeToParcel(Parcel p, byte[] value) { // if (value != null) { // p.writeInt(value.length); // p.writeByteArray(value); // } else { // p.writeInt(-1); // } // } // // @Override // public byte[] readFromCursor(Cursor c, int idx) { // return (c.isNull(idx) ? null : (c.getBlob(idx))); // } // // @Override // public void putToContentValues(ContentValues values, String columnName, byte[] value) { // values.put(columnName, value); // } // // @Override // public String stringValue(byte[] value) { // if (value == null) { // return null; // } else { // StringBuilder sb = new StringBuilder(); // for (byte b : value) { // if (0 <= b && b < 0x10) { // sb.append('0'); // } // sb.append(Integer.toHexString(b)); // } // return sb.toString(); // } // }; // }; // Path: cathandsgendroid-core/src/main/java/net/cattaka/util/cathandsgendroid/accessor/ParcelableAccessor.java import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import net.cattaka.util.cathandsgendroid.accessor.Accessors.BlobAccessor; import android.content.ContentValues; import android.database.Cursor; import android.os.Parcel; import android.os.Parcelable; package net.cattaka.util.cathandsgendroid.accessor; public class ParcelableAccessor<T extends Parcelable> implements IAccessor<T> { private Class<T> clazz; public static <T extends Parcelable> IAccessor<T> createAccessor(Class<T> clazz) { return new ParcelableAccessor<T>(clazz); } public ParcelableAccessor(Class<T> clazz) { super(); this.clazz = clazz; } @Override public T readFromStream(DataInputStream in) throws IOException {
byte[] bs = BlobAccessor.createAccessor(byte[].class).readFromStream(in);
cattaka/CatHandsGendroid
cathandsgendroid-apt/src/main/java/net/cattaka/util/cathandsgendroid/apt/InnerFieldType.java
// Path: cathandsgendroid-apt/src/main/java/net/cattaka/util/cathandsgendroid/apt/util/Functions.java // public class Functions { // public static String join(List<?> objects, String delim) { // if (objects == null) { // return ""; // } // StringBuilder sb = new StringBuilder(); // int i = 0; // for (Object object : objects) { // if (i > 0) { // sb.append(delim); // } // sb.append(String.valueOf(object)); // i++; // } // return sb.toString(); // } // // public static List<String> pullTypes(DeclaredType tm) { // List<String> results = new ArrayList<String>(); // results.add(String.valueOf(tm.asElement())); // if (tm instanceof DeclaredType) { // for (TypeMirror t : ((DeclaredType)tm).getTypeArguments()) { // results.addAll(pullTypes((DeclaredType)t)); // } // } // return results; // } // }
import net.cattaka.util.cathandsgendroid.apt.util.Functions; import java.util.Locale; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror;
public final String dbDataType; public final String javaDataType; public final String origJavaDataType; public final String primitiveJavaDataType; public final boolean primitiveType; public final boolean isNumber; public InnerFieldType(boolean primitiveType, boolean isNumber, String accessor, String dbDataType, String javaDataType, String primitiveJavaDataType) { this(primitiveType, isNumber, accessor, dbDataType, javaDataType, javaDataType, primitiveJavaDataType); } private InnerFieldType(boolean primitiveType, boolean isNumber, String accessor, String dbDataType, String javaDataType, String origJavaDataType, String primitiveJavaDataType) { super(); this.primitiveType = primitiveType; this.accessor = accessor; this.dbDataType = dbDataType; this.javaDataType = javaDataType; this.origJavaDataType = origJavaDataType; this.primitiveJavaDataType = (primitiveJavaDataType != null) ? primitiveJavaDataType : "(not supported)"; this.isNumber = isNumber; } public static InnerFieldType createCustomType(TypeMirror tm, String accessor, String dbDataType) { String javaDataType = String.valueOf(tm); String args; String typeParams; if (tm instanceof DeclaredType) { DeclaredType dt = (DeclaredType) tm;
// Path: cathandsgendroid-apt/src/main/java/net/cattaka/util/cathandsgendroid/apt/util/Functions.java // public class Functions { // public static String join(List<?> objects, String delim) { // if (objects == null) { // return ""; // } // StringBuilder sb = new StringBuilder(); // int i = 0; // for (Object object : objects) { // if (i > 0) { // sb.append(delim); // } // sb.append(String.valueOf(object)); // i++; // } // return sb.toString(); // } // // public static List<String> pullTypes(DeclaredType tm) { // List<String> results = new ArrayList<String>(); // results.add(String.valueOf(tm.asElement())); // if (tm instanceof DeclaredType) { // for (TypeMirror t : ((DeclaredType)tm).getTypeArguments()) { // results.addAll(pullTypes((DeclaredType)t)); // } // } // return results; // } // } // Path: cathandsgendroid-apt/src/main/java/net/cattaka/util/cathandsgendroid/apt/InnerFieldType.java import net.cattaka.util.cathandsgendroid.apt.util.Functions; import java.util.Locale; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; public final String dbDataType; public final String javaDataType; public final String origJavaDataType; public final String primitiveJavaDataType; public final boolean primitiveType; public final boolean isNumber; public InnerFieldType(boolean primitiveType, boolean isNumber, String accessor, String dbDataType, String javaDataType, String primitiveJavaDataType) { this(primitiveType, isNumber, accessor, dbDataType, javaDataType, javaDataType, primitiveJavaDataType); } private InnerFieldType(boolean primitiveType, boolean isNumber, String accessor, String dbDataType, String javaDataType, String origJavaDataType, String primitiveJavaDataType) { super(); this.primitiveType = primitiveType; this.accessor = accessor; this.dbDataType = dbDataType; this.javaDataType = javaDataType; this.origJavaDataType = origJavaDataType; this.primitiveJavaDataType = (primitiveJavaDataType != null) ? primitiveJavaDataType : "(not supported)"; this.isNumber = isNumber; } public static InnerFieldType createCustomType(TypeMirror tm, String accessor, String dbDataType) { String javaDataType = String.valueOf(tm); String args; String typeParams; if (tm instanceof DeclaredType) { DeclaredType dt = (DeclaredType) tm;
args = Functions.join(Functions.pullTypes(dt), ".class, ") + ".class";
cattaka/CatHandsGendroid
cathandsgendroid-apt/tmp/net/cattaka/util/cathandsgendroid/test/asyncif/SimpleInterfaceAsync.java
// Path: cathandsgendroid-core/src/main/java/net/cattaka/util/cathandsgendroid/exception/AsyncInterfaceException.java // public class AsyncInterfaceException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public AsyncInterfaceException() { // super(); // } // // public AsyncInterfaceException(String message, Throwable cause) { // super(message, cause); // } // // public AsyncInterfaceException(String message) { // super(message); // } // // public AsyncInterfaceException(Throwable cause) { // super(cause); // } // // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/asyncif/SimpleInterface.java // @AsyncInterface // public interface SimpleInterface { // public void run(); // public int add(int a, int b); // public List<Integer> runLists(List<Integer> args); // }
import java.util.HashMap; import java.util.Map; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.Handler.Callback; import net.cattaka.util.cathandsgendroid.exception.AsyncInterfaceException; import net.cattaka.util.cathandsgendroid.test.asyncif.SimpleInterface;
work[0] = this; work[1] = orig; mHandler.obtainMessage(EVENT_METHOD_0_run, work).sendToTarget(); } @Override public int add(int arg0, int arg1) { if (Looper.myLooper() == mHandler.getLooper()) { return orig.add(arg0, arg1); } Object[] work = obtain(); work[0] = this; work[1] = orig; work[0+2] = arg0; work[1+2] = arg1; synchronized (work) { mHandler.obtainMessage(EVENT_METHOD_1_add, work) .sendToTarget(); try { work.wait(); } catch (InterruptedException e) {
// Path: cathandsgendroid-core/src/main/java/net/cattaka/util/cathandsgendroid/exception/AsyncInterfaceException.java // public class AsyncInterfaceException extends RuntimeException { // private static final long serialVersionUID = 1L; // // public AsyncInterfaceException() { // super(); // } // // public AsyncInterfaceException(String message, Throwable cause) { // super(message, cause); // } // // public AsyncInterfaceException(String message) { // super(message); // } // // public AsyncInterfaceException(Throwable cause) { // super(cause); // } // // } // // Path: cathandsgendroid-apt/src/test/java/net/cattaka/util/cathandsgendroid/test/asyncif/SimpleInterface.java // @AsyncInterface // public interface SimpleInterface { // public void run(); // public int add(int a, int b); // public List<Integer> runLists(List<Integer> args); // } // Path: cathandsgendroid-apt/tmp/net/cattaka/util/cathandsgendroid/test/asyncif/SimpleInterfaceAsync.java import java.util.HashMap; import java.util.Map; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.Handler.Callback; import net.cattaka.util.cathandsgendroid.exception.AsyncInterfaceException; import net.cattaka.util.cathandsgendroid.test.asyncif.SimpleInterface; work[0] = this; work[1] = orig; mHandler.obtainMessage(EVENT_METHOD_0_run, work).sendToTarget(); } @Override public int add(int arg0, int arg1) { if (Looper.myLooper() == mHandler.getLooper()) { return orig.add(arg0, arg1); } Object[] work = obtain(); work[0] = this; work[1] = orig; work[0+2] = arg0; work[1+2] = arg1; synchronized (work) { mHandler.obtainMessage(EVENT_METHOD_1_add, work) .sendToTarget(); try { work.wait(); } catch (InterruptedException e) {
throw new AsyncInterfaceException(e);
jnr/jnr-x86asm
src/main/java/com/kenai/jnr/x86asm/Label.java
// Path: src/main/java/com/kenai/jnr/x86asm/LABEL_STATE.java // @Deprecated // public enum LABEL_STATE { // /** Label is unused. */ // LABEL_STATE_UNUSED, // // /** Label is linked (waiting to be bound) */ // LABEL_STATE_LINKED, // // /** Label is bound */ // LABEL_STATE_BOUND; // }
import java.util.LinkedList; import java.util.List; import static com.kenai.jnr.x86asm.LABEL_STATE.*;
// // Copyright (C) 2010 Wayne Meissner // Copyright (c) 2008-2009, Petr Kobalicek <kobalicek.petr@gmail.com> // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. package com.kenai.jnr.x86asm; /** * */ @Deprecated public final class Label extends Operand { /** Label Id (0 means unknown). */ final int id; /** State of label, see {@link LABEL_STATE}. */
// Path: src/main/java/com/kenai/jnr/x86asm/LABEL_STATE.java // @Deprecated // public enum LABEL_STATE { // /** Label is unused. */ // LABEL_STATE_UNUSED, // // /** Label is linked (waiting to be bound) */ // LABEL_STATE_LINKED, // // /** Label is bound */ // LABEL_STATE_BOUND; // } // Path: src/main/java/com/kenai/jnr/x86asm/Label.java import java.util.LinkedList; import java.util.List; import static com.kenai.jnr.x86asm.LABEL_STATE.*; // // Copyright (C) 2010 Wayne Meissner // Copyright (c) 2008-2009, Petr Kobalicek <kobalicek.petr@gmail.com> // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. package com.kenai.jnr.x86asm; /** * */ @Deprecated public final class Label extends Operand { /** Label Id (0 means unknown). */ final int id; /** State of label, see {@link LABEL_STATE}. */
LABEL_STATE state;
bertrandmartel/speed-test-lib
examples/src/main/java/fr/bmartel/speedtest/examples/RepeatUploadExample.java
// Path: jspeedtest/src/main/java/fr/bmartel/speedtest/inter/IRepeatListener.java // public interface IRepeatListener { // // /** // * called when repeat download task is finished. // * // * @param report speed examples report // */ // void onCompletion(SpeedTestReport report); // // /** // * called when a speed examples report is sent. // * // * @param report speed examples report // */ // void onReport(SpeedTestReport report); // } // // Path: jspeedtest/src/main/java/fr/bmartel/speedtest/inter/ISpeedTestListener.java // public interface ISpeedTestListener { // // /** // * download/upload process completion with transfer rate in bit/s and octet/s. // * // * @param report download speed test report // */ // void onCompletion(SpeedTestReport report); // // /** // * monitor download/upload progress. // * // * @param percent % of progress // * @param report current speed test download report // */ // void onProgress(float percent, SpeedTestReport report); // // /** // * Error catch. // * // * @param speedTestError error enum // * @param errorMessage error message // */ // void onError(SpeedTestError speedTestError, String errorMessage); // } // // Path: jspeedtest/src/main/java/fr/bmartel/speedtest/model/SpeedTestError.java // public enum SpeedTestError { // // /** // * invalid http response was returned. // */ // INVALID_HTTP_RESPONSE, // /** // * socket error occured. // */ // SOCKET_ERROR, // /** // * socket timeout occured. // */ // SOCKET_TIMEOUT, // /** // * connection error occured. // */ // CONNECTION_ERROR, // /** // * Malformed URI // */ // MALFORMED_URI, // /** // * protocol can be FTP or HTTP // */ // UNSUPPORTED_PROTOCOL // }
import fr.bmartel.speedtest.*; import fr.bmartel.speedtest.inter.IRepeatListener; import fr.bmartel.speedtest.inter.ISpeedTestListener; import fr.bmartel.speedtest.model.SpeedTestError; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger;
/* * The MIT License (MIT) * <p/> * Copyright (c) 2016-2017 Bertrand Martel * <p/> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p/> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p/> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package fr.bmartel.speedtest.examples; /** * Upload a file repeatedly from speed test server during a fixed amount of time. * * @author Bertrand Martel */ public class RepeatUploadExample { /** * spedd examples server uri. */ private final static String SPEED_TEST_SERVER_URI_UL = "http://ipv4.ikoula.testdebit.info/"; /** * logger. */ private final static Logger LOGGER = LogManager.getLogger(RepeatUploadExample.class.getName()); /** * speed test duration set to 11s. */ private static final int SPEED_TEST_DURATION = 11000; /** * amount of time between each speed test report set to 1s. */ private static final int REPORT_INTERVAL = 1000; /** * set socket timeout to 3s. */ private static final int SOCKET_TIMEOUT = 3000; /** * upload 1Mo file size. */ private static final int FILE_SIZE = 1000000; /** * Repeat upload example main. * * @param args no args required */ public static void main(final String[] args) { final SpeedTestSocket speedTestSocket = new SpeedTestSocket(); speedTestSocket.setSocketTimeout(SOCKET_TIMEOUT);
// Path: jspeedtest/src/main/java/fr/bmartel/speedtest/inter/IRepeatListener.java // public interface IRepeatListener { // // /** // * called when repeat download task is finished. // * // * @param report speed examples report // */ // void onCompletion(SpeedTestReport report); // // /** // * called when a speed examples report is sent. // * // * @param report speed examples report // */ // void onReport(SpeedTestReport report); // } // // Path: jspeedtest/src/main/java/fr/bmartel/speedtest/inter/ISpeedTestListener.java // public interface ISpeedTestListener { // // /** // * download/upload process completion with transfer rate in bit/s and octet/s. // * // * @param report download speed test report // */ // void onCompletion(SpeedTestReport report); // // /** // * monitor download/upload progress. // * // * @param percent % of progress // * @param report current speed test download report // */ // void onProgress(float percent, SpeedTestReport report); // // /** // * Error catch. // * // * @param speedTestError error enum // * @param errorMessage error message // */ // void onError(SpeedTestError speedTestError, String errorMessage); // } // // Path: jspeedtest/src/main/java/fr/bmartel/speedtest/model/SpeedTestError.java // public enum SpeedTestError { // // /** // * invalid http response was returned. // */ // INVALID_HTTP_RESPONSE, // /** // * socket error occured. // */ // SOCKET_ERROR, // /** // * socket timeout occured. // */ // SOCKET_TIMEOUT, // /** // * connection error occured. // */ // CONNECTION_ERROR, // /** // * Malformed URI // */ // MALFORMED_URI, // /** // * protocol can be FTP or HTTP // */ // UNSUPPORTED_PROTOCOL // } // Path: examples/src/main/java/fr/bmartel/speedtest/examples/RepeatUploadExample.java import fr.bmartel.speedtest.*; import fr.bmartel.speedtest.inter.IRepeatListener; import fr.bmartel.speedtest.inter.ISpeedTestListener; import fr.bmartel.speedtest.model.SpeedTestError; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /* * The MIT License (MIT) * <p/> * Copyright (c) 2016-2017 Bertrand Martel * <p/> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p/> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p/> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package fr.bmartel.speedtest.examples; /** * Upload a file repeatedly from speed test server during a fixed amount of time. * * @author Bertrand Martel */ public class RepeatUploadExample { /** * spedd examples server uri. */ private final static String SPEED_TEST_SERVER_URI_UL = "http://ipv4.ikoula.testdebit.info/"; /** * logger. */ private final static Logger LOGGER = LogManager.getLogger(RepeatUploadExample.class.getName()); /** * speed test duration set to 11s. */ private static final int SPEED_TEST_DURATION = 11000; /** * amount of time between each speed test report set to 1s. */ private static final int REPORT_INTERVAL = 1000; /** * set socket timeout to 3s. */ private static final int SOCKET_TIMEOUT = 3000; /** * upload 1Mo file size. */ private static final int FILE_SIZE = 1000000; /** * Repeat upload example main. * * @param args no args required */ public static void main(final String[] args) { final SpeedTestSocket speedTestSocket = new SpeedTestSocket(); speedTestSocket.setSocketTimeout(SOCKET_TIMEOUT);
speedTestSocket.addSpeedTestListener(new ISpeedTestListener() {
bertrandmartel/speed-test-lib
examples/src/main/java/fr/bmartel/speedtest/examples/RepeatUploadExample.java
// Path: jspeedtest/src/main/java/fr/bmartel/speedtest/inter/IRepeatListener.java // public interface IRepeatListener { // // /** // * called when repeat download task is finished. // * // * @param report speed examples report // */ // void onCompletion(SpeedTestReport report); // // /** // * called when a speed examples report is sent. // * // * @param report speed examples report // */ // void onReport(SpeedTestReport report); // } // // Path: jspeedtest/src/main/java/fr/bmartel/speedtest/inter/ISpeedTestListener.java // public interface ISpeedTestListener { // // /** // * download/upload process completion with transfer rate in bit/s and octet/s. // * // * @param report download speed test report // */ // void onCompletion(SpeedTestReport report); // // /** // * monitor download/upload progress. // * // * @param percent % of progress // * @param report current speed test download report // */ // void onProgress(float percent, SpeedTestReport report); // // /** // * Error catch. // * // * @param speedTestError error enum // * @param errorMessage error message // */ // void onError(SpeedTestError speedTestError, String errorMessage); // } // // Path: jspeedtest/src/main/java/fr/bmartel/speedtest/model/SpeedTestError.java // public enum SpeedTestError { // // /** // * invalid http response was returned. // */ // INVALID_HTTP_RESPONSE, // /** // * socket error occured. // */ // SOCKET_ERROR, // /** // * socket timeout occured. // */ // SOCKET_TIMEOUT, // /** // * connection error occured. // */ // CONNECTION_ERROR, // /** // * Malformed URI // */ // MALFORMED_URI, // /** // * protocol can be FTP or HTTP // */ // UNSUPPORTED_PROTOCOL // }
import fr.bmartel.speedtest.*; import fr.bmartel.speedtest.inter.IRepeatListener; import fr.bmartel.speedtest.inter.ISpeedTestListener; import fr.bmartel.speedtest.model.SpeedTestError; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger;
/* * The MIT License (MIT) * <p/> * Copyright (c) 2016-2017 Bertrand Martel * <p/> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p/> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p/> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package fr.bmartel.speedtest.examples; /** * Upload a file repeatedly from speed test server during a fixed amount of time. * * @author Bertrand Martel */ public class RepeatUploadExample { /** * spedd examples server uri. */ private final static String SPEED_TEST_SERVER_URI_UL = "http://ipv4.ikoula.testdebit.info/"; /** * logger. */ private final static Logger LOGGER = LogManager.getLogger(RepeatUploadExample.class.getName()); /** * speed test duration set to 11s. */ private static final int SPEED_TEST_DURATION = 11000; /** * amount of time between each speed test report set to 1s. */ private static final int REPORT_INTERVAL = 1000; /** * set socket timeout to 3s. */ private static final int SOCKET_TIMEOUT = 3000; /** * upload 1Mo file size. */ private static final int FILE_SIZE = 1000000; /** * Repeat upload example main. * * @param args no args required */ public static void main(final String[] args) { final SpeedTestSocket speedTestSocket = new SpeedTestSocket(); speedTestSocket.setSocketTimeout(SOCKET_TIMEOUT); speedTestSocket.addSpeedTestListener(new ISpeedTestListener() { @Override public void onCompletion(final SpeedTestReport report) { //called when download/upload is complete } @Override
// Path: jspeedtest/src/main/java/fr/bmartel/speedtest/inter/IRepeatListener.java // public interface IRepeatListener { // // /** // * called when repeat download task is finished. // * // * @param report speed examples report // */ // void onCompletion(SpeedTestReport report); // // /** // * called when a speed examples report is sent. // * // * @param report speed examples report // */ // void onReport(SpeedTestReport report); // } // // Path: jspeedtest/src/main/java/fr/bmartel/speedtest/inter/ISpeedTestListener.java // public interface ISpeedTestListener { // // /** // * download/upload process completion with transfer rate in bit/s and octet/s. // * // * @param report download speed test report // */ // void onCompletion(SpeedTestReport report); // // /** // * monitor download/upload progress. // * // * @param percent % of progress // * @param report current speed test download report // */ // void onProgress(float percent, SpeedTestReport report); // // /** // * Error catch. // * // * @param speedTestError error enum // * @param errorMessage error message // */ // void onError(SpeedTestError speedTestError, String errorMessage); // } // // Path: jspeedtest/src/main/java/fr/bmartel/speedtest/model/SpeedTestError.java // public enum SpeedTestError { // // /** // * invalid http response was returned. // */ // INVALID_HTTP_RESPONSE, // /** // * socket error occured. // */ // SOCKET_ERROR, // /** // * socket timeout occured. // */ // SOCKET_TIMEOUT, // /** // * connection error occured. // */ // CONNECTION_ERROR, // /** // * Malformed URI // */ // MALFORMED_URI, // /** // * protocol can be FTP or HTTP // */ // UNSUPPORTED_PROTOCOL // } // Path: examples/src/main/java/fr/bmartel/speedtest/examples/RepeatUploadExample.java import fr.bmartel.speedtest.*; import fr.bmartel.speedtest.inter.IRepeatListener; import fr.bmartel.speedtest.inter.ISpeedTestListener; import fr.bmartel.speedtest.model.SpeedTestError; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /* * The MIT License (MIT) * <p/> * Copyright (c) 2016-2017 Bertrand Martel * <p/> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p/> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p/> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package fr.bmartel.speedtest.examples; /** * Upload a file repeatedly from speed test server during a fixed amount of time. * * @author Bertrand Martel */ public class RepeatUploadExample { /** * spedd examples server uri. */ private final static String SPEED_TEST_SERVER_URI_UL = "http://ipv4.ikoula.testdebit.info/"; /** * logger. */ private final static Logger LOGGER = LogManager.getLogger(RepeatUploadExample.class.getName()); /** * speed test duration set to 11s. */ private static final int SPEED_TEST_DURATION = 11000; /** * amount of time between each speed test report set to 1s. */ private static final int REPORT_INTERVAL = 1000; /** * set socket timeout to 3s. */ private static final int SOCKET_TIMEOUT = 3000; /** * upload 1Mo file size. */ private static final int FILE_SIZE = 1000000; /** * Repeat upload example main. * * @param args no args required */ public static void main(final String[] args) { final SpeedTestSocket speedTestSocket = new SpeedTestSocket(); speedTestSocket.setSocketTimeout(SOCKET_TIMEOUT); speedTestSocket.addSpeedTestListener(new ISpeedTestListener() { @Override public void onCompletion(final SpeedTestReport report) { //called when download/upload is complete } @Override
public void onError(final SpeedTestError speedTestError, final String errorMessage) {
bertrandmartel/speed-test-lib
examples/src/main/java/fr/bmartel/speedtest/examples/RepeatUploadExample.java
// Path: jspeedtest/src/main/java/fr/bmartel/speedtest/inter/IRepeatListener.java // public interface IRepeatListener { // // /** // * called when repeat download task is finished. // * // * @param report speed examples report // */ // void onCompletion(SpeedTestReport report); // // /** // * called when a speed examples report is sent. // * // * @param report speed examples report // */ // void onReport(SpeedTestReport report); // } // // Path: jspeedtest/src/main/java/fr/bmartel/speedtest/inter/ISpeedTestListener.java // public interface ISpeedTestListener { // // /** // * download/upload process completion with transfer rate in bit/s and octet/s. // * // * @param report download speed test report // */ // void onCompletion(SpeedTestReport report); // // /** // * monitor download/upload progress. // * // * @param percent % of progress // * @param report current speed test download report // */ // void onProgress(float percent, SpeedTestReport report); // // /** // * Error catch. // * // * @param speedTestError error enum // * @param errorMessage error message // */ // void onError(SpeedTestError speedTestError, String errorMessage); // } // // Path: jspeedtest/src/main/java/fr/bmartel/speedtest/model/SpeedTestError.java // public enum SpeedTestError { // // /** // * invalid http response was returned. // */ // INVALID_HTTP_RESPONSE, // /** // * socket error occured. // */ // SOCKET_ERROR, // /** // * socket timeout occured. // */ // SOCKET_TIMEOUT, // /** // * connection error occured. // */ // CONNECTION_ERROR, // /** // * Malformed URI // */ // MALFORMED_URI, // /** // * protocol can be FTP or HTTP // */ // UNSUPPORTED_PROTOCOL // }
import fr.bmartel.speedtest.*; import fr.bmartel.speedtest.inter.IRepeatListener; import fr.bmartel.speedtest.inter.ISpeedTestListener; import fr.bmartel.speedtest.model.SpeedTestError; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger;
/* * The MIT License (MIT) * <p/> * Copyright (c) 2016-2017 Bertrand Martel * <p/> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p/> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p/> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package fr.bmartel.speedtest.examples; /** * Upload a file repeatedly from speed test server during a fixed amount of time. * * @author Bertrand Martel */ public class RepeatUploadExample { /** * spedd examples server uri. */ private final static String SPEED_TEST_SERVER_URI_UL = "http://ipv4.ikoula.testdebit.info/"; /** * logger. */ private final static Logger LOGGER = LogManager.getLogger(RepeatUploadExample.class.getName()); /** * speed test duration set to 11s. */ private static final int SPEED_TEST_DURATION = 11000; /** * amount of time between each speed test report set to 1s. */ private static final int REPORT_INTERVAL = 1000; /** * set socket timeout to 3s. */ private static final int SOCKET_TIMEOUT = 3000; /** * upload 1Mo file size. */ private static final int FILE_SIZE = 1000000; /** * Repeat upload example main. * * @param args no args required */ public static void main(final String[] args) { final SpeedTestSocket speedTestSocket = new SpeedTestSocket(); speedTestSocket.setSocketTimeout(SOCKET_TIMEOUT); speedTestSocket.addSpeedTestListener(new ISpeedTestListener() { @Override public void onCompletion(final SpeedTestReport report) { //called when download/upload is complete } @Override public void onError(final SpeedTestError speedTestError, final String errorMessage) { if (LOGGER.isErrorEnabled()) { LOGGER.error(errorMessage); } } @Override public void onProgress(final float percent, final SpeedTestReport downloadReport) { //notify progress } }); speedTestSocket.startUploadRepeat(SPEED_TEST_SERVER_URI_UL, SPEED_TEST_DURATION, REPORT_INTERVAL, FILE_SIZE, new
// Path: jspeedtest/src/main/java/fr/bmartel/speedtest/inter/IRepeatListener.java // public interface IRepeatListener { // // /** // * called when repeat download task is finished. // * // * @param report speed examples report // */ // void onCompletion(SpeedTestReport report); // // /** // * called when a speed examples report is sent. // * // * @param report speed examples report // */ // void onReport(SpeedTestReport report); // } // // Path: jspeedtest/src/main/java/fr/bmartel/speedtest/inter/ISpeedTestListener.java // public interface ISpeedTestListener { // // /** // * download/upload process completion with transfer rate in bit/s and octet/s. // * // * @param report download speed test report // */ // void onCompletion(SpeedTestReport report); // // /** // * monitor download/upload progress. // * // * @param percent % of progress // * @param report current speed test download report // */ // void onProgress(float percent, SpeedTestReport report); // // /** // * Error catch. // * // * @param speedTestError error enum // * @param errorMessage error message // */ // void onError(SpeedTestError speedTestError, String errorMessage); // } // // Path: jspeedtest/src/main/java/fr/bmartel/speedtest/model/SpeedTestError.java // public enum SpeedTestError { // // /** // * invalid http response was returned. // */ // INVALID_HTTP_RESPONSE, // /** // * socket error occured. // */ // SOCKET_ERROR, // /** // * socket timeout occured. // */ // SOCKET_TIMEOUT, // /** // * connection error occured. // */ // CONNECTION_ERROR, // /** // * Malformed URI // */ // MALFORMED_URI, // /** // * protocol can be FTP or HTTP // */ // UNSUPPORTED_PROTOCOL // } // Path: examples/src/main/java/fr/bmartel/speedtest/examples/RepeatUploadExample.java import fr.bmartel.speedtest.*; import fr.bmartel.speedtest.inter.IRepeatListener; import fr.bmartel.speedtest.inter.ISpeedTestListener; import fr.bmartel.speedtest.model.SpeedTestError; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /* * The MIT License (MIT) * <p/> * Copyright (c) 2016-2017 Bertrand Martel * <p/> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p/> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p/> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package fr.bmartel.speedtest.examples; /** * Upload a file repeatedly from speed test server during a fixed amount of time. * * @author Bertrand Martel */ public class RepeatUploadExample { /** * spedd examples server uri. */ private final static String SPEED_TEST_SERVER_URI_UL = "http://ipv4.ikoula.testdebit.info/"; /** * logger. */ private final static Logger LOGGER = LogManager.getLogger(RepeatUploadExample.class.getName()); /** * speed test duration set to 11s. */ private static final int SPEED_TEST_DURATION = 11000; /** * amount of time between each speed test report set to 1s. */ private static final int REPORT_INTERVAL = 1000; /** * set socket timeout to 3s. */ private static final int SOCKET_TIMEOUT = 3000; /** * upload 1Mo file size. */ private static final int FILE_SIZE = 1000000; /** * Repeat upload example main. * * @param args no args required */ public static void main(final String[] args) { final SpeedTestSocket speedTestSocket = new SpeedTestSocket(); speedTestSocket.setSocketTimeout(SOCKET_TIMEOUT); speedTestSocket.addSpeedTestListener(new ISpeedTestListener() { @Override public void onCompletion(final SpeedTestReport report) { //called when download/upload is complete } @Override public void onError(final SpeedTestError speedTestError, final String errorMessage) { if (LOGGER.isErrorEnabled()) { LOGGER.error(errorMessage); } } @Override public void onProgress(final float percent, final SpeedTestReport downloadReport) { //notify progress } }); speedTestSocket.startUploadRepeat(SPEED_TEST_SERVER_URI_UL, SPEED_TEST_DURATION, REPORT_INTERVAL, FILE_SIZE, new
IRepeatListener() {
bertrandmartel/speed-test-lib
jspeedtest/src/main/java/fr/bmartel/speedtest/SpeedTestReport.java
// Path: jspeedtest/src/main/java/fr/bmartel/speedtest/model/SpeedTestMode.java // public enum SpeedTestMode { // /** // * no examples. // */ // NONE, // /** // * download examples. // */ // DOWNLOAD, // /** // * upload examples. // */ // UPLOAD // }
import fr.bmartel.speedtest.model.SpeedTestMode; import java.math.BigDecimal;
/* * The MIT License (MIT) * <p/> * Copyright (c) 2016-2017 Bertrand Martel * <p/> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p/> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p/> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package fr.bmartel.speedtest; /** * Speed examples report. * <p/> * feature current report measurement for DOWNLOAD/UPLOAD * * @author Bertrand Martel */ public class SpeedTestReport { /** * current size of file to upload. */ private final long mTempPacketSize; /** * total file size. */ private final long mTotalPacketSize; /** * transfer rate in octet/s. */ private final BigDecimal mTransferRateOctet; /** * transfer rate in bit/s. */ private final BigDecimal mTransferRateBit; /** * upload start time in nanoseconds. */ private final long mStartTime; /** * upload report time in nanoseconds. */ private final long mReportTime; /** * speed examples mode for this report. */
// Path: jspeedtest/src/main/java/fr/bmartel/speedtest/model/SpeedTestMode.java // public enum SpeedTestMode { // /** // * no examples. // */ // NONE, // /** // * download examples. // */ // DOWNLOAD, // /** // * upload examples. // */ // UPLOAD // } // Path: jspeedtest/src/main/java/fr/bmartel/speedtest/SpeedTestReport.java import fr.bmartel.speedtest.model.SpeedTestMode; import java.math.BigDecimal; /* * The MIT License (MIT) * <p/> * Copyright (c) 2016-2017 Bertrand Martel * <p/> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p/> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p/> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package fr.bmartel.speedtest; /** * Speed examples report. * <p/> * feature current report measurement for DOWNLOAD/UPLOAD * * @author Bertrand Martel */ public class SpeedTestReport { /** * current size of file to upload. */ private final long mTempPacketSize; /** * total file size. */ private final long mTotalPacketSize; /** * transfer rate in octet/s. */ private final BigDecimal mTransferRateOctet; /** * transfer rate in bit/s. */ private final BigDecimal mTransferRateBit; /** * upload start time in nanoseconds. */ private final long mStartTime; /** * upload report time in nanoseconds. */ private final long mReportTime; /** * speed examples mode for this report. */
private final SpeedTestMode mSpeedTestMode;
bertrandmartel/speed-test-lib
examples/src/main/java/fr/bmartel/speedtest/examples/ChainingRepeatExample.java
// Path: jspeedtest/src/main/java/fr/bmartel/speedtest/inter/IRepeatListener.java // public interface IRepeatListener { // // /** // * called when repeat download task is finished. // * // * @param report speed examples report // */ // void onCompletion(SpeedTestReport report); // // /** // * called when a speed examples report is sent. // * // * @param report speed examples report // */ // void onReport(SpeedTestReport report); // } // // Path: jspeedtest/src/main/java/fr/bmartel/speedtest/inter/ISpeedTestListener.java // public interface ISpeedTestListener { // // /** // * download/upload process completion with transfer rate in bit/s and octet/s. // * // * @param report download speed test report // */ // void onCompletion(SpeedTestReport report); // // /** // * monitor download/upload progress. // * // * @param percent % of progress // * @param report current speed test download report // */ // void onProgress(float percent, SpeedTestReport report); // // /** // * Error catch. // * // * @param speedTestError error enum // * @param errorMessage error message // */ // void onError(SpeedTestError speedTestError, String errorMessage); // } // // Path: jspeedtest/src/main/java/fr/bmartel/speedtest/model/SpeedTestError.java // public enum SpeedTestError { // // /** // * invalid http response was returned. // */ // INVALID_HTTP_RESPONSE, // /** // * socket error occured. // */ // SOCKET_ERROR, // /** // * socket timeout occured. // */ // SOCKET_TIMEOUT, // /** // * connection error occured. // */ // CONNECTION_ERROR, // /** // * Malformed URI // */ // MALFORMED_URI, // /** // * protocol can be FTP or HTTP // */ // UNSUPPORTED_PROTOCOL // }
import fr.bmartel.speedtest.*; import fr.bmartel.speedtest.inter.IRepeatListener; import fr.bmartel.speedtest.inter.ISpeedTestListener; import fr.bmartel.speedtest.model.SpeedTestError; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger;
/* * The MIT License (MIT) * <p/> * Copyright (c) 2016-2017 Bertrand Martel * <p/> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p/> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p/> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package fr.bmartel.speedtest.examples; /** * Chaining 2x (Download + Upload) file repeatedly from speed test server during a fixed amount of time. * Download during 3 seconds then Upload during 3 seconds. * * @author Bertrand Martel */ public class ChainingRepeatExample { /** * spedd examples server uri. */ private final static String SPEED_TEST_SERVER_URI_DL = "http://ipv4.ikoula.testdebit.info/1M.iso"; /** * logger. */ private final static Logger LOGGER = LogManager.getLogger(RepeatDownloadExample.class.getName()); /** * speed test duration set to 3s. */ private static final int SPEED_TEST_DURATION = 3000; /** * amount of time between each speed test report set to 1s. */ private static final int REPORT_INTERVAL = 1000; /** * set socket timeout to 3s. */ private static final int SOCKET_TIMEOUT = 3000; /** * speed test socket. */ private static SpeedTestSocket speedTestSocket = new SpeedTestSocket(); /** * speed examples server uri. */ private final static String SPEED_TEST_SERVER_URI_UL = "http://2.testdebit.info/"; /** * upload 1Mo file size. */ private static final int FILE_SIZE = 1000000; /** * chain request counter. */ private static int chainCount = 2; /** * Repeat download example main. * * @param args no args required */ public static void main(final String[] args) { speedTestSocket.setSocketTimeout(SOCKET_TIMEOUT);
// Path: jspeedtest/src/main/java/fr/bmartel/speedtest/inter/IRepeatListener.java // public interface IRepeatListener { // // /** // * called when repeat download task is finished. // * // * @param report speed examples report // */ // void onCompletion(SpeedTestReport report); // // /** // * called when a speed examples report is sent. // * // * @param report speed examples report // */ // void onReport(SpeedTestReport report); // } // // Path: jspeedtest/src/main/java/fr/bmartel/speedtest/inter/ISpeedTestListener.java // public interface ISpeedTestListener { // // /** // * download/upload process completion with transfer rate in bit/s and octet/s. // * // * @param report download speed test report // */ // void onCompletion(SpeedTestReport report); // // /** // * monitor download/upload progress. // * // * @param percent % of progress // * @param report current speed test download report // */ // void onProgress(float percent, SpeedTestReport report); // // /** // * Error catch. // * // * @param speedTestError error enum // * @param errorMessage error message // */ // void onError(SpeedTestError speedTestError, String errorMessage); // } // // Path: jspeedtest/src/main/java/fr/bmartel/speedtest/model/SpeedTestError.java // public enum SpeedTestError { // // /** // * invalid http response was returned. // */ // INVALID_HTTP_RESPONSE, // /** // * socket error occured. // */ // SOCKET_ERROR, // /** // * socket timeout occured. // */ // SOCKET_TIMEOUT, // /** // * connection error occured. // */ // CONNECTION_ERROR, // /** // * Malformed URI // */ // MALFORMED_URI, // /** // * protocol can be FTP or HTTP // */ // UNSUPPORTED_PROTOCOL // } // Path: examples/src/main/java/fr/bmartel/speedtest/examples/ChainingRepeatExample.java import fr.bmartel.speedtest.*; import fr.bmartel.speedtest.inter.IRepeatListener; import fr.bmartel.speedtest.inter.ISpeedTestListener; import fr.bmartel.speedtest.model.SpeedTestError; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /* * The MIT License (MIT) * <p/> * Copyright (c) 2016-2017 Bertrand Martel * <p/> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p/> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p/> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package fr.bmartel.speedtest.examples; /** * Chaining 2x (Download + Upload) file repeatedly from speed test server during a fixed amount of time. * Download during 3 seconds then Upload during 3 seconds. * * @author Bertrand Martel */ public class ChainingRepeatExample { /** * spedd examples server uri. */ private final static String SPEED_TEST_SERVER_URI_DL = "http://ipv4.ikoula.testdebit.info/1M.iso"; /** * logger. */ private final static Logger LOGGER = LogManager.getLogger(RepeatDownloadExample.class.getName()); /** * speed test duration set to 3s. */ private static final int SPEED_TEST_DURATION = 3000; /** * amount of time between each speed test report set to 1s. */ private static final int REPORT_INTERVAL = 1000; /** * set socket timeout to 3s. */ private static final int SOCKET_TIMEOUT = 3000; /** * speed test socket. */ private static SpeedTestSocket speedTestSocket = new SpeedTestSocket(); /** * speed examples server uri. */ private final static String SPEED_TEST_SERVER_URI_UL = "http://2.testdebit.info/"; /** * upload 1Mo file size. */ private static final int FILE_SIZE = 1000000; /** * chain request counter. */ private static int chainCount = 2; /** * Repeat download example main. * * @param args no args required */ public static void main(final String[] args) { speedTestSocket.setSocketTimeout(SOCKET_TIMEOUT);
speedTestSocket.addSpeedTestListener(new ISpeedTestListener() {
bertrandmartel/speed-test-lib
examples/src/main/java/fr/bmartel/speedtest/examples/ChainingRepeatExample.java
// Path: jspeedtest/src/main/java/fr/bmartel/speedtest/inter/IRepeatListener.java // public interface IRepeatListener { // // /** // * called when repeat download task is finished. // * // * @param report speed examples report // */ // void onCompletion(SpeedTestReport report); // // /** // * called when a speed examples report is sent. // * // * @param report speed examples report // */ // void onReport(SpeedTestReport report); // } // // Path: jspeedtest/src/main/java/fr/bmartel/speedtest/inter/ISpeedTestListener.java // public interface ISpeedTestListener { // // /** // * download/upload process completion with transfer rate in bit/s and octet/s. // * // * @param report download speed test report // */ // void onCompletion(SpeedTestReport report); // // /** // * monitor download/upload progress. // * // * @param percent % of progress // * @param report current speed test download report // */ // void onProgress(float percent, SpeedTestReport report); // // /** // * Error catch. // * // * @param speedTestError error enum // * @param errorMessage error message // */ // void onError(SpeedTestError speedTestError, String errorMessage); // } // // Path: jspeedtest/src/main/java/fr/bmartel/speedtest/model/SpeedTestError.java // public enum SpeedTestError { // // /** // * invalid http response was returned. // */ // INVALID_HTTP_RESPONSE, // /** // * socket error occured. // */ // SOCKET_ERROR, // /** // * socket timeout occured. // */ // SOCKET_TIMEOUT, // /** // * connection error occured. // */ // CONNECTION_ERROR, // /** // * Malformed URI // */ // MALFORMED_URI, // /** // * protocol can be FTP or HTTP // */ // UNSUPPORTED_PROTOCOL // }
import fr.bmartel.speedtest.*; import fr.bmartel.speedtest.inter.IRepeatListener; import fr.bmartel.speedtest.inter.ISpeedTestListener; import fr.bmartel.speedtest.model.SpeedTestError; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger;
/* * The MIT License (MIT) * <p/> * Copyright (c) 2016-2017 Bertrand Martel * <p/> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p/> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p/> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package fr.bmartel.speedtest.examples; /** * Chaining 2x (Download + Upload) file repeatedly from speed test server during a fixed amount of time. * Download during 3 seconds then Upload during 3 seconds. * * @author Bertrand Martel */ public class ChainingRepeatExample { /** * spedd examples server uri. */ private final static String SPEED_TEST_SERVER_URI_DL = "http://ipv4.ikoula.testdebit.info/1M.iso"; /** * logger. */ private final static Logger LOGGER = LogManager.getLogger(RepeatDownloadExample.class.getName()); /** * speed test duration set to 3s. */ private static final int SPEED_TEST_DURATION = 3000; /** * amount of time between each speed test report set to 1s. */ private static final int REPORT_INTERVAL = 1000; /** * set socket timeout to 3s. */ private static final int SOCKET_TIMEOUT = 3000; /** * speed test socket. */ private static SpeedTestSocket speedTestSocket = new SpeedTestSocket(); /** * speed examples server uri. */ private final static String SPEED_TEST_SERVER_URI_UL = "http://2.testdebit.info/"; /** * upload 1Mo file size. */ private static final int FILE_SIZE = 1000000; /** * chain request counter. */ private static int chainCount = 2; /** * Repeat download example main. * * @param args no args required */ public static void main(final String[] args) { speedTestSocket.setSocketTimeout(SOCKET_TIMEOUT); speedTestSocket.addSpeedTestListener(new ISpeedTestListener() { @Override public void onCompletion(final SpeedTestReport report) { //called when download/upload is complete } @Override
// Path: jspeedtest/src/main/java/fr/bmartel/speedtest/inter/IRepeatListener.java // public interface IRepeatListener { // // /** // * called when repeat download task is finished. // * // * @param report speed examples report // */ // void onCompletion(SpeedTestReport report); // // /** // * called when a speed examples report is sent. // * // * @param report speed examples report // */ // void onReport(SpeedTestReport report); // } // // Path: jspeedtest/src/main/java/fr/bmartel/speedtest/inter/ISpeedTestListener.java // public interface ISpeedTestListener { // // /** // * download/upload process completion with transfer rate in bit/s and octet/s. // * // * @param report download speed test report // */ // void onCompletion(SpeedTestReport report); // // /** // * monitor download/upload progress. // * // * @param percent % of progress // * @param report current speed test download report // */ // void onProgress(float percent, SpeedTestReport report); // // /** // * Error catch. // * // * @param speedTestError error enum // * @param errorMessage error message // */ // void onError(SpeedTestError speedTestError, String errorMessage); // } // // Path: jspeedtest/src/main/java/fr/bmartel/speedtest/model/SpeedTestError.java // public enum SpeedTestError { // // /** // * invalid http response was returned. // */ // INVALID_HTTP_RESPONSE, // /** // * socket error occured. // */ // SOCKET_ERROR, // /** // * socket timeout occured. // */ // SOCKET_TIMEOUT, // /** // * connection error occured. // */ // CONNECTION_ERROR, // /** // * Malformed URI // */ // MALFORMED_URI, // /** // * protocol can be FTP or HTTP // */ // UNSUPPORTED_PROTOCOL // } // Path: examples/src/main/java/fr/bmartel/speedtest/examples/ChainingRepeatExample.java import fr.bmartel.speedtest.*; import fr.bmartel.speedtest.inter.IRepeatListener; import fr.bmartel.speedtest.inter.ISpeedTestListener; import fr.bmartel.speedtest.model.SpeedTestError; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /* * The MIT License (MIT) * <p/> * Copyright (c) 2016-2017 Bertrand Martel * <p/> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p/> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p/> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package fr.bmartel.speedtest.examples; /** * Chaining 2x (Download + Upload) file repeatedly from speed test server during a fixed amount of time. * Download during 3 seconds then Upload during 3 seconds. * * @author Bertrand Martel */ public class ChainingRepeatExample { /** * spedd examples server uri. */ private final static String SPEED_TEST_SERVER_URI_DL = "http://ipv4.ikoula.testdebit.info/1M.iso"; /** * logger. */ private final static Logger LOGGER = LogManager.getLogger(RepeatDownloadExample.class.getName()); /** * speed test duration set to 3s. */ private static final int SPEED_TEST_DURATION = 3000; /** * amount of time between each speed test report set to 1s. */ private static final int REPORT_INTERVAL = 1000; /** * set socket timeout to 3s. */ private static final int SOCKET_TIMEOUT = 3000; /** * speed test socket. */ private static SpeedTestSocket speedTestSocket = new SpeedTestSocket(); /** * speed examples server uri. */ private final static String SPEED_TEST_SERVER_URI_UL = "http://2.testdebit.info/"; /** * upload 1Mo file size. */ private static final int FILE_SIZE = 1000000; /** * chain request counter. */ private static int chainCount = 2; /** * Repeat download example main. * * @param args no args required */ public static void main(final String[] args) { speedTestSocket.setSocketTimeout(SOCKET_TIMEOUT); speedTestSocket.addSpeedTestListener(new ISpeedTestListener() { @Override public void onCompletion(final SpeedTestReport report) { //called when download/upload is complete } @Override
public void onError(final SpeedTestError speedTestError, final String errorMessage) {
bertrandmartel/speed-test-lib
examples/src/main/java/fr/bmartel/speedtest/examples/ChainingRepeatExample.java
// Path: jspeedtest/src/main/java/fr/bmartel/speedtest/inter/IRepeatListener.java // public interface IRepeatListener { // // /** // * called when repeat download task is finished. // * // * @param report speed examples report // */ // void onCompletion(SpeedTestReport report); // // /** // * called when a speed examples report is sent. // * // * @param report speed examples report // */ // void onReport(SpeedTestReport report); // } // // Path: jspeedtest/src/main/java/fr/bmartel/speedtest/inter/ISpeedTestListener.java // public interface ISpeedTestListener { // // /** // * download/upload process completion with transfer rate in bit/s and octet/s. // * // * @param report download speed test report // */ // void onCompletion(SpeedTestReport report); // // /** // * monitor download/upload progress. // * // * @param percent % of progress // * @param report current speed test download report // */ // void onProgress(float percent, SpeedTestReport report); // // /** // * Error catch. // * // * @param speedTestError error enum // * @param errorMessage error message // */ // void onError(SpeedTestError speedTestError, String errorMessage); // } // // Path: jspeedtest/src/main/java/fr/bmartel/speedtest/model/SpeedTestError.java // public enum SpeedTestError { // // /** // * invalid http response was returned. // */ // INVALID_HTTP_RESPONSE, // /** // * socket error occured. // */ // SOCKET_ERROR, // /** // * socket timeout occured. // */ // SOCKET_TIMEOUT, // /** // * connection error occured. // */ // CONNECTION_ERROR, // /** // * Malformed URI // */ // MALFORMED_URI, // /** // * protocol can be FTP or HTTP // */ // UNSUPPORTED_PROTOCOL // }
import fr.bmartel.speedtest.*; import fr.bmartel.speedtest.inter.IRepeatListener; import fr.bmartel.speedtest.inter.ISpeedTestListener; import fr.bmartel.speedtest.model.SpeedTestError; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger;
speedTestSocket.addSpeedTestListener(new ISpeedTestListener() { @Override public void onCompletion(final SpeedTestReport report) { //called when download/upload is complete } @Override public void onError(final SpeedTestError speedTestError, final String errorMessage) { if (LOGGER.isErrorEnabled()) { LOGGER.error(errorMessage); } } @Override public void onProgress(final float percent, final SpeedTestReport downloadReport) { //notify progress } }); startDownload(); } /** * Start downloading. */ private static void startDownload() { speedTestSocket.startDownloadRepeat(SPEED_TEST_SERVER_URI_DL, SPEED_TEST_DURATION, REPORT_INTERVAL, new
// Path: jspeedtest/src/main/java/fr/bmartel/speedtest/inter/IRepeatListener.java // public interface IRepeatListener { // // /** // * called when repeat download task is finished. // * // * @param report speed examples report // */ // void onCompletion(SpeedTestReport report); // // /** // * called when a speed examples report is sent. // * // * @param report speed examples report // */ // void onReport(SpeedTestReport report); // } // // Path: jspeedtest/src/main/java/fr/bmartel/speedtest/inter/ISpeedTestListener.java // public interface ISpeedTestListener { // // /** // * download/upload process completion with transfer rate in bit/s and octet/s. // * // * @param report download speed test report // */ // void onCompletion(SpeedTestReport report); // // /** // * monitor download/upload progress. // * // * @param percent % of progress // * @param report current speed test download report // */ // void onProgress(float percent, SpeedTestReport report); // // /** // * Error catch. // * // * @param speedTestError error enum // * @param errorMessage error message // */ // void onError(SpeedTestError speedTestError, String errorMessage); // } // // Path: jspeedtest/src/main/java/fr/bmartel/speedtest/model/SpeedTestError.java // public enum SpeedTestError { // // /** // * invalid http response was returned. // */ // INVALID_HTTP_RESPONSE, // /** // * socket error occured. // */ // SOCKET_ERROR, // /** // * socket timeout occured. // */ // SOCKET_TIMEOUT, // /** // * connection error occured. // */ // CONNECTION_ERROR, // /** // * Malformed URI // */ // MALFORMED_URI, // /** // * protocol can be FTP or HTTP // */ // UNSUPPORTED_PROTOCOL // } // Path: examples/src/main/java/fr/bmartel/speedtest/examples/ChainingRepeatExample.java import fr.bmartel.speedtest.*; import fr.bmartel.speedtest.inter.IRepeatListener; import fr.bmartel.speedtest.inter.ISpeedTestListener; import fr.bmartel.speedtest.model.SpeedTestError; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; speedTestSocket.addSpeedTestListener(new ISpeedTestListener() { @Override public void onCompletion(final SpeedTestReport report) { //called when download/upload is complete } @Override public void onError(final SpeedTestError speedTestError, final String errorMessage) { if (LOGGER.isErrorEnabled()) { LOGGER.error(errorMessage); } } @Override public void onProgress(final float percent, final SpeedTestReport downloadReport) { //notify progress } }); startDownload(); } /** * Start downloading. */ private static void startDownload() { speedTestSocket.startDownloadRepeat(SPEED_TEST_SERVER_URI_DL, SPEED_TEST_DURATION, REPORT_INTERVAL, new
IRepeatListener() {
bertrandmartel/speed-test-lib
jspeedtest/src/test/java/fr/bmartel/speedtest/test/RandomGenTest.java
// Path: jspeedtest/src/test/java/fr/bmartel/speedtest/test/utils/TestUtils.java // public class TestUtils { // // /** // * generate a header for unit examples message. // * // * @param className class name to print // * @return message prefix // */ // public static String generateMessageHeader(final Class className) { // return "[" + className.getSimpleName() + "] "; // } // } // // Path: jspeedtest/src/main/java/fr/bmartel/speedtest/utils/RandomGen.java // public class RandomGen { // // /** // * Random object. // */ // private final Random mRandom = new Random(); // // /** // * Random generated file. // */ // private File mFile; // // /** // * Generate random byte array. // * // * @param length number of bytes to be generated // * @return random byte array // */ // public byte[] generateRandomArray(final int length) { // // final byte[] buffer = new byte[length]; // // final int iter = length / SpeedTestConst.UPLOAD_FILE_WRITE_CHUNK; // final int remain = length % SpeedTestConst.UPLOAD_FILE_WRITE_CHUNK; // // for (int i = 0; i < iter; i++) { // final byte[] random = new byte[SpeedTestConst.UPLOAD_FILE_WRITE_CHUNK]; // mRandom.nextBytes(random); // System.arraycopy(random, 0, buffer, i * SpeedTestConst.UPLOAD_FILE_WRITE_CHUNK, SpeedTestConst // .UPLOAD_FILE_WRITE_CHUNK); // } // if (remain > 0) { // final byte[] random = new byte[remain]; // mRandom.nextBytes(random); // System.arraycopy(random, 0, buffer, iter * SpeedTestConst.UPLOAD_FILE_WRITE_CHUNK, remain); // } // return buffer; // } // // /** // * Generate random file. // * // * @param length number of bytes to be generated // * @return file with random content // */ // public RandomAccessFile generateRandomFile(final int length) throws IOException { // // mFile = File.createTempFile(SpeedTestConst.UPLOAD_TEMP_FILE_NAME, // SpeedTestConst.UPLOAD_TEMP_FILE_EXTENSION); // // final RandomAccessFile randomFile = new RandomAccessFile(mFile.getAbsolutePath(), "rw"); // randomFile.setLength(length); // // final int iter = length / SpeedTestConst.UPLOAD_FILE_WRITE_CHUNK; // final int remain = length % SpeedTestConst.UPLOAD_FILE_WRITE_CHUNK; // // for (int i = 0; i < iter; i++) { // final byte[] random = new byte[SpeedTestConst.UPLOAD_FILE_WRITE_CHUNK]; // mRandom.nextBytes(random); // randomFile.write(random); // } // if (remain > 0) { // final byte[] random = new byte[remain]; // mRandom.nextBytes(random); // randomFile.write(random); // } // // return randomFile; // } // // /** // * Delete random file. // */ // public void deleteFile() { // if (mFile != null) { // mFile.delete(); // } // } // }
import fr.bmartel.speedtest.test.utils.TestUtils; import fr.bmartel.speedtest.utils.RandomGen; import org.junit.Assert; import org.junit.Test;
/* * The MIT License (MIT) * <p/> * Copyright (c) 2016-2017 Bertrand Martel * <p/> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p/> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p/> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package fr.bmartel.speedtest.test; /** * Random file generator examples. * * @author Bertrand Martel */ public class RandomGenTest { /** * unit examples message header. */ private static final String HEADER = TestUtils.generateMessageHeader(RandomGenTest.class); /** * file size tested. */ private final int[] SIZES = new int[]{1, 10, 10000, 10000000}; /** * test generated file for upload. */ @Test public void randomGenTest() { for (int i = 0; i < SIZES.length; i++) {
// Path: jspeedtest/src/test/java/fr/bmartel/speedtest/test/utils/TestUtils.java // public class TestUtils { // // /** // * generate a header for unit examples message. // * // * @param className class name to print // * @return message prefix // */ // public static String generateMessageHeader(final Class className) { // return "[" + className.getSimpleName() + "] "; // } // } // // Path: jspeedtest/src/main/java/fr/bmartel/speedtest/utils/RandomGen.java // public class RandomGen { // // /** // * Random object. // */ // private final Random mRandom = new Random(); // // /** // * Random generated file. // */ // private File mFile; // // /** // * Generate random byte array. // * // * @param length number of bytes to be generated // * @return random byte array // */ // public byte[] generateRandomArray(final int length) { // // final byte[] buffer = new byte[length]; // // final int iter = length / SpeedTestConst.UPLOAD_FILE_WRITE_CHUNK; // final int remain = length % SpeedTestConst.UPLOAD_FILE_WRITE_CHUNK; // // for (int i = 0; i < iter; i++) { // final byte[] random = new byte[SpeedTestConst.UPLOAD_FILE_WRITE_CHUNK]; // mRandom.nextBytes(random); // System.arraycopy(random, 0, buffer, i * SpeedTestConst.UPLOAD_FILE_WRITE_CHUNK, SpeedTestConst // .UPLOAD_FILE_WRITE_CHUNK); // } // if (remain > 0) { // final byte[] random = new byte[remain]; // mRandom.nextBytes(random); // System.arraycopy(random, 0, buffer, iter * SpeedTestConst.UPLOAD_FILE_WRITE_CHUNK, remain); // } // return buffer; // } // // /** // * Generate random file. // * // * @param length number of bytes to be generated // * @return file with random content // */ // public RandomAccessFile generateRandomFile(final int length) throws IOException { // // mFile = File.createTempFile(SpeedTestConst.UPLOAD_TEMP_FILE_NAME, // SpeedTestConst.UPLOAD_TEMP_FILE_EXTENSION); // // final RandomAccessFile randomFile = new RandomAccessFile(mFile.getAbsolutePath(), "rw"); // randomFile.setLength(length); // // final int iter = length / SpeedTestConst.UPLOAD_FILE_WRITE_CHUNK; // final int remain = length % SpeedTestConst.UPLOAD_FILE_WRITE_CHUNK; // // for (int i = 0; i < iter; i++) { // final byte[] random = new byte[SpeedTestConst.UPLOAD_FILE_WRITE_CHUNK]; // mRandom.nextBytes(random); // randomFile.write(random); // } // if (remain > 0) { // final byte[] random = new byte[remain]; // mRandom.nextBytes(random); // randomFile.write(random); // } // // return randomFile; // } // // /** // * Delete random file. // */ // public void deleteFile() { // if (mFile != null) { // mFile.delete(); // } // } // } // Path: jspeedtest/src/test/java/fr/bmartel/speedtest/test/RandomGenTest.java import fr.bmartel.speedtest.test.utils.TestUtils; import fr.bmartel.speedtest.utils.RandomGen; import org.junit.Assert; import org.junit.Test; /* * The MIT License (MIT) * <p/> * Copyright (c) 2016-2017 Bertrand Martel * <p/> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p/> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p/> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package fr.bmartel.speedtest.test; /** * Random file generator examples. * * @author Bertrand Martel */ public class RandomGenTest { /** * unit examples message header. */ private static final String HEADER = TestUtils.generateMessageHeader(RandomGenTest.class); /** * file size tested. */ private final int[] SIZES = new int[]{1, 10, 10000, 10000000}; /** * test generated file for upload. */ @Test public void randomGenTest() { for (int i = 0; i < SIZES.length; i++) {
final RandomGen random = new RandomGen();
deepakpk009/JScreenRecorder
src/com/deepak/jscreenrecorder/core/ProjectInitiliser.java
// Path: src/com/deepak/jscreenrecorder/core/constants/Directory.java // public interface Directory { // // public String CURSOR_DB = "CURSORS/"; // public String VIDEO_DB = "RECORDED_VIDEOS/"; // public String WATERMARK_DB = "WATERMARKS/"; // }
import com.deepak.jscreenrecorder.core.constants.Directory; import java.io.File; import java.io.IOException;
/* This file is part of JScreenRecorder v0.3 JScreenRecorder is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. JScreenRecorder is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with JScreenRecorder. If not, see <http://www.gnu.org/licenses/>. */ package com.deepak.jscreenrecorder.core; /** * * @author deepak */ // this class impliments the project initiliser public class ProjectInitiliser { // method to initilise the project public void initilise() throws IOException { // if the database directories are not present then create them File f;
// Path: src/com/deepak/jscreenrecorder/core/constants/Directory.java // public interface Directory { // // public String CURSOR_DB = "CURSORS/"; // public String VIDEO_DB = "RECORDED_VIDEOS/"; // public String WATERMARK_DB = "WATERMARKS/"; // } // Path: src/com/deepak/jscreenrecorder/core/ProjectInitiliser.java import com.deepak.jscreenrecorder.core.constants.Directory; import java.io.File; import java.io.IOException; /* This file is part of JScreenRecorder v0.3 JScreenRecorder is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. JScreenRecorder is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with JScreenRecorder. If not, see <http://www.gnu.org/licenses/>. */ package com.deepak.jscreenrecorder.core; /** * * @author deepak */ // this class impliments the project initiliser public class ProjectInitiliser { // method to initilise the project public void initilise() throws IOException { // if the database directories are not present then create them File f;
f = new File(Directory.CURSOR_DB);
deepakpk009/JScreenRecorder
src/com/deepak/jscreenrecorder/core/filters/VideoFileFilter.java
// Path: src/com/deepak/jscreenrecorder/core/constants/Extension.java // public interface Extension { // // public String CURSOR_EXTENSION = ".png"; // // #update in v0.3 : video extension changed from .avi to .mp4 // public String VIDEO_EXTENSION = ".mp4"; // public String WATERMARK_EXTENSION = ".png"; // }
import com.deepak.jscreenrecorder.core.constants.Extension; import java.io.File; import javax.swing.filechooser.FileFilter;
/* This file is part of JScreenRecorder v0.3 JScreenRecorder is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. JScreenRecorder is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with JScreenRecorder. If not, see <http://www.gnu.org/licenses/>. */ package com.deepak.jscreenrecorder.core.filters; /** * * @author deepak */ // this class provides implimentaion for the video file filter public class VideoFileFilter extends FileFilter { @Override public boolean accept(File f) { String name = f.getName().toLowerCase(); // accept only the specified formated video files and directories return f.isDirectory()
// Path: src/com/deepak/jscreenrecorder/core/constants/Extension.java // public interface Extension { // // public String CURSOR_EXTENSION = ".png"; // // #update in v0.3 : video extension changed from .avi to .mp4 // public String VIDEO_EXTENSION = ".mp4"; // public String WATERMARK_EXTENSION = ".png"; // } // Path: src/com/deepak/jscreenrecorder/core/filters/VideoFileFilter.java import com.deepak.jscreenrecorder.core.constants.Extension; import java.io.File; import javax.swing.filechooser.FileFilter; /* This file is part of JScreenRecorder v0.3 JScreenRecorder is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. JScreenRecorder is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with JScreenRecorder. If not, see <http://www.gnu.org/licenses/>. */ package com.deepak.jscreenrecorder.core.filters; /** * * @author deepak */ // this class provides implimentaion for the video file filter public class VideoFileFilter extends FileFilter { @Override public boolean accept(File f) { String name = f.getName().toLowerCase(); // accept only the specified formated video files and directories return f.isDirectory()
|| name.endsWith(Extension.VIDEO_EXTENSION);
deepakpk009/JScreenRecorder
src/com/deepak/jscreenrecorder/main/Main.java
// Path: src/com/deepak/jscreenrecorder/core/ProjectInitiliser.java // public class ProjectInitiliser { // // // method to initilise the project // public void initilise() throws IOException { // // // if the database directories are not present then create them // File f; // // f = new File(Directory.CURSOR_DB); // if (!f.exists()) { // f.mkdir(); // } // // f = new File(Directory.VIDEO_DB); // if (!f.exists()) { // f.mkdir(); // } // // f = new File(Directory.WATERMARK_DB); // if (!f.exists()) { // f.mkdir(); // } // // } // } // // Path: src/com/deepak/jscreenrecorder/gui/MainWindow.java // public class MainWindow extends javax.swing.JFrame { // // the local record configuration reference // // private RecordConfig recConfig = null; // // // the default constructor // public MainWindow() { // // create a new record configuration object // recConfig = new RecordConfig(); // // initilise the components // initComponents(); // } // // /** // * This method is called from within the constructor to initialize the form. // * WARNING: Do NOT modify this code. The content of this method is always // * regenerated by the Form Editor. // */ // @SuppressWarnings("unchecked") // // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents // private void initComponents() { // // recordControlPanel = new com.deepak.jscreenrecorder.gui.RecordControlPanel(recConfig); // recordConfigInfoPanel = new com.deepak.jscreenrecorder.gui.RecordConfigInfoPanel(recConfig); // // setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); // setTitle("JScreenRecorder v0.3"); // setResizable(false); // // recordControlPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Record Controls")); // // recordConfigInfoPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Record Config Info")); // // javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); // getContentPane().setLayout(layout); // layout.setHorizontalGroup( // layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) // .addGroup(layout.createSequentialGroup() // .addContainerGap() // .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) // .addComponent(recordControlPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) // .addComponent(recordConfigInfoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) // .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) // ); // // layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {recordConfigInfoPanel, recordControlPanel}); // // layout.setVerticalGroup( // layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) // .addGroup(layout.createSequentialGroup() // .addContainerGap() // .addComponent(recordControlPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) // .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) // .addComponent(recordConfigInfoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) // .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) // ); // // pack(); // setLocationRelativeTo(null); // }// </editor-fold>//GEN-END:initComponents // // Variables declaration - do not modify//GEN-BEGIN:variables // private com.deepak.jscreenrecorder.gui.RecordConfigInfoPanel recordConfigInfoPanel; // private com.deepak.jscreenrecorder.gui.RecordControlPanel recordControlPanel; // // End of variables declaration//GEN-END:variables // }
import com.deepak.jscreenrecorder.core.ProjectInitiliser; import com.deepak.jscreenrecorder.gui.MainWindow; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane;
/* ----------------------------------- * JScreenRecorder v0.3 * ------------------------------------- * a java based desktop screen recorder. * ------------------------------------- * Developed By : deepak pk * Email : deepakpk009@yahoo.in * ------------------------------------- * This Project is Licensed under LGPL * ------------------------------------- * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.deepak.jscreenrecorder.main; /** * * @author deepak */ public class Main { /** * @param args the command line arguments */ public static void main(String args[]) { // initialise the project try {
// Path: src/com/deepak/jscreenrecorder/core/ProjectInitiliser.java // public class ProjectInitiliser { // // // method to initilise the project // public void initilise() throws IOException { // // // if the database directories are not present then create them // File f; // // f = new File(Directory.CURSOR_DB); // if (!f.exists()) { // f.mkdir(); // } // // f = new File(Directory.VIDEO_DB); // if (!f.exists()) { // f.mkdir(); // } // // f = new File(Directory.WATERMARK_DB); // if (!f.exists()) { // f.mkdir(); // } // // } // } // // Path: src/com/deepak/jscreenrecorder/gui/MainWindow.java // public class MainWindow extends javax.swing.JFrame { // // the local record configuration reference // // private RecordConfig recConfig = null; // // // the default constructor // public MainWindow() { // // create a new record configuration object // recConfig = new RecordConfig(); // // initilise the components // initComponents(); // } // // /** // * This method is called from within the constructor to initialize the form. // * WARNING: Do NOT modify this code. The content of this method is always // * regenerated by the Form Editor. // */ // @SuppressWarnings("unchecked") // // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents // private void initComponents() { // // recordControlPanel = new com.deepak.jscreenrecorder.gui.RecordControlPanel(recConfig); // recordConfigInfoPanel = new com.deepak.jscreenrecorder.gui.RecordConfigInfoPanel(recConfig); // // setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); // setTitle("JScreenRecorder v0.3"); // setResizable(false); // // recordControlPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Record Controls")); // // recordConfigInfoPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Record Config Info")); // // javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); // getContentPane().setLayout(layout); // layout.setHorizontalGroup( // layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) // .addGroup(layout.createSequentialGroup() // .addContainerGap() // .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) // .addComponent(recordControlPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) // .addComponent(recordConfigInfoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) // .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) // ); // // layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {recordConfigInfoPanel, recordControlPanel}); // // layout.setVerticalGroup( // layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) // .addGroup(layout.createSequentialGroup() // .addContainerGap() // .addComponent(recordControlPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) // .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) // .addComponent(recordConfigInfoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) // .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) // ); // // pack(); // setLocationRelativeTo(null); // }// </editor-fold>//GEN-END:initComponents // // Variables declaration - do not modify//GEN-BEGIN:variables // private com.deepak.jscreenrecorder.gui.RecordConfigInfoPanel recordConfigInfoPanel; // private com.deepak.jscreenrecorder.gui.RecordControlPanel recordControlPanel; // // End of variables declaration//GEN-END:variables // } // Path: src/com/deepak/jscreenrecorder/main/Main.java import com.deepak.jscreenrecorder.core.ProjectInitiliser; import com.deepak.jscreenrecorder.gui.MainWindow; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; /* ----------------------------------- * JScreenRecorder v0.3 * ------------------------------------- * a java based desktop screen recorder. * ------------------------------------- * Developed By : deepak pk * Email : deepakpk009@yahoo.in * ------------------------------------- * This Project is Licensed under LGPL * ------------------------------------- * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.deepak.jscreenrecorder.main; /** * * @author deepak */ public class Main { /** * @param args the command line arguments */ public static void main(String args[]) { // initialise the project try {
new ProjectInitiliser().initilise();
deepakpk009/JScreenRecorder
src/com/deepak/jscreenrecorder/core/TextWatermarkCreator.java
// Path: src/com/deepak/jscreenrecorder/gui/WatermarkDisplayPanel.java // public class WatermarkDisplayPanel extends javax.swing.JPanel { // // // the local refernce to the watermark image // private BufferedImage watermarkImage = null; // // the alpha value for the transparency // private float watermarkAlpha = 0.0f; // // the final watermark image which is created based on the // // watermark image and the alpha transparency value // private BufferedImage finalWatermarkImage = null; // // the final watermark image graphics reference object // private Graphics2D finalWatermarkImageGraphics = null; // // // the default constructor // public WatermarkDisplayPanel() { // // set the default watermark transparency alpha value // watermarkAlpha = 0.5f; // // initilise the components // initComponents(); // } // // // the overriden paint method of the watermark display panel // @Override // public void paint(Graphics g) { // // paint the panel // super.paint(g); // // if the watermark image is not null then // if (watermarkImage != null) { // // get the watermark image width // int w = watermarkImage.getWidth(); // // get the watermark image height // int h = watermarkImage.getHeight(); // // create finalwatermark image with resolution of the current watermark image // finalWatermarkImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB_PRE); // // get the graphics object refernce // finalWatermarkImageGraphics = finalWatermarkImage.createGraphics(); // // set the alpha transparency // finalWatermarkImageGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, watermarkAlpha)); // // draw watermark image on final watermark image // finalWatermarkImageGraphics.drawImage(watermarkImage, 0, 0, this); // // dispose all final watermark graphics resources // finalWatermarkImageGraphics.dispose(); // // draw finalwatermark image on panel at the centre // g.drawImage(finalWatermarkImage, (this.getWidth() / 2) - (w / 2), (this.getHeight() / 2) - (h / 2), this); // } // } // // /** // * This method is called from within the constructor to initialize the form. // * WARNING: Do NOT modify this code. The content of this method is always // * regenerated by the Form Editor. // */ // @SuppressWarnings("unchecked") // // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents // private void initComponents() { // // setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true)); // // javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); // this.setLayout(layout); // layout.setHorizontalGroup( // layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) // .addGap(0, 174, Short.MAX_VALUE) // ); // layout.setVerticalGroup( // layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) // .addGap(0, 134, Short.MAX_VALUE) // ); // }// </editor-fold>//GEN-END:initComponents // // Variables declaration - do not modify//GEN-BEGIN:variables // // End of variables declaration//GEN-END:variables // // // getter for the watermark image // public BufferedImage getWatermarkImage() { // return watermarkImage; // } // // // setter for the watermark image // public void setWatermarkImage(BufferedImage watermarkImage) { // this.watermarkImage = watermarkImage; // // on setting the watermark image repaint the panel // this.repaint(); // } // // // getter for the watermakr alpha value // public float getWatermarkAlpha() { // return watermarkAlpha; // } // // // setter for the watermakr alpha value // public void setWatermarkAlpha(float watermarkAlpha) { // this.watermarkAlpha = watermarkAlpha; // // on setting the watermark alpha value repaint the panel // this.repaint(); // } // // // getter for the final watermark image // public BufferedImage getFinalWatermarkImage() { // return finalWatermarkImage; // } // }
import com.deepak.jscreenrecorder.gui.WatermarkDisplayPanel; import com.deepak.jtextchooser.JTextChooser; import java.awt.Graphics2D; import java.awt.font.FontRenderContext; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage;
/* This file is part of JScreenRecorder v0.3 JScreenRecorder is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. JScreenRecorder is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with JScreenRecorder. If not, see <http://www.gnu.org/licenses/>. */ package com.deepak.jscreenrecorder.core; /** * * @author deepak */ // this class implements the text watermark creator public class TextWatermarkCreator { // the text watermark image object private BufferedImage textWatermarkImage = null; // the watermark display panel refernce
// Path: src/com/deepak/jscreenrecorder/gui/WatermarkDisplayPanel.java // public class WatermarkDisplayPanel extends javax.swing.JPanel { // // // the local refernce to the watermark image // private BufferedImage watermarkImage = null; // // the alpha value for the transparency // private float watermarkAlpha = 0.0f; // // the final watermark image which is created based on the // // watermark image and the alpha transparency value // private BufferedImage finalWatermarkImage = null; // // the final watermark image graphics reference object // private Graphics2D finalWatermarkImageGraphics = null; // // // the default constructor // public WatermarkDisplayPanel() { // // set the default watermark transparency alpha value // watermarkAlpha = 0.5f; // // initilise the components // initComponents(); // } // // // the overriden paint method of the watermark display panel // @Override // public void paint(Graphics g) { // // paint the panel // super.paint(g); // // if the watermark image is not null then // if (watermarkImage != null) { // // get the watermark image width // int w = watermarkImage.getWidth(); // // get the watermark image height // int h = watermarkImage.getHeight(); // // create finalwatermark image with resolution of the current watermark image // finalWatermarkImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB_PRE); // // get the graphics object refernce // finalWatermarkImageGraphics = finalWatermarkImage.createGraphics(); // // set the alpha transparency // finalWatermarkImageGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, watermarkAlpha)); // // draw watermark image on final watermark image // finalWatermarkImageGraphics.drawImage(watermarkImage, 0, 0, this); // // dispose all final watermark graphics resources // finalWatermarkImageGraphics.dispose(); // // draw finalwatermark image on panel at the centre // g.drawImage(finalWatermarkImage, (this.getWidth() / 2) - (w / 2), (this.getHeight() / 2) - (h / 2), this); // } // } // // /** // * This method is called from within the constructor to initialize the form. // * WARNING: Do NOT modify this code. The content of this method is always // * regenerated by the Form Editor. // */ // @SuppressWarnings("unchecked") // // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents // private void initComponents() { // // setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true)); // // javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); // this.setLayout(layout); // layout.setHorizontalGroup( // layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) // .addGap(0, 174, Short.MAX_VALUE) // ); // layout.setVerticalGroup( // layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) // .addGap(0, 134, Short.MAX_VALUE) // ); // }// </editor-fold>//GEN-END:initComponents // // Variables declaration - do not modify//GEN-BEGIN:variables // // End of variables declaration//GEN-END:variables // // // getter for the watermark image // public BufferedImage getWatermarkImage() { // return watermarkImage; // } // // // setter for the watermark image // public void setWatermarkImage(BufferedImage watermarkImage) { // this.watermarkImage = watermarkImage; // // on setting the watermark image repaint the panel // this.repaint(); // } // // // getter for the watermakr alpha value // public float getWatermarkAlpha() { // return watermarkAlpha; // } // // // setter for the watermakr alpha value // public void setWatermarkAlpha(float watermarkAlpha) { // this.watermarkAlpha = watermarkAlpha; // // on setting the watermark alpha value repaint the panel // this.repaint(); // } // // // getter for the final watermark image // public BufferedImage getFinalWatermarkImage() { // return finalWatermarkImage; // } // } // Path: src/com/deepak/jscreenrecorder/core/TextWatermarkCreator.java import com.deepak.jscreenrecorder.gui.WatermarkDisplayPanel; import com.deepak.jtextchooser.JTextChooser; import java.awt.Graphics2D; import java.awt.font.FontRenderContext; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; /* This file is part of JScreenRecorder v0.3 JScreenRecorder is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. JScreenRecorder is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with JScreenRecorder. If not, see <http://www.gnu.org/licenses/>. */ package com.deepak.jscreenrecorder.core; /** * * @author deepak */ // this class implements the text watermark creator public class TextWatermarkCreator { // the text watermark image object private BufferedImage textWatermarkImage = null; // the watermark display panel refernce
private WatermarkDisplayPanel watermarkDisplayPanel = null;
deepakpk009/JScreenRecorder
src/com/deepak/jscreenrecorder/util/AddImage.java
// Path: src/com/deepak/jscreenrecorder/core/filters/ImageFileFilter.java // public class ImageFileFilter extends FileFilter { // // @Override // public boolean accept(File f) { // // String name = f.getName().toLowerCase(); // // accept only image files and directories // return f.isDirectory() // || name.endsWith(".bmp") // || name.endsWith(".jpg") // || name.endsWith(".jpeg") // || name.endsWith(".png") // || name.endsWith(".ico") // || name.endsWith(".gif"); // // } // // @Override // public String getDescription() { // return "Image Files"; // } // }
import com.deepak.jscreenrecorder.core.filters.ImageFileFilter; import java.io.File; import java.io.IOException; import javax.swing.JFileChooser; import javax.swing.JOptionPane;
/* This file is part of JScreenRecorder v0.3 JScreenRecorder is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. JScreenRecorder is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with JScreenRecorder. If not, see <http://www.gnu.org/licenses/>. */ package com.deepak.jscreenrecorder.util; /** * * @author deepak */ // this class provides methos to add images to a directory public class AddImage { // method to add images to the specified directory // parameters: the input directory path and the file save extension public int add(String toDir, String fileExtension) { // create a file chooser JFileChooser jfc = new JFileChooser(); // set the image file filter
// Path: src/com/deepak/jscreenrecorder/core/filters/ImageFileFilter.java // public class ImageFileFilter extends FileFilter { // // @Override // public boolean accept(File f) { // // String name = f.getName().toLowerCase(); // // accept only image files and directories // return f.isDirectory() // || name.endsWith(".bmp") // || name.endsWith(".jpg") // || name.endsWith(".jpeg") // || name.endsWith(".png") // || name.endsWith(".ico") // || name.endsWith(".gif"); // // } // // @Override // public String getDescription() { // return "Image Files"; // } // } // Path: src/com/deepak/jscreenrecorder/util/AddImage.java import com.deepak.jscreenrecorder.core.filters.ImageFileFilter; import java.io.File; import java.io.IOException; import javax.swing.JFileChooser; import javax.swing.JOptionPane; /* This file is part of JScreenRecorder v0.3 JScreenRecorder is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. JScreenRecorder is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with JScreenRecorder. If not, see <http://www.gnu.org/licenses/>. */ package com.deepak.jscreenrecorder.util; /** * * @author deepak */ // this class provides methos to add images to a directory public class AddImage { // method to add images to the specified directory // parameters: the input directory path and the file save extension public int add(String toDir, String fileExtension) { // create a file chooser JFileChooser jfc = new JFileChooser(); // set the image file filter
jfc.setFileFilter(new ImageFileFilter());
deepakpk009/JScreenRecorder
src/com/deepak/jscreenrecorder/core/recorder/ScreenLiveStream.java
// Path: src/com/deepak/jscreenrecorder/core/config/RecordConfig.java // public class RecordConfig { // // // the video length // private long videoLength; // // the capture frame rate // private int framesRate; // // the capture area dimension // private Rectangle frameDimension; // // the watermark image // private BufferedImage watermarkImage; // // the watermark location // private Point watermarkLocation; // // the cursor image // private BufferedImage cursorImage; // // the save file // private File videoFile; // // // default constructor // public RecordConfig() { // // set the default field values // videoLength = 0; // // #update in v0.3 : frameRate changed from 12 to 24 // framesRate = 24; // frameDimension = null; // watermarkImage = null; // watermarkLocation = null; // cursorImage = null; // videoFile = null; // } // // /* // * GETTER AND SETTER FOR THE FILEDS // */ // public long getVideoLength() { // return videoLength; // } // // public void setVideoLength(long videoLength) { // this.videoLength = videoLength; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public int getFramesRate() { // return framesRate; // } // // public void setFramesRate(int framesRate) { // this.framesRate = framesRate; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public Rectangle getFrameDimension() { // return frameDimension; // } // // public void setFrameDimension(Rectangle frameDimension) { // this.frameDimension = frameDimension; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public BufferedImage getWatermarkImage() { // return watermarkImage; // } // // public void setWatermarkImage(BufferedImage watermarkImage) { // this.watermarkImage = watermarkImage; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public BufferedImage getCursorImage() { // return cursorImage; // } // // public void setCursorImage(BufferedImage cursorImage) { // this.cursorImage = cursorImage; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public File getVideoFile() { // return videoFile; // } // // public void setVideoFile(File videoFile) { // this.videoFile = videoFile; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public Point getWatermarkLocation() { // return watermarkLocation; // } // // public void setWatermarkLocation(Point watermarkLocation) { // this.watermarkLocation = watermarkLocation; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // ------- PROPERY CHANGE SUPPORT --------------------- // private String propertyName = "RECORD_CONFIG_CHANGE"; // // /** // * Get the value of propertyName // * // * @return the value of propertyName // */ // public String getPropertyName() { // return propertyName; // } // // /** // * Set the value of propertyName // * // * @param propertyName new value of propertyName // */ // public void setPropertyName(String propertyName) { // this.propertyName = propertyName; // } // private transient final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this); // // /** // * Add PropertyChangeListener. // * // * @param listener // */ // public void addPropertyChangeListener(PropertyChangeListener listener) { // propertyChangeSupport.addPropertyChangeListener(listener); // } // // /** // * Remove PropertyChangeListener. // * // * @param listener // */ // public void removePropertyChangeListener(PropertyChangeListener listener) { // propertyChangeSupport.removePropertyChangeListener(listener); // } // }
import com.deepak.jscreenrecorder.core.config.RecordConfig; import java.awt.AWTException; import java.awt.Graphics; import java.awt.MouseInfo; import java.awt.Point; import java.awt.Rectangle; import java.awt.Robot; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.TimerTask;
/* This file is part of JScreenRecorder v0.3 JScreenRecorder is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. JScreenRecorder is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with JScreenRecorder. If not, see <http://www.gnu.org/licenses/>. */ package com.deepak.jscreenrecorder.core.recorder; // this class impliments a LiveStream that takes snapshots // and feeds it to the sequenceEncoder to encode them public class ScreenLiveStream extends TimerTask { private Robot robot = null; // the capture area bound private Rectangle captureAreaBounds = null; // the local record config reference object
// Path: src/com/deepak/jscreenrecorder/core/config/RecordConfig.java // public class RecordConfig { // // // the video length // private long videoLength; // // the capture frame rate // private int framesRate; // // the capture area dimension // private Rectangle frameDimension; // // the watermark image // private BufferedImage watermarkImage; // // the watermark location // private Point watermarkLocation; // // the cursor image // private BufferedImage cursorImage; // // the save file // private File videoFile; // // // default constructor // public RecordConfig() { // // set the default field values // videoLength = 0; // // #update in v0.3 : frameRate changed from 12 to 24 // framesRate = 24; // frameDimension = null; // watermarkImage = null; // watermarkLocation = null; // cursorImage = null; // videoFile = null; // } // // /* // * GETTER AND SETTER FOR THE FILEDS // */ // public long getVideoLength() { // return videoLength; // } // // public void setVideoLength(long videoLength) { // this.videoLength = videoLength; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public int getFramesRate() { // return framesRate; // } // // public void setFramesRate(int framesRate) { // this.framesRate = framesRate; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public Rectangle getFrameDimension() { // return frameDimension; // } // // public void setFrameDimension(Rectangle frameDimension) { // this.frameDimension = frameDimension; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public BufferedImage getWatermarkImage() { // return watermarkImage; // } // // public void setWatermarkImage(BufferedImage watermarkImage) { // this.watermarkImage = watermarkImage; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public BufferedImage getCursorImage() { // return cursorImage; // } // // public void setCursorImage(BufferedImage cursorImage) { // this.cursorImage = cursorImage; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public File getVideoFile() { // return videoFile; // } // // public void setVideoFile(File videoFile) { // this.videoFile = videoFile; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public Point getWatermarkLocation() { // return watermarkLocation; // } // // public void setWatermarkLocation(Point watermarkLocation) { // this.watermarkLocation = watermarkLocation; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // ------- PROPERY CHANGE SUPPORT --------------------- // private String propertyName = "RECORD_CONFIG_CHANGE"; // // /** // * Get the value of propertyName // * // * @return the value of propertyName // */ // public String getPropertyName() { // return propertyName; // } // // /** // * Set the value of propertyName // * // * @param propertyName new value of propertyName // */ // public void setPropertyName(String propertyName) { // this.propertyName = propertyName; // } // private transient final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this); // // /** // * Add PropertyChangeListener. // * // * @param listener // */ // public void addPropertyChangeListener(PropertyChangeListener listener) { // propertyChangeSupport.addPropertyChangeListener(listener); // } // // /** // * Remove PropertyChangeListener. // * // * @param listener // */ // public void removePropertyChangeListener(PropertyChangeListener listener) { // propertyChangeSupport.removePropertyChangeListener(listener); // } // } // Path: src/com/deepak/jscreenrecorder/core/recorder/ScreenLiveStream.java import com.deepak.jscreenrecorder.core.config.RecordConfig; import java.awt.AWTException; import java.awt.Graphics; import java.awt.MouseInfo; import java.awt.Point; import java.awt.Rectangle; import java.awt.Robot; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.TimerTask; /* This file is part of JScreenRecorder v0.3 JScreenRecorder is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. JScreenRecorder is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with JScreenRecorder. If not, see <http://www.gnu.org/licenses/>. */ package com.deepak.jscreenrecorder.core.recorder; // this class impliments a LiveStream that takes snapshots // and feeds it to the sequenceEncoder to encode them public class ScreenLiveStream extends TimerTask { private Robot robot = null; // the capture area bound private Rectangle captureAreaBounds = null; // the local record config reference object
private RecordConfig recConfig = null;
deepakpk009/JScreenRecorder
src/com/deepak/jscreenrecorder/core/recorder/ScreenRecorder.java
// Path: src/com/deepak/jscreenrecorder/core/config/RecordConfig.java // public class RecordConfig { // // // the video length // private long videoLength; // // the capture frame rate // private int framesRate; // // the capture area dimension // private Rectangle frameDimension; // // the watermark image // private BufferedImage watermarkImage; // // the watermark location // private Point watermarkLocation; // // the cursor image // private BufferedImage cursorImage; // // the save file // private File videoFile; // // // default constructor // public RecordConfig() { // // set the default field values // videoLength = 0; // // #update in v0.3 : frameRate changed from 12 to 24 // framesRate = 24; // frameDimension = null; // watermarkImage = null; // watermarkLocation = null; // cursorImage = null; // videoFile = null; // } // // /* // * GETTER AND SETTER FOR THE FILEDS // */ // public long getVideoLength() { // return videoLength; // } // // public void setVideoLength(long videoLength) { // this.videoLength = videoLength; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public int getFramesRate() { // return framesRate; // } // // public void setFramesRate(int framesRate) { // this.framesRate = framesRate; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public Rectangle getFrameDimension() { // return frameDimension; // } // // public void setFrameDimension(Rectangle frameDimension) { // this.frameDimension = frameDimension; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public BufferedImage getWatermarkImage() { // return watermarkImage; // } // // public void setWatermarkImage(BufferedImage watermarkImage) { // this.watermarkImage = watermarkImage; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public BufferedImage getCursorImage() { // return cursorImage; // } // // public void setCursorImage(BufferedImage cursorImage) { // this.cursorImage = cursorImage; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public File getVideoFile() { // return videoFile; // } // // public void setVideoFile(File videoFile) { // this.videoFile = videoFile; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public Point getWatermarkLocation() { // return watermarkLocation; // } // // public void setWatermarkLocation(Point watermarkLocation) { // this.watermarkLocation = watermarkLocation; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // ------- PROPERY CHANGE SUPPORT --------------------- // private String propertyName = "RECORD_CONFIG_CHANGE"; // // /** // * Get the value of propertyName // * // * @return the value of propertyName // */ // public String getPropertyName() { // return propertyName; // } // // /** // * Set the value of propertyName // * // * @param propertyName new value of propertyName // */ // public void setPropertyName(String propertyName) { // this.propertyName = propertyName; // } // private transient final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this); // // /** // * Add PropertyChangeListener. // * // * @param listener // */ // public void addPropertyChangeListener(PropertyChangeListener listener) { // propertyChangeSupport.addPropertyChangeListener(listener); // } // // /** // * Remove PropertyChangeListener. // * // * @param listener // */ // public void removePropertyChangeListener(PropertyChangeListener listener) { // propertyChangeSupport.removePropertyChangeListener(listener); // } // }
import com.deepak.jscreenrecorder.core.config.RecordConfig; import java.io.IOException; import java.util.Timer; import java.util.TimerTask;
/* This file is part of JScreenRecorder v0.3 JScreenRecorder is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. JScreenRecorder is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with JScreenRecorder. If not, see <http://www.gnu.org/licenses/>. */ package com.deepak.jscreenrecorder.core.recorder; /** * * @author deepak */ // this class impliments the screen recorder public class ScreenRecorder { // the timer delay value private long timerDelay = 0; private int encodingRate = 0; private TimerTask streamer = null; private Timer timer = null; private SequenceEncoder sequenceEncoder = null; // method to start recording the video
// Path: src/com/deepak/jscreenrecorder/core/config/RecordConfig.java // public class RecordConfig { // // // the video length // private long videoLength; // // the capture frame rate // private int framesRate; // // the capture area dimension // private Rectangle frameDimension; // // the watermark image // private BufferedImage watermarkImage; // // the watermark location // private Point watermarkLocation; // // the cursor image // private BufferedImage cursorImage; // // the save file // private File videoFile; // // // default constructor // public RecordConfig() { // // set the default field values // videoLength = 0; // // #update in v0.3 : frameRate changed from 12 to 24 // framesRate = 24; // frameDimension = null; // watermarkImage = null; // watermarkLocation = null; // cursorImage = null; // videoFile = null; // } // // /* // * GETTER AND SETTER FOR THE FILEDS // */ // public long getVideoLength() { // return videoLength; // } // // public void setVideoLength(long videoLength) { // this.videoLength = videoLength; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public int getFramesRate() { // return framesRate; // } // // public void setFramesRate(int framesRate) { // this.framesRate = framesRate; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public Rectangle getFrameDimension() { // return frameDimension; // } // // public void setFrameDimension(Rectangle frameDimension) { // this.frameDimension = frameDimension; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public BufferedImage getWatermarkImage() { // return watermarkImage; // } // // public void setWatermarkImage(BufferedImage watermarkImage) { // this.watermarkImage = watermarkImage; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public BufferedImage getCursorImage() { // return cursorImage; // } // // public void setCursorImage(BufferedImage cursorImage) { // this.cursorImage = cursorImage; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public File getVideoFile() { // return videoFile; // } // // public void setVideoFile(File videoFile) { // this.videoFile = videoFile; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public Point getWatermarkLocation() { // return watermarkLocation; // } // // public void setWatermarkLocation(Point watermarkLocation) { // this.watermarkLocation = watermarkLocation; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // ------- PROPERY CHANGE SUPPORT --------------------- // private String propertyName = "RECORD_CONFIG_CHANGE"; // // /** // * Get the value of propertyName // * // * @return the value of propertyName // */ // public String getPropertyName() { // return propertyName; // } // // /** // * Set the value of propertyName // * // * @param propertyName new value of propertyName // */ // public void setPropertyName(String propertyName) { // this.propertyName = propertyName; // } // private transient final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this); // // /** // * Add PropertyChangeListener. // * // * @param listener // */ // public void addPropertyChangeListener(PropertyChangeListener listener) { // propertyChangeSupport.addPropertyChangeListener(listener); // } // // /** // * Remove PropertyChangeListener. // * // * @param listener // */ // public void removePropertyChangeListener(PropertyChangeListener listener) { // propertyChangeSupport.removePropertyChangeListener(listener); // } // } // Path: src/com/deepak/jscreenrecorder/core/recorder/ScreenRecorder.java import com.deepak.jscreenrecorder.core.config.RecordConfig; import java.io.IOException; import java.util.Timer; import java.util.TimerTask; /* This file is part of JScreenRecorder v0.3 JScreenRecorder is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. JScreenRecorder is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with JScreenRecorder. If not, see <http://www.gnu.org/licenses/>. */ package com.deepak.jscreenrecorder.core.recorder; /** * * @author deepak */ // this class impliments the screen recorder public class ScreenRecorder { // the timer delay value private long timerDelay = 0; private int encodingRate = 0; private TimerTask streamer = null; private Timer timer = null; private SequenceEncoder sequenceEncoder = null; // method to start recording the video
public void startRecording(RecordConfig recConfig) throws IOException {
deepakpk009/JScreenRecorder
src/com/deepak/jscreenrecorder/core/SaveFileChooser.java
// Path: src/com/deepak/jscreenrecorder/core/config/RecordConfig.java // public class RecordConfig { // // // the video length // private long videoLength; // // the capture frame rate // private int framesRate; // // the capture area dimension // private Rectangle frameDimension; // // the watermark image // private BufferedImage watermarkImage; // // the watermark location // private Point watermarkLocation; // // the cursor image // private BufferedImage cursorImage; // // the save file // private File videoFile; // // // default constructor // public RecordConfig() { // // set the default field values // videoLength = 0; // // #update in v0.3 : frameRate changed from 12 to 24 // framesRate = 24; // frameDimension = null; // watermarkImage = null; // watermarkLocation = null; // cursorImage = null; // videoFile = null; // } // // /* // * GETTER AND SETTER FOR THE FILEDS // */ // public long getVideoLength() { // return videoLength; // } // // public void setVideoLength(long videoLength) { // this.videoLength = videoLength; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public int getFramesRate() { // return framesRate; // } // // public void setFramesRate(int framesRate) { // this.framesRate = framesRate; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public Rectangle getFrameDimension() { // return frameDimension; // } // // public void setFrameDimension(Rectangle frameDimension) { // this.frameDimension = frameDimension; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public BufferedImage getWatermarkImage() { // return watermarkImage; // } // // public void setWatermarkImage(BufferedImage watermarkImage) { // this.watermarkImage = watermarkImage; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public BufferedImage getCursorImage() { // return cursorImage; // } // // public void setCursorImage(BufferedImage cursorImage) { // this.cursorImage = cursorImage; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public File getVideoFile() { // return videoFile; // } // // public void setVideoFile(File videoFile) { // this.videoFile = videoFile; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public Point getWatermarkLocation() { // return watermarkLocation; // } // // public void setWatermarkLocation(Point watermarkLocation) { // this.watermarkLocation = watermarkLocation; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // ------- PROPERY CHANGE SUPPORT --------------------- // private String propertyName = "RECORD_CONFIG_CHANGE"; // // /** // * Get the value of propertyName // * // * @return the value of propertyName // */ // public String getPropertyName() { // return propertyName; // } // // /** // * Set the value of propertyName // * // * @param propertyName new value of propertyName // */ // public void setPropertyName(String propertyName) { // this.propertyName = propertyName; // } // private transient final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this); // // /** // * Add PropertyChangeListener. // * // * @param listener // */ // public void addPropertyChangeListener(PropertyChangeListener listener) { // propertyChangeSupport.addPropertyChangeListener(listener); // } // // /** // * Remove PropertyChangeListener. // * // * @param listener // */ // public void removePropertyChangeListener(PropertyChangeListener listener) { // propertyChangeSupport.removePropertyChangeListener(listener); // } // } // // Path: src/com/deepak/jscreenrecorder/core/constants/Directory.java // public interface Directory { // // public String CURSOR_DB = "CURSORS/"; // public String VIDEO_DB = "RECORDED_VIDEOS/"; // public String WATERMARK_DB = "WATERMARKS/"; // } // // Path: src/com/deepak/jscreenrecorder/core/constants/Extension.java // public interface Extension { // // public String CURSOR_EXTENSION = ".png"; // // #update in v0.3 : video extension changed from .avi to .mp4 // public String VIDEO_EXTENSION = ".mp4"; // public String WATERMARK_EXTENSION = ".png"; // } // // Path: src/com/deepak/jscreenrecorder/core/filters/VideoFileFilter.java // public class VideoFileFilter extends FileFilter { // // @Override // public boolean accept(File f) { // // String name = f.getName().toLowerCase(); // // accept only the specified formated video files and directories // return f.isDirectory() // || name.endsWith(Extension.VIDEO_EXTENSION); // // } // // @Override // public String getDescription() { // return "Video Files"; // } // }
import com.deepak.jscreenrecorder.core.config.RecordConfig; import com.deepak.jscreenrecorder.core.constants.Directory; import com.deepak.jscreenrecorder.core.constants.Extension; import com.deepak.jscreenrecorder.core.filters.VideoFileFilter; import java.io.File; import javax.swing.JFileChooser;
/* This file is part of JScreenRecorder v0.3 JScreenRecorder is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. JScreenRecorder is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with JScreenRecorder. If not, see <http://www.gnu.org/licenses/>. */ package com.deepak.jscreenrecorder.core; /** * * @author deepak */ // this class impliments the video file save chooser public class SaveFileChooser { // the constructor with the record config as parameter public SaveFileChooser(RecordConfig reConfig) { // create a file chooser
// Path: src/com/deepak/jscreenrecorder/core/config/RecordConfig.java // public class RecordConfig { // // // the video length // private long videoLength; // // the capture frame rate // private int framesRate; // // the capture area dimension // private Rectangle frameDimension; // // the watermark image // private BufferedImage watermarkImage; // // the watermark location // private Point watermarkLocation; // // the cursor image // private BufferedImage cursorImage; // // the save file // private File videoFile; // // // default constructor // public RecordConfig() { // // set the default field values // videoLength = 0; // // #update in v0.3 : frameRate changed from 12 to 24 // framesRate = 24; // frameDimension = null; // watermarkImage = null; // watermarkLocation = null; // cursorImage = null; // videoFile = null; // } // // /* // * GETTER AND SETTER FOR THE FILEDS // */ // public long getVideoLength() { // return videoLength; // } // // public void setVideoLength(long videoLength) { // this.videoLength = videoLength; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public int getFramesRate() { // return framesRate; // } // // public void setFramesRate(int framesRate) { // this.framesRate = framesRate; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public Rectangle getFrameDimension() { // return frameDimension; // } // // public void setFrameDimension(Rectangle frameDimension) { // this.frameDimension = frameDimension; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public BufferedImage getWatermarkImage() { // return watermarkImage; // } // // public void setWatermarkImage(BufferedImage watermarkImage) { // this.watermarkImage = watermarkImage; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public BufferedImage getCursorImage() { // return cursorImage; // } // // public void setCursorImage(BufferedImage cursorImage) { // this.cursorImage = cursorImage; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public File getVideoFile() { // return videoFile; // } // // public void setVideoFile(File videoFile) { // this.videoFile = videoFile; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // public Point getWatermarkLocation() { // return watermarkLocation; // } // // public void setWatermarkLocation(Point watermarkLocation) { // this.watermarkLocation = watermarkLocation; // propertyChangeSupport.firePropertyChange(propertyName, 0, 1); // } // // ------- PROPERY CHANGE SUPPORT --------------------- // private String propertyName = "RECORD_CONFIG_CHANGE"; // // /** // * Get the value of propertyName // * // * @return the value of propertyName // */ // public String getPropertyName() { // return propertyName; // } // // /** // * Set the value of propertyName // * // * @param propertyName new value of propertyName // */ // public void setPropertyName(String propertyName) { // this.propertyName = propertyName; // } // private transient final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this); // // /** // * Add PropertyChangeListener. // * // * @param listener // */ // public void addPropertyChangeListener(PropertyChangeListener listener) { // propertyChangeSupport.addPropertyChangeListener(listener); // } // // /** // * Remove PropertyChangeListener. // * // * @param listener // */ // public void removePropertyChangeListener(PropertyChangeListener listener) { // propertyChangeSupport.removePropertyChangeListener(listener); // } // } // // Path: src/com/deepak/jscreenrecorder/core/constants/Directory.java // public interface Directory { // // public String CURSOR_DB = "CURSORS/"; // public String VIDEO_DB = "RECORDED_VIDEOS/"; // public String WATERMARK_DB = "WATERMARKS/"; // } // // Path: src/com/deepak/jscreenrecorder/core/constants/Extension.java // public interface Extension { // // public String CURSOR_EXTENSION = ".png"; // // #update in v0.3 : video extension changed from .avi to .mp4 // public String VIDEO_EXTENSION = ".mp4"; // public String WATERMARK_EXTENSION = ".png"; // } // // Path: src/com/deepak/jscreenrecorder/core/filters/VideoFileFilter.java // public class VideoFileFilter extends FileFilter { // // @Override // public boolean accept(File f) { // // String name = f.getName().toLowerCase(); // // accept only the specified formated video files and directories // return f.isDirectory() // || name.endsWith(Extension.VIDEO_EXTENSION); // // } // // @Override // public String getDescription() { // return "Video Files"; // } // } // Path: src/com/deepak/jscreenrecorder/core/SaveFileChooser.java import com.deepak.jscreenrecorder.core.config.RecordConfig; import com.deepak.jscreenrecorder.core.constants.Directory; import com.deepak.jscreenrecorder.core.constants.Extension; import com.deepak.jscreenrecorder.core.filters.VideoFileFilter; import java.io.File; import javax.swing.JFileChooser; /* This file is part of JScreenRecorder v0.3 JScreenRecorder is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. JScreenRecorder is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with JScreenRecorder. If not, see <http://www.gnu.org/licenses/>. */ package com.deepak.jscreenrecorder.core; /** * * @author deepak */ // this class impliments the video file save chooser public class SaveFileChooser { // the constructor with the record config as parameter public SaveFileChooser(RecordConfig reConfig) { // create a file chooser
JFileChooser jfc = new JFileChooser(Directory.VIDEO_DB);
casid/jusecase-builders
src/main/java/org/jusecase/builders/io/PathBuilder.java
// Path: src/main/java/org/jusecase/builders/Builder.java // public interface Builder<T> { // T build(); // } // // Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // }
import org.jusecase.builders.Builder; import org.jusecase.builders.BuilderException; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths;
package org.jusecase.builders.io; public class PathBuilder implements Builder<Path> { private String resource; public PathBuilder withResource(String resource) { this.resource = resource; if (resource == null) { throw new NullPointerException("Resource may not be null."); } return this; } @Override public Path build() { if (resource == null) { return Paths.get(""); } URL url = Thread.currentThread().getContextClassLoader().getResource(resource); if (url == null) {
// Path: src/main/java/org/jusecase/builders/Builder.java // public interface Builder<T> { // T build(); // } // // Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/main/java/org/jusecase/builders/io/PathBuilder.java import org.jusecase.builders.Builder; import org.jusecase.builders.BuilderException; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; package org.jusecase.builders.io; public class PathBuilder implements Builder<Path> { private String resource; public PathBuilder withResource(String resource) { this.resource = resource; if (resource == null) { throw new NullPointerException("Resource may not be null."); } return this; } @Override public Path build() { if (resource == null) { return Paths.get(""); } URL url = Thread.currentThread().getContextClassLoader().getResource(resource); if (url == null) {
throw new BuilderException("Resource " + resource + " not found.");
casid/jusecase-builders
src/main/java/org/jusecase/builders/time/ZonedDateTimeBuilder.java
// Path: src/main/java/org/jusecase/builders/Builder.java // public interface Builder<T> { // T build(); // } // // Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // }
import org.jusecase.builders.Builder; import org.jusecase.builders.BuilderException; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter;
package org.jusecase.builders.time; public class ZonedDateTimeBuilder implements Builder<ZonedDateTime> { private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z"); private String string; public ZonedDateTimeBuilder() { this("2015-10-21 07:28:00 Europe/Berlin"); } public ZonedDateTimeBuilder(String string) { this.string = string; } @Override public ZonedDateTime build() { try { return ZonedDateTime.parse(string, FORMATTER); } catch (Exception e) {
// Path: src/main/java/org/jusecase/builders/Builder.java // public interface Builder<T> { // T build(); // } // // Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/main/java/org/jusecase/builders/time/ZonedDateTimeBuilder.java import org.jusecase.builders.Builder; import org.jusecase.builders.BuilderException; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; package org.jusecase.builders.time; public class ZonedDateTimeBuilder implements Builder<ZonedDateTime> { private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z"); private String string; public ZonedDateTimeBuilder() { this("2015-10-21 07:28:00 Europe/Berlin"); } public ZonedDateTimeBuilder(String string) { this.string = string; } @Override public ZonedDateTime build() { try { return ZonedDateTime.parse(string, FORMATTER); } catch (Exception e) {
throw new BuilderException("Failed to parse date from string.", e);
casid/jusecase-builders
src/test/java/org/jusecase/builders/time/ZonedDateTimeBuilderTest.java
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static ZonedDateTimeBuilder zonedDateTime() { // return new ZonedDateTimeBuilder(); // }
import org.junit.Test; import org.jusecase.builders.BuilderException; import java.time.ZonedDateTime; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.zonedDateTime;
package org.jusecase.builders.time; public class ZonedDateTimeBuilderTest { @Test(expected = BuilderException.class) public void dateCannotBeParsed() {
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static ZonedDateTimeBuilder zonedDateTime() { // return new ZonedDateTimeBuilder(); // } // Path: src/test/java/org/jusecase/builders/time/ZonedDateTimeBuilderTest.java import org.junit.Test; import org.jusecase.builders.BuilderException; import java.time.ZonedDateTime; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.zonedDateTime; package org.jusecase.builders.time; public class ZonedDateTimeBuilderTest { @Test(expected = BuilderException.class) public void dateCannotBeParsed() {
a(zonedDateTime("iedio"));
casid/jusecase-builders
src/test/java/org/jusecase/builders/time/ZonedDateTimeBuilderTest.java
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static ZonedDateTimeBuilder zonedDateTime() { // return new ZonedDateTimeBuilder(); // }
import org.junit.Test; import org.jusecase.builders.BuilderException; import java.time.ZonedDateTime; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.zonedDateTime;
package org.jusecase.builders.time; public class ZonedDateTimeBuilderTest { @Test(expected = BuilderException.class) public void dateCannotBeParsed() {
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static ZonedDateTimeBuilder zonedDateTime() { // return new ZonedDateTimeBuilder(); // } // Path: src/test/java/org/jusecase/builders/time/ZonedDateTimeBuilderTest.java import org.junit.Test; import org.jusecase.builders.BuilderException; import java.time.ZonedDateTime; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.zonedDateTime; package org.jusecase.builders.time; public class ZonedDateTimeBuilderTest { @Test(expected = BuilderException.class) public void dateCannotBeParsed() {
a(zonedDateTime("iedio"));
casid/jusecase-builders
src/test/java/org/jusecase/builders/time/LocalDateBuilderTest.java
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static LocalDateBuilder localDate() { // return new LocalDateBuilder(); // }
import org.junit.Test; import org.jusecase.builders.BuilderException; import java.time.LocalDate; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.localDate;
package org.jusecase.builders.time; public class LocalDateBuilderTest { @Test(expected = BuilderException.class) public void dateCannotBeParsed() {
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static LocalDateBuilder localDate() { // return new LocalDateBuilder(); // } // Path: src/test/java/org/jusecase/builders/time/LocalDateBuilderTest.java import org.junit.Test; import org.jusecase.builders.BuilderException; import java.time.LocalDate; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.localDate; package org.jusecase.builders.time; public class LocalDateBuilderTest { @Test(expected = BuilderException.class) public void dateCannotBeParsed() {
a(localDate("iedio"));
casid/jusecase-builders
src/test/java/org/jusecase/builders/time/LocalDateBuilderTest.java
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static LocalDateBuilder localDate() { // return new LocalDateBuilder(); // }
import org.junit.Test; import org.jusecase.builders.BuilderException; import java.time.LocalDate; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.localDate;
package org.jusecase.builders.time; public class LocalDateBuilderTest { @Test(expected = BuilderException.class) public void dateCannotBeParsed() {
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static LocalDateBuilder localDate() { // return new LocalDateBuilder(); // } // Path: src/test/java/org/jusecase/builders/time/LocalDateBuilderTest.java import org.junit.Test; import org.jusecase.builders.BuilderException; import java.time.LocalDate; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.localDate; package org.jusecase.builders.time; public class LocalDateBuilderTest { @Test(expected = BuilderException.class) public void dateCannotBeParsed() {
a(localDate("iedio"));
casid/jusecase-builders
src/test/java/org/jusecase/builders/streams/InputStreamBuilderTest.java
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static InputStreamBuilder inputStream() { // return new InputStreamBuilder(); // }
import org.apache.commons.io.IOUtils; import org.junit.Test; import org.jusecase.builders.BuilderException; import java.io.InputStream; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.inputStream;
package org.jusecase.builders.streams; public class InputStreamBuilderTest { @Test public void inputStreamWithoutAdjustments() throws Exception {
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static InputStreamBuilder inputStream() { // return new InputStreamBuilder(); // } // Path: src/test/java/org/jusecase/builders/streams/InputStreamBuilderTest.java import org.apache.commons.io.IOUtils; import org.junit.Test; import org.jusecase.builders.BuilderException; import java.io.InputStream; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.inputStream; package org.jusecase.builders.streams; public class InputStreamBuilderTest { @Test public void inputStreamWithoutAdjustments() throws Exception {
inputStreamIsEqualTo(a(inputStream()), "");
casid/jusecase-builders
src/test/java/org/jusecase/builders/streams/InputStreamBuilderTest.java
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static InputStreamBuilder inputStream() { // return new InputStreamBuilder(); // }
import org.apache.commons.io.IOUtils; import org.junit.Test; import org.jusecase.builders.BuilderException; import java.io.InputStream; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.inputStream;
package org.jusecase.builders.streams; public class InputStreamBuilderTest { @Test public void inputStreamWithoutAdjustments() throws Exception {
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static InputStreamBuilder inputStream() { // return new InputStreamBuilder(); // } // Path: src/test/java/org/jusecase/builders/streams/InputStreamBuilderTest.java import org.apache.commons.io.IOUtils; import org.junit.Test; import org.jusecase.builders.BuilderException; import java.io.InputStream; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.inputStream; package org.jusecase.builders.streams; public class InputStreamBuilderTest { @Test public void inputStreamWithoutAdjustments() throws Exception {
inputStreamIsEqualTo(a(inputStream()), "");
casid/jusecase-builders
src/test/java/org/jusecase/builders/streams/InputStreamBuilderTest.java
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static InputStreamBuilder inputStream() { // return new InputStreamBuilder(); // }
import org.apache.commons.io.IOUtils; import org.junit.Test; import org.jusecase.builders.BuilderException; import java.io.InputStream; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.inputStream;
package org.jusecase.builders.streams; public class InputStreamBuilderTest { @Test public void inputStreamWithoutAdjustments() throws Exception { inputStreamIsEqualTo(a(inputStream()), ""); } @Test(expected = NullPointerException.class) public void inputStreamWithNullString() throws Exception { a(inputStream().withString(null)); } @Test public void inputStreamWithString() throws Exception { inputStreamIsEqualTo(a(inputStream().withString("1234")), "1234"); } @Test(expected = NullPointerException.class) public void inputStreamWithNullResource() throws Exception { a(inputStream().withResource(null)); }
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static InputStreamBuilder inputStream() { // return new InputStreamBuilder(); // } // Path: src/test/java/org/jusecase/builders/streams/InputStreamBuilderTest.java import org.apache.commons.io.IOUtils; import org.junit.Test; import org.jusecase.builders.BuilderException; import java.io.InputStream; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.inputStream; package org.jusecase.builders.streams; public class InputStreamBuilderTest { @Test public void inputStreamWithoutAdjustments() throws Exception { inputStreamIsEqualTo(a(inputStream()), ""); } @Test(expected = NullPointerException.class) public void inputStreamWithNullString() throws Exception { a(inputStream().withString(null)); } @Test public void inputStreamWithString() throws Exception { inputStreamIsEqualTo(a(inputStream().withString("1234")), "1234"); } @Test(expected = NullPointerException.class) public void inputStreamWithNullResource() throws Exception { a(inputStream().withResource(null)); }
@Test(expected = BuilderException.class)
casid/jusecase-builders
src/test/java/org/jusecase/builders/time/LocalDateTimeBuilderTest.java
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static LocalDateTimeBuilder localDateTime() { // return new LocalDateTimeBuilder(); // }
import org.junit.Test; import org.jusecase.builders.BuilderException; import java.time.LocalDateTime; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.localDateTime;
package org.jusecase.builders.time; public class LocalDateTimeBuilderTest { @Test(expected = BuilderException.class) public void dateCannotBeParsed() {
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static LocalDateTimeBuilder localDateTime() { // return new LocalDateTimeBuilder(); // } // Path: src/test/java/org/jusecase/builders/time/LocalDateTimeBuilderTest.java import org.junit.Test; import org.jusecase.builders.BuilderException; import java.time.LocalDateTime; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.localDateTime; package org.jusecase.builders.time; public class LocalDateTimeBuilderTest { @Test(expected = BuilderException.class) public void dateCannotBeParsed() {
a(localDateTime("iedio"));
casid/jusecase-builders
src/test/java/org/jusecase/builders/time/LocalDateTimeBuilderTest.java
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static LocalDateTimeBuilder localDateTime() { // return new LocalDateTimeBuilder(); // }
import org.junit.Test; import org.jusecase.builders.BuilderException; import java.time.LocalDateTime; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.localDateTime;
package org.jusecase.builders.time; public class LocalDateTimeBuilderTest { @Test(expected = BuilderException.class) public void dateCannotBeParsed() {
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static LocalDateTimeBuilder localDateTime() { // return new LocalDateTimeBuilder(); // } // Path: src/test/java/org/jusecase/builders/time/LocalDateTimeBuilderTest.java import org.junit.Test; import org.jusecase.builders.BuilderException; import java.time.LocalDateTime; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.localDateTime; package org.jusecase.builders.time; public class LocalDateTimeBuilderTest { @Test(expected = BuilderException.class) public void dateCannotBeParsed() {
a(localDateTime("iedio"));
casid/jusecase-builders
src/test/java/org/jusecase/builders/time/DateBuilderTest.java
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static DateBuilder date() { // return new DateBuilder(); // }
import org.junit.Test; import org.jusecase.builders.BuilderException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.jusecase.Builders.a; import static org.jusecase.Builders.date;
package org.jusecase.builders.time; public class DateBuilderTest { private static final long CET_DIFFERENCE = 3600 * 1000;
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static DateBuilder date() { // return new DateBuilder(); // } // Path: src/test/java/org/jusecase/builders/time/DateBuilderTest.java import org.junit.Test; import org.jusecase.builders.BuilderException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.jusecase.Builders.a; import static org.jusecase.Builders.date; package org.jusecase.builders.time; public class DateBuilderTest { private static final long CET_DIFFERENCE = 3600 * 1000;
@Test(expected = BuilderException.class)
casid/jusecase-builders
src/test/java/org/jusecase/builders/time/DateBuilderTest.java
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static DateBuilder date() { // return new DateBuilder(); // }
import org.junit.Test; import org.jusecase.builders.BuilderException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.jusecase.Builders.a; import static org.jusecase.Builders.date;
package org.jusecase.builders.time; public class DateBuilderTest { private static final long CET_DIFFERENCE = 3600 * 1000; @Test(expected = BuilderException.class) public void dateCannotBeParsed() {
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static DateBuilder date() { // return new DateBuilder(); // } // Path: src/test/java/org/jusecase/builders/time/DateBuilderTest.java import org.junit.Test; import org.jusecase.builders.BuilderException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.jusecase.Builders.a; import static org.jusecase.Builders.date; package org.jusecase.builders.time; public class DateBuilderTest { private static final long CET_DIFFERENCE = 3600 * 1000; @Test(expected = BuilderException.class) public void dateCannotBeParsed() {
a(date().with("iedio"));
casid/jusecase-builders
src/test/java/org/jusecase/builders/time/DateBuilderTest.java
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static DateBuilder date() { // return new DateBuilder(); // }
import org.junit.Test; import org.jusecase.builders.BuilderException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.jusecase.Builders.a; import static org.jusecase.Builders.date;
package org.jusecase.builders.time; public class DateBuilderTest { private static final long CET_DIFFERENCE = 3600 * 1000; @Test(expected = BuilderException.class) public void dateCannotBeParsed() {
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static DateBuilder date() { // return new DateBuilder(); // } // Path: src/test/java/org/jusecase/builders/time/DateBuilderTest.java import org.junit.Test; import org.jusecase.builders.BuilderException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.jusecase.Builders.a; import static org.jusecase.Builders.date; package org.jusecase.builders.time; public class DateBuilderTest { private static final long CET_DIFFERENCE = 3600 * 1000; @Test(expected = BuilderException.class) public void dateCannotBeParsed() {
a(date().with("iedio"));
casid/jusecase-builders
src/test/java/org/jusecase/builders/collections/MapEntryBuilderTest.java
// Path: src/main/java/org/jusecase/Builders.java // public static <T> T an(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static <K, V> Builder<Map.Entry<K, V>> entry(final K key, final V value) { // return new MapEntryBuilder<>(key, value); // }
import org.junit.Test; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.an; import static org.jusecase.Builders.entry;
package org.jusecase.builders.collections; public class MapEntryBuilderTest { @Test public void testEntryContainsKeyAndValue(){
// Path: src/main/java/org/jusecase/Builders.java // public static <T> T an(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static <K, V> Builder<Map.Entry<K, V>> entry(final K key, final V value) { // return new MapEntryBuilder<>(key, value); // } // Path: src/test/java/org/jusecase/builders/collections/MapEntryBuilderTest.java import org.junit.Test; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.an; import static org.jusecase.Builders.entry; package org.jusecase.builders.collections; public class MapEntryBuilderTest { @Test public void testEntryContainsKeyAndValue(){
final Map.Entry<String,String> mapEntry = an(entry("a", "b"));
casid/jusecase-builders
src/test/java/org/jusecase/builders/collections/MapEntryBuilderTest.java
// Path: src/main/java/org/jusecase/Builders.java // public static <T> T an(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static <K, V> Builder<Map.Entry<K, V>> entry(final K key, final V value) { // return new MapEntryBuilder<>(key, value); // }
import org.junit.Test; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.an; import static org.jusecase.Builders.entry;
package org.jusecase.builders.collections; public class MapEntryBuilderTest { @Test public void testEntryContainsKeyAndValue(){
// Path: src/main/java/org/jusecase/Builders.java // public static <T> T an(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static <K, V> Builder<Map.Entry<K, V>> entry(final K key, final V value) { // return new MapEntryBuilder<>(key, value); // } // Path: src/test/java/org/jusecase/builders/collections/MapEntryBuilderTest.java import org.junit.Test; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.an; import static org.jusecase.Builders.entry; package org.jusecase.builders.collections; public class MapEntryBuilderTest { @Test public void testEntryContainsKeyAndValue(){
final Map.Entry<String,String> mapEntry = an(entry("a", "b"));
casid/jusecase-builders
src/main/java/org/jusecase/builders/time/LocalDateTimeBuilder.java
// Path: src/main/java/org/jusecase/Builders.java // public class Builders { // // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // public static <T> T an(final Builder<T> builder) { // return builder.build(); // } // // public static <T> T of(final T entity) { // return entity; // } // // @SafeVarargs // public static <T> T[] of(final T... entities) { // return entities; // } // // @SafeVarargs // public static <T> Builder<T[]> array(final T... items) { // return new ArrayBuilder<T>(items); // } // // @SafeVarargs // public static <T> Builder<List<T>> list(final T... items) { // return arrayList(items); // } // // @SafeVarargs // public static <T> Builder<List<T>> arrayList(final T... items) { // return new ListBuilder<T>(new ArrayList<T>(), items); // } // // @SafeVarargs // public static <T> Builder<List<T>> linkedList(final T... items) { // return new ListBuilder<T>(new LinkedList<T>(), items); // } // // @SafeVarargs // public static <T> Builder<Set<T>> set(final T... items) { // return hashSet(items); // } // // @SafeVarargs // public static <T> Builder<Set<T>> hashSet(final T... items) { // return new SetBuilder<T>(new HashSet<T>(), items); // } // // @SafeVarargs // public static <T> Builder<Set<T>> sortedSet(final T... items) { // return new SetBuilder<T>(new TreeSet<T>(), items); // } // // public static DateBuilder date() { // return new DateBuilder(); // } // // public static DateBuilder date(String string) { // return new DateBuilder().with(string); // } // // public static LocalDateBuilder localDate() { // return new LocalDateBuilder(); // } // // public static LocalDateBuilder localDate(String string) { // return new LocalDateBuilder(string); // } // // public static LocalDateTimeBuilder localDateTime() { // return new LocalDateTimeBuilder(); // } // // public static LocalDateTimeBuilder localDateTime(String string) { // return new LocalDateTimeBuilder(string); // } // // public static ZonedDateTimeBuilder zonedDateTime() { // return new ZonedDateTimeBuilder(); // } // // public static ZonedDateTimeBuilder zonedDateTime(String string) { // return new ZonedDateTimeBuilder(string); // } // // public static InputStreamBuilder inputStream() { // return new InputStreamBuilder(); // } // // public static PathBuilder path() { // return new PathBuilder(); // } // // public static FileBuilder file() { // return new FileBuilder(); // } // // public static <K, V> Builder<Map.Entry<K, V>> entry(final K key, final V value) { // return new MapEntryBuilder<>(key, value); // } // // @SafeVarargs // public static <K, V> Builder<Map<K, V>> map(final Map.Entry<K, V>... entries) { // return hashMap(entries); // } // // @SafeVarargs // public static <K, V> Builder<Map<K, V>> hashMap(final Map.Entry<K, V>... entries) { // return new MapBuilder<>(new HashMap<K, V>(), entries); // } // // @SafeVarargs // public static <K, V> Builder<Map<K, V>> linkedHashMap(final Map.Entry<K, V>... entries) { // return new MapBuilder<>(new LinkedHashMap<K, V>(), entries); // } // } // // Path: src/main/java/org/jusecase/builders/Builder.java // public interface Builder<T> { // T build(); // } // // Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static LocalDateBuilder localDate() { // return new LocalDateBuilder(); // }
import org.jusecase.Builders; import org.jusecase.builders.Builder; import org.jusecase.builders.BuilderException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import static org.jusecase.Builders.a; import static org.jusecase.Builders.localDate;
package org.jusecase.builders.time; public class LocalDateTimeBuilder implements Builder<LocalDateTime> { private static final String FORMAT = "yyyy-MM-dd HH:mm:ss"; private static final String SHORT_FORMAT = "yyyy-MM-dd"; private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(FORMAT); private String string; public LocalDateTimeBuilder() { this("2015-10-21 07:28:00"); } public LocalDateTimeBuilder(String string) { this.string = string; } @Override public LocalDateTime build() { try { return parse(); } catch (Exception e) {
// Path: src/main/java/org/jusecase/Builders.java // public class Builders { // // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // public static <T> T an(final Builder<T> builder) { // return builder.build(); // } // // public static <T> T of(final T entity) { // return entity; // } // // @SafeVarargs // public static <T> T[] of(final T... entities) { // return entities; // } // // @SafeVarargs // public static <T> Builder<T[]> array(final T... items) { // return new ArrayBuilder<T>(items); // } // // @SafeVarargs // public static <T> Builder<List<T>> list(final T... items) { // return arrayList(items); // } // // @SafeVarargs // public static <T> Builder<List<T>> arrayList(final T... items) { // return new ListBuilder<T>(new ArrayList<T>(), items); // } // // @SafeVarargs // public static <T> Builder<List<T>> linkedList(final T... items) { // return new ListBuilder<T>(new LinkedList<T>(), items); // } // // @SafeVarargs // public static <T> Builder<Set<T>> set(final T... items) { // return hashSet(items); // } // // @SafeVarargs // public static <T> Builder<Set<T>> hashSet(final T... items) { // return new SetBuilder<T>(new HashSet<T>(), items); // } // // @SafeVarargs // public static <T> Builder<Set<T>> sortedSet(final T... items) { // return new SetBuilder<T>(new TreeSet<T>(), items); // } // // public static DateBuilder date() { // return new DateBuilder(); // } // // public static DateBuilder date(String string) { // return new DateBuilder().with(string); // } // // public static LocalDateBuilder localDate() { // return new LocalDateBuilder(); // } // // public static LocalDateBuilder localDate(String string) { // return new LocalDateBuilder(string); // } // // public static LocalDateTimeBuilder localDateTime() { // return new LocalDateTimeBuilder(); // } // // public static LocalDateTimeBuilder localDateTime(String string) { // return new LocalDateTimeBuilder(string); // } // // public static ZonedDateTimeBuilder zonedDateTime() { // return new ZonedDateTimeBuilder(); // } // // public static ZonedDateTimeBuilder zonedDateTime(String string) { // return new ZonedDateTimeBuilder(string); // } // // public static InputStreamBuilder inputStream() { // return new InputStreamBuilder(); // } // // public static PathBuilder path() { // return new PathBuilder(); // } // // public static FileBuilder file() { // return new FileBuilder(); // } // // public static <K, V> Builder<Map.Entry<K, V>> entry(final K key, final V value) { // return new MapEntryBuilder<>(key, value); // } // // @SafeVarargs // public static <K, V> Builder<Map<K, V>> map(final Map.Entry<K, V>... entries) { // return hashMap(entries); // } // // @SafeVarargs // public static <K, V> Builder<Map<K, V>> hashMap(final Map.Entry<K, V>... entries) { // return new MapBuilder<>(new HashMap<K, V>(), entries); // } // // @SafeVarargs // public static <K, V> Builder<Map<K, V>> linkedHashMap(final Map.Entry<K, V>... entries) { // return new MapBuilder<>(new LinkedHashMap<K, V>(), entries); // } // } // // Path: src/main/java/org/jusecase/builders/Builder.java // public interface Builder<T> { // T build(); // } // // Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static LocalDateBuilder localDate() { // return new LocalDateBuilder(); // } // Path: src/main/java/org/jusecase/builders/time/LocalDateTimeBuilder.java import org.jusecase.Builders; import org.jusecase.builders.Builder; import org.jusecase.builders.BuilderException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import static org.jusecase.Builders.a; import static org.jusecase.Builders.localDate; package org.jusecase.builders.time; public class LocalDateTimeBuilder implements Builder<LocalDateTime> { private static final String FORMAT = "yyyy-MM-dd HH:mm:ss"; private static final String SHORT_FORMAT = "yyyy-MM-dd"; private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(FORMAT); private String string; public LocalDateTimeBuilder() { this("2015-10-21 07:28:00"); } public LocalDateTimeBuilder(String string) { this.string = string; } @Override public LocalDateTime build() { try { return parse(); } catch (Exception e) {
throw new BuilderException("Failed to parse date from string.", e);
casid/jusecase-builders
src/main/java/org/jusecase/builders/time/LocalDateTimeBuilder.java
// Path: src/main/java/org/jusecase/Builders.java // public class Builders { // // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // public static <T> T an(final Builder<T> builder) { // return builder.build(); // } // // public static <T> T of(final T entity) { // return entity; // } // // @SafeVarargs // public static <T> T[] of(final T... entities) { // return entities; // } // // @SafeVarargs // public static <T> Builder<T[]> array(final T... items) { // return new ArrayBuilder<T>(items); // } // // @SafeVarargs // public static <T> Builder<List<T>> list(final T... items) { // return arrayList(items); // } // // @SafeVarargs // public static <T> Builder<List<T>> arrayList(final T... items) { // return new ListBuilder<T>(new ArrayList<T>(), items); // } // // @SafeVarargs // public static <T> Builder<List<T>> linkedList(final T... items) { // return new ListBuilder<T>(new LinkedList<T>(), items); // } // // @SafeVarargs // public static <T> Builder<Set<T>> set(final T... items) { // return hashSet(items); // } // // @SafeVarargs // public static <T> Builder<Set<T>> hashSet(final T... items) { // return new SetBuilder<T>(new HashSet<T>(), items); // } // // @SafeVarargs // public static <T> Builder<Set<T>> sortedSet(final T... items) { // return new SetBuilder<T>(new TreeSet<T>(), items); // } // // public static DateBuilder date() { // return new DateBuilder(); // } // // public static DateBuilder date(String string) { // return new DateBuilder().with(string); // } // // public static LocalDateBuilder localDate() { // return new LocalDateBuilder(); // } // // public static LocalDateBuilder localDate(String string) { // return new LocalDateBuilder(string); // } // // public static LocalDateTimeBuilder localDateTime() { // return new LocalDateTimeBuilder(); // } // // public static LocalDateTimeBuilder localDateTime(String string) { // return new LocalDateTimeBuilder(string); // } // // public static ZonedDateTimeBuilder zonedDateTime() { // return new ZonedDateTimeBuilder(); // } // // public static ZonedDateTimeBuilder zonedDateTime(String string) { // return new ZonedDateTimeBuilder(string); // } // // public static InputStreamBuilder inputStream() { // return new InputStreamBuilder(); // } // // public static PathBuilder path() { // return new PathBuilder(); // } // // public static FileBuilder file() { // return new FileBuilder(); // } // // public static <K, V> Builder<Map.Entry<K, V>> entry(final K key, final V value) { // return new MapEntryBuilder<>(key, value); // } // // @SafeVarargs // public static <K, V> Builder<Map<K, V>> map(final Map.Entry<K, V>... entries) { // return hashMap(entries); // } // // @SafeVarargs // public static <K, V> Builder<Map<K, V>> hashMap(final Map.Entry<K, V>... entries) { // return new MapBuilder<>(new HashMap<K, V>(), entries); // } // // @SafeVarargs // public static <K, V> Builder<Map<K, V>> linkedHashMap(final Map.Entry<K, V>... entries) { // return new MapBuilder<>(new LinkedHashMap<K, V>(), entries); // } // } // // Path: src/main/java/org/jusecase/builders/Builder.java // public interface Builder<T> { // T build(); // } // // Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static LocalDateBuilder localDate() { // return new LocalDateBuilder(); // }
import org.jusecase.Builders; import org.jusecase.builders.Builder; import org.jusecase.builders.BuilderException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import static org.jusecase.Builders.a; import static org.jusecase.Builders.localDate;
package org.jusecase.builders.time; public class LocalDateTimeBuilder implements Builder<LocalDateTime> { private static final String FORMAT = "yyyy-MM-dd HH:mm:ss"; private static final String SHORT_FORMAT = "yyyy-MM-dd"; private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(FORMAT); private String string; public LocalDateTimeBuilder() { this("2015-10-21 07:28:00"); } public LocalDateTimeBuilder(String string) { this.string = string; } @Override public LocalDateTime build() { try { return parse(); } catch (Exception e) { throw new BuilderException("Failed to parse date from string.", e); } } private LocalDateTime parse() { if ( string.length() <= SHORT_FORMAT.length() ) {
// Path: src/main/java/org/jusecase/Builders.java // public class Builders { // // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // public static <T> T an(final Builder<T> builder) { // return builder.build(); // } // // public static <T> T of(final T entity) { // return entity; // } // // @SafeVarargs // public static <T> T[] of(final T... entities) { // return entities; // } // // @SafeVarargs // public static <T> Builder<T[]> array(final T... items) { // return new ArrayBuilder<T>(items); // } // // @SafeVarargs // public static <T> Builder<List<T>> list(final T... items) { // return arrayList(items); // } // // @SafeVarargs // public static <T> Builder<List<T>> arrayList(final T... items) { // return new ListBuilder<T>(new ArrayList<T>(), items); // } // // @SafeVarargs // public static <T> Builder<List<T>> linkedList(final T... items) { // return new ListBuilder<T>(new LinkedList<T>(), items); // } // // @SafeVarargs // public static <T> Builder<Set<T>> set(final T... items) { // return hashSet(items); // } // // @SafeVarargs // public static <T> Builder<Set<T>> hashSet(final T... items) { // return new SetBuilder<T>(new HashSet<T>(), items); // } // // @SafeVarargs // public static <T> Builder<Set<T>> sortedSet(final T... items) { // return new SetBuilder<T>(new TreeSet<T>(), items); // } // // public static DateBuilder date() { // return new DateBuilder(); // } // // public static DateBuilder date(String string) { // return new DateBuilder().with(string); // } // // public static LocalDateBuilder localDate() { // return new LocalDateBuilder(); // } // // public static LocalDateBuilder localDate(String string) { // return new LocalDateBuilder(string); // } // // public static LocalDateTimeBuilder localDateTime() { // return new LocalDateTimeBuilder(); // } // // public static LocalDateTimeBuilder localDateTime(String string) { // return new LocalDateTimeBuilder(string); // } // // public static ZonedDateTimeBuilder zonedDateTime() { // return new ZonedDateTimeBuilder(); // } // // public static ZonedDateTimeBuilder zonedDateTime(String string) { // return new ZonedDateTimeBuilder(string); // } // // public static InputStreamBuilder inputStream() { // return new InputStreamBuilder(); // } // // public static PathBuilder path() { // return new PathBuilder(); // } // // public static FileBuilder file() { // return new FileBuilder(); // } // // public static <K, V> Builder<Map.Entry<K, V>> entry(final K key, final V value) { // return new MapEntryBuilder<>(key, value); // } // // @SafeVarargs // public static <K, V> Builder<Map<K, V>> map(final Map.Entry<K, V>... entries) { // return hashMap(entries); // } // // @SafeVarargs // public static <K, V> Builder<Map<K, V>> hashMap(final Map.Entry<K, V>... entries) { // return new MapBuilder<>(new HashMap<K, V>(), entries); // } // // @SafeVarargs // public static <K, V> Builder<Map<K, V>> linkedHashMap(final Map.Entry<K, V>... entries) { // return new MapBuilder<>(new LinkedHashMap<K, V>(), entries); // } // } // // Path: src/main/java/org/jusecase/builders/Builder.java // public interface Builder<T> { // T build(); // } // // Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static LocalDateBuilder localDate() { // return new LocalDateBuilder(); // } // Path: src/main/java/org/jusecase/builders/time/LocalDateTimeBuilder.java import org.jusecase.Builders; import org.jusecase.builders.Builder; import org.jusecase.builders.BuilderException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import static org.jusecase.Builders.a; import static org.jusecase.Builders.localDate; package org.jusecase.builders.time; public class LocalDateTimeBuilder implements Builder<LocalDateTime> { private static final String FORMAT = "yyyy-MM-dd HH:mm:ss"; private static final String SHORT_FORMAT = "yyyy-MM-dd"; private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(FORMAT); private String string; public LocalDateTimeBuilder() { this("2015-10-21 07:28:00"); } public LocalDateTimeBuilder(String string) { this.string = string; } @Override public LocalDateTime build() { try { return parse(); } catch (Exception e) { throw new BuilderException("Failed to parse date from string.", e); } } private LocalDateTime parse() { if ( string.length() <= SHORT_FORMAT.length() ) {
LocalDate localDate = a(localDate(string));
casid/jusecase-builders
src/main/java/org/jusecase/builders/time/LocalDateTimeBuilder.java
// Path: src/main/java/org/jusecase/Builders.java // public class Builders { // // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // public static <T> T an(final Builder<T> builder) { // return builder.build(); // } // // public static <T> T of(final T entity) { // return entity; // } // // @SafeVarargs // public static <T> T[] of(final T... entities) { // return entities; // } // // @SafeVarargs // public static <T> Builder<T[]> array(final T... items) { // return new ArrayBuilder<T>(items); // } // // @SafeVarargs // public static <T> Builder<List<T>> list(final T... items) { // return arrayList(items); // } // // @SafeVarargs // public static <T> Builder<List<T>> arrayList(final T... items) { // return new ListBuilder<T>(new ArrayList<T>(), items); // } // // @SafeVarargs // public static <T> Builder<List<T>> linkedList(final T... items) { // return new ListBuilder<T>(new LinkedList<T>(), items); // } // // @SafeVarargs // public static <T> Builder<Set<T>> set(final T... items) { // return hashSet(items); // } // // @SafeVarargs // public static <T> Builder<Set<T>> hashSet(final T... items) { // return new SetBuilder<T>(new HashSet<T>(), items); // } // // @SafeVarargs // public static <T> Builder<Set<T>> sortedSet(final T... items) { // return new SetBuilder<T>(new TreeSet<T>(), items); // } // // public static DateBuilder date() { // return new DateBuilder(); // } // // public static DateBuilder date(String string) { // return new DateBuilder().with(string); // } // // public static LocalDateBuilder localDate() { // return new LocalDateBuilder(); // } // // public static LocalDateBuilder localDate(String string) { // return new LocalDateBuilder(string); // } // // public static LocalDateTimeBuilder localDateTime() { // return new LocalDateTimeBuilder(); // } // // public static LocalDateTimeBuilder localDateTime(String string) { // return new LocalDateTimeBuilder(string); // } // // public static ZonedDateTimeBuilder zonedDateTime() { // return new ZonedDateTimeBuilder(); // } // // public static ZonedDateTimeBuilder zonedDateTime(String string) { // return new ZonedDateTimeBuilder(string); // } // // public static InputStreamBuilder inputStream() { // return new InputStreamBuilder(); // } // // public static PathBuilder path() { // return new PathBuilder(); // } // // public static FileBuilder file() { // return new FileBuilder(); // } // // public static <K, V> Builder<Map.Entry<K, V>> entry(final K key, final V value) { // return new MapEntryBuilder<>(key, value); // } // // @SafeVarargs // public static <K, V> Builder<Map<K, V>> map(final Map.Entry<K, V>... entries) { // return hashMap(entries); // } // // @SafeVarargs // public static <K, V> Builder<Map<K, V>> hashMap(final Map.Entry<K, V>... entries) { // return new MapBuilder<>(new HashMap<K, V>(), entries); // } // // @SafeVarargs // public static <K, V> Builder<Map<K, V>> linkedHashMap(final Map.Entry<K, V>... entries) { // return new MapBuilder<>(new LinkedHashMap<K, V>(), entries); // } // } // // Path: src/main/java/org/jusecase/builders/Builder.java // public interface Builder<T> { // T build(); // } // // Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static LocalDateBuilder localDate() { // return new LocalDateBuilder(); // }
import org.jusecase.Builders; import org.jusecase.builders.Builder; import org.jusecase.builders.BuilderException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import static org.jusecase.Builders.a; import static org.jusecase.Builders.localDate;
package org.jusecase.builders.time; public class LocalDateTimeBuilder implements Builder<LocalDateTime> { private static final String FORMAT = "yyyy-MM-dd HH:mm:ss"; private static final String SHORT_FORMAT = "yyyy-MM-dd"; private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(FORMAT); private String string; public LocalDateTimeBuilder() { this("2015-10-21 07:28:00"); } public LocalDateTimeBuilder(String string) { this.string = string; } @Override public LocalDateTime build() { try { return parse(); } catch (Exception e) { throw new BuilderException("Failed to parse date from string.", e); } } private LocalDateTime parse() { if ( string.length() <= SHORT_FORMAT.length() ) {
// Path: src/main/java/org/jusecase/Builders.java // public class Builders { // // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // public static <T> T an(final Builder<T> builder) { // return builder.build(); // } // // public static <T> T of(final T entity) { // return entity; // } // // @SafeVarargs // public static <T> T[] of(final T... entities) { // return entities; // } // // @SafeVarargs // public static <T> Builder<T[]> array(final T... items) { // return new ArrayBuilder<T>(items); // } // // @SafeVarargs // public static <T> Builder<List<T>> list(final T... items) { // return arrayList(items); // } // // @SafeVarargs // public static <T> Builder<List<T>> arrayList(final T... items) { // return new ListBuilder<T>(new ArrayList<T>(), items); // } // // @SafeVarargs // public static <T> Builder<List<T>> linkedList(final T... items) { // return new ListBuilder<T>(new LinkedList<T>(), items); // } // // @SafeVarargs // public static <T> Builder<Set<T>> set(final T... items) { // return hashSet(items); // } // // @SafeVarargs // public static <T> Builder<Set<T>> hashSet(final T... items) { // return new SetBuilder<T>(new HashSet<T>(), items); // } // // @SafeVarargs // public static <T> Builder<Set<T>> sortedSet(final T... items) { // return new SetBuilder<T>(new TreeSet<T>(), items); // } // // public static DateBuilder date() { // return new DateBuilder(); // } // // public static DateBuilder date(String string) { // return new DateBuilder().with(string); // } // // public static LocalDateBuilder localDate() { // return new LocalDateBuilder(); // } // // public static LocalDateBuilder localDate(String string) { // return new LocalDateBuilder(string); // } // // public static LocalDateTimeBuilder localDateTime() { // return new LocalDateTimeBuilder(); // } // // public static LocalDateTimeBuilder localDateTime(String string) { // return new LocalDateTimeBuilder(string); // } // // public static ZonedDateTimeBuilder zonedDateTime() { // return new ZonedDateTimeBuilder(); // } // // public static ZonedDateTimeBuilder zonedDateTime(String string) { // return new ZonedDateTimeBuilder(string); // } // // public static InputStreamBuilder inputStream() { // return new InputStreamBuilder(); // } // // public static PathBuilder path() { // return new PathBuilder(); // } // // public static FileBuilder file() { // return new FileBuilder(); // } // // public static <K, V> Builder<Map.Entry<K, V>> entry(final K key, final V value) { // return new MapEntryBuilder<>(key, value); // } // // @SafeVarargs // public static <K, V> Builder<Map<K, V>> map(final Map.Entry<K, V>... entries) { // return hashMap(entries); // } // // @SafeVarargs // public static <K, V> Builder<Map<K, V>> hashMap(final Map.Entry<K, V>... entries) { // return new MapBuilder<>(new HashMap<K, V>(), entries); // } // // @SafeVarargs // public static <K, V> Builder<Map<K, V>> linkedHashMap(final Map.Entry<K, V>... entries) { // return new MapBuilder<>(new LinkedHashMap<K, V>(), entries); // } // } // // Path: src/main/java/org/jusecase/builders/Builder.java // public interface Builder<T> { // T build(); // } // // Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static LocalDateBuilder localDate() { // return new LocalDateBuilder(); // } // Path: src/main/java/org/jusecase/builders/time/LocalDateTimeBuilder.java import org.jusecase.Builders; import org.jusecase.builders.Builder; import org.jusecase.builders.BuilderException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import static org.jusecase.Builders.a; import static org.jusecase.Builders.localDate; package org.jusecase.builders.time; public class LocalDateTimeBuilder implements Builder<LocalDateTime> { private static final String FORMAT = "yyyy-MM-dd HH:mm:ss"; private static final String SHORT_FORMAT = "yyyy-MM-dd"; private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(FORMAT); private String string; public LocalDateTimeBuilder() { this("2015-10-21 07:28:00"); } public LocalDateTimeBuilder(String string) { this.string = string; } @Override public LocalDateTime build() { try { return parse(); } catch (Exception e) { throw new BuilderException("Failed to parse date from string.", e); } } private LocalDateTime parse() { if ( string.length() <= SHORT_FORMAT.length() ) {
LocalDate localDate = a(localDate(string));
casid/jusecase-builders
src/main/java/org/jusecase/builders/streams/ResourceInputStreamBuilder.java
// Path: src/main/java/org/jusecase/builders/Builder.java // public interface Builder<T> { // T build(); // } // // Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // }
import org.jusecase.builders.Builder; import org.jusecase.builders.BuilderException; import java.io.InputStream;
package org.jusecase.builders.streams; public class ResourceInputStreamBuilder implements Builder<InputStream> { private final String resource; public ResourceInputStreamBuilder(final String resource){ if (resource == null) { throw new NullPointerException("Resource may not be null."); } this.resource = resource; } public InputStream build() { InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource); if (is == null) {
// Path: src/main/java/org/jusecase/builders/Builder.java // public interface Builder<T> { // T build(); // } // // Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/main/java/org/jusecase/builders/streams/ResourceInputStreamBuilder.java import org.jusecase.builders.Builder; import org.jusecase.builders.BuilderException; import java.io.InputStream; package org.jusecase.builders.streams; public class ResourceInputStreamBuilder implements Builder<InputStream> { private final String resource; public ResourceInputStreamBuilder(final String resource){ if (resource == null) { throw new NullPointerException("Resource may not be null."); } this.resource = resource; } public InputStream build() { InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource); if (is == null) {
throw new BuilderException("Resource " + resource + " not found.");
casid/jusecase-builders
src/test/java/org/jusecase/builders/io/FileBuilderTest.java
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static FileBuilder file() { // return new FileBuilder(); // }
import org.junit.Test; import org.jusecase.builders.BuilderException; import java.io.File; import java.nio.file.Files; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.file;
package org.jusecase.builders.io; public class FileBuilderTest { @Test public void defaultFile() {
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static FileBuilder file() { // return new FileBuilder(); // } // Path: src/test/java/org/jusecase/builders/io/FileBuilderTest.java import org.junit.Test; import org.jusecase.builders.BuilderException; import java.io.File; import java.nio.file.Files; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.file; package org.jusecase.builders.io; public class FileBuilderTest { @Test public void defaultFile() {
assertEquals(new File(""), a(file()));
casid/jusecase-builders
src/test/java/org/jusecase/builders/io/FileBuilderTest.java
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static FileBuilder file() { // return new FileBuilder(); // }
import org.junit.Test; import org.jusecase.builders.BuilderException; import java.io.File; import java.nio.file.Files; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.file;
package org.jusecase.builders.io; public class FileBuilderTest { @Test public void defaultFile() {
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static FileBuilder file() { // return new FileBuilder(); // } // Path: src/test/java/org/jusecase/builders/io/FileBuilderTest.java import org.junit.Test; import org.jusecase.builders.BuilderException; import java.io.File; import java.nio.file.Files; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.file; package org.jusecase.builders.io; public class FileBuilderTest { @Test public void defaultFile() {
assertEquals(new File(""), a(file()));
casid/jusecase-builders
src/test/java/org/jusecase/builders/io/FileBuilderTest.java
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static FileBuilder file() { // return new FileBuilder(); // }
import org.junit.Test; import org.jusecase.builders.BuilderException; import java.io.File; import java.nio.file.Files; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.file;
package org.jusecase.builders.io; public class FileBuilderTest { @Test public void defaultFile() { assertEquals(new File(""), a(file())); } @Test(expected = NullPointerException.class) public void nullResource() { a(file().withResource(null)); }
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static FileBuilder file() { // return new FileBuilder(); // } // Path: src/test/java/org/jusecase/builders/io/FileBuilderTest.java import org.junit.Test; import org.jusecase.builders.BuilderException; import java.io.File; import java.nio.file.Files; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.file; package org.jusecase.builders.io; public class FileBuilderTest { @Test public void defaultFile() { assertEquals(new File(""), a(file())); } @Test(expected = NullPointerException.class) public void nullResource() { a(file().withResource(null)); }
@Test(expected = BuilderException.class)
casid/jusecase-builders
src/main/java/org/jusecase/builders/time/LocalDateBuilder.java
// Path: src/main/java/org/jusecase/builders/Builder.java // public interface Builder<T> { // T build(); // } // // Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // }
import org.jusecase.builders.Builder; import org.jusecase.builders.BuilderException; import java.time.LocalDate;
package org.jusecase.builders.time; public class LocalDateBuilder implements Builder<LocalDate> { private String string; public LocalDateBuilder() { this("2015-10-21"); } public LocalDateBuilder(String string) { this.string = string; } @Override public LocalDate build() { try { return LocalDate.parse(string); } catch (Exception e) {
// Path: src/main/java/org/jusecase/builders/Builder.java // public interface Builder<T> { // T build(); // } // // Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/main/java/org/jusecase/builders/time/LocalDateBuilder.java import org.jusecase.builders.Builder; import org.jusecase.builders.BuilderException; import java.time.LocalDate; package org.jusecase.builders.time; public class LocalDateBuilder implements Builder<LocalDate> { private String string; public LocalDateBuilder() { this("2015-10-21"); } public LocalDateBuilder(String string) { this.string = string; } @Override public LocalDate build() { try { return LocalDate.parse(string); } catch (Exception e) {
throw new BuilderException("Failed to parse date from string.", e);
casid/jusecase-builders
src/main/java/org/jusecase/builders/io/FileBuilder.java
// Path: src/main/java/org/jusecase/builders/Builder.java // public interface Builder<T> { // T build(); // } // // Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // }
import org.jusecase.builders.Builder; import org.jusecase.builders.BuilderException; import java.io.File; import java.net.URISyntaxException; import java.net.URL;
package org.jusecase.builders.io; public class FileBuilder implements Builder<File> { private String resource; public FileBuilder withResource(String resource) { this.resource = resource; if (resource == null) { throw new NullPointerException("Resource may not be null."); } return this; } @Override public File build() { if (resource == null) { return new File(""); } URL url = Thread.currentThread().getContextClassLoader().getResource(resource); if (url == null) {
// Path: src/main/java/org/jusecase/builders/Builder.java // public interface Builder<T> { // T build(); // } // // Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/main/java/org/jusecase/builders/io/FileBuilder.java import org.jusecase.builders.Builder; import org.jusecase.builders.BuilderException; import java.io.File; import java.net.URISyntaxException; import java.net.URL; package org.jusecase.builders.io; public class FileBuilder implements Builder<File> { private String resource; public FileBuilder withResource(String resource) { this.resource = resource; if (resource == null) { throw new NullPointerException("Resource may not be null."); } return this; } @Override public File build() { if (resource == null) { return new File(""); } URL url = Thread.currentThread().getContextClassLoader().getResource(resource); if (url == null) {
throw new BuilderException("Resource " + resource + " not found.");
casid/jusecase-builders
src/test/java/org/jusecase/builders/io/PathBuilderTest.java
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static PathBuilder path() { // return new PathBuilder(); // }
import org.junit.Test; import org.jusecase.builders.BuilderException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.path;
package org.jusecase.builders.io; public class PathBuilderTest { @Test public void defaultPath() {
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static PathBuilder path() { // return new PathBuilder(); // } // Path: src/test/java/org/jusecase/builders/io/PathBuilderTest.java import org.junit.Test; import org.jusecase.builders.BuilderException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.path; package org.jusecase.builders.io; public class PathBuilderTest { @Test public void defaultPath() {
assertEquals(Paths.get(""), a(path()));
casid/jusecase-builders
src/test/java/org/jusecase/builders/io/PathBuilderTest.java
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static PathBuilder path() { // return new PathBuilder(); // }
import org.junit.Test; import org.jusecase.builders.BuilderException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.path;
package org.jusecase.builders.io; public class PathBuilderTest { @Test public void defaultPath() {
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static PathBuilder path() { // return new PathBuilder(); // } // Path: src/test/java/org/jusecase/builders/io/PathBuilderTest.java import org.junit.Test; import org.jusecase.builders.BuilderException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.path; package org.jusecase.builders.io; public class PathBuilderTest { @Test public void defaultPath() {
assertEquals(Paths.get(""), a(path()));
casid/jusecase-builders
src/test/java/org/jusecase/builders/io/PathBuilderTest.java
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static PathBuilder path() { // return new PathBuilder(); // }
import org.junit.Test; import org.jusecase.builders.BuilderException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.path;
package org.jusecase.builders.io; public class PathBuilderTest { @Test public void defaultPath() { assertEquals(Paths.get(""), a(path())); } @Test(expected = NullPointerException.class) public void nullResource() { a(path().withResource(null)); }
// Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/org/jusecase/Builders.java // public static <T> T a(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // public static PathBuilder path() { // return new PathBuilder(); // } // Path: src/test/java/org/jusecase/builders/io/PathBuilderTest.java import org.junit.Test; import org.jusecase.builders.BuilderException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import static org.junit.Assert.assertEquals; import static org.jusecase.Builders.a; import static org.jusecase.Builders.path; package org.jusecase.builders.io; public class PathBuilderTest { @Test public void defaultPath() { assertEquals(Paths.get(""), a(path())); } @Test(expected = NullPointerException.class) public void nullResource() { a(path().withResource(null)); }
@Test(expected = BuilderException.class)
casid/jusecase-builders
src/main/java/org/jusecase/builders/time/DateBuilder.java
// Path: src/main/java/org/jusecase/builders/Builder.java // public interface Builder<T> { // T build(); // } // // Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // }
import org.jusecase.builders.Builder; import org.jusecase.builders.BuilderException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone;
} /** * Use withFormat() instead */ @Deprecated public DateBuilder with(String string, String format) { return this.with(string).withFormat(format); } /** * Use withFormat() instead */ @Deprecated public DateBuilder with(String string, SimpleDateFormat format) { return this.with(string).withFormat(format); } public Date build() { if (string == null) { return new Date(); } if (formatString == null && string.length() <= SHORT_FORMAT_STRING.length() ) { formatString = SHORT_FORMAT_STRING; } try { return getFormat().parse(string); } catch (ParseException e) {
// Path: src/main/java/org/jusecase/builders/Builder.java // public interface Builder<T> { // T build(); // } // // Path: src/main/java/org/jusecase/builders/BuilderException.java // public class BuilderException extends RuntimeException { // public BuilderException(String message) { // super(message); // } // // public BuilderException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/main/java/org/jusecase/builders/time/DateBuilder.java import org.jusecase.builders.Builder; import org.jusecase.builders.BuilderException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; } /** * Use withFormat() instead */ @Deprecated public DateBuilder with(String string, String format) { return this.with(string).withFormat(format); } /** * Use withFormat() instead */ @Deprecated public DateBuilder with(String string, SimpleDateFormat format) { return this.with(string).withFormat(format); } public Date build() { if (string == null) { return new Date(); } if (formatString == null && string.length() <= SHORT_FORMAT_STRING.length() ) { formatString = SHORT_FORMAT_STRING; } try { return getFormat().parse(string); } catch (ParseException e) {
throw new BuilderException("Failed to parse date from string.", e);
casid/jusecase-builders
src/test/java/org/jusecase/builders/structures/ArrayBuilderTest.java
// Path: src/main/java/org/jusecase/Builders.java // public static <T> T an(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // @SafeVarargs // public static <T> Builder<T[]> array(final T... items) { // return new ArrayBuilder<T>(items); // }
import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertNotSame; import static org.jusecase.Builders.an; import static org.jusecase.Builders.array;
package org.jusecase.builders.structures; public class ArrayBuilderTest { @Test public void filledArray() {
// Path: src/main/java/org/jusecase/Builders.java // public static <T> T an(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // @SafeVarargs // public static <T> Builder<T[]> array(final T... items) { // return new ArrayBuilder<T>(items); // } // Path: src/test/java/org/jusecase/builders/structures/ArrayBuilderTest.java import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertNotSame; import static org.jusecase.Builders.an; import static org.jusecase.Builders.array; package org.jusecase.builders.structures; public class ArrayBuilderTest { @Test public void filledArray() {
assertArrayEquals(new Integer[]{1,2,3,4}, an(array(1, 2, 3, 4)));
casid/jusecase-builders
src/test/java/org/jusecase/builders/structures/ArrayBuilderTest.java
// Path: src/main/java/org/jusecase/Builders.java // public static <T> T an(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // @SafeVarargs // public static <T> Builder<T[]> array(final T... items) { // return new ArrayBuilder<T>(items); // }
import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertNotSame; import static org.jusecase.Builders.an; import static org.jusecase.Builders.array;
package org.jusecase.builders.structures; public class ArrayBuilderTest { @Test public void filledArray() {
// Path: src/main/java/org/jusecase/Builders.java // public static <T> T an(final Builder<T> builder) { // return builder.build(); // } // // Path: src/main/java/org/jusecase/Builders.java // @SafeVarargs // public static <T> Builder<T[]> array(final T... items) { // return new ArrayBuilder<T>(items); // } // Path: src/test/java/org/jusecase/builders/structures/ArrayBuilderTest.java import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertNotSame; import static org.jusecase.Builders.an; import static org.jusecase.Builders.array; package org.jusecase.builders.structures; public class ArrayBuilderTest { @Test public void filledArray() {
assertArrayEquals(new Integer[]{1,2,3,4}, an(array(1, 2, 3, 4)));
dperezcabrera/jpoker
src/main/java/org/poker/api/game/PlayerInfo.java
// Path: src/main/java/org/poker/api/core/Card.java // @Immutable // public final class Card { // // private static final String STRING_RANK_CARDS = "23456789TJQKA"; // // public enum Suit { // // SPADE('♠'), HEART('♥'), DIAMOND('♦'), CLUB('♣'); // // private final char c; // // private Suit(char c) { // this.c = c; // } // // } // // public enum Rank { // // TWO, TRHEE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE // } // // private final Suit suit; // private final Rank rank; // // public Card(Suit suit, Rank rank) { // ExceptionUtil.checkNullArgument(rank, "rank"); // ExceptionUtil.checkNullArgument(suit, "suit"); // this.suit = suit; // this.rank = rank; // } // // public Suit getSuit() { // return suit; // } // // public Rank getRank() { // return rank; // } // // @Override // public int hashCode() { // return rank.ordinal() * Suit.values().length + suit.ordinal(); // } // // @Override // public boolean equals(Object obj) { // boolean result = true; // if (this != obj) { // result = false; // if (obj != null && getClass() == obj.getClass()) { // result = hashCode() == ((Card) obj).hashCode(); // } // } // return result; // } // // @Override // public String toString() { // return STRING_RANK_CARDS.substring(rank.ordinal(), rank.ordinal() + 1) + suit.c; // } // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public enum PlayerState { // // READY(true), // OUT(false), // FOLD(false), // CHECK(true), // CALL(true), // RAISE(true), // ALL_IN(false); // // private final boolean active; // // private PlayerState(boolean isActive) { // this.active = isActive; // } // // public boolean isActive() { // return active; // } // }
import net.jcip.annotations.NotThreadSafe; import org.poker.api.core.Card; import org.poker.api.game.TexasHoldEmUtil.PlayerState;
/* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.game; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 */ @NotThreadSafe public class PlayerInfo { private String name; private long chips; private long bet;
// Path: src/main/java/org/poker/api/core/Card.java // @Immutable // public final class Card { // // private static final String STRING_RANK_CARDS = "23456789TJQKA"; // // public enum Suit { // // SPADE('♠'), HEART('♥'), DIAMOND('♦'), CLUB('♣'); // // private final char c; // // private Suit(char c) { // this.c = c; // } // // } // // public enum Rank { // // TWO, TRHEE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE // } // // private final Suit suit; // private final Rank rank; // // public Card(Suit suit, Rank rank) { // ExceptionUtil.checkNullArgument(rank, "rank"); // ExceptionUtil.checkNullArgument(suit, "suit"); // this.suit = suit; // this.rank = rank; // } // // public Suit getSuit() { // return suit; // } // // public Rank getRank() { // return rank; // } // // @Override // public int hashCode() { // return rank.ordinal() * Suit.values().length + suit.ordinal(); // } // // @Override // public boolean equals(Object obj) { // boolean result = true; // if (this != obj) { // result = false; // if (obj != null && getClass() == obj.getClass()) { // result = hashCode() == ((Card) obj).hashCode(); // } // } // return result; // } // // @Override // public String toString() { // return STRING_RANK_CARDS.substring(rank.ordinal(), rank.ordinal() + 1) + suit.c; // } // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public enum PlayerState { // // READY(true), // OUT(false), // FOLD(false), // CHECK(true), // CALL(true), // RAISE(true), // ALL_IN(false); // // private final boolean active; // // private PlayerState(boolean isActive) { // this.active = isActive; // } // // public boolean isActive() { // return active; // } // } // Path: src/main/java/org/poker/api/game/PlayerInfo.java import net.jcip.annotations.NotThreadSafe; import org.poker.api.core.Card; import org.poker.api.game.TexasHoldEmUtil.PlayerState; /* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.game; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 */ @NotThreadSafe public class PlayerInfo { private String name; private long chips; private long bet;
private final Card[] cards = new Card[TexasHoldEmUtil.PLAYER_CARDS];
dperezcabrera/jpoker
src/main/java/org/poker/api/game/PlayerInfo.java
// Path: src/main/java/org/poker/api/core/Card.java // @Immutable // public final class Card { // // private static final String STRING_RANK_CARDS = "23456789TJQKA"; // // public enum Suit { // // SPADE('♠'), HEART('♥'), DIAMOND('♦'), CLUB('♣'); // // private final char c; // // private Suit(char c) { // this.c = c; // } // // } // // public enum Rank { // // TWO, TRHEE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE // } // // private final Suit suit; // private final Rank rank; // // public Card(Suit suit, Rank rank) { // ExceptionUtil.checkNullArgument(rank, "rank"); // ExceptionUtil.checkNullArgument(suit, "suit"); // this.suit = suit; // this.rank = rank; // } // // public Suit getSuit() { // return suit; // } // // public Rank getRank() { // return rank; // } // // @Override // public int hashCode() { // return rank.ordinal() * Suit.values().length + suit.ordinal(); // } // // @Override // public boolean equals(Object obj) { // boolean result = true; // if (this != obj) { // result = false; // if (obj != null && getClass() == obj.getClass()) { // result = hashCode() == ((Card) obj).hashCode(); // } // } // return result; // } // // @Override // public String toString() { // return STRING_RANK_CARDS.substring(rank.ordinal(), rank.ordinal() + 1) + suit.c; // } // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public enum PlayerState { // // READY(true), // OUT(false), // FOLD(false), // CHECK(true), // CALL(true), // RAISE(true), // ALL_IN(false); // // private final boolean active; // // private PlayerState(boolean isActive) { // this.active = isActive; // } // // public boolean isActive() { // return active; // } // }
import net.jcip.annotations.NotThreadSafe; import org.poker.api.core.Card; import org.poker.api.game.TexasHoldEmUtil.PlayerState;
/* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.game; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 */ @NotThreadSafe public class PlayerInfo { private String name; private long chips; private long bet; private final Card[] cards = new Card[TexasHoldEmUtil.PLAYER_CARDS];
// Path: src/main/java/org/poker/api/core/Card.java // @Immutable // public final class Card { // // private static final String STRING_RANK_CARDS = "23456789TJQKA"; // // public enum Suit { // // SPADE('♠'), HEART('♥'), DIAMOND('♦'), CLUB('♣'); // // private final char c; // // private Suit(char c) { // this.c = c; // } // // } // // public enum Rank { // // TWO, TRHEE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE // } // // private final Suit suit; // private final Rank rank; // // public Card(Suit suit, Rank rank) { // ExceptionUtil.checkNullArgument(rank, "rank"); // ExceptionUtil.checkNullArgument(suit, "suit"); // this.suit = suit; // this.rank = rank; // } // // public Suit getSuit() { // return suit; // } // // public Rank getRank() { // return rank; // } // // @Override // public int hashCode() { // return rank.ordinal() * Suit.values().length + suit.ordinal(); // } // // @Override // public boolean equals(Object obj) { // boolean result = true; // if (this != obj) { // result = false; // if (obj != null && getClass() == obj.getClass()) { // result = hashCode() == ((Card) obj).hashCode(); // } // } // return result; // } // // @Override // public String toString() { // return STRING_RANK_CARDS.substring(rank.ordinal(), rank.ordinal() + 1) + suit.c; // } // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public enum PlayerState { // // READY(true), // OUT(false), // FOLD(false), // CHECK(true), // CALL(true), // RAISE(true), // ALL_IN(false); // // private final boolean active; // // private PlayerState(boolean isActive) { // this.active = isActive; // } // // public boolean isActive() { // return active; // } // } // Path: src/main/java/org/poker/api/game/PlayerInfo.java import net.jcip.annotations.NotThreadSafe; import org.poker.api.core.Card; import org.poker.api.game.TexasHoldEmUtil.PlayerState; /* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.game; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 */ @NotThreadSafe public class PlayerInfo { private String name; private long chips; private long bet; private final Card[] cards = new Card[TexasHoldEmUtil.PLAYER_CARDS];
private PlayerState state;
dperezcabrera/jpoker
src/main/java/org/poker/engine/model/PlayerEntity.java
// Path: src/main/java/org/poker/api/game/BetCommand.java // @NotThreadSafe // public class BetCommand { // // private final BetCommandType type; // private long chips; // // public BetCommand(BetCommandType type) { // this(type, 0); // } // // public BetCommand(BetCommandType type, long chips) { // ExceptionUtil.checkNullArgument(type, "type"); // ExceptionUtil.checkMinValueArgument(chips, 0L, "chips"); // this.type = type; // this.chips = chips; // } // // public BetCommandType getType() { // return type; // } // // public long getChips() { // return chips; // } // // public void setChips(long chips) { // this.chips = chips; // } // // @Override // public String toString() { // return String.join("{class:'BetCommand', type:'", type.toString(), "', chips:", Long.toString(chips), "}"); // } // } // // Path: src/main/java/org/poker/api/game/PlayerInfo.java // @NotThreadSafe // public class PlayerInfo { // // private String name; // private long chips; // private long bet; // private final Card[] cards = new Card[TexasHoldEmUtil.PLAYER_CARDS]; // private PlayerState state; // private int errors; // // public boolean isActive() { // return state.isActive(); // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public long getChips() { // return chips; // } // // public void setChips(long chips) { // this.chips = chips; // } // // public void addChips(long chips) { // this.chips += chips; // } // // public long getBet() { // return bet; // } // // public void setBet(long bet) { // this.bet = bet; // } // // public Card[] getCards() { // return new Card[]{cards[0], cards[1]}; // } // // public void setCards(Card[] cards) { // this.cards[0] = cards[0]; // this.cards[1] = cards[1]; // } // // public PlayerState getState() { // return state; // } // // public void setState(PlayerState state) { // this.state = state; // } // // public int getErrors() { // return errors; // } // // public void setErrors(int errors) { // this.errors = errors; // } // // public Card getCard(int index) { // return cards[index]; // } // // public void setCards(Card card0, Card card1) { // this.cards[0] = card0; // this.cards[1] = card1; // } // // @Override // public String toString() { // return "{class:'PlayerInfo', name:'" + name + "', chips:" + chips + ", bet:" + bet + ", cards:[" + cards[0] + ", " + cards[1] + "], state:'" + state + "', errors:" + errors + '}'; // } // }
import org.poker.api.game.BetCommand; import org.poker.api.game.PlayerInfo;
/* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.engine.model; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 */ public class PlayerEntity extends PlayerInfo { private int handValue = 0;
// Path: src/main/java/org/poker/api/game/BetCommand.java // @NotThreadSafe // public class BetCommand { // // private final BetCommandType type; // private long chips; // // public BetCommand(BetCommandType type) { // this(type, 0); // } // // public BetCommand(BetCommandType type, long chips) { // ExceptionUtil.checkNullArgument(type, "type"); // ExceptionUtil.checkMinValueArgument(chips, 0L, "chips"); // this.type = type; // this.chips = chips; // } // // public BetCommandType getType() { // return type; // } // // public long getChips() { // return chips; // } // // public void setChips(long chips) { // this.chips = chips; // } // // @Override // public String toString() { // return String.join("{class:'BetCommand', type:'", type.toString(), "', chips:", Long.toString(chips), "}"); // } // } // // Path: src/main/java/org/poker/api/game/PlayerInfo.java // @NotThreadSafe // public class PlayerInfo { // // private String name; // private long chips; // private long bet; // private final Card[] cards = new Card[TexasHoldEmUtil.PLAYER_CARDS]; // private PlayerState state; // private int errors; // // public boolean isActive() { // return state.isActive(); // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public long getChips() { // return chips; // } // // public void setChips(long chips) { // this.chips = chips; // } // // public void addChips(long chips) { // this.chips += chips; // } // // public long getBet() { // return bet; // } // // public void setBet(long bet) { // this.bet = bet; // } // // public Card[] getCards() { // return new Card[]{cards[0], cards[1]}; // } // // public void setCards(Card[] cards) { // this.cards[0] = cards[0]; // this.cards[1] = cards[1]; // } // // public PlayerState getState() { // return state; // } // // public void setState(PlayerState state) { // this.state = state; // } // // public int getErrors() { // return errors; // } // // public void setErrors(int errors) { // this.errors = errors; // } // // public Card getCard(int index) { // return cards[index]; // } // // public void setCards(Card card0, Card card1) { // this.cards[0] = card0; // this.cards[1] = card1; // } // // @Override // public String toString() { // return "{class:'PlayerInfo', name:'" + name + "', chips:" + chips + ", bet:" + bet + ", cards:[" + cards[0] + ", " + cards[1] + "], state:'" + state + "', errors:" + errors + '}'; // } // } // Path: src/main/java/org/poker/engine/model/PlayerEntity.java import org.poker.api.game.BetCommand; import org.poker.api.game.PlayerInfo; /* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.engine.model; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 */ public class PlayerEntity extends PlayerInfo { private int handValue = 0;
private BetCommand betCommand;
dperezcabrera/jpoker
src/main/java/org/poker/api/game/GameInfo.java
// Path: src/main/java/org/poker/api/core/Card.java // @Immutable // public final class Card { // // private static final String STRING_RANK_CARDS = "23456789TJQKA"; // // public enum Suit { // // SPADE('♠'), HEART('♥'), DIAMOND('♦'), CLUB('♣'); // // private final char c; // // private Suit(char c) { // this.c = c; // } // // } // // public enum Rank { // // TWO, TRHEE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE // } // // private final Suit suit; // private final Rank rank; // // public Card(Suit suit, Rank rank) { // ExceptionUtil.checkNullArgument(rank, "rank"); // ExceptionUtil.checkNullArgument(suit, "suit"); // this.suit = suit; // this.rank = rank; // } // // public Suit getSuit() { // return suit; // } // // public Rank getRank() { // return rank; // } // // @Override // public int hashCode() { // return rank.ordinal() * Suit.values().length + suit.ordinal(); // } // // @Override // public boolean equals(Object obj) { // boolean result = true; // if (this != obj) { // result = false; // if (obj != null && getClass() == obj.getClass()) { // result = hashCode() == ((Card) obj).hashCode(); // } // } // return result; // } // // @Override // public String toString() { // return STRING_RANK_CARDS.substring(rank.ordinal(), rank.ordinal() + 1) + suit.c; // } // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public static final int COMMUNITY_CARDS = 5; // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public enum GameState { // // PRE_FLOP, // FLOP, // TURN, // RIVER, // SHOWDOWN, // END, // }
import java.util.ArrayList; import java.util.List; import net.jcip.annotations.NotThreadSafe; import org.poker.api.core.Card; import static org.poker.api.game.TexasHoldEmUtil.COMMUNITY_CARDS; import org.poker.api.game.TexasHoldEmUtil.GameState;
/* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.game; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 * * @param <P> */ @NotThreadSafe public class GameInfo<P extends PlayerInfo> { private int round; private int dealer; private int playerTurn;
// Path: src/main/java/org/poker/api/core/Card.java // @Immutable // public final class Card { // // private static final String STRING_RANK_CARDS = "23456789TJQKA"; // // public enum Suit { // // SPADE('♠'), HEART('♥'), DIAMOND('♦'), CLUB('♣'); // // private final char c; // // private Suit(char c) { // this.c = c; // } // // } // // public enum Rank { // // TWO, TRHEE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE // } // // private final Suit suit; // private final Rank rank; // // public Card(Suit suit, Rank rank) { // ExceptionUtil.checkNullArgument(rank, "rank"); // ExceptionUtil.checkNullArgument(suit, "suit"); // this.suit = suit; // this.rank = rank; // } // // public Suit getSuit() { // return suit; // } // // public Rank getRank() { // return rank; // } // // @Override // public int hashCode() { // return rank.ordinal() * Suit.values().length + suit.ordinal(); // } // // @Override // public boolean equals(Object obj) { // boolean result = true; // if (this != obj) { // result = false; // if (obj != null && getClass() == obj.getClass()) { // result = hashCode() == ((Card) obj).hashCode(); // } // } // return result; // } // // @Override // public String toString() { // return STRING_RANK_CARDS.substring(rank.ordinal(), rank.ordinal() + 1) + suit.c; // } // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public static final int COMMUNITY_CARDS = 5; // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public enum GameState { // // PRE_FLOP, // FLOP, // TURN, // RIVER, // SHOWDOWN, // END, // } // Path: src/main/java/org/poker/api/game/GameInfo.java import java.util.ArrayList; import java.util.List; import net.jcip.annotations.NotThreadSafe; import org.poker.api.core.Card; import static org.poker.api.game.TexasHoldEmUtil.COMMUNITY_CARDS; import org.poker.api.game.TexasHoldEmUtil.GameState; /* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.game; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 * * @param <P> */ @NotThreadSafe public class GameInfo<P extends PlayerInfo> { private int round; private int dealer; private int playerTurn;
private GameState gameState;
dperezcabrera/jpoker
src/main/java/org/poker/api/game/GameInfo.java
// Path: src/main/java/org/poker/api/core/Card.java // @Immutable // public final class Card { // // private static final String STRING_RANK_CARDS = "23456789TJQKA"; // // public enum Suit { // // SPADE('♠'), HEART('♥'), DIAMOND('♦'), CLUB('♣'); // // private final char c; // // private Suit(char c) { // this.c = c; // } // // } // // public enum Rank { // // TWO, TRHEE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE // } // // private final Suit suit; // private final Rank rank; // // public Card(Suit suit, Rank rank) { // ExceptionUtil.checkNullArgument(rank, "rank"); // ExceptionUtil.checkNullArgument(suit, "suit"); // this.suit = suit; // this.rank = rank; // } // // public Suit getSuit() { // return suit; // } // // public Rank getRank() { // return rank; // } // // @Override // public int hashCode() { // return rank.ordinal() * Suit.values().length + suit.ordinal(); // } // // @Override // public boolean equals(Object obj) { // boolean result = true; // if (this != obj) { // result = false; // if (obj != null && getClass() == obj.getClass()) { // result = hashCode() == ((Card) obj).hashCode(); // } // } // return result; // } // // @Override // public String toString() { // return STRING_RANK_CARDS.substring(rank.ordinal(), rank.ordinal() + 1) + suit.c; // } // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public static final int COMMUNITY_CARDS = 5; // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public enum GameState { // // PRE_FLOP, // FLOP, // TURN, // RIVER, // SHOWDOWN, // END, // }
import java.util.ArrayList; import java.util.List; import net.jcip.annotations.NotThreadSafe; import org.poker.api.core.Card; import static org.poker.api.game.TexasHoldEmUtil.COMMUNITY_CARDS; import org.poker.api.game.TexasHoldEmUtil.GameState;
/* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.game; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 * * @param <P> */ @NotThreadSafe public class GameInfo<P extends PlayerInfo> { private int round; private int dealer; private int playerTurn; private GameState gameState;
// Path: src/main/java/org/poker/api/core/Card.java // @Immutable // public final class Card { // // private static final String STRING_RANK_CARDS = "23456789TJQKA"; // // public enum Suit { // // SPADE('♠'), HEART('♥'), DIAMOND('♦'), CLUB('♣'); // // private final char c; // // private Suit(char c) { // this.c = c; // } // // } // // public enum Rank { // // TWO, TRHEE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE // } // // private final Suit suit; // private final Rank rank; // // public Card(Suit suit, Rank rank) { // ExceptionUtil.checkNullArgument(rank, "rank"); // ExceptionUtil.checkNullArgument(suit, "suit"); // this.suit = suit; // this.rank = rank; // } // // public Suit getSuit() { // return suit; // } // // public Rank getRank() { // return rank; // } // // @Override // public int hashCode() { // return rank.ordinal() * Suit.values().length + suit.ordinal(); // } // // @Override // public boolean equals(Object obj) { // boolean result = true; // if (this != obj) { // result = false; // if (obj != null && getClass() == obj.getClass()) { // result = hashCode() == ((Card) obj).hashCode(); // } // } // return result; // } // // @Override // public String toString() { // return STRING_RANK_CARDS.substring(rank.ordinal(), rank.ordinal() + 1) + suit.c; // } // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public static final int COMMUNITY_CARDS = 5; // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public enum GameState { // // PRE_FLOP, // FLOP, // TURN, // RIVER, // SHOWDOWN, // END, // } // Path: src/main/java/org/poker/api/game/GameInfo.java import java.util.ArrayList; import java.util.List; import net.jcip.annotations.NotThreadSafe; import org.poker.api.core.Card; import static org.poker.api.game.TexasHoldEmUtil.COMMUNITY_CARDS; import org.poker.api.game.TexasHoldEmUtil.GameState; /* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.game; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 * * @param <P> */ @NotThreadSafe public class GameInfo<P extends PlayerInfo> { private int round; private int dealer; private int playerTurn; private GameState gameState;
private final List<Card> communityCards = new ArrayList<>(COMMUNITY_CARDS);
dperezcabrera/jpoker
src/main/java/org/poker/api/game/GameInfo.java
// Path: src/main/java/org/poker/api/core/Card.java // @Immutable // public final class Card { // // private static final String STRING_RANK_CARDS = "23456789TJQKA"; // // public enum Suit { // // SPADE('♠'), HEART('♥'), DIAMOND('♦'), CLUB('♣'); // // private final char c; // // private Suit(char c) { // this.c = c; // } // // } // // public enum Rank { // // TWO, TRHEE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE // } // // private final Suit suit; // private final Rank rank; // // public Card(Suit suit, Rank rank) { // ExceptionUtil.checkNullArgument(rank, "rank"); // ExceptionUtil.checkNullArgument(suit, "suit"); // this.suit = suit; // this.rank = rank; // } // // public Suit getSuit() { // return suit; // } // // public Rank getRank() { // return rank; // } // // @Override // public int hashCode() { // return rank.ordinal() * Suit.values().length + suit.ordinal(); // } // // @Override // public boolean equals(Object obj) { // boolean result = true; // if (this != obj) { // result = false; // if (obj != null && getClass() == obj.getClass()) { // result = hashCode() == ((Card) obj).hashCode(); // } // } // return result; // } // // @Override // public String toString() { // return STRING_RANK_CARDS.substring(rank.ordinal(), rank.ordinal() + 1) + suit.c; // } // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public static final int COMMUNITY_CARDS = 5; // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public enum GameState { // // PRE_FLOP, // FLOP, // TURN, // RIVER, // SHOWDOWN, // END, // }
import java.util.ArrayList; import java.util.List; import net.jcip.annotations.NotThreadSafe; import org.poker.api.core.Card; import static org.poker.api.game.TexasHoldEmUtil.COMMUNITY_CARDS; import org.poker.api.game.TexasHoldEmUtil.GameState;
/* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.game; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 * * @param <P> */ @NotThreadSafe public class GameInfo<P extends PlayerInfo> { private int round; private int dealer; private int playerTurn; private GameState gameState;
// Path: src/main/java/org/poker/api/core/Card.java // @Immutable // public final class Card { // // private static final String STRING_RANK_CARDS = "23456789TJQKA"; // // public enum Suit { // // SPADE('♠'), HEART('♥'), DIAMOND('♦'), CLUB('♣'); // // private final char c; // // private Suit(char c) { // this.c = c; // } // // } // // public enum Rank { // // TWO, TRHEE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE // } // // private final Suit suit; // private final Rank rank; // // public Card(Suit suit, Rank rank) { // ExceptionUtil.checkNullArgument(rank, "rank"); // ExceptionUtil.checkNullArgument(suit, "suit"); // this.suit = suit; // this.rank = rank; // } // // public Suit getSuit() { // return suit; // } // // public Rank getRank() { // return rank; // } // // @Override // public int hashCode() { // return rank.ordinal() * Suit.values().length + suit.ordinal(); // } // // @Override // public boolean equals(Object obj) { // boolean result = true; // if (this != obj) { // result = false; // if (obj != null && getClass() == obj.getClass()) { // result = hashCode() == ((Card) obj).hashCode(); // } // } // return result; // } // // @Override // public String toString() { // return STRING_RANK_CARDS.substring(rank.ordinal(), rank.ordinal() + 1) + suit.c; // } // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public static final int COMMUNITY_CARDS = 5; // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public enum GameState { // // PRE_FLOP, // FLOP, // TURN, // RIVER, // SHOWDOWN, // END, // } // Path: src/main/java/org/poker/api/game/GameInfo.java import java.util.ArrayList; import java.util.List; import net.jcip.annotations.NotThreadSafe; import org.poker.api.core.Card; import static org.poker.api.game.TexasHoldEmUtil.COMMUNITY_CARDS; import org.poker.api.game.TexasHoldEmUtil.GameState; /* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.game; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 * * @param <P> */ @NotThreadSafe public class GameInfo<P extends PlayerInfo> { private int round; private int dealer; private int playerTurn; private GameState gameState;
private final List<Card> communityCards = new ArrayList<>(COMMUNITY_CARDS);
dperezcabrera/jpoker
src/main/java/org/poker/api/core/HandEvaluator.java
// Path: src/main/java/org/util/exceptions/ExceptionUtil.java // public final class ExceptionUtil { // // public static final String MIN_VALUE_ERR_MSG = "El argumento {0} no puede tener un valor inferior a <{1}> y tiene <{2}>."; // public static final String NULL_ERR_MSG = "El argumento {0} no puede ser nulo."; // public static final String LENGTH_ERR_MSG = "El argumento {0} no puede ser nulo y debe tener una longitud de {1}."; // public static final String SIZE_ERR_MSG = "El argumento {0} no puede ser nulo y debe tener {1} elementos."; // // private ExceptionUtil() { // } // // public static void checkMinValueArgument(int o, int minValue, String name) { // if (o < minValue) { // throw new IllegalArgumentException(MessageFormat.format(MIN_VALUE_ERR_MSG, name, minValue, o)); // } // } // // public static void checkMinValueArgument(long o, long minValue, String name) { // if (o < minValue) { // throw new IllegalArgumentException(MessageFormat.format(MIN_VALUE_ERR_MSG, name, minValue, o)); // } // } // // public static void checkNullArgument(Object o, String name) { // if (o == null) { // throw new IllegalArgumentException(MessageFormat.format(NULL_ERR_MSG, name)); // } // } // // public static void checkListSizeArgument(List a, String name, int length) { // if (a == null || a.size() != length) { // throw new IllegalArgumentException(MessageFormat.format(SIZE_ERR_MSG, name, length)); // } // } // // public static <T> void checkArrayLengthArgument(T[] a, String name, int length) { // if (a == null || a.length != length) { // throw new IllegalArgumentException(MessageFormat.format(LENGTH_ERR_MSG, name, length)); // } // } // // public static void checkArgument(boolean throwException, String message, Object... args) { // if (throwException) { // throw new IllegalArgumentException(MessageFormat.format(message, args)); // } // } // } // // Path: src/main/java/org/poker/api/core/Hands.java // public enum Type { // // HIGH_CARD, // ONE_PAIR, // TWO_PAIR, // THREE_OF_A_KIND, // STRAIGHT, // FLUSH, // FULL_HOUSE, // FOUR_OF_A_KIND, // STRAIGHT_FLUSH // }
import org.util.exceptions.ExceptionUtil; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import net.jcip.annotations.NotThreadSafe; import org.poker.api.core.Hands.Type;
/* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.core; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 */ @NotThreadSafe public final class HandEvaluator implements IHandEvaluator { private static final int ENCODE_BASE = Card.Rank.ACE.ordinal() + 1; private static final int INDEXES_LENGTH = 2; private static final int RANK_INDEX = 0; private static final int REPEATS_INDEX = 1;
// Path: src/main/java/org/util/exceptions/ExceptionUtil.java // public final class ExceptionUtil { // // public static final String MIN_VALUE_ERR_MSG = "El argumento {0} no puede tener un valor inferior a <{1}> y tiene <{2}>."; // public static final String NULL_ERR_MSG = "El argumento {0} no puede ser nulo."; // public static final String LENGTH_ERR_MSG = "El argumento {0} no puede ser nulo y debe tener una longitud de {1}."; // public static final String SIZE_ERR_MSG = "El argumento {0} no puede ser nulo y debe tener {1} elementos."; // // private ExceptionUtil() { // } // // public static void checkMinValueArgument(int o, int minValue, String name) { // if (o < minValue) { // throw new IllegalArgumentException(MessageFormat.format(MIN_VALUE_ERR_MSG, name, minValue, o)); // } // } // // public static void checkMinValueArgument(long o, long minValue, String name) { // if (o < minValue) { // throw new IllegalArgumentException(MessageFormat.format(MIN_VALUE_ERR_MSG, name, minValue, o)); // } // } // // public static void checkNullArgument(Object o, String name) { // if (o == null) { // throw new IllegalArgumentException(MessageFormat.format(NULL_ERR_MSG, name)); // } // } // // public static void checkListSizeArgument(List a, String name, int length) { // if (a == null || a.size() != length) { // throw new IllegalArgumentException(MessageFormat.format(SIZE_ERR_MSG, name, length)); // } // } // // public static <T> void checkArrayLengthArgument(T[] a, String name, int length) { // if (a == null || a.length != length) { // throw new IllegalArgumentException(MessageFormat.format(LENGTH_ERR_MSG, name, length)); // } // } // // public static void checkArgument(boolean throwException, String message, Object... args) { // if (throwException) { // throw new IllegalArgumentException(MessageFormat.format(message, args)); // } // } // } // // Path: src/main/java/org/poker/api/core/Hands.java // public enum Type { // // HIGH_CARD, // ONE_PAIR, // TWO_PAIR, // THREE_OF_A_KIND, // STRAIGHT, // FLUSH, // FULL_HOUSE, // FOUR_OF_A_KIND, // STRAIGHT_FLUSH // } // Path: src/main/java/org/poker/api/core/HandEvaluator.java import org.util.exceptions.ExceptionUtil; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import net.jcip.annotations.NotThreadSafe; import org.poker.api.core.Hands.Type; /* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.core; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 */ @NotThreadSafe public final class HandEvaluator implements IHandEvaluator { private static final int ENCODE_BASE = Card.Rank.ACE.ordinal() + 1; private static final int INDEXES_LENGTH = 2; private static final int RANK_INDEX = 0; private static final int REPEATS_INDEX = 1;
private static final Type[][] MATRIX_TYPES = {
dperezcabrera/jpoker
src/main/java/org/poker/api/core/HandEvaluator.java
// Path: src/main/java/org/util/exceptions/ExceptionUtil.java // public final class ExceptionUtil { // // public static final String MIN_VALUE_ERR_MSG = "El argumento {0} no puede tener un valor inferior a <{1}> y tiene <{2}>."; // public static final String NULL_ERR_MSG = "El argumento {0} no puede ser nulo."; // public static final String LENGTH_ERR_MSG = "El argumento {0} no puede ser nulo y debe tener una longitud de {1}."; // public static final String SIZE_ERR_MSG = "El argumento {0} no puede ser nulo y debe tener {1} elementos."; // // private ExceptionUtil() { // } // // public static void checkMinValueArgument(int o, int minValue, String name) { // if (o < minValue) { // throw new IllegalArgumentException(MessageFormat.format(MIN_VALUE_ERR_MSG, name, minValue, o)); // } // } // // public static void checkMinValueArgument(long o, long minValue, String name) { // if (o < minValue) { // throw new IllegalArgumentException(MessageFormat.format(MIN_VALUE_ERR_MSG, name, minValue, o)); // } // } // // public static void checkNullArgument(Object o, String name) { // if (o == null) { // throw new IllegalArgumentException(MessageFormat.format(NULL_ERR_MSG, name)); // } // } // // public static void checkListSizeArgument(List a, String name, int length) { // if (a == null || a.size() != length) { // throw new IllegalArgumentException(MessageFormat.format(SIZE_ERR_MSG, name, length)); // } // } // // public static <T> void checkArrayLengthArgument(T[] a, String name, int length) { // if (a == null || a.length != length) { // throw new IllegalArgumentException(MessageFormat.format(LENGTH_ERR_MSG, name, length)); // } // } // // public static void checkArgument(boolean throwException, String message, Object... args) { // if (throwException) { // throw new IllegalArgumentException(MessageFormat.format(message, args)); // } // } // } // // Path: src/main/java/org/poker/api/core/Hands.java // public enum Type { // // HIGH_CARD, // ONE_PAIR, // TWO_PAIR, // THREE_OF_A_KIND, // STRAIGHT, // FLUSH, // FULL_HOUSE, // FOUR_OF_A_KIND, // STRAIGHT_FLUSH // }
import org.util.exceptions.ExceptionUtil; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import net.jcip.annotations.NotThreadSafe; import org.poker.api.core.Hands.Type;
/* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.core; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 */ @NotThreadSafe public final class HandEvaluator implements IHandEvaluator { private static final int ENCODE_BASE = Card.Rank.ACE.ordinal() + 1; private static final int INDEXES_LENGTH = 2; private static final int RANK_INDEX = 0; private static final int REPEATS_INDEX = 1; private static final Type[][] MATRIX_TYPES = { {Type.HIGH_CARD}, {Type.ONE_PAIR, Type.TWO_PAIR}, {Type.THREE_OF_A_KIND, Type.FULL_HOUSE}, {Type.FOUR_OF_A_KIND} }; private final int[][] indexes = new int[Hands.CARDS][INDEXES_LENGTH]; private final int[] ranks = new int[ENCODE_BASE]; private final int[] suits = new int[Card.Suit.values().length]; private boolean isStraight = false; private boolean isFlush = false; @Override public int eval(Card[] cards) {
// Path: src/main/java/org/util/exceptions/ExceptionUtil.java // public final class ExceptionUtil { // // public static final String MIN_VALUE_ERR_MSG = "El argumento {0} no puede tener un valor inferior a <{1}> y tiene <{2}>."; // public static final String NULL_ERR_MSG = "El argumento {0} no puede ser nulo."; // public static final String LENGTH_ERR_MSG = "El argumento {0} no puede ser nulo y debe tener una longitud de {1}."; // public static final String SIZE_ERR_MSG = "El argumento {0} no puede ser nulo y debe tener {1} elementos."; // // private ExceptionUtil() { // } // // public static void checkMinValueArgument(int o, int minValue, String name) { // if (o < minValue) { // throw new IllegalArgumentException(MessageFormat.format(MIN_VALUE_ERR_MSG, name, minValue, o)); // } // } // // public static void checkMinValueArgument(long o, long minValue, String name) { // if (o < minValue) { // throw new IllegalArgumentException(MessageFormat.format(MIN_VALUE_ERR_MSG, name, minValue, o)); // } // } // // public static void checkNullArgument(Object o, String name) { // if (o == null) { // throw new IllegalArgumentException(MessageFormat.format(NULL_ERR_MSG, name)); // } // } // // public static void checkListSizeArgument(List a, String name, int length) { // if (a == null || a.size() != length) { // throw new IllegalArgumentException(MessageFormat.format(SIZE_ERR_MSG, name, length)); // } // } // // public static <T> void checkArrayLengthArgument(T[] a, String name, int length) { // if (a == null || a.length != length) { // throw new IllegalArgumentException(MessageFormat.format(LENGTH_ERR_MSG, name, length)); // } // } // // public static void checkArgument(boolean throwException, String message, Object... args) { // if (throwException) { // throw new IllegalArgumentException(MessageFormat.format(message, args)); // } // } // } // // Path: src/main/java/org/poker/api/core/Hands.java // public enum Type { // // HIGH_CARD, // ONE_PAIR, // TWO_PAIR, // THREE_OF_A_KIND, // STRAIGHT, // FLUSH, // FULL_HOUSE, // FOUR_OF_A_KIND, // STRAIGHT_FLUSH // } // Path: src/main/java/org/poker/api/core/HandEvaluator.java import org.util.exceptions.ExceptionUtil; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import net.jcip.annotations.NotThreadSafe; import org.poker.api.core.Hands.Type; /* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.core; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 */ @NotThreadSafe public final class HandEvaluator implements IHandEvaluator { private static final int ENCODE_BASE = Card.Rank.ACE.ordinal() + 1; private static final int INDEXES_LENGTH = 2; private static final int RANK_INDEX = 0; private static final int REPEATS_INDEX = 1; private static final Type[][] MATRIX_TYPES = { {Type.HIGH_CARD}, {Type.ONE_PAIR, Type.TWO_PAIR}, {Type.THREE_OF_A_KIND, Type.FULL_HOUSE}, {Type.FOUR_OF_A_KIND} }; private final int[][] indexes = new int[Hands.CARDS][INDEXES_LENGTH]; private final int[] ranks = new int[ENCODE_BASE]; private final int[] suits = new int[Card.Suit.values().length]; private boolean isStraight = false; private boolean isFlush = false; @Override public int eval(Card[] cards) {
ExceptionUtil.checkArrayLengthArgument(cards, "cards", Hands.CARDS);
dperezcabrera/jpoker
src/main/java/org/poker/api/game/Hand7Evaluator.java
// Path: src/main/java/org/poker/api/core/Card.java // @Immutable // public final class Card { // // private static final String STRING_RANK_CARDS = "23456789TJQKA"; // // public enum Suit { // // SPADE('♠'), HEART('♥'), DIAMOND('♦'), CLUB('♣'); // // private final char c; // // private Suit(char c) { // this.c = c; // } // // } // // public enum Rank { // // TWO, TRHEE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE // } // // private final Suit suit; // private final Rank rank; // // public Card(Suit suit, Rank rank) { // ExceptionUtil.checkNullArgument(rank, "rank"); // ExceptionUtil.checkNullArgument(suit, "suit"); // this.suit = suit; // this.rank = rank; // } // // public Suit getSuit() { // return suit; // } // // public Rank getRank() { // return rank; // } // // @Override // public int hashCode() { // return rank.ordinal() * Suit.values().length + suit.ordinal(); // } // // @Override // public boolean equals(Object obj) { // boolean result = true; // if (this != obj) { // result = false; // if (obj != null && getClass() == obj.getClass()) { // result = hashCode() == ((Card) obj).hashCode(); // } // } // return result; // } // // @Override // public String toString() { // return STRING_RANK_CARDS.substring(rank.ordinal(), rank.ordinal() + 1) + suit.c; // } // } // // Path: src/main/java/org/poker/api/core/IHandEvaluator.java // @FunctionalInterface // public interface IHandEvaluator { // // public int eval(Card[] cards); // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public static final int COMMUNITY_CARDS = 5; // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public static final int PLAYER_CARDS = 2; // // Path: src/main/java/org/util/combinatorial/Combination.java // @NotThreadSafe // public class Combination implements ICombinatorial { // // private final int items; // private final int[] indexes; // // public Combination(int subItems, int items) { // ExceptionUtil.checkMinValueArgument(subItems, 1, "subItems"); // ExceptionUtil.checkMinValueArgument(items, subItems, "items"); // this.indexes = new int[subItems]; // this.items = items; // init(); // } // // @Override // public long combinations() { // return combinations(indexes.length, items); // } // // @Override // public int size() { // return indexes.length; // } // // public int getSubItems() { // return indexes.length; // } // // public int getItems() { // return items; // } // // private boolean hasNext(int index) { // return indexes[index] + (indexes.length - index) < items; // } // // private void move(int index) { // if (hasNext(index)) { // indexes[index]++; // int last = indexes[index]; // for (int i = index + 1; i < indexes.length; i++) { // this.indexes[i] = ++last; // } // } else { // move(index - 1); // } // } // // @Override // public int[] next(int[] items) { // if (hasNext()) { // move(indexes.length - 1); // System.arraycopy(indexes, 0, items, 0, indexes.length); // } // return items; // } // // @Override // public boolean hasNext() { // return hasNext(0) || hasNext(indexes.length - 1); // } // // private void init() { // int index = indexes.length; // for (int i = 0; i < indexes.length; i++) { // this.indexes[i] = i; // } // this.indexes[index - 1]--; // } // // @Override // public void clear() { // init(); // } // // public static long combinations(int subItems, int items) { // long result = 1; // int sub = Math.max(subItems, items - subItems); // for (int i = sub + 1; i <= items; i++) { // result = (result * i) / (i - sub); // } // return result; // } // }
import java.util.List; import net.jcip.annotations.NotThreadSafe; import org.poker.api.core.Card; import org.poker.api.core.IHandEvaluator; import static org.poker.api.game.TexasHoldEmUtil.COMMUNITY_CARDS; import static org.poker.api.game.TexasHoldEmUtil.PLAYER_CARDS; import org.util.combinatorial.Combination;
/* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.game; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 * */ @NotThreadSafe public class Hand7Evaluator {
// Path: src/main/java/org/poker/api/core/Card.java // @Immutable // public final class Card { // // private static final String STRING_RANK_CARDS = "23456789TJQKA"; // // public enum Suit { // // SPADE('♠'), HEART('♥'), DIAMOND('♦'), CLUB('♣'); // // private final char c; // // private Suit(char c) { // this.c = c; // } // // } // // public enum Rank { // // TWO, TRHEE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE // } // // private final Suit suit; // private final Rank rank; // // public Card(Suit suit, Rank rank) { // ExceptionUtil.checkNullArgument(rank, "rank"); // ExceptionUtil.checkNullArgument(suit, "suit"); // this.suit = suit; // this.rank = rank; // } // // public Suit getSuit() { // return suit; // } // // public Rank getRank() { // return rank; // } // // @Override // public int hashCode() { // return rank.ordinal() * Suit.values().length + suit.ordinal(); // } // // @Override // public boolean equals(Object obj) { // boolean result = true; // if (this != obj) { // result = false; // if (obj != null && getClass() == obj.getClass()) { // result = hashCode() == ((Card) obj).hashCode(); // } // } // return result; // } // // @Override // public String toString() { // return STRING_RANK_CARDS.substring(rank.ordinal(), rank.ordinal() + 1) + suit.c; // } // } // // Path: src/main/java/org/poker/api/core/IHandEvaluator.java // @FunctionalInterface // public interface IHandEvaluator { // // public int eval(Card[] cards); // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public static final int COMMUNITY_CARDS = 5; // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public static final int PLAYER_CARDS = 2; // // Path: src/main/java/org/util/combinatorial/Combination.java // @NotThreadSafe // public class Combination implements ICombinatorial { // // private final int items; // private final int[] indexes; // // public Combination(int subItems, int items) { // ExceptionUtil.checkMinValueArgument(subItems, 1, "subItems"); // ExceptionUtil.checkMinValueArgument(items, subItems, "items"); // this.indexes = new int[subItems]; // this.items = items; // init(); // } // // @Override // public long combinations() { // return combinations(indexes.length, items); // } // // @Override // public int size() { // return indexes.length; // } // // public int getSubItems() { // return indexes.length; // } // // public int getItems() { // return items; // } // // private boolean hasNext(int index) { // return indexes[index] + (indexes.length - index) < items; // } // // private void move(int index) { // if (hasNext(index)) { // indexes[index]++; // int last = indexes[index]; // for (int i = index + 1; i < indexes.length; i++) { // this.indexes[i] = ++last; // } // } else { // move(index - 1); // } // } // // @Override // public int[] next(int[] items) { // if (hasNext()) { // move(indexes.length - 1); // System.arraycopy(indexes, 0, items, 0, indexes.length); // } // return items; // } // // @Override // public boolean hasNext() { // return hasNext(0) || hasNext(indexes.length - 1); // } // // private void init() { // int index = indexes.length; // for (int i = 0; i < indexes.length; i++) { // this.indexes[i] = i; // } // this.indexes[index - 1]--; // } // // @Override // public void clear() { // init(); // } // // public static long combinations(int subItems, int items) { // long result = 1; // int sub = Math.max(subItems, items - subItems); // for (int i = sub + 1; i <= items; i++) { // result = (result * i) / (i - sub); // } // return result; // } // } // Path: src/main/java/org/poker/api/game/Hand7Evaluator.java import java.util.List; import net.jcip.annotations.NotThreadSafe; import org.poker.api.core.Card; import org.poker.api.core.IHandEvaluator; import static org.poker.api.game.TexasHoldEmUtil.COMMUNITY_CARDS; import static org.poker.api.game.TexasHoldEmUtil.PLAYER_CARDS; import org.util.combinatorial.Combination; /* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.game; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 * */ @NotThreadSafe public class Hand7Evaluator {
public static final int TOTAL_CARDS = PLAYER_CARDS + COMMUNITY_CARDS;
dperezcabrera/jpoker
src/main/java/org/poker/api/game/Hand7Evaluator.java
// Path: src/main/java/org/poker/api/core/Card.java // @Immutable // public final class Card { // // private static final String STRING_RANK_CARDS = "23456789TJQKA"; // // public enum Suit { // // SPADE('♠'), HEART('♥'), DIAMOND('♦'), CLUB('♣'); // // private final char c; // // private Suit(char c) { // this.c = c; // } // // } // // public enum Rank { // // TWO, TRHEE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE // } // // private final Suit suit; // private final Rank rank; // // public Card(Suit suit, Rank rank) { // ExceptionUtil.checkNullArgument(rank, "rank"); // ExceptionUtil.checkNullArgument(suit, "suit"); // this.suit = suit; // this.rank = rank; // } // // public Suit getSuit() { // return suit; // } // // public Rank getRank() { // return rank; // } // // @Override // public int hashCode() { // return rank.ordinal() * Suit.values().length + suit.ordinal(); // } // // @Override // public boolean equals(Object obj) { // boolean result = true; // if (this != obj) { // result = false; // if (obj != null && getClass() == obj.getClass()) { // result = hashCode() == ((Card) obj).hashCode(); // } // } // return result; // } // // @Override // public String toString() { // return STRING_RANK_CARDS.substring(rank.ordinal(), rank.ordinal() + 1) + suit.c; // } // } // // Path: src/main/java/org/poker/api/core/IHandEvaluator.java // @FunctionalInterface // public interface IHandEvaluator { // // public int eval(Card[] cards); // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public static final int COMMUNITY_CARDS = 5; // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public static final int PLAYER_CARDS = 2; // // Path: src/main/java/org/util/combinatorial/Combination.java // @NotThreadSafe // public class Combination implements ICombinatorial { // // private final int items; // private final int[] indexes; // // public Combination(int subItems, int items) { // ExceptionUtil.checkMinValueArgument(subItems, 1, "subItems"); // ExceptionUtil.checkMinValueArgument(items, subItems, "items"); // this.indexes = new int[subItems]; // this.items = items; // init(); // } // // @Override // public long combinations() { // return combinations(indexes.length, items); // } // // @Override // public int size() { // return indexes.length; // } // // public int getSubItems() { // return indexes.length; // } // // public int getItems() { // return items; // } // // private boolean hasNext(int index) { // return indexes[index] + (indexes.length - index) < items; // } // // private void move(int index) { // if (hasNext(index)) { // indexes[index]++; // int last = indexes[index]; // for (int i = index + 1; i < indexes.length; i++) { // this.indexes[i] = ++last; // } // } else { // move(index - 1); // } // } // // @Override // public int[] next(int[] items) { // if (hasNext()) { // move(indexes.length - 1); // System.arraycopy(indexes, 0, items, 0, indexes.length); // } // return items; // } // // @Override // public boolean hasNext() { // return hasNext(0) || hasNext(indexes.length - 1); // } // // private void init() { // int index = indexes.length; // for (int i = 0; i < indexes.length; i++) { // this.indexes[i] = i; // } // this.indexes[index - 1]--; // } // // @Override // public void clear() { // init(); // } // // public static long combinations(int subItems, int items) { // long result = 1; // int sub = Math.max(subItems, items - subItems); // for (int i = sub + 1; i <= items; i++) { // result = (result * i) / (i - sub); // } // return result; // } // }
import java.util.List; import net.jcip.annotations.NotThreadSafe; import org.poker.api.core.Card; import org.poker.api.core.IHandEvaluator; import static org.poker.api.game.TexasHoldEmUtil.COMMUNITY_CARDS; import static org.poker.api.game.TexasHoldEmUtil.PLAYER_CARDS; import org.util.combinatorial.Combination;
/* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.game; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 * */ @NotThreadSafe public class Hand7Evaluator {
// Path: src/main/java/org/poker/api/core/Card.java // @Immutable // public final class Card { // // private static final String STRING_RANK_CARDS = "23456789TJQKA"; // // public enum Suit { // // SPADE('♠'), HEART('♥'), DIAMOND('♦'), CLUB('♣'); // // private final char c; // // private Suit(char c) { // this.c = c; // } // // } // // public enum Rank { // // TWO, TRHEE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE // } // // private final Suit suit; // private final Rank rank; // // public Card(Suit suit, Rank rank) { // ExceptionUtil.checkNullArgument(rank, "rank"); // ExceptionUtil.checkNullArgument(suit, "suit"); // this.suit = suit; // this.rank = rank; // } // // public Suit getSuit() { // return suit; // } // // public Rank getRank() { // return rank; // } // // @Override // public int hashCode() { // return rank.ordinal() * Suit.values().length + suit.ordinal(); // } // // @Override // public boolean equals(Object obj) { // boolean result = true; // if (this != obj) { // result = false; // if (obj != null && getClass() == obj.getClass()) { // result = hashCode() == ((Card) obj).hashCode(); // } // } // return result; // } // // @Override // public String toString() { // return STRING_RANK_CARDS.substring(rank.ordinal(), rank.ordinal() + 1) + suit.c; // } // } // // Path: src/main/java/org/poker/api/core/IHandEvaluator.java // @FunctionalInterface // public interface IHandEvaluator { // // public int eval(Card[] cards); // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public static final int COMMUNITY_CARDS = 5; // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public static final int PLAYER_CARDS = 2; // // Path: src/main/java/org/util/combinatorial/Combination.java // @NotThreadSafe // public class Combination implements ICombinatorial { // // private final int items; // private final int[] indexes; // // public Combination(int subItems, int items) { // ExceptionUtil.checkMinValueArgument(subItems, 1, "subItems"); // ExceptionUtil.checkMinValueArgument(items, subItems, "items"); // this.indexes = new int[subItems]; // this.items = items; // init(); // } // // @Override // public long combinations() { // return combinations(indexes.length, items); // } // // @Override // public int size() { // return indexes.length; // } // // public int getSubItems() { // return indexes.length; // } // // public int getItems() { // return items; // } // // private boolean hasNext(int index) { // return indexes[index] + (indexes.length - index) < items; // } // // private void move(int index) { // if (hasNext(index)) { // indexes[index]++; // int last = indexes[index]; // for (int i = index + 1; i < indexes.length; i++) { // this.indexes[i] = ++last; // } // } else { // move(index - 1); // } // } // // @Override // public int[] next(int[] items) { // if (hasNext()) { // move(indexes.length - 1); // System.arraycopy(indexes, 0, items, 0, indexes.length); // } // return items; // } // // @Override // public boolean hasNext() { // return hasNext(0) || hasNext(indexes.length - 1); // } // // private void init() { // int index = indexes.length; // for (int i = 0; i < indexes.length; i++) { // this.indexes[i] = i; // } // this.indexes[index - 1]--; // } // // @Override // public void clear() { // init(); // } // // public static long combinations(int subItems, int items) { // long result = 1; // int sub = Math.max(subItems, items - subItems); // for (int i = sub + 1; i <= items; i++) { // result = (result * i) / (i - sub); // } // return result; // } // } // Path: src/main/java/org/poker/api/game/Hand7Evaluator.java import java.util.List; import net.jcip.annotations.NotThreadSafe; import org.poker.api.core.Card; import org.poker.api.core.IHandEvaluator; import static org.poker.api.game.TexasHoldEmUtil.COMMUNITY_CARDS; import static org.poker.api.game.TexasHoldEmUtil.PLAYER_CARDS; import org.util.combinatorial.Combination; /* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.game; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 * */ @NotThreadSafe public class Hand7Evaluator {
public static final int TOTAL_CARDS = PLAYER_CARDS + COMMUNITY_CARDS;
dperezcabrera/jpoker
src/main/java/org/poker/api/game/Hand7Evaluator.java
// Path: src/main/java/org/poker/api/core/Card.java // @Immutable // public final class Card { // // private static final String STRING_RANK_CARDS = "23456789TJQKA"; // // public enum Suit { // // SPADE('♠'), HEART('♥'), DIAMOND('♦'), CLUB('♣'); // // private final char c; // // private Suit(char c) { // this.c = c; // } // // } // // public enum Rank { // // TWO, TRHEE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE // } // // private final Suit suit; // private final Rank rank; // // public Card(Suit suit, Rank rank) { // ExceptionUtil.checkNullArgument(rank, "rank"); // ExceptionUtil.checkNullArgument(suit, "suit"); // this.suit = suit; // this.rank = rank; // } // // public Suit getSuit() { // return suit; // } // // public Rank getRank() { // return rank; // } // // @Override // public int hashCode() { // return rank.ordinal() * Suit.values().length + suit.ordinal(); // } // // @Override // public boolean equals(Object obj) { // boolean result = true; // if (this != obj) { // result = false; // if (obj != null && getClass() == obj.getClass()) { // result = hashCode() == ((Card) obj).hashCode(); // } // } // return result; // } // // @Override // public String toString() { // return STRING_RANK_CARDS.substring(rank.ordinal(), rank.ordinal() + 1) + suit.c; // } // } // // Path: src/main/java/org/poker/api/core/IHandEvaluator.java // @FunctionalInterface // public interface IHandEvaluator { // // public int eval(Card[] cards); // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public static final int COMMUNITY_CARDS = 5; // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public static final int PLAYER_CARDS = 2; // // Path: src/main/java/org/util/combinatorial/Combination.java // @NotThreadSafe // public class Combination implements ICombinatorial { // // private final int items; // private final int[] indexes; // // public Combination(int subItems, int items) { // ExceptionUtil.checkMinValueArgument(subItems, 1, "subItems"); // ExceptionUtil.checkMinValueArgument(items, subItems, "items"); // this.indexes = new int[subItems]; // this.items = items; // init(); // } // // @Override // public long combinations() { // return combinations(indexes.length, items); // } // // @Override // public int size() { // return indexes.length; // } // // public int getSubItems() { // return indexes.length; // } // // public int getItems() { // return items; // } // // private boolean hasNext(int index) { // return indexes[index] + (indexes.length - index) < items; // } // // private void move(int index) { // if (hasNext(index)) { // indexes[index]++; // int last = indexes[index]; // for (int i = index + 1; i < indexes.length; i++) { // this.indexes[i] = ++last; // } // } else { // move(index - 1); // } // } // // @Override // public int[] next(int[] items) { // if (hasNext()) { // move(indexes.length - 1); // System.arraycopy(indexes, 0, items, 0, indexes.length); // } // return items; // } // // @Override // public boolean hasNext() { // return hasNext(0) || hasNext(indexes.length - 1); // } // // private void init() { // int index = indexes.length; // for (int i = 0; i < indexes.length; i++) { // this.indexes[i] = i; // } // this.indexes[index - 1]--; // } // // @Override // public void clear() { // init(); // } // // public static long combinations(int subItems, int items) { // long result = 1; // int sub = Math.max(subItems, items - subItems); // for (int i = sub + 1; i <= items; i++) { // result = (result * i) / (i - sub); // } // return result; // } // }
import java.util.List; import net.jcip.annotations.NotThreadSafe; import org.poker.api.core.Card; import org.poker.api.core.IHandEvaluator; import static org.poker.api.game.TexasHoldEmUtil.COMMUNITY_CARDS; import static org.poker.api.game.TexasHoldEmUtil.PLAYER_CARDS; import org.util.combinatorial.Combination;
/* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.game; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 * */ @NotThreadSafe public class Hand7Evaluator { public static final int TOTAL_CARDS = PLAYER_CARDS + COMMUNITY_CARDS; private final int[] combinatorialBuffer = new int[COMMUNITY_CARDS];
// Path: src/main/java/org/poker/api/core/Card.java // @Immutable // public final class Card { // // private static final String STRING_RANK_CARDS = "23456789TJQKA"; // // public enum Suit { // // SPADE('♠'), HEART('♥'), DIAMOND('♦'), CLUB('♣'); // // private final char c; // // private Suit(char c) { // this.c = c; // } // // } // // public enum Rank { // // TWO, TRHEE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE // } // // private final Suit suit; // private final Rank rank; // // public Card(Suit suit, Rank rank) { // ExceptionUtil.checkNullArgument(rank, "rank"); // ExceptionUtil.checkNullArgument(suit, "suit"); // this.suit = suit; // this.rank = rank; // } // // public Suit getSuit() { // return suit; // } // // public Rank getRank() { // return rank; // } // // @Override // public int hashCode() { // return rank.ordinal() * Suit.values().length + suit.ordinal(); // } // // @Override // public boolean equals(Object obj) { // boolean result = true; // if (this != obj) { // result = false; // if (obj != null && getClass() == obj.getClass()) { // result = hashCode() == ((Card) obj).hashCode(); // } // } // return result; // } // // @Override // public String toString() { // return STRING_RANK_CARDS.substring(rank.ordinal(), rank.ordinal() + 1) + suit.c; // } // } // // Path: src/main/java/org/poker/api/core/IHandEvaluator.java // @FunctionalInterface // public interface IHandEvaluator { // // public int eval(Card[] cards); // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public static final int COMMUNITY_CARDS = 5; // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public static final int PLAYER_CARDS = 2; // // Path: src/main/java/org/util/combinatorial/Combination.java // @NotThreadSafe // public class Combination implements ICombinatorial { // // private final int items; // private final int[] indexes; // // public Combination(int subItems, int items) { // ExceptionUtil.checkMinValueArgument(subItems, 1, "subItems"); // ExceptionUtil.checkMinValueArgument(items, subItems, "items"); // this.indexes = new int[subItems]; // this.items = items; // init(); // } // // @Override // public long combinations() { // return combinations(indexes.length, items); // } // // @Override // public int size() { // return indexes.length; // } // // public int getSubItems() { // return indexes.length; // } // // public int getItems() { // return items; // } // // private boolean hasNext(int index) { // return indexes[index] + (indexes.length - index) < items; // } // // private void move(int index) { // if (hasNext(index)) { // indexes[index]++; // int last = indexes[index]; // for (int i = index + 1; i < indexes.length; i++) { // this.indexes[i] = ++last; // } // } else { // move(index - 1); // } // } // // @Override // public int[] next(int[] items) { // if (hasNext()) { // move(indexes.length - 1); // System.arraycopy(indexes, 0, items, 0, indexes.length); // } // return items; // } // // @Override // public boolean hasNext() { // return hasNext(0) || hasNext(indexes.length - 1); // } // // private void init() { // int index = indexes.length; // for (int i = 0; i < indexes.length; i++) { // this.indexes[i] = i; // } // this.indexes[index - 1]--; // } // // @Override // public void clear() { // init(); // } // // public static long combinations(int subItems, int items) { // long result = 1; // int sub = Math.max(subItems, items - subItems); // for (int i = sub + 1; i <= items; i++) { // result = (result * i) / (i - sub); // } // return result; // } // } // Path: src/main/java/org/poker/api/game/Hand7Evaluator.java import java.util.List; import net.jcip.annotations.NotThreadSafe; import org.poker.api.core.Card; import org.poker.api.core.IHandEvaluator; import static org.poker.api.game.TexasHoldEmUtil.COMMUNITY_CARDS; import static org.poker.api.game.TexasHoldEmUtil.PLAYER_CARDS; import org.util.combinatorial.Combination; /* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.game; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 * */ @NotThreadSafe public class Hand7Evaluator { public static final int TOTAL_CARDS = PLAYER_CARDS + COMMUNITY_CARDS; private final int[] combinatorialBuffer = new int[COMMUNITY_CARDS];
private final Combination combinatorial = new Combination(COMMUNITY_CARDS, TOTAL_CARDS);
dperezcabrera/jpoker
src/main/java/org/poker/api/game/Hand7Evaluator.java
// Path: src/main/java/org/poker/api/core/Card.java // @Immutable // public final class Card { // // private static final String STRING_RANK_CARDS = "23456789TJQKA"; // // public enum Suit { // // SPADE('♠'), HEART('♥'), DIAMOND('♦'), CLUB('♣'); // // private final char c; // // private Suit(char c) { // this.c = c; // } // // } // // public enum Rank { // // TWO, TRHEE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE // } // // private final Suit suit; // private final Rank rank; // // public Card(Suit suit, Rank rank) { // ExceptionUtil.checkNullArgument(rank, "rank"); // ExceptionUtil.checkNullArgument(suit, "suit"); // this.suit = suit; // this.rank = rank; // } // // public Suit getSuit() { // return suit; // } // // public Rank getRank() { // return rank; // } // // @Override // public int hashCode() { // return rank.ordinal() * Suit.values().length + suit.ordinal(); // } // // @Override // public boolean equals(Object obj) { // boolean result = true; // if (this != obj) { // result = false; // if (obj != null && getClass() == obj.getClass()) { // result = hashCode() == ((Card) obj).hashCode(); // } // } // return result; // } // // @Override // public String toString() { // return STRING_RANK_CARDS.substring(rank.ordinal(), rank.ordinal() + 1) + suit.c; // } // } // // Path: src/main/java/org/poker/api/core/IHandEvaluator.java // @FunctionalInterface // public interface IHandEvaluator { // // public int eval(Card[] cards); // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public static final int COMMUNITY_CARDS = 5; // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public static final int PLAYER_CARDS = 2; // // Path: src/main/java/org/util/combinatorial/Combination.java // @NotThreadSafe // public class Combination implements ICombinatorial { // // private final int items; // private final int[] indexes; // // public Combination(int subItems, int items) { // ExceptionUtil.checkMinValueArgument(subItems, 1, "subItems"); // ExceptionUtil.checkMinValueArgument(items, subItems, "items"); // this.indexes = new int[subItems]; // this.items = items; // init(); // } // // @Override // public long combinations() { // return combinations(indexes.length, items); // } // // @Override // public int size() { // return indexes.length; // } // // public int getSubItems() { // return indexes.length; // } // // public int getItems() { // return items; // } // // private boolean hasNext(int index) { // return indexes[index] + (indexes.length - index) < items; // } // // private void move(int index) { // if (hasNext(index)) { // indexes[index]++; // int last = indexes[index]; // for (int i = index + 1; i < indexes.length; i++) { // this.indexes[i] = ++last; // } // } else { // move(index - 1); // } // } // // @Override // public int[] next(int[] items) { // if (hasNext()) { // move(indexes.length - 1); // System.arraycopy(indexes, 0, items, 0, indexes.length); // } // return items; // } // // @Override // public boolean hasNext() { // return hasNext(0) || hasNext(indexes.length - 1); // } // // private void init() { // int index = indexes.length; // for (int i = 0; i < indexes.length; i++) { // this.indexes[i] = i; // } // this.indexes[index - 1]--; // } // // @Override // public void clear() { // init(); // } // // public static long combinations(int subItems, int items) { // long result = 1; // int sub = Math.max(subItems, items - subItems); // for (int i = sub + 1; i <= items; i++) { // result = (result * i) / (i - sub); // } // return result; // } // }
import java.util.List; import net.jcip.annotations.NotThreadSafe; import org.poker.api.core.Card; import org.poker.api.core.IHandEvaluator; import static org.poker.api.game.TexasHoldEmUtil.COMMUNITY_CARDS; import static org.poker.api.game.TexasHoldEmUtil.PLAYER_CARDS; import org.util.combinatorial.Combination;
/* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.game; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 * */ @NotThreadSafe public class Hand7Evaluator { public static final int TOTAL_CARDS = PLAYER_CARDS + COMMUNITY_CARDS; private final int[] combinatorialBuffer = new int[COMMUNITY_CARDS]; private final Combination combinatorial = new Combination(COMMUNITY_CARDS, TOTAL_CARDS);
// Path: src/main/java/org/poker/api/core/Card.java // @Immutable // public final class Card { // // private static final String STRING_RANK_CARDS = "23456789TJQKA"; // // public enum Suit { // // SPADE('♠'), HEART('♥'), DIAMOND('♦'), CLUB('♣'); // // private final char c; // // private Suit(char c) { // this.c = c; // } // // } // // public enum Rank { // // TWO, TRHEE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE // } // // private final Suit suit; // private final Rank rank; // // public Card(Suit suit, Rank rank) { // ExceptionUtil.checkNullArgument(rank, "rank"); // ExceptionUtil.checkNullArgument(suit, "suit"); // this.suit = suit; // this.rank = rank; // } // // public Suit getSuit() { // return suit; // } // // public Rank getRank() { // return rank; // } // // @Override // public int hashCode() { // return rank.ordinal() * Suit.values().length + suit.ordinal(); // } // // @Override // public boolean equals(Object obj) { // boolean result = true; // if (this != obj) { // result = false; // if (obj != null && getClass() == obj.getClass()) { // result = hashCode() == ((Card) obj).hashCode(); // } // } // return result; // } // // @Override // public String toString() { // return STRING_RANK_CARDS.substring(rank.ordinal(), rank.ordinal() + 1) + suit.c; // } // } // // Path: src/main/java/org/poker/api/core/IHandEvaluator.java // @FunctionalInterface // public interface IHandEvaluator { // // public int eval(Card[] cards); // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public static final int COMMUNITY_CARDS = 5; // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public static final int PLAYER_CARDS = 2; // // Path: src/main/java/org/util/combinatorial/Combination.java // @NotThreadSafe // public class Combination implements ICombinatorial { // // private final int items; // private final int[] indexes; // // public Combination(int subItems, int items) { // ExceptionUtil.checkMinValueArgument(subItems, 1, "subItems"); // ExceptionUtil.checkMinValueArgument(items, subItems, "items"); // this.indexes = new int[subItems]; // this.items = items; // init(); // } // // @Override // public long combinations() { // return combinations(indexes.length, items); // } // // @Override // public int size() { // return indexes.length; // } // // public int getSubItems() { // return indexes.length; // } // // public int getItems() { // return items; // } // // private boolean hasNext(int index) { // return indexes[index] + (indexes.length - index) < items; // } // // private void move(int index) { // if (hasNext(index)) { // indexes[index]++; // int last = indexes[index]; // for (int i = index + 1; i < indexes.length; i++) { // this.indexes[i] = ++last; // } // } else { // move(index - 1); // } // } // // @Override // public int[] next(int[] items) { // if (hasNext()) { // move(indexes.length - 1); // System.arraycopy(indexes, 0, items, 0, indexes.length); // } // return items; // } // // @Override // public boolean hasNext() { // return hasNext(0) || hasNext(indexes.length - 1); // } // // private void init() { // int index = indexes.length; // for (int i = 0; i < indexes.length; i++) { // this.indexes[i] = i; // } // this.indexes[index - 1]--; // } // // @Override // public void clear() { // init(); // } // // public static long combinations(int subItems, int items) { // long result = 1; // int sub = Math.max(subItems, items - subItems); // for (int i = sub + 1; i <= items; i++) { // result = (result * i) / (i - sub); // } // return result; // } // } // Path: src/main/java/org/poker/api/game/Hand7Evaluator.java import java.util.List; import net.jcip.annotations.NotThreadSafe; import org.poker.api.core.Card; import org.poker.api.core.IHandEvaluator; import static org.poker.api.game.TexasHoldEmUtil.COMMUNITY_CARDS; import static org.poker.api.game.TexasHoldEmUtil.PLAYER_CARDS; import org.util.combinatorial.Combination; /* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.game; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 * */ @NotThreadSafe public class Hand7Evaluator { public static final int TOTAL_CARDS = PLAYER_CARDS + COMMUNITY_CARDS; private final int[] combinatorialBuffer = new int[COMMUNITY_CARDS]; private final Combination combinatorial = new Combination(COMMUNITY_CARDS, TOTAL_CARDS);
private final IHandEvaluator evaluator;
dperezcabrera/jpoker
src/main/java/org/poker/api/game/Hand7Evaluator.java
// Path: src/main/java/org/poker/api/core/Card.java // @Immutable // public final class Card { // // private static final String STRING_RANK_CARDS = "23456789TJQKA"; // // public enum Suit { // // SPADE('♠'), HEART('♥'), DIAMOND('♦'), CLUB('♣'); // // private final char c; // // private Suit(char c) { // this.c = c; // } // // } // // public enum Rank { // // TWO, TRHEE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE // } // // private final Suit suit; // private final Rank rank; // // public Card(Suit suit, Rank rank) { // ExceptionUtil.checkNullArgument(rank, "rank"); // ExceptionUtil.checkNullArgument(suit, "suit"); // this.suit = suit; // this.rank = rank; // } // // public Suit getSuit() { // return suit; // } // // public Rank getRank() { // return rank; // } // // @Override // public int hashCode() { // return rank.ordinal() * Suit.values().length + suit.ordinal(); // } // // @Override // public boolean equals(Object obj) { // boolean result = true; // if (this != obj) { // result = false; // if (obj != null && getClass() == obj.getClass()) { // result = hashCode() == ((Card) obj).hashCode(); // } // } // return result; // } // // @Override // public String toString() { // return STRING_RANK_CARDS.substring(rank.ordinal(), rank.ordinal() + 1) + suit.c; // } // } // // Path: src/main/java/org/poker/api/core/IHandEvaluator.java // @FunctionalInterface // public interface IHandEvaluator { // // public int eval(Card[] cards); // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public static final int COMMUNITY_CARDS = 5; // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public static final int PLAYER_CARDS = 2; // // Path: src/main/java/org/util/combinatorial/Combination.java // @NotThreadSafe // public class Combination implements ICombinatorial { // // private final int items; // private final int[] indexes; // // public Combination(int subItems, int items) { // ExceptionUtil.checkMinValueArgument(subItems, 1, "subItems"); // ExceptionUtil.checkMinValueArgument(items, subItems, "items"); // this.indexes = new int[subItems]; // this.items = items; // init(); // } // // @Override // public long combinations() { // return combinations(indexes.length, items); // } // // @Override // public int size() { // return indexes.length; // } // // public int getSubItems() { // return indexes.length; // } // // public int getItems() { // return items; // } // // private boolean hasNext(int index) { // return indexes[index] + (indexes.length - index) < items; // } // // private void move(int index) { // if (hasNext(index)) { // indexes[index]++; // int last = indexes[index]; // for (int i = index + 1; i < indexes.length; i++) { // this.indexes[i] = ++last; // } // } else { // move(index - 1); // } // } // // @Override // public int[] next(int[] items) { // if (hasNext()) { // move(indexes.length - 1); // System.arraycopy(indexes, 0, items, 0, indexes.length); // } // return items; // } // // @Override // public boolean hasNext() { // return hasNext(0) || hasNext(indexes.length - 1); // } // // private void init() { // int index = indexes.length; // for (int i = 0; i < indexes.length; i++) { // this.indexes[i] = i; // } // this.indexes[index - 1]--; // } // // @Override // public void clear() { // init(); // } // // public static long combinations(int subItems, int items) { // long result = 1; // int sub = Math.max(subItems, items - subItems); // for (int i = sub + 1; i <= items; i++) { // result = (result * i) / (i - sub); // } // return result; // } // }
import java.util.List; import net.jcip.annotations.NotThreadSafe; import org.poker.api.core.Card; import org.poker.api.core.IHandEvaluator; import static org.poker.api.game.TexasHoldEmUtil.COMMUNITY_CARDS; import static org.poker.api.game.TexasHoldEmUtil.PLAYER_CARDS; import org.util.combinatorial.Combination;
/* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.game; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 * */ @NotThreadSafe public class Hand7Evaluator { public static final int TOTAL_CARDS = PLAYER_CARDS + COMMUNITY_CARDS; private final int[] combinatorialBuffer = new int[COMMUNITY_CARDS]; private final Combination combinatorial = new Combination(COMMUNITY_CARDS, TOTAL_CARDS); private final IHandEvaluator evaluator;
// Path: src/main/java/org/poker/api/core/Card.java // @Immutable // public final class Card { // // private static final String STRING_RANK_CARDS = "23456789TJQKA"; // // public enum Suit { // // SPADE('♠'), HEART('♥'), DIAMOND('♦'), CLUB('♣'); // // private final char c; // // private Suit(char c) { // this.c = c; // } // // } // // public enum Rank { // // TWO, TRHEE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE // } // // private final Suit suit; // private final Rank rank; // // public Card(Suit suit, Rank rank) { // ExceptionUtil.checkNullArgument(rank, "rank"); // ExceptionUtil.checkNullArgument(suit, "suit"); // this.suit = suit; // this.rank = rank; // } // // public Suit getSuit() { // return suit; // } // // public Rank getRank() { // return rank; // } // // @Override // public int hashCode() { // return rank.ordinal() * Suit.values().length + suit.ordinal(); // } // // @Override // public boolean equals(Object obj) { // boolean result = true; // if (this != obj) { // result = false; // if (obj != null && getClass() == obj.getClass()) { // result = hashCode() == ((Card) obj).hashCode(); // } // } // return result; // } // // @Override // public String toString() { // return STRING_RANK_CARDS.substring(rank.ordinal(), rank.ordinal() + 1) + suit.c; // } // } // // Path: src/main/java/org/poker/api/core/IHandEvaluator.java // @FunctionalInterface // public interface IHandEvaluator { // // public int eval(Card[] cards); // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public static final int COMMUNITY_CARDS = 5; // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public static final int PLAYER_CARDS = 2; // // Path: src/main/java/org/util/combinatorial/Combination.java // @NotThreadSafe // public class Combination implements ICombinatorial { // // private final int items; // private final int[] indexes; // // public Combination(int subItems, int items) { // ExceptionUtil.checkMinValueArgument(subItems, 1, "subItems"); // ExceptionUtil.checkMinValueArgument(items, subItems, "items"); // this.indexes = new int[subItems]; // this.items = items; // init(); // } // // @Override // public long combinations() { // return combinations(indexes.length, items); // } // // @Override // public int size() { // return indexes.length; // } // // public int getSubItems() { // return indexes.length; // } // // public int getItems() { // return items; // } // // private boolean hasNext(int index) { // return indexes[index] + (indexes.length - index) < items; // } // // private void move(int index) { // if (hasNext(index)) { // indexes[index]++; // int last = indexes[index]; // for (int i = index + 1; i < indexes.length; i++) { // this.indexes[i] = ++last; // } // } else { // move(index - 1); // } // } // // @Override // public int[] next(int[] items) { // if (hasNext()) { // move(indexes.length - 1); // System.arraycopy(indexes, 0, items, 0, indexes.length); // } // return items; // } // // @Override // public boolean hasNext() { // return hasNext(0) || hasNext(indexes.length - 1); // } // // private void init() { // int index = indexes.length; // for (int i = 0; i < indexes.length; i++) { // this.indexes[i] = i; // } // this.indexes[index - 1]--; // } // // @Override // public void clear() { // init(); // } // // public static long combinations(int subItems, int items) { // long result = 1; // int sub = Math.max(subItems, items - subItems); // for (int i = sub + 1; i <= items; i++) { // result = (result * i) / (i - sub); // } // return result; // } // } // Path: src/main/java/org/poker/api/game/Hand7Evaluator.java import java.util.List; import net.jcip.annotations.NotThreadSafe; import org.poker.api.core.Card; import org.poker.api.core.IHandEvaluator; import static org.poker.api.game.TexasHoldEmUtil.COMMUNITY_CARDS; import static org.poker.api.game.TexasHoldEmUtil.PLAYER_CARDS; import org.util.combinatorial.Combination; /* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.game; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 * */ @NotThreadSafe public class Hand7Evaluator { public static final int TOTAL_CARDS = PLAYER_CARDS + COMMUNITY_CARDS; private final int[] combinatorialBuffer = new int[COMMUNITY_CARDS]; private final Combination combinatorial = new Combination(COMMUNITY_CARDS, TOTAL_CARDS); private final IHandEvaluator evaluator;
private final Card[] evalBuffer = new Card[COMMUNITY_CARDS];
dperezcabrera/jpoker
src/main/java/org/poker/api/core/Card.java
// Path: src/main/java/org/util/exceptions/ExceptionUtil.java // public final class ExceptionUtil { // // public static final String MIN_VALUE_ERR_MSG = "El argumento {0} no puede tener un valor inferior a <{1}> y tiene <{2}>."; // public static final String NULL_ERR_MSG = "El argumento {0} no puede ser nulo."; // public static final String LENGTH_ERR_MSG = "El argumento {0} no puede ser nulo y debe tener una longitud de {1}."; // public static final String SIZE_ERR_MSG = "El argumento {0} no puede ser nulo y debe tener {1} elementos."; // // private ExceptionUtil() { // } // // public static void checkMinValueArgument(int o, int minValue, String name) { // if (o < minValue) { // throw new IllegalArgumentException(MessageFormat.format(MIN_VALUE_ERR_MSG, name, minValue, o)); // } // } // // public static void checkMinValueArgument(long o, long minValue, String name) { // if (o < minValue) { // throw new IllegalArgumentException(MessageFormat.format(MIN_VALUE_ERR_MSG, name, minValue, o)); // } // } // // public static void checkNullArgument(Object o, String name) { // if (o == null) { // throw new IllegalArgumentException(MessageFormat.format(NULL_ERR_MSG, name)); // } // } // // public static void checkListSizeArgument(List a, String name, int length) { // if (a == null || a.size() != length) { // throw new IllegalArgumentException(MessageFormat.format(SIZE_ERR_MSG, name, length)); // } // } // // public static <T> void checkArrayLengthArgument(T[] a, String name, int length) { // if (a == null || a.length != length) { // throw new IllegalArgumentException(MessageFormat.format(LENGTH_ERR_MSG, name, length)); // } // } // // public static void checkArgument(boolean throwException, String message, Object... args) { // if (throwException) { // throw new IllegalArgumentException(MessageFormat.format(message, args)); // } // } // }
import net.jcip.annotations.Immutable; import org.util.exceptions.ExceptionUtil;
/* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.core; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 */ @Immutable public final class Card { private static final String STRING_RANK_CARDS = "23456789TJQKA"; public enum Suit { SPADE('♠'), HEART('♥'), DIAMOND('♦'), CLUB('♣'); private final char c; private Suit(char c) { this.c = c; } } public enum Rank { TWO, TRHEE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE } private final Suit suit; private final Rank rank; public Card(Suit suit, Rank rank) {
// Path: src/main/java/org/util/exceptions/ExceptionUtil.java // public final class ExceptionUtil { // // public static final String MIN_VALUE_ERR_MSG = "El argumento {0} no puede tener un valor inferior a <{1}> y tiene <{2}>."; // public static final String NULL_ERR_MSG = "El argumento {0} no puede ser nulo."; // public static final String LENGTH_ERR_MSG = "El argumento {0} no puede ser nulo y debe tener una longitud de {1}."; // public static final String SIZE_ERR_MSG = "El argumento {0} no puede ser nulo y debe tener {1} elementos."; // // private ExceptionUtil() { // } // // public static void checkMinValueArgument(int o, int minValue, String name) { // if (o < minValue) { // throw new IllegalArgumentException(MessageFormat.format(MIN_VALUE_ERR_MSG, name, minValue, o)); // } // } // // public static void checkMinValueArgument(long o, long minValue, String name) { // if (o < minValue) { // throw new IllegalArgumentException(MessageFormat.format(MIN_VALUE_ERR_MSG, name, minValue, o)); // } // } // // public static void checkNullArgument(Object o, String name) { // if (o == null) { // throw new IllegalArgumentException(MessageFormat.format(NULL_ERR_MSG, name)); // } // } // // public static void checkListSizeArgument(List a, String name, int length) { // if (a == null || a.size() != length) { // throw new IllegalArgumentException(MessageFormat.format(SIZE_ERR_MSG, name, length)); // } // } // // public static <T> void checkArrayLengthArgument(T[] a, String name, int length) { // if (a == null || a.length != length) { // throw new IllegalArgumentException(MessageFormat.format(LENGTH_ERR_MSG, name, length)); // } // } // // public static void checkArgument(boolean throwException, String message, Object... args) { // if (throwException) { // throw new IllegalArgumentException(MessageFormat.format(message, args)); // } // } // } // Path: src/main/java/org/poker/api/core/Card.java import net.jcip.annotations.Immutable; import org.util.exceptions.ExceptionUtil; /* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.core; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 */ @Immutable public final class Card { private static final String STRING_RANK_CARDS = "23456789TJQKA"; public enum Suit { SPADE('♠'), HEART('♥'), DIAMOND('♦'), CLUB('♣'); private final char c; private Suit(char c) { this.c = c; } } public enum Rank { TWO, TRHEE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE } private final Suit suit; private final Rank rank; public Card(Suit suit, Rank rank) {
ExceptionUtil.checkNullArgument(rank, "rank");
dperezcabrera/jpoker
src/main/java/org/poker/engine/model/ModelUtil.java
// Path: src/main/java/org/poker/api/game/Settings.java // @NotThreadSafe // public class Settings implements Serializable{ // private static final long serialVersionUID = 1L; // // private int maxPlayers; // private long time; // private int maxErrors; // private int maxRounds; // private long playerChip; // private long smallBlind; // private int rounds4IncrementBlind; // // public Settings() { // // Default constructor. // } // // public Settings(Settings s) { // this.maxPlayers = s.maxPlayers; // this.time = s.time; // this.maxErrors = s.maxErrors; // this.playerChip = s.playerChip; // this.smallBlind = s.smallBlind; // this.maxRounds = s.maxRounds; // this.rounds4IncrementBlind = s.rounds4IncrementBlind; // } // // public int getMaxErrors() { // return maxErrors; // } // // public void setMaxErrors(int maxErrors) { // this.maxErrors = maxErrors; // } // // public int getMaxPlayers() { // return maxPlayers; // } // // public void setMaxPlayers(int maxPlayers) { // this.maxPlayers = maxPlayers; // } // // public long getTime() { // return time; // } // // public void setTime(long time) { // this.time = time; // } // // public long getPlayerChip() { // return playerChip; // } // // public void setPlayerChip(long playerChip) { // this.playerChip = playerChip; // } // // public long getSmallBlind() { // return smallBlind; // } // // public long getBigBlind() { // return smallBlind * 2; // } // // public void setSmallBlind(long smallBlind) { // this.smallBlind = smallBlind; // } // // public int getMaxRounds() { // return maxRounds; // } // // public void setMaxRounds(int maxRounds) { // this.maxRounds = maxRounds; // } // // public int getRounds4IncrementBlind() { // return rounds4IncrementBlind; // } // // public void setRounds4IncrementBlind(int rounds4IncrementBlind) { // this.rounds4IncrementBlind = rounds4IncrementBlind; // } // // @Override // public String toString() { // return "{class:'Settings', maxPlayers:" + maxPlayers + ", time:" + time + ", maxErrors:" + maxErrors + ", playerChip:" + playerChip + ", maxRounds:" + maxRounds + ", smallBlind:" + smallBlind + ", rounds4IncrementBlind:" + rounds4IncrementBlind + '}'; // } // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public enum BetCommandType { // // ERROR, // TIMEOUT, // FOLD, // CHECK, // CALL, // RAISE, // ALL_IN // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public enum PlayerState { // // READY(true), // OUT(false), // FOLD(false), // CHECK(true), // CALL(true), // RAISE(true), // ALL_IN(false); // // private final boolean active; // // private PlayerState(boolean isActive) { // this.active = isActive; // } // // public boolean isActive() { // return active; // } // }
import org.poker.api.game.Settings; import org.poker.api.game.TexasHoldEmUtil.BetCommandType; import org.poker.api.game.TexasHoldEmUtil.PlayerState;
/* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.engine.model; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 */ public final class ModelUtil { public static final int NO_PLAYER_TURN = -1; private ModelUtil() { } public static boolean range(int min, int max, int value) { return min <= value && value < max; } public static int nextPlayer(ModelContext model, int turn) { int result = NO_PLAYER_TURN; int players = model.getNumPlayers(); if (players > 1 && range(0, players, turn)) { int i = (turn + 1) % players; while (i != turn && result == NO_PLAYER_TURN) { if (model.getPlayer(i).isActive()) { result = i; } else { i = (i + 1) % players; } } result = checkNextPlayer(model, result); } return result; } private static int checkNextPlayer(ModelContext model, int index) { int result = index; if (result != NO_PLAYER_TURN && model.getPlayer(result).getBet() == model.getHighBet()
// Path: src/main/java/org/poker/api/game/Settings.java // @NotThreadSafe // public class Settings implements Serializable{ // private static final long serialVersionUID = 1L; // // private int maxPlayers; // private long time; // private int maxErrors; // private int maxRounds; // private long playerChip; // private long smallBlind; // private int rounds4IncrementBlind; // // public Settings() { // // Default constructor. // } // // public Settings(Settings s) { // this.maxPlayers = s.maxPlayers; // this.time = s.time; // this.maxErrors = s.maxErrors; // this.playerChip = s.playerChip; // this.smallBlind = s.smallBlind; // this.maxRounds = s.maxRounds; // this.rounds4IncrementBlind = s.rounds4IncrementBlind; // } // // public int getMaxErrors() { // return maxErrors; // } // // public void setMaxErrors(int maxErrors) { // this.maxErrors = maxErrors; // } // // public int getMaxPlayers() { // return maxPlayers; // } // // public void setMaxPlayers(int maxPlayers) { // this.maxPlayers = maxPlayers; // } // // public long getTime() { // return time; // } // // public void setTime(long time) { // this.time = time; // } // // public long getPlayerChip() { // return playerChip; // } // // public void setPlayerChip(long playerChip) { // this.playerChip = playerChip; // } // // public long getSmallBlind() { // return smallBlind; // } // // public long getBigBlind() { // return smallBlind * 2; // } // // public void setSmallBlind(long smallBlind) { // this.smallBlind = smallBlind; // } // // public int getMaxRounds() { // return maxRounds; // } // // public void setMaxRounds(int maxRounds) { // this.maxRounds = maxRounds; // } // // public int getRounds4IncrementBlind() { // return rounds4IncrementBlind; // } // // public void setRounds4IncrementBlind(int rounds4IncrementBlind) { // this.rounds4IncrementBlind = rounds4IncrementBlind; // } // // @Override // public String toString() { // return "{class:'Settings', maxPlayers:" + maxPlayers + ", time:" + time + ", maxErrors:" + maxErrors + ", playerChip:" + playerChip + ", maxRounds:" + maxRounds + ", smallBlind:" + smallBlind + ", rounds4IncrementBlind:" + rounds4IncrementBlind + '}'; // } // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public enum BetCommandType { // // ERROR, // TIMEOUT, // FOLD, // CHECK, // CALL, // RAISE, // ALL_IN // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public enum PlayerState { // // READY(true), // OUT(false), // FOLD(false), // CHECK(true), // CALL(true), // RAISE(true), // ALL_IN(false); // // private final boolean active; // // private PlayerState(boolean isActive) { // this.active = isActive; // } // // public boolean isActive() { // return active; // } // } // Path: src/main/java/org/poker/engine/model/ModelUtil.java import org.poker.api.game.Settings; import org.poker.api.game.TexasHoldEmUtil.BetCommandType; import org.poker.api.game.TexasHoldEmUtil.PlayerState; /* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.engine.model; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 */ public final class ModelUtil { public static final int NO_PLAYER_TURN = -1; private ModelUtil() { } public static boolean range(int min, int max, int value) { return min <= value && value < max; } public static int nextPlayer(ModelContext model, int turn) { int result = NO_PLAYER_TURN; int players = model.getNumPlayers(); if (players > 1 && range(0, players, turn)) { int i = (turn + 1) % players; while (i != turn && result == NO_PLAYER_TURN) { if (model.getPlayer(i).isActive()) { result = i; } else { i = (i + 1) % players; } } result = checkNextPlayer(model, result); } return result; } private static int checkNextPlayer(ModelContext model, int index) { int result = index; if (result != NO_PLAYER_TURN && model.getPlayer(result).getBet() == model.getHighBet()
&& (model.getPlayer(result).getState() != PlayerState.READY
dperezcabrera/jpoker
src/main/java/org/poker/engine/model/ModelUtil.java
// Path: src/main/java/org/poker/api/game/Settings.java // @NotThreadSafe // public class Settings implements Serializable{ // private static final long serialVersionUID = 1L; // // private int maxPlayers; // private long time; // private int maxErrors; // private int maxRounds; // private long playerChip; // private long smallBlind; // private int rounds4IncrementBlind; // // public Settings() { // // Default constructor. // } // // public Settings(Settings s) { // this.maxPlayers = s.maxPlayers; // this.time = s.time; // this.maxErrors = s.maxErrors; // this.playerChip = s.playerChip; // this.smallBlind = s.smallBlind; // this.maxRounds = s.maxRounds; // this.rounds4IncrementBlind = s.rounds4IncrementBlind; // } // // public int getMaxErrors() { // return maxErrors; // } // // public void setMaxErrors(int maxErrors) { // this.maxErrors = maxErrors; // } // // public int getMaxPlayers() { // return maxPlayers; // } // // public void setMaxPlayers(int maxPlayers) { // this.maxPlayers = maxPlayers; // } // // public long getTime() { // return time; // } // // public void setTime(long time) { // this.time = time; // } // // public long getPlayerChip() { // return playerChip; // } // // public void setPlayerChip(long playerChip) { // this.playerChip = playerChip; // } // // public long getSmallBlind() { // return smallBlind; // } // // public long getBigBlind() { // return smallBlind * 2; // } // // public void setSmallBlind(long smallBlind) { // this.smallBlind = smallBlind; // } // // public int getMaxRounds() { // return maxRounds; // } // // public void setMaxRounds(int maxRounds) { // this.maxRounds = maxRounds; // } // // public int getRounds4IncrementBlind() { // return rounds4IncrementBlind; // } // // public void setRounds4IncrementBlind(int rounds4IncrementBlind) { // this.rounds4IncrementBlind = rounds4IncrementBlind; // } // // @Override // public String toString() { // return "{class:'Settings', maxPlayers:" + maxPlayers + ", time:" + time + ", maxErrors:" + maxErrors + ", playerChip:" + playerChip + ", maxRounds:" + maxRounds + ", smallBlind:" + smallBlind + ", rounds4IncrementBlind:" + rounds4IncrementBlind + '}'; // } // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public enum BetCommandType { // // ERROR, // TIMEOUT, // FOLD, // CHECK, // CALL, // RAISE, // ALL_IN // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public enum PlayerState { // // READY(true), // OUT(false), // FOLD(false), // CHECK(true), // CALL(true), // RAISE(true), // ALL_IN(false); // // private final boolean active; // // private PlayerState(boolean isActive) { // this.active = isActive; // } // // public boolean isActive() { // return active; // } // }
import org.poker.api.game.Settings; import org.poker.api.game.TexasHoldEmUtil.BetCommandType; import org.poker.api.game.TexasHoldEmUtil.PlayerState;
} public static int nextPlayer(ModelContext model, int turn) { int result = NO_PLAYER_TURN; int players = model.getNumPlayers(); if (players > 1 && range(0, players, turn)) { int i = (turn + 1) % players; while (i != turn && result == NO_PLAYER_TURN) { if (model.getPlayer(i).isActive()) { result = i; } else { i = (i + 1) % players; } } result = checkNextPlayer(model, result); } return result; } private static int checkNextPlayer(ModelContext model, int index) { int result = index; if (result != NO_PLAYER_TURN && model.getPlayer(result).getBet() == model.getHighBet() && (model.getPlayer(result).getState() != PlayerState.READY || model.getActivePlayers() == 1)) { result = NO_PLAYER_TURN; } return result; }
// Path: src/main/java/org/poker/api/game/Settings.java // @NotThreadSafe // public class Settings implements Serializable{ // private static final long serialVersionUID = 1L; // // private int maxPlayers; // private long time; // private int maxErrors; // private int maxRounds; // private long playerChip; // private long smallBlind; // private int rounds4IncrementBlind; // // public Settings() { // // Default constructor. // } // // public Settings(Settings s) { // this.maxPlayers = s.maxPlayers; // this.time = s.time; // this.maxErrors = s.maxErrors; // this.playerChip = s.playerChip; // this.smallBlind = s.smallBlind; // this.maxRounds = s.maxRounds; // this.rounds4IncrementBlind = s.rounds4IncrementBlind; // } // // public int getMaxErrors() { // return maxErrors; // } // // public void setMaxErrors(int maxErrors) { // this.maxErrors = maxErrors; // } // // public int getMaxPlayers() { // return maxPlayers; // } // // public void setMaxPlayers(int maxPlayers) { // this.maxPlayers = maxPlayers; // } // // public long getTime() { // return time; // } // // public void setTime(long time) { // this.time = time; // } // // public long getPlayerChip() { // return playerChip; // } // // public void setPlayerChip(long playerChip) { // this.playerChip = playerChip; // } // // public long getSmallBlind() { // return smallBlind; // } // // public long getBigBlind() { // return smallBlind * 2; // } // // public void setSmallBlind(long smallBlind) { // this.smallBlind = smallBlind; // } // // public int getMaxRounds() { // return maxRounds; // } // // public void setMaxRounds(int maxRounds) { // this.maxRounds = maxRounds; // } // // public int getRounds4IncrementBlind() { // return rounds4IncrementBlind; // } // // public void setRounds4IncrementBlind(int rounds4IncrementBlind) { // this.rounds4IncrementBlind = rounds4IncrementBlind; // } // // @Override // public String toString() { // return "{class:'Settings', maxPlayers:" + maxPlayers + ", time:" + time + ", maxErrors:" + maxErrors + ", playerChip:" + playerChip + ", maxRounds:" + maxRounds + ", smallBlind:" + smallBlind + ", rounds4IncrementBlind:" + rounds4IncrementBlind + '}'; // } // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public enum BetCommandType { // // ERROR, // TIMEOUT, // FOLD, // CHECK, // CALL, // RAISE, // ALL_IN // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public enum PlayerState { // // READY(true), // OUT(false), // FOLD(false), // CHECK(true), // CALL(true), // RAISE(true), // ALL_IN(false); // // private final boolean active; // // private PlayerState(boolean isActive) { // this.active = isActive; // } // // public boolean isActive() { // return active; // } // } // Path: src/main/java/org/poker/engine/model/ModelUtil.java import org.poker.api.game.Settings; import org.poker.api.game.TexasHoldEmUtil.BetCommandType; import org.poker.api.game.TexasHoldEmUtil.PlayerState; } public static int nextPlayer(ModelContext model, int turn) { int result = NO_PLAYER_TURN; int players = model.getNumPlayers(); if (players > 1 && range(0, players, turn)) { int i = (turn + 1) % players; while (i != turn && result == NO_PLAYER_TURN) { if (model.getPlayer(i).isActive()) { result = i; } else { i = (i + 1) % players; } } result = checkNextPlayer(model, result); } return result; } private static int checkNextPlayer(ModelContext model, int index) { int result = index; if (result != NO_PLAYER_TURN && model.getPlayer(result).getBet() == model.getHighBet() && (model.getPlayer(result).getState() != PlayerState.READY || model.getActivePlayers() == 1)) { result = NO_PLAYER_TURN; } return result; }
public static void playerBet(ModelContext model, PlayerEntity player, BetCommandType betCommand, long chips) {
dperezcabrera/jpoker
src/main/java/org/poker/engine/model/ModelUtil.java
// Path: src/main/java/org/poker/api/game/Settings.java // @NotThreadSafe // public class Settings implements Serializable{ // private static final long serialVersionUID = 1L; // // private int maxPlayers; // private long time; // private int maxErrors; // private int maxRounds; // private long playerChip; // private long smallBlind; // private int rounds4IncrementBlind; // // public Settings() { // // Default constructor. // } // // public Settings(Settings s) { // this.maxPlayers = s.maxPlayers; // this.time = s.time; // this.maxErrors = s.maxErrors; // this.playerChip = s.playerChip; // this.smallBlind = s.smallBlind; // this.maxRounds = s.maxRounds; // this.rounds4IncrementBlind = s.rounds4IncrementBlind; // } // // public int getMaxErrors() { // return maxErrors; // } // // public void setMaxErrors(int maxErrors) { // this.maxErrors = maxErrors; // } // // public int getMaxPlayers() { // return maxPlayers; // } // // public void setMaxPlayers(int maxPlayers) { // this.maxPlayers = maxPlayers; // } // // public long getTime() { // return time; // } // // public void setTime(long time) { // this.time = time; // } // // public long getPlayerChip() { // return playerChip; // } // // public void setPlayerChip(long playerChip) { // this.playerChip = playerChip; // } // // public long getSmallBlind() { // return smallBlind; // } // // public long getBigBlind() { // return smallBlind * 2; // } // // public void setSmallBlind(long smallBlind) { // this.smallBlind = smallBlind; // } // // public int getMaxRounds() { // return maxRounds; // } // // public void setMaxRounds(int maxRounds) { // this.maxRounds = maxRounds; // } // // public int getRounds4IncrementBlind() { // return rounds4IncrementBlind; // } // // public void setRounds4IncrementBlind(int rounds4IncrementBlind) { // this.rounds4IncrementBlind = rounds4IncrementBlind; // } // // @Override // public String toString() { // return "{class:'Settings', maxPlayers:" + maxPlayers + ", time:" + time + ", maxErrors:" + maxErrors + ", playerChip:" + playerChip + ", maxRounds:" + maxRounds + ", smallBlind:" + smallBlind + ", rounds4IncrementBlind:" + rounds4IncrementBlind + '}'; // } // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public enum BetCommandType { // // ERROR, // TIMEOUT, // FOLD, // CHECK, // CALL, // RAISE, // ALL_IN // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public enum PlayerState { // // READY(true), // OUT(false), // FOLD(false), // CHECK(true), // CALL(true), // RAISE(true), // ALL_IN(false); // // private final boolean active; // // private PlayerState(boolean isActive) { // this.active = isActive; // } // // public boolean isActive() { // return active; // } // }
import org.poker.api.game.Settings; import org.poker.api.game.TexasHoldEmUtil.BetCommandType; import org.poker.api.game.TexasHoldEmUtil.PlayerState;
} private static int checkNextPlayer(ModelContext model, int index) { int result = index; if (result != NO_PLAYER_TURN && model.getPlayer(result).getBet() == model.getHighBet() && (model.getPlayer(result).getState() != PlayerState.READY || model.getActivePlayers() == 1)) { result = NO_PLAYER_TURN; } return result; } public static void playerBet(ModelContext model, PlayerEntity player, BetCommandType betCommand, long chips) { if (betCommand == BetCommandType.ALL_IN) { model.setPlayersAllIn(model.getPlayersAllIn() + 1); model.setActivePlayers(model.getActivePlayers() - 1); } else if (betCommand == BetCommandType.FOLD || betCommand == BetCommandType.TIMEOUT) { model.setActivePlayers(model.getActivePlayers() - 1); } playerBet(player, chips); model.setHighBet(Math.max(model.getHighBet(), player.getBet())); model.setBets(model.getBets() + 1); } public static void playerBet(PlayerEntity player, long chips) { player.setBet(player.getBet() + chips); player.setChips(player.getChips() - chips); }
// Path: src/main/java/org/poker/api/game/Settings.java // @NotThreadSafe // public class Settings implements Serializable{ // private static final long serialVersionUID = 1L; // // private int maxPlayers; // private long time; // private int maxErrors; // private int maxRounds; // private long playerChip; // private long smallBlind; // private int rounds4IncrementBlind; // // public Settings() { // // Default constructor. // } // // public Settings(Settings s) { // this.maxPlayers = s.maxPlayers; // this.time = s.time; // this.maxErrors = s.maxErrors; // this.playerChip = s.playerChip; // this.smallBlind = s.smallBlind; // this.maxRounds = s.maxRounds; // this.rounds4IncrementBlind = s.rounds4IncrementBlind; // } // // public int getMaxErrors() { // return maxErrors; // } // // public void setMaxErrors(int maxErrors) { // this.maxErrors = maxErrors; // } // // public int getMaxPlayers() { // return maxPlayers; // } // // public void setMaxPlayers(int maxPlayers) { // this.maxPlayers = maxPlayers; // } // // public long getTime() { // return time; // } // // public void setTime(long time) { // this.time = time; // } // // public long getPlayerChip() { // return playerChip; // } // // public void setPlayerChip(long playerChip) { // this.playerChip = playerChip; // } // // public long getSmallBlind() { // return smallBlind; // } // // public long getBigBlind() { // return smallBlind * 2; // } // // public void setSmallBlind(long smallBlind) { // this.smallBlind = smallBlind; // } // // public int getMaxRounds() { // return maxRounds; // } // // public void setMaxRounds(int maxRounds) { // this.maxRounds = maxRounds; // } // // public int getRounds4IncrementBlind() { // return rounds4IncrementBlind; // } // // public void setRounds4IncrementBlind(int rounds4IncrementBlind) { // this.rounds4IncrementBlind = rounds4IncrementBlind; // } // // @Override // public String toString() { // return "{class:'Settings', maxPlayers:" + maxPlayers + ", time:" + time + ", maxErrors:" + maxErrors + ", playerChip:" + playerChip + ", maxRounds:" + maxRounds + ", smallBlind:" + smallBlind + ", rounds4IncrementBlind:" + rounds4IncrementBlind + '}'; // } // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public enum BetCommandType { // // ERROR, // TIMEOUT, // FOLD, // CHECK, // CALL, // RAISE, // ALL_IN // } // // Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public enum PlayerState { // // READY(true), // OUT(false), // FOLD(false), // CHECK(true), // CALL(true), // RAISE(true), // ALL_IN(false); // // private final boolean active; // // private PlayerState(boolean isActive) { // this.active = isActive; // } // // public boolean isActive() { // return active; // } // } // Path: src/main/java/org/poker/engine/model/ModelUtil.java import org.poker.api.game.Settings; import org.poker.api.game.TexasHoldEmUtil.BetCommandType; import org.poker.api.game.TexasHoldEmUtil.PlayerState; } private static int checkNextPlayer(ModelContext model, int index) { int result = index; if (result != NO_PLAYER_TURN && model.getPlayer(result).getBet() == model.getHighBet() && (model.getPlayer(result).getState() != PlayerState.READY || model.getActivePlayers() == 1)) { result = NO_PLAYER_TURN; } return result; } public static void playerBet(ModelContext model, PlayerEntity player, BetCommandType betCommand, long chips) { if (betCommand == BetCommandType.ALL_IN) { model.setPlayersAllIn(model.getPlayersAllIn() + 1); model.setActivePlayers(model.getActivePlayers() - 1); } else if (betCommand == BetCommandType.FOLD || betCommand == BetCommandType.TIMEOUT) { model.setActivePlayers(model.getActivePlayers() - 1); } playerBet(player, chips); model.setHighBet(Math.max(model.getHighBet(), player.getBet())); model.setBets(model.getBets() + 1); } public static void playerBet(PlayerEntity player, long chips) { player.setBet(player.getBet() + chips); player.setChips(player.getChips() - chips); }
public static void incrementErrors(PlayerEntity player, Settings settings) {
dperezcabrera/jpoker
src/main/java/org/poker/api/game/BetCommand.java
// Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public enum BetCommandType { // // ERROR, // TIMEOUT, // FOLD, // CHECK, // CALL, // RAISE, // ALL_IN // } // // Path: src/main/java/org/util/exceptions/ExceptionUtil.java // public final class ExceptionUtil { // // public static final String MIN_VALUE_ERR_MSG = "El argumento {0} no puede tener un valor inferior a <{1}> y tiene <{2}>."; // public static final String NULL_ERR_MSG = "El argumento {0} no puede ser nulo."; // public static final String LENGTH_ERR_MSG = "El argumento {0} no puede ser nulo y debe tener una longitud de {1}."; // public static final String SIZE_ERR_MSG = "El argumento {0} no puede ser nulo y debe tener {1} elementos."; // // private ExceptionUtil() { // } // // public static void checkMinValueArgument(int o, int minValue, String name) { // if (o < minValue) { // throw new IllegalArgumentException(MessageFormat.format(MIN_VALUE_ERR_MSG, name, minValue, o)); // } // } // // public static void checkMinValueArgument(long o, long minValue, String name) { // if (o < minValue) { // throw new IllegalArgumentException(MessageFormat.format(MIN_VALUE_ERR_MSG, name, minValue, o)); // } // } // // public static void checkNullArgument(Object o, String name) { // if (o == null) { // throw new IllegalArgumentException(MessageFormat.format(NULL_ERR_MSG, name)); // } // } // // public static void checkListSizeArgument(List a, String name, int length) { // if (a == null || a.size() != length) { // throw new IllegalArgumentException(MessageFormat.format(SIZE_ERR_MSG, name, length)); // } // } // // public static <T> void checkArrayLengthArgument(T[] a, String name, int length) { // if (a == null || a.length != length) { // throw new IllegalArgumentException(MessageFormat.format(LENGTH_ERR_MSG, name, length)); // } // } // // public static void checkArgument(boolean throwException, String message, Object... args) { // if (throwException) { // throw new IllegalArgumentException(MessageFormat.format(message, args)); // } // } // }
import net.jcip.annotations.NotThreadSafe; import org.poker.api.game.TexasHoldEmUtil.BetCommandType; import org.util.exceptions.ExceptionUtil;
/* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.game; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 */ @NotThreadSafe public class BetCommand {
// Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public enum BetCommandType { // // ERROR, // TIMEOUT, // FOLD, // CHECK, // CALL, // RAISE, // ALL_IN // } // // Path: src/main/java/org/util/exceptions/ExceptionUtil.java // public final class ExceptionUtil { // // public static final String MIN_VALUE_ERR_MSG = "El argumento {0} no puede tener un valor inferior a <{1}> y tiene <{2}>."; // public static final String NULL_ERR_MSG = "El argumento {0} no puede ser nulo."; // public static final String LENGTH_ERR_MSG = "El argumento {0} no puede ser nulo y debe tener una longitud de {1}."; // public static final String SIZE_ERR_MSG = "El argumento {0} no puede ser nulo y debe tener {1} elementos."; // // private ExceptionUtil() { // } // // public static void checkMinValueArgument(int o, int minValue, String name) { // if (o < minValue) { // throw new IllegalArgumentException(MessageFormat.format(MIN_VALUE_ERR_MSG, name, minValue, o)); // } // } // // public static void checkMinValueArgument(long o, long minValue, String name) { // if (o < minValue) { // throw new IllegalArgumentException(MessageFormat.format(MIN_VALUE_ERR_MSG, name, minValue, o)); // } // } // // public static void checkNullArgument(Object o, String name) { // if (o == null) { // throw new IllegalArgumentException(MessageFormat.format(NULL_ERR_MSG, name)); // } // } // // public static void checkListSizeArgument(List a, String name, int length) { // if (a == null || a.size() != length) { // throw new IllegalArgumentException(MessageFormat.format(SIZE_ERR_MSG, name, length)); // } // } // // public static <T> void checkArrayLengthArgument(T[] a, String name, int length) { // if (a == null || a.length != length) { // throw new IllegalArgumentException(MessageFormat.format(LENGTH_ERR_MSG, name, length)); // } // } // // public static void checkArgument(boolean throwException, String message, Object... args) { // if (throwException) { // throw new IllegalArgumentException(MessageFormat.format(message, args)); // } // } // } // Path: src/main/java/org/poker/api/game/BetCommand.java import net.jcip.annotations.NotThreadSafe; import org.poker.api.game.TexasHoldEmUtil.BetCommandType; import org.util.exceptions.ExceptionUtil; /* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.game; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 */ @NotThreadSafe public class BetCommand {
private final BetCommandType type;
dperezcabrera/jpoker
src/main/java/org/poker/api/game/BetCommand.java
// Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public enum BetCommandType { // // ERROR, // TIMEOUT, // FOLD, // CHECK, // CALL, // RAISE, // ALL_IN // } // // Path: src/main/java/org/util/exceptions/ExceptionUtil.java // public final class ExceptionUtil { // // public static final String MIN_VALUE_ERR_MSG = "El argumento {0} no puede tener un valor inferior a <{1}> y tiene <{2}>."; // public static final String NULL_ERR_MSG = "El argumento {0} no puede ser nulo."; // public static final String LENGTH_ERR_MSG = "El argumento {0} no puede ser nulo y debe tener una longitud de {1}."; // public static final String SIZE_ERR_MSG = "El argumento {0} no puede ser nulo y debe tener {1} elementos."; // // private ExceptionUtil() { // } // // public static void checkMinValueArgument(int o, int minValue, String name) { // if (o < minValue) { // throw new IllegalArgumentException(MessageFormat.format(MIN_VALUE_ERR_MSG, name, minValue, o)); // } // } // // public static void checkMinValueArgument(long o, long minValue, String name) { // if (o < minValue) { // throw new IllegalArgumentException(MessageFormat.format(MIN_VALUE_ERR_MSG, name, minValue, o)); // } // } // // public static void checkNullArgument(Object o, String name) { // if (o == null) { // throw new IllegalArgumentException(MessageFormat.format(NULL_ERR_MSG, name)); // } // } // // public static void checkListSizeArgument(List a, String name, int length) { // if (a == null || a.size() != length) { // throw new IllegalArgumentException(MessageFormat.format(SIZE_ERR_MSG, name, length)); // } // } // // public static <T> void checkArrayLengthArgument(T[] a, String name, int length) { // if (a == null || a.length != length) { // throw new IllegalArgumentException(MessageFormat.format(LENGTH_ERR_MSG, name, length)); // } // } // // public static void checkArgument(boolean throwException, String message, Object... args) { // if (throwException) { // throw new IllegalArgumentException(MessageFormat.format(message, args)); // } // } // }
import net.jcip.annotations.NotThreadSafe; import org.poker.api.game.TexasHoldEmUtil.BetCommandType; import org.util.exceptions.ExceptionUtil;
/* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.game; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 */ @NotThreadSafe public class BetCommand { private final BetCommandType type; private long chips; public BetCommand(BetCommandType type) { this(type, 0); } public BetCommand(BetCommandType type, long chips) {
// Path: src/main/java/org/poker/api/game/TexasHoldEmUtil.java // public enum BetCommandType { // // ERROR, // TIMEOUT, // FOLD, // CHECK, // CALL, // RAISE, // ALL_IN // } // // Path: src/main/java/org/util/exceptions/ExceptionUtil.java // public final class ExceptionUtil { // // public static final String MIN_VALUE_ERR_MSG = "El argumento {0} no puede tener un valor inferior a <{1}> y tiene <{2}>."; // public static final String NULL_ERR_MSG = "El argumento {0} no puede ser nulo."; // public static final String LENGTH_ERR_MSG = "El argumento {0} no puede ser nulo y debe tener una longitud de {1}."; // public static final String SIZE_ERR_MSG = "El argumento {0} no puede ser nulo y debe tener {1} elementos."; // // private ExceptionUtil() { // } // // public static void checkMinValueArgument(int o, int minValue, String name) { // if (o < minValue) { // throw new IllegalArgumentException(MessageFormat.format(MIN_VALUE_ERR_MSG, name, minValue, o)); // } // } // // public static void checkMinValueArgument(long o, long minValue, String name) { // if (o < minValue) { // throw new IllegalArgumentException(MessageFormat.format(MIN_VALUE_ERR_MSG, name, minValue, o)); // } // } // // public static void checkNullArgument(Object o, String name) { // if (o == null) { // throw new IllegalArgumentException(MessageFormat.format(NULL_ERR_MSG, name)); // } // } // // public static void checkListSizeArgument(List a, String name, int length) { // if (a == null || a.size() != length) { // throw new IllegalArgumentException(MessageFormat.format(SIZE_ERR_MSG, name, length)); // } // } // // public static <T> void checkArrayLengthArgument(T[] a, String name, int length) { // if (a == null || a.length != length) { // throw new IllegalArgumentException(MessageFormat.format(LENGTH_ERR_MSG, name, length)); // } // } // // public static void checkArgument(boolean throwException, String message, Object... args) { // if (throwException) { // throw new IllegalArgumentException(MessageFormat.format(message, args)); // } // } // } // Path: src/main/java/org/poker/api/game/BetCommand.java import net.jcip.annotations.NotThreadSafe; import org.poker.api.game.TexasHoldEmUtil.BetCommandType; import org.util.exceptions.ExceptionUtil; /* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.game; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 */ @NotThreadSafe public class BetCommand { private final BetCommandType type; private long chips; public BetCommand(BetCommandType type) { this(type, 0); } public BetCommand(BetCommandType type, long chips) {
ExceptionUtil.checkNullArgument(type, "type");
dperezcabrera/jpoker
src/test/java/org/poker/api/core/CardTest.java
// Path: src/main/java/org/poker/api/core/Deck.java // public static List<Card> getAllCards() { // int numCards = Card.Suit.values().length * Card.Rank.values().length; // List<Card> result = new ArrayList<>(numCards); // for (Card.Suit suit : Card.Suit.values()) { // for (Card.Rank rank : Card.Rank.values()) { // result.add(new Card(suit, rank)); // } // } // return result; // }
import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.Test; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.not; import org.junit.Rule; import org.junit.rules.ExpectedException; import static org.poker.api.core.Deck.getAllCards;
Card instance = new Card(Card.Suit.CLUB, expRank); Card.Rank rankResult = instance.getRank(); assertEquals(expRank, rankResult); } @Test public void testContructorSuitNull() { System.out.println("card(SuitNull)"); Card.Suit expSuit = null; Card.Rank expRank = Card.Rank.TWO; thrown.expect(IllegalArgumentException.class); Card instance = new Card(expSuit, expRank); } @Test public void testContructorRankNull() { System.out.println("card(RankNull)"); Card.Suit expSuit = Card.Suit.CLUB; Card.Rank expRank = null; thrown.expect(IllegalArgumentException.class); Card instance = new Card(expSuit, expRank); } @Test public void testHashCode() { System.out.println("hashCode");
// Path: src/main/java/org/poker/api/core/Deck.java // public static List<Card> getAllCards() { // int numCards = Card.Suit.values().length * Card.Rank.values().length; // List<Card> result = new ArrayList<>(numCards); // for (Card.Suit suit : Card.Suit.values()) { // for (Card.Rank rank : Card.Rank.values()) { // result.add(new Card(suit, rank)); // } // } // return result; // } // Path: src/test/java/org/poker/api/core/CardTest.java import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.Test; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.not; import org.junit.Rule; import org.junit.rules.ExpectedException; import static org.poker.api.core.Deck.getAllCards; Card instance = new Card(Card.Suit.CLUB, expRank); Card.Rank rankResult = instance.getRank(); assertEquals(expRank, rankResult); } @Test public void testContructorSuitNull() { System.out.println("card(SuitNull)"); Card.Suit expSuit = null; Card.Rank expRank = Card.Rank.TWO; thrown.expect(IllegalArgumentException.class); Card instance = new Card(expSuit, expRank); } @Test public void testContructorRankNull() { System.out.println("card(RankNull)"); Card.Suit expSuit = Card.Suit.CLUB; Card.Rank expRank = null; thrown.expect(IllegalArgumentException.class); Card instance = new Card(expSuit, expRank); } @Test public void testHashCode() { System.out.println("hashCode");
List<Card> allCards = getAllCards();
dperezcabrera/jpoker
src/main/java/org/poker/api/game/IStrategy.java
// Path: src/main/java/org/poker/api/core/Card.java // @Immutable // public final class Card { // // private static final String STRING_RANK_CARDS = "23456789TJQKA"; // // public enum Suit { // // SPADE('♠'), HEART('♥'), DIAMOND('♦'), CLUB('♣'); // // private final char c; // // private Suit(char c) { // this.c = c; // } // // } // // public enum Rank { // // TWO, TRHEE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE // } // // private final Suit suit; // private final Rank rank; // // public Card(Suit suit, Rank rank) { // ExceptionUtil.checkNullArgument(rank, "rank"); // ExceptionUtil.checkNullArgument(suit, "suit"); // this.suit = suit; // this.rank = rank; // } // // public Suit getSuit() { // return suit; // } // // public Rank getRank() { // return rank; // } // // @Override // public int hashCode() { // return rank.ordinal() * Suit.values().length + suit.ordinal(); // } // // @Override // public boolean equals(Object obj) { // boolean result = true; // if (this != obj) { // result = false; // if (obj != null && getClass() == obj.getClass()) { // result = hashCode() == ((Card) obj).hashCode(); // } // } // return result; // } // // @Override // public String toString() { // return STRING_RANK_CARDS.substring(rank.ordinal(), rank.ordinal() + 1) + suit.c; // } // }
import java.util.List; import java.util.Map; import org.poker.api.core.Card;
/* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.game; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 */ @FunctionalInterface public interface IStrategy { public String getName(); public default BetCommand getCommand(GameInfo<PlayerInfo> state) { return null; } public default void initHand(GameInfo<PlayerInfo> state) { } public default void endHand(GameInfo<PlayerInfo> state) { } public default void endGame(Map<String, Double> scores) { }
// Path: src/main/java/org/poker/api/core/Card.java // @Immutable // public final class Card { // // private static final String STRING_RANK_CARDS = "23456789TJQKA"; // // public enum Suit { // // SPADE('♠'), HEART('♥'), DIAMOND('♦'), CLUB('♣'); // // private final char c; // // private Suit(char c) { // this.c = c; // } // // } // // public enum Rank { // // TWO, TRHEE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE // } // // private final Suit suit; // private final Rank rank; // // public Card(Suit suit, Rank rank) { // ExceptionUtil.checkNullArgument(rank, "rank"); // ExceptionUtil.checkNullArgument(suit, "suit"); // this.suit = suit; // this.rank = rank; // } // // public Suit getSuit() { // return suit; // } // // public Rank getRank() { // return rank; // } // // @Override // public int hashCode() { // return rank.ordinal() * Suit.values().length + suit.ordinal(); // } // // @Override // public boolean equals(Object obj) { // boolean result = true; // if (this != obj) { // result = false; // if (obj != null && getClass() == obj.getClass()) { // result = hashCode() == ((Card) obj).hashCode(); // } // } // return result; // } // // @Override // public String toString() { // return STRING_RANK_CARDS.substring(rank.ordinal(), rank.ordinal() + 1) + suit.c; // } // } // Path: src/main/java/org/poker/api/game/IStrategy.java import java.util.List; import java.util.Map; import org.poker.api.core.Card; /* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.game; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 */ @FunctionalInterface public interface IStrategy { public String getName(); public default BetCommand getCommand(GameInfo<PlayerInfo> state) { return null; } public default void initHand(GameInfo<PlayerInfo> state) { } public default void endHand(GameInfo<PlayerInfo> state) { } public default void endGame(Map<String, Double> scores) { }
public default void check(List<Card> communityCards) {
dperezcabrera/jpoker
src/test/java/org/poker/api/core/CardUtil4Testing.java
// Path: src/main/java/org/poker/api/core/Deck.java // public static List<Card> getAllCards() { // int numCards = Card.Suit.values().length * Card.Rank.values().length; // List<Card> result = new ArrayList<>(numCards); // for (Card.Suit suit : Card.Suit.values()) { // for (Card.Rank rank : Card.Rank.values()) { // result.add(new Card(suit, rank)); // } // } // return result; // }
import java.util.Map; import java.util.StringTokenizer; import java.util.stream.Collectors; import static org.poker.api.core.Deck.getAllCards;
/* * Copyright (C) 2015 David Perez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.core; /** * * @author David Perez Cabrera <dperezcabrera@gmail.com> */ public final class CardUtil4Testing { private static final String ARGUMENTO_NO_VALIDO = "Argumento {} no valido"; private static final int CARD_STRING_LENGTH = 2; private static final char SEPARATOR = ' ';
// Path: src/main/java/org/poker/api/core/Deck.java // public static List<Card> getAllCards() { // int numCards = Card.Suit.values().length * Card.Rank.values().length; // List<Card> result = new ArrayList<>(numCards); // for (Card.Suit suit : Card.Suit.values()) { // for (Card.Rank rank : Card.Rank.values()) { // result.add(new Card(suit, rank)); // } // } // return result; // } // Path: src/test/java/org/poker/api/core/CardUtil4Testing.java import java.util.Map; import java.util.StringTokenizer; import java.util.stream.Collectors; import static org.poker.api.core.Deck.getAllCards; /* * Copyright (C) 2015 David Perez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.api.core; /** * * @author David Perez Cabrera <dperezcabrera@gmail.com> */ public final class CardUtil4Testing { private static final String ARGUMENTO_NO_VALIDO = "Argumento {} no valido"; private static final int CARD_STRING_LENGTH = 2; private static final char SEPARATOR = ' ';
private static final Map<String, Card> STRING_TO_CARD = getAllCards().stream().collect(Collectors.groupingBy(Card::toString, Collectors.reducing(null, (c, t) -> t)));
dperezcabrera/jpoker
src/main/java/org/util/combinatorial/Combination.java
// Path: src/main/java/org/util/exceptions/ExceptionUtil.java // public final class ExceptionUtil { // // public static final String MIN_VALUE_ERR_MSG = "El argumento {0} no puede tener un valor inferior a <{1}> y tiene <{2}>."; // public static final String NULL_ERR_MSG = "El argumento {0} no puede ser nulo."; // public static final String LENGTH_ERR_MSG = "El argumento {0} no puede ser nulo y debe tener una longitud de {1}."; // public static final String SIZE_ERR_MSG = "El argumento {0} no puede ser nulo y debe tener {1} elementos."; // // private ExceptionUtil() { // } // // public static void checkMinValueArgument(int o, int minValue, String name) { // if (o < minValue) { // throw new IllegalArgumentException(MessageFormat.format(MIN_VALUE_ERR_MSG, name, minValue, o)); // } // } // // public static void checkMinValueArgument(long o, long minValue, String name) { // if (o < minValue) { // throw new IllegalArgumentException(MessageFormat.format(MIN_VALUE_ERR_MSG, name, minValue, o)); // } // } // // public static void checkNullArgument(Object o, String name) { // if (o == null) { // throw new IllegalArgumentException(MessageFormat.format(NULL_ERR_MSG, name)); // } // } // // public static void checkListSizeArgument(List a, String name, int length) { // if (a == null || a.size() != length) { // throw new IllegalArgumentException(MessageFormat.format(SIZE_ERR_MSG, name, length)); // } // } // // public static <T> void checkArrayLengthArgument(T[] a, String name, int length) { // if (a == null || a.length != length) { // throw new IllegalArgumentException(MessageFormat.format(LENGTH_ERR_MSG, name, length)); // } // } // // public static void checkArgument(boolean throwException, String message, Object... args) { // if (throwException) { // throw new IllegalArgumentException(MessageFormat.format(message, args)); // } // } // }
import net.jcip.annotations.NotThreadSafe; import org.util.exceptions.ExceptionUtil;
/* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.util.combinatorial; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 */ @NotThreadSafe public class Combination implements ICombinatorial { private final int items; private final int[] indexes; public Combination(int subItems, int items) {
// Path: src/main/java/org/util/exceptions/ExceptionUtil.java // public final class ExceptionUtil { // // public static final String MIN_VALUE_ERR_MSG = "El argumento {0} no puede tener un valor inferior a <{1}> y tiene <{2}>."; // public static final String NULL_ERR_MSG = "El argumento {0} no puede ser nulo."; // public static final String LENGTH_ERR_MSG = "El argumento {0} no puede ser nulo y debe tener una longitud de {1}."; // public static final String SIZE_ERR_MSG = "El argumento {0} no puede ser nulo y debe tener {1} elementos."; // // private ExceptionUtil() { // } // // public static void checkMinValueArgument(int o, int minValue, String name) { // if (o < minValue) { // throw new IllegalArgumentException(MessageFormat.format(MIN_VALUE_ERR_MSG, name, minValue, o)); // } // } // // public static void checkMinValueArgument(long o, long minValue, String name) { // if (o < minValue) { // throw new IllegalArgumentException(MessageFormat.format(MIN_VALUE_ERR_MSG, name, minValue, o)); // } // } // // public static void checkNullArgument(Object o, String name) { // if (o == null) { // throw new IllegalArgumentException(MessageFormat.format(NULL_ERR_MSG, name)); // } // } // // public static void checkListSizeArgument(List a, String name, int length) { // if (a == null || a.size() != length) { // throw new IllegalArgumentException(MessageFormat.format(SIZE_ERR_MSG, name, length)); // } // } // // public static <T> void checkArrayLengthArgument(T[] a, String name, int length) { // if (a == null || a.length != length) { // throw new IllegalArgumentException(MessageFormat.format(LENGTH_ERR_MSG, name, length)); // } // } // // public static void checkArgument(boolean throwException, String message, Object... args) { // if (throwException) { // throw new IllegalArgumentException(MessageFormat.format(message, args)); // } // } // } // Path: src/main/java/org/util/combinatorial/Combination.java import net.jcip.annotations.NotThreadSafe; import org.util.exceptions.ExceptionUtil; /* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.util.combinatorial; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 */ @NotThreadSafe public class Combination implements ICombinatorial { private final int items; private final int[] indexes; public Combination(int subItems, int items) {
ExceptionUtil.checkMinValueArgument(subItems, 1, "subItems");
dperezcabrera/jpoker
src/main/java/org/poker/gui/TexasHoldEmView.java
// Path: src/main/java/org/poker/api/game/IStrategy.java // @FunctionalInterface // public interface IStrategy { // // public String getName(); // // public default BetCommand getCommand(GameInfo<PlayerInfo> state) { // return null; // } // // public default void initHand(GameInfo<PlayerInfo> state) { // } // // public default void endHand(GameInfo<PlayerInfo> state) { // } // // public default void endGame(Map<String, Double> scores) { // } // // public default void check(List<Card> communityCards) { // } // // public default void onPlayerCommand(String player, BetCommand betCommand) { // } // }
import org.poker.api.game.IStrategy; import static org.poker.gui.ImageManager.IMAGES_PATH;
/* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.gui; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 */ public class TexasHoldEmView extends javax.swing.JFrame { private static final int WINDOW_HEIGHT = 800; private static final int WINDOW_WITH = 1280; private static final String WINDOW_TITLE = "J Poker"; private static final String WINDOW_ICON = IMAGES_PATH + "poker-chip.png"; private TexasHoldEmTablePanel jTablePanel;
// Path: src/main/java/org/poker/api/game/IStrategy.java // @FunctionalInterface // public interface IStrategy { // // public String getName(); // // public default BetCommand getCommand(GameInfo<PlayerInfo> state) { // return null; // } // // public default void initHand(GameInfo<PlayerInfo> state) { // } // // public default void endHand(GameInfo<PlayerInfo> state) { // } // // public default void endGame(Map<String, Double> scores) { // } // // public default void check(List<Card> communityCards) { // } // // public default void onPlayerCommand(String player, BetCommand betCommand) { // } // } // Path: src/main/java/org/poker/gui/TexasHoldEmView.java import org.poker.api.game.IStrategy; import static org.poker.gui.ImageManager.IMAGES_PATH; /* * Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.poker.gui; /** * * @author David Pérez Cabrera <dperezcabrera@gmail.com> * @since 1.0.0 */ public class TexasHoldEmView extends javax.swing.JFrame { private static final int WINDOW_HEIGHT = 800; private static final int WINDOW_WITH = 1280; private static final String WINDOW_TITLE = "J Poker"; private static final String WINDOW_ICON = IMAGES_PATH + "poker-chip.png"; private TexasHoldEmTablePanel jTablePanel;
public TexasHoldEmView(IStrategy delegate) {
thomas-kendall/trivia-microservices
trivia-user-management-service/src/main/java/trivia/usermanagement/service/UserManagementService.java
// Path: trivia-user-management-service/src/main/java/trivia/usermanagement/dto/RoleDTO.java // public class RoleDTO { // public int id; // public String name; // // public RoleDTO() { // } // // public RoleDTO(int id, String name) { // this.id = id; // this.name = name; // } // // public RoleDTO(String name) { // this.name = name; // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/dto/UserDTO.java // public class UserDTO { // public int id; // public String email; // public String password; // public Collection<Integer> roleIds; // // public UserDTO() { // } // // public UserDTO(int id, String email, Collection<Integer> roleIds) { // this.id = id; // this.email = email; // this.roleIds = roleIds; // } // // public UserDTO(String email, String password, Collection<Integer> roleIds) { // this.email = email; // this.password = password; // this.roleIds = roleIds; // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/model/Role.java // @Entity // public class Role { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // private String name; // // protected Role() { // // } // // public Role(String name) { // this.name = name; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public void setId(int id) { // this.id = id; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return String.format("Role[id=%d, name=%s]", id, name); // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/model/User.java // @Entity // public class User { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // private String email; // // @ManyToMany // @JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) // private Set<Role> roles; // // // For simplicity sake, we keep a simple hash code. In the real world, we // // would do something better. // private int passwordHash; // // protected User() { // } // // public User(String email, String password) { // this.email = email; // setPassword(password); // } // // public User(String email, String password, Set<Role> roles) { // this.email = email; // setPassword(password); // this.roles = roles; // } // // public String getEmail() { // return email; // } // // public int getId() { // return id; // } // // public int getPasswordHash() { // return passwordHash; // } // // public Set<Role> getRoles() { // return roles; // } // // public void setEmail(String email) { // this.email = email; // } // // public void setId(int id) { // this.id = id; // } // // public void setPassword(String password) { // int hc = password.hashCode(); // setPasswordHash(hc); // } // // public void setPasswordHash(int passwordHash) { // this.passwordHash = passwordHash; // } // // public void setRoles(Set<Role> roles) { // this.roles = roles; // } // // @Override // public String toString() { // String rolesString = ""; // if (roles != null) { // for (Role role : roles) { // rolesString += role.toString(); // } // } // // return String.format("User[id=%d, email=%s, roles=%s]", id, email, rolesString); // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/repository/RoleRepository.java // @Repository // public interface RoleRepository extends JpaRepository<Role, Integer> { // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/repository/UserRepository.java // @Repository // public interface UserRepository extends JpaRepository<User, Integer> { // public User findByEmail(String email); // }
import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import trivia.usermanagement.dto.RoleDTO; import trivia.usermanagement.dto.UserDTO; import trivia.usermanagement.model.Role; import trivia.usermanagement.model.User; import trivia.usermanagement.repository.RoleRepository; import trivia.usermanagement.repository.UserRepository;
package trivia.usermanagement.service; @Service @Transactional public class UserManagementService { @Autowired
// Path: trivia-user-management-service/src/main/java/trivia/usermanagement/dto/RoleDTO.java // public class RoleDTO { // public int id; // public String name; // // public RoleDTO() { // } // // public RoleDTO(int id, String name) { // this.id = id; // this.name = name; // } // // public RoleDTO(String name) { // this.name = name; // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/dto/UserDTO.java // public class UserDTO { // public int id; // public String email; // public String password; // public Collection<Integer> roleIds; // // public UserDTO() { // } // // public UserDTO(int id, String email, Collection<Integer> roleIds) { // this.id = id; // this.email = email; // this.roleIds = roleIds; // } // // public UserDTO(String email, String password, Collection<Integer> roleIds) { // this.email = email; // this.password = password; // this.roleIds = roleIds; // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/model/Role.java // @Entity // public class Role { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // private String name; // // protected Role() { // // } // // public Role(String name) { // this.name = name; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public void setId(int id) { // this.id = id; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return String.format("Role[id=%d, name=%s]", id, name); // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/model/User.java // @Entity // public class User { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // private String email; // // @ManyToMany // @JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) // private Set<Role> roles; // // // For simplicity sake, we keep a simple hash code. In the real world, we // // would do something better. // private int passwordHash; // // protected User() { // } // // public User(String email, String password) { // this.email = email; // setPassword(password); // } // // public User(String email, String password, Set<Role> roles) { // this.email = email; // setPassword(password); // this.roles = roles; // } // // public String getEmail() { // return email; // } // // public int getId() { // return id; // } // // public int getPasswordHash() { // return passwordHash; // } // // public Set<Role> getRoles() { // return roles; // } // // public void setEmail(String email) { // this.email = email; // } // // public void setId(int id) { // this.id = id; // } // // public void setPassword(String password) { // int hc = password.hashCode(); // setPasswordHash(hc); // } // // public void setPasswordHash(int passwordHash) { // this.passwordHash = passwordHash; // } // // public void setRoles(Set<Role> roles) { // this.roles = roles; // } // // @Override // public String toString() { // String rolesString = ""; // if (roles != null) { // for (Role role : roles) { // rolesString += role.toString(); // } // } // // return String.format("User[id=%d, email=%s, roles=%s]", id, email, rolesString); // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/repository/RoleRepository.java // @Repository // public interface RoleRepository extends JpaRepository<Role, Integer> { // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/repository/UserRepository.java // @Repository // public interface UserRepository extends JpaRepository<User, Integer> { // public User findByEmail(String email); // } // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/service/UserManagementService.java import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import trivia.usermanagement.dto.RoleDTO; import trivia.usermanagement.dto.UserDTO; import trivia.usermanagement.model.Role; import trivia.usermanagement.model.User; import trivia.usermanagement.repository.RoleRepository; import trivia.usermanagement.repository.UserRepository; package trivia.usermanagement.service; @Service @Transactional public class UserManagementService { @Autowired
private RoleRepository roleRepository;
thomas-kendall/trivia-microservices
trivia-user-management-service/src/main/java/trivia/usermanagement/service/UserManagementService.java
// Path: trivia-user-management-service/src/main/java/trivia/usermanagement/dto/RoleDTO.java // public class RoleDTO { // public int id; // public String name; // // public RoleDTO() { // } // // public RoleDTO(int id, String name) { // this.id = id; // this.name = name; // } // // public RoleDTO(String name) { // this.name = name; // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/dto/UserDTO.java // public class UserDTO { // public int id; // public String email; // public String password; // public Collection<Integer> roleIds; // // public UserDTO() { // } // // public UserDTO(int id, String email, Collection<Integer> roleIds) { // this.id = id; // this.email = email; // this.roleIds = roleIds; // } // // public UserDTO(String email, String password, Collection<Integer> roleIds) { // this.email = email; // this.password = password; // this.roleIds = roleIds; // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/model/Role.java // @Entity // public class Role { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // private String name; // // protected Role() { // // } // // public Role(String name) { // this.name = name; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public void setId(int id) { // this.id = id; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return String.format("Role[id=%d, name=%s]", id, name); // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/model/User.java // @Entity // public class User { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // private String email; // // @ManyToMany // @JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) // private Set<Role> roles; // // // For simplicity sake, we keep a simple hash code. In the real world, we // // would do something better. // private int passwordHash; // // protected User() { // } // // public User(String email, String password) { // this.email = email; // setPassword(password); // } // // public User(String email, String password, Set<Role> roles) { // this.email = email; // setPassword(password); // this.roles = roles; // } // // public String getEmail() { // return email; // } // // public int getId() { // return id; // } // // public int getPasswordHash() { // return passwordHash; // } // // public Set<Role> getRoles() { // return roles; // } // // public void setEmail(String email) { // this.email = email; // } // // public void setId(int id) { // this.id = id; // } // // public void setPassword(String password) { // int hc = password.hashCode(); // setPasswordHash(hc); // } // // public void setPasswordHash(int passwordHash) { // this.passwordHash = passwordHash; // } // // public void setRoles(Set<Role> roles) { // this.roles = roles; // } // // @Override // public String toString() { // String rolesString = ""; // if (roles != null) { // for (Role role : roles) { // rolesString += role.toString(); // } // } // // return String.format("User[id=%d, email=%s, roles=%s]", id, email, rolesString); // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/repository/RoleRepository.java // @Repository // public interface RoleRepository extends JpaRepository<Role, Integer> { // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/repository/UserRepository.java // @Repository // public interface UserRepository extends JpaRepository<User, Integer> { // public User findByEmail(String email); // }
import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import trivia.usermanagement.dto.RoleDTO; import trivia.usermanagement.dto.UserDTO; import trivia.usermanagement.model.Role; import trivia.usermanagement.model.User; import trivia.usermanagement.repository.RoleRepository; import trivia.usermanagement.repository.UserRepository;
package trivia.usermanagement.service; @Service @Transactional public class UserManagementService { @Autowired private RoleRepository roleRepository; @Autowired
// Path: trivia-user-management-service/src/main/java/trivia/usermanagement/dto/RoleDTO.java // public class RoleDTO { // public int id; // public String name; // // public RoleDTO() { // } // // public RoleDTO(int id, String name) { // this.id = id; // this.name = name; // } // // public RoleDTO(String name) { // this.name = name; // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/dto/UserDTO.java // public class UserDTO { // public int id; // public String email; // public String password; // public Collection<Integer> roleIds; // // public UserDTO() { // } // // public UserDTO(int id, String email, Collection<Integer> roleIds) { // this.id = id; // this.email = email; // this.roleIds = roleIds; // } // // public UserDTO(String email, String password, Collection<Integer> roleIds) { // this.email = email; // this.password = password; // this.roleIds = roleIds; // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/model/Role.java // @Entity // public class Role { // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // private String name; // // protected Role() { // // } // // public Role(String name) { // this.name = name; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public void setId(int id) { // this.id = id; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return String.format("Role[id=%d, name=%s]", id, name); // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/model/User.java // @Entity // public class User { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private int id; // // private String email; // // @ManyToMany // @JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) // private Set<Role> roles; // // // For simplicity sake, we keep a simple hash code. In the real world, we // // would do something better. // private int passwordHash; // // protected User() { // } // // public User(String email, String password) { // this.email = email; // setPassword(password); // } // // public User(String email, String password, Set<Role> roles) { // this.email = email; // setPassword(password); // this.roles = roles; // } // // public String getEmail() { // return email; // } // // public int getId() { // return id; // } // // public int getPasswordHash() { // return passwordHash; // } // // public Set<Role> getRoles() { // return roles; // } // // public void setEmail(String email) { // this.email = email; // } // // public void setId(int id) { // this.id = id; // } // // public void setPassword(String password) { // int hc = password.hashCode(); // setPasswordHash(hc); // } // // public void setPasswordHash(int passwordHash) { // this.passwordHash = passwordHash; // } // // public void setRoles(Set<Role> roles) { // this.roles = roles; // } // // @Override // public String toString() { // String rolesString = ""; // if (roles != null) { // for (Role role : roles) { // rolesString += role.toString(); // } // } // // return String.format("User[id=%d, email=%s, roles=%s]", id, email, rolesString); // } // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/repository/RoleRepository.java // @Repository // public interface RoleRepository extends JpaRepository<Role, Integer> { // } // // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/repository/UserRepository.java // @Repository // public interface UserRepository extends JpaRepository<User, Integer> { // public User findByEmail(String email); // } // Path: trivia-user-management-service/src/main/java/trivia/usermanagement/service/UserManagementService.java import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import trivia.usermanagement.dto.RoleDTO; import trivia.usermanagement.dto.UserDTO; import trivia.usermanagement.model.Role; import trivia.usermanagement.model.User; import trivia.usermanagement.repository.RoleRepository; import trivia.usermanagement.repository.UserRepository; package trivia.usermanagement.service; @Service @Transactional public class UserManagementService { @Autowired private RoleRepository roleRepository; @Autowired
private UserRepository userRepository;