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 |
|---|---|---|---|---|---|---|
CyberCRI/RedMetrics | src/test/java/org/cri/redmetrics/GameBackendTest.java | // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/GameBackend.java
// public class GameBackend extends HttpBackend<TestGame> {
//
// GameBackend() {
// super("game", TestGame.class);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/GameVersionBackend.java
// public class GameVersionBackend extends HttpBackend<TestGameVersion> {
//
// GameVersionBackend() {
// super("gameVersion", TestGameVersion.class);
// }
//
// public List<TestGameVersion> getGameVersions(String gameId) throws IOException {
// GenericUrl url = new GenericUrl(BASE_PATH + "game/" + gameId + "/versions");
// return (List<TestGameVersion>) requestFactory.buildGetRequest(url).execute().parseAs(arrayType);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGame.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGame extends TestEntity {
//
// @Key
// private String adminKey;
//
// @Key
// private String name;
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGameVersion extends TestEntity {
//
// @Key
// private String game;
//
// @Key
// private String name = "v1";
//
// }
| import com.google.api.client.http.HttpResponseException;
import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.GameBackend;
import org.cri.redmetrics.backend.GameVersionBackend;
import org.cri.redmetrics.model.TestGame;
import org.cri.redmetrics.model.TestGameVersion;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.failBecauseExceptionWasNotThrown; | package org.cri.redmetrics;
public class GameBackendTest {
static final GameBackend games = Backends.GAME; | // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/GameBackend.java
// public class GameBackend extends HttpBackend<TestGame> {
//
// GameBackend() {
// super("game", TestGame.class);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/GameVersionBackend.java
// public class GameVersionBackend extends HttpBackend<TestGameVersion> {
//
// GameVersionBackend() {
// super("gameVersion", TestGameVersion.class);
// }
//
// public List<TestGameVersion> getGameVersions(String gameId) throws IOException {
// GenericUrl url = new GenericUrl(BASE_PATH + "game/" + gameId + "/versions");
// return (List<TestGameVersion>) requestFactory.buildGetRequest(url).execute().parseAs(arrayType);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGame.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGame extends TestEntity {
//
// @Key
// private String adminKey;
//
// @Key
// private String name;
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGameVersion extends TestEntity {
//
// @Key
// private String game;
//
// @Key
// private String name = "v1";
//
// }
// Path: src/test/java/org/cri/redmetrics/GameBackendTest.java
import com.google.api.client.http.HttpResponseException;
import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.GameBackend;
import org.cri.redmetrics.backend.GameVersionBackend;
import org.cri.redmetrics.model.TestGame;
import org.cri.redmetrics.model.TestGameVersion;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.failBecauseExceptionWasNotThrown;
package org.cri.redmetrics;
public class GameBackendTest {
static final GameBackend games = Backends.GAME; | static final GameVersionBackend gameVersions = Backends.GAME_VERSION; |
CyberCRI/RedMetrics | src/test/java/org/cri/redmetrics/GameBackendTest.java | // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/GameBackend.java
// public class GameBackend extends HttpBackend<TestGame> {
//
// GameBackend() {
// super("game", TestGame.class);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/GameVersionBackend.java
// public class GameVersionBackend extends HttpBackend<TestGameVersion> {
//
// GameVersionBackend() {
// super("gameVersion", TestGameVersion.class);
// }
//
// public List<TestGameVersion> getGameVersions(String gameId) throws IOException {
// GenericUrl url = new GenericUrl(BASE_PATH + "game/" + gameId + "/versions");
// return (List<TestGameVersion>) requestFactory.buildGetRequest(url).execute().parseAs(arrayType);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGame.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGame extends TestEntity {
//
// @Key
// private String adminKey;
//
// @Key
// private String name;
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGameVersion extends TestEntity {
//
// @Key
// private String game;
//
// @Key
// private String name = "v1";
//
// }
| import com.google.api.client.http.HttpResponseException;
import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.GameBackend;
import org.cri.redmetrics.backend.GameVersionBackend;
import org.cri.redmetrics.model.TestGame;
import org.cri.redmetrics.model.TestGameVersion;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.failBecauseExceptionWasNotThrown; | package org.cri.redmetrics;
public class GameBackendTest {
static final GameBackend games = Backends.GAME;
static final GameVersionBackend gameVersions = Backends.GAME_VERSION;
static final String GAME_NAME = "Asteroids";
static final String UPDATED_GAME_NAME = "Gasteroids";
| // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/GameBackend.java
// public class GameBackend extends HttpBackend<TestGame> {
//
// GameBackend() {
// super("game", TestGame.class);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/GameVersionBackend.java
// public class GameVersionBackend extends HttpBackend<TestGameVersion> {
//
// GameVersionBackend() {
// super("gameVersion", TestGameVersion.class);
// }
//
// public List<TestGameVersion> getGameVersions(String gameId) throws IOException {
// GenericUrl url = new GenericUrl(BASE_PATH + "game/" + gameId + "/versions");
// return (List<TestGameVersion>) requestFactory.buildGetRequest(url).execute().parseAs(arrayType);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGame.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGame extends TestEntity {
//
// @Key
// private String adminKey;
//
// @Key
// private String name;
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGameVersion extends TestEntity {
//
// @Key
// private String game;
//
// @Key
// private String name = "v1";
//
// }
// Path: src/test/java/org/cri/redmetrics/GameBackendTest.java
import com.google.api.client.http.HttpResponseException;
import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.GameBackend;
import org.cri.redmetrics.backend.GameVersionBackend;
import org.cri.redmetrics.model.TestGame;
import org.cri.redmetrics.model.TestGameVersion;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.failBecauseExceptionWasNotThrown;
package org.cri.redmetrics;
public class GameBackendTest {
static final GameBackend games = Backends.GAME;
static final GameVersionBackend gameVersions = Backends.GAME_VERSION;
static final String GAME_NAME = "Asteroids";
static final String UPDATED_GAME_NAME = "Gasteroids";
| TestGame createdGame; |
CyberCRI/RedMetrics | src/test/java/org/cri/redmetrics/GameBackendTest.java | // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/GameBackend.java
// public class GameBackend extends HttpBackend<TestGame> {
//
// GameBackend() {
// super("game", TestGame.class);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/GameVersionBackend.java
// public class GameVersionBackend extends HttpBackend<TestGameVersion> {
//
// GameVersionBackend() {
// super("gameVersion", TestGameVersion.class);
// }
//
// public List<TestGameVersion> getGameVersions(String gameId) throws IOException {
// GenericUrl url = new GenericUrl(BASE_PATH + "game/" + gameId + "/versions");
// return (List<TestGameVersion>) requestFactory.buildGetRequest(url).execute().parseAs(arrayType);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGame.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGame extends TestEntity {
//
// @Key
// private String adminKey;
//
// @Key
// private String name;
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGameVersion extends TestEntity {
//
// @Key
// private String game;
//
// @Key
// private String name = "v1";
//
// }
| import com.google.api.client.http.HttpResponseException;
import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.GameBackend;
import org.cri.redmetrics.backend.GameVersionBackend;
import org.cri.redmetrics.model.TestGame;
import org.cri.redmetrics.model.TestGameVersion;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.failBecauseExceptionWasNotThrown; | @Test
public void shouldForbidUnnamedGameCreation() throws IOException {
try {
games.post(new TestGame());
failBecauseExceptionWasNotThrown(HttpResponseException.class);
} catch (HttpResponseException e) {
assertThat(e.getStatusCode()).isEqualTo(400);
}
}
// READ
@Test
public void canReadGame() throws IOException {
TestGame readGame = games.getById(createdGame.getId());
assertThat(readGame.getName()).isEqualTo(GAME_NAME);
}
@Test
public void shouldFailWhenReadingUnknownId() throws IOException {
try {
games.getById(UUID.randomUUID().toString());
failBecauseExceptionWasNotThrown(HttpResponseException.class);
} catch (HttpResponseException e) {
assertThat(e.getStatusCode()).isEqualTo(404);
}
}
@Test
public void canFindGameVersions() throws IOException { | // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/GameBackend.java
// public class GameBackend extends HttpBackend<TestGame> {
//
// GameBackend() {
// super("game", TestGame.class);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/GameVersionBackend.java
// public class GameVersionBackend extends HttpBackend<TestGameVersion> {
//
// GameVersionBackend() {
// super("gameVersion", TestGameVersion.class);
// }
//
// public List<TestGameVersion> getGameVersions(String gameId) throws IOException {
// GenericUrl url = new GenericUrl(BASE_PATH + "game/" + gameId + "/versions");
// return (List<TestGameVersion>) requestFactory.buildGetRequest(url).execute().parseAs(arrayType);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGame.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGame extends TestEntity {
//
// @Key
// private String adminKey;
//
// @Key
// private String name;
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGameVersion extends TestEntity {
//
// @Key
// private String game;
//
// @Key
// private String name = "v1";
//
// }
// Path: src/test/java/org/cri/redmetrics/GameBackendTest.java
import com.google.api.client.http.HttpResponseException;
import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.GameBackend;
import org.cri.redmetrics.backend.GameVersionBackend;
import org.cri.redmetrics.model.TestGame;
import org.cri.redmetrics.model.TestGameVersion;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.failBecauseExceptionWasNotThrown;
@Test
public void shouldForbidUnnamedGameCreation() throws IOException {
try {
games.post(new TestGame());
failBecauseExceptionWasNotThrown(HttpResponseException.class);
} catch (HttpResponseException e) {
assertThat(e.getStatusCode()).isEqualTo(400);
}
}
// READ
@Test
public void canReadGame() throws IOException {
TestGame readGame = games.getById(createdGame.getId());
assertThat(readGame.getName()).isEqualTo(GAME_NAME);
}
@Test
public void shouldFailWhenReadingUnknownId() throws IOException {
try {
games.getById(UUID.randomUUID().toString());
failBecauseExceptionWasNotThrown(HttpResponseException.class);
} catch (HttpResponseException e) {
assertThat(e.getStatusCode()).isEqualTo(404);
}
}
@Test
public void canFindGameVersions() throws IOException { | TestGameVersion gameVersion1 = new TestGameVersion(); |
CyberCRI/RedMetrics | src/test/java/org/cri/redmetrics/GameVersionBackendTest.java | // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/GameBackend.java
// public class GameBackend extends HttpBackend<TestGame> {
//
// GameBackend() {
// super("game", TestGame.class);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/GameVersionBackend.java
// public class GameVersionBackend extends HttpBackend<TestGameVersion> {
//
// GameVersionBackend() {
// super("gameVersion", TestGameVersion.class);
// }
//
// public List<TestGameVersion> getGameVersions(String gameId) throws IOException {
// GenericUrl url = new GenericUrl(BASE_PATH + "game/" + gameId + "/versions");
// return (List<TestGameVersion>) requestFactory.buildGetRequest(url).execute().parseAs(arrayType);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGame.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGame extends TestEntity {
//
// @Key
// private String adminKey;
//
// @Key
// private String name;
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGameVersion extends TestEntity {
//
// @Key
// private String game;
//
// @Key
// private String name = "v1";
//
// }
| import java.io.IOException;
import java.util.ArrayList;
import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.GameBackend;
import org.cri.redmetrics.backend.GameVersionBackend;
import org.cri.redmetrics.model.TestGame;
import org.cri.redmetrics.model.TestGameVersion;
import static org.fest.assertions.api.Assertions.assertThat;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test; | package org.cri.redmetrics;
public class GameVersionBackendTest {
static final GameBackend games = Backends.GAME; | // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/GameBackend.java
// public class GameBackend extends HttpBackend<TestGame> {
//
// GameBackend() {
// super("game", TestGame.class);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/GameVersionBackend.java
// public class GameVersionBackend extends HttpBackend<TestGameVersion> {
//
// GameVersionBackend() {
// super("gameVersion", TestGameVersion.class);
// }
//
// public List<TestGameVersion> getGameVersions(String gameId) throws IOException {
// GenericUrl url = new GenericUrl(BASE_PATH + "game/" + gameId + "/versions");
// return (List<TestGameVersion>) requestFactory.buildGetRequest(url).execute().parseAs(arrayType);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGame.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGame extends TestEntity {
//
// @Key
// private String adminKey;
//
// @Key
// private String name;
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGameVersion extends TestEntity {
//
// @Key
// private String game;
//
// @Key
// private String name = "v1";
//
// }
// Path: src/test/java/org/cri/redmetrics/GameVersionBackendTest.java
import java.io.IOException;
import java.util.ArrayList;
import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.GameBackend;
import org.cri.redmetrics.backend.GameVersionBackend;
import org.cri.redmetrics.model.TestGame;
import org.cri.redmetrics.model.TestGameVersion;
import static org.fest.assertions.api.Assertions.assertThat;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
package org.cri.redmetrics;
public class GameVersionBackendTest {
static final GameBackend games = Backends.GAME; | static final GameVersionBackend gameVersions = Backends.GAME_VERSION; |
CyberCRI/RedMetrics | src/test/java/org/cri/redmetrics/GameVersionBackendTest.java | // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/GameBackend.java
// public class GameBackend extends HttpBackend<TestGame> {
//
// GameBackend() {
// super("game", TestGame.class);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/GameVersionBackend.java
// public class GameVersionBackend extends HttpBackend<TestGameVersion> {
//
// GameVersionBackend() {
// super("gameVersion", TestGameVersion.class);
// }
//
// public List<TestGameVersion> getGameVersions(String gameId) throws IOException {
// GenericUrl url = new GenericUrl(BASE_PATH + "game/" + gameId + "/versions");
// return (List<TestGameVersion>) requestFactory.buildGetRequest(url).execute().parseAs(arrayType);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGame.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGame extends TestEntity {
//
// @Key
// private String adminKey;
//
// @Key
// private String name;
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGameVersion extends TestEntity {
//
// @Key
// private String game;
//
// @Key
// private String name = "v1";
//
// }
| import java.io.IOException;
import java.util.ArrayList;
import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.GameBackend;
import org.cri.redmetrics.backend.GameVersionBackend;
import org.cri.redmetrics.model.TestGame;
import org.cri.redmetrics.model.TestGameVersion;
import static org.fest.assertions.api.Assertions.assertThat;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test; | package org.cri.redmetrics;
public class GameVersionBackendTest {
static final GameBackend games = Backends.GAME;
static final GameVersionBackend gameVersions = Backends.GAME_VERSION;
static final String GAME_NAMES[] = {"I wanna be the dude", "Call of pupy", "Tong Rider", "Partial Annihilation"};
static final String[] GAME_VERSION_NAMES = {"V12", "alpha0.2", "Gamma3", "W3.1"};
| // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/GameBackend.java
// public class GameBackend extends HttpBackend<TestGame> {
//
// GameBackend() {
// super("game", TestGame.class);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/GameVersionBackend.java
// public class GameVersionBackend extends HttpBackend<TestGameVersion> {
//
// GameVersionBackend() {
// super("gameVersion", TestGameVersion.class);
// }
//
// public List<TestGameVersion> getGameVersions(String gameId) throws IOException {
// GenericUrl url = new GenericUrl(BASE_PATH + "game/" + gameId + "/versions");
// return (List<TestGameVersion>) requestFactory.buildGetRequest(url).execute().parseAs(arrayType);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGame.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGame extends TestEntity {
//
// @Key
// private String adminKey;
//
// @Key
// private String name;
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGameVersion extends TestEntity {
//
// @Key
// private String game;
//
// @Key
// private String name = "v1";
//
// }
// Path: src/test/java/org/cri/redmetrics/GameVersionBackendTest.java
import java.io.IOException;
import java.util.ArrayList;
import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.GameBackend;
import org.cri.redmetrics.backend.GameVersionBackend;
import org.cri.redmetrics.model.TestGame;
import org.cri.redmetrics.model.TestGameVersion;
import static org.fest.assertions.api.Assertions.assertThat;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
package org.cri.redmetrics;
public class GameVersionBackendTest {
static final GameBackend games = Backends.GAME;
static final GameVersionBackend gameVersions = Backends.GAME_VERSION;
static final String GAME_NAMES[] = {"I wanna be the dude", "Call of pupy", "Tong Rider", "Partial Annihilation"};
static final String[] GAME_VERSION_NAMES = {"V12", "alpha0.2", "Gamma3", "W3.1"};
| ArrayList<TestGame> createdGames = new ArrayList<>(); |
CyberCRI/RedMetrics | src/test/java/org/cri/redmetrics/GameVersionBackendTest.java | // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/GameBackend.java
// public class GameBackend extends HttpBackend<TestGame> {
//
// GameBackend() {
// super("game", TestGame.class);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/GameVersionBackend.java
// public class GameVersionBackend extends HttpBackend<TestGameVersion> {
//
// GameVersionBackend() {
// super("gameVersion", TestGameVersion.class);
// }
//
// public List<TestGameVersion> getGameVersions(String gameId) throws IOException {
// GenericUrl url = new GenericUrl(BASE_PATH + "game/" + gameId + "/versions");
// return (List<TestGameVersion>) requestFactory.buildGetRequest(url).execute().parseAs(arrayType);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGame.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGame extends TestEntity {
//
// @Key
// private String adminKey;
//
// @Key
// private String name;
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGameVersion extends TestEntity {
//
// @Key
// private String game;
//
// @Key
// private String name = "v1";
//
// }
| import java.io.IOException;
import java.util.ArrayList;
import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.GameBackend;
import org.cri.redmetrics.backend.GameVersionBackend;
import org.cri.redmetrics.model.TestGame;
import org.cri.redmetrics.model.TestGameVersion;
import static org.fest.assertions.api.Assertions.assertThat;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test; | package org.cri.redmetrics;
public class GameVersionBackendTest {
static final GameBackend games = Backends.GAME;
static final GameVersionBackend gameVersions = Backends.GAME_VERSION;
static final String GAME_NAMES[] = {"I wanna be the dude", "Call of pupy", "Tong Rider", "Partial Annihilation"};
static final String[] GAME_VERSION_NAMES = {"V12", "alpha0.2", "Gamma3", "W3.1"};
ArrayList<TestGame> createdGames = new ArrayList<>(); | // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/GameBackend.java
// public class GameBackend extends HttpBackend<TestGame> {
//
// GameBackend() {
// super("game", TestGame.class);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/GameVersionBackend.java
// public class GameVersionBackend extends HttpBackend<TestGameVersion> {
//
// GameVersionBackend() {
// super("gameVersion", TestGameVersion.class);
// }
//
// public List<TestGameVersion> getGameVersions(String gameId) throws IOException {
// GenericUrl url = new GenericUrl(BASE_PATH + "game/" + gameId + "/versions");
// return (List<TestGameVersion>) requestFactory.buildGetRequest(url).execute().parseAs(arrayType);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGame.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGame extends TestEntity {
//
// @Key
// private String adminKey;
//
// @Key
// private String name;
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGameVersion extends TestEntity {
//
// @Key
// private String game;
//
// @Key
// private String name = "v1";
//
// }
// Path: src/test/java/org/cri/redmetrics/GameVersionBackendTest.java
import java.io.IOException;
import java.util.ArrayList;
import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.GameBackend;
import org.cri.redmetrics.backend.GameVersionBackend;
import org.cri.redmetrics.model.TestGame;
import org.cri.redmetrics.model.TestGameVersion;
import static org.fest.assertions.api.Assertions.assertThat;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
package org.cri.redmetrics;
public class GameVersionBackendTest {
static final GameBackend games = Backends.GAME;
static final GameVersionBackend gameVersions = Backends.GAME_VERSION;
static final String GAME_NAMES[] = {"I wanna be the dude", "Call of pupy", "Tong Rider", "Partial Annihilation"};
static final String[] GAME_VERSION_NAMES = {"V12", "alpha0.2", "Gamma3", "W3.1"};
ArrayList<TestGame> createdGames = new ArrayList<>(); | ArrayList<TestGameVersion> createdVersions = new ArrayList<>(); |
CyberCRI/RedMetrics | src/main/java/org/cri/redmetrics/json/JsonConverter.java | // Path: src/main/java/org/cri/redmetrics/model/Entity.java
// @Data
// public abstract class Entity {
//
// public static UUID parseId(String id) {
// return UUID.fromString(id);
// }
//
// @DatabaseField(generatedId = true)
// private UUID id;
//
// @DatabaseField(columnDefinition = "text")
// private String customData;
//
// }
//
// Path: src/main/java/org/cri/redmetrics/util/RouteHelper.java
// public class RouteHelper {
//
// public enum HttpVerb {
// GET,
// POST,
// PUT,
// DELETE,
// OPTIONS
// }
//
// public enum ContentType {
// JSON,
// CSV
// }
//
// public enum DataType {
// ENTITY,
// ENTITY_OR_ID_LIST,
// ENTITY_LIST_OR_RESULTS_PAGE,
// BIN_COUNT_LIST
// }
//
// public static ContentType determineContentType(Request request) {
// // If the user requests a format in the URL
// if(request.url().endsWith(".json")) {
// return ContentType.JSON;
// }
// else if(request.url().endsWith(".csv")) {
// return ContentType.CSV;
// }
//
// // If the user requests a format in the query string
// if(request.queryMap("format").hasValue()) {
// if ("json".equalsIgnoreCase(request.queryMap("format").value())) {
// return ContentType.JSON;
// }
// if ("csv".equalsIgnoreCase(request.queryMap("format").value())) {
// return ContentType.CSV;
// }
//
// throw new IllegalArgumentException("Incorrect format requested. Only CSV or JSON is recognized");
// }
//
// // If the user requests a format in the header
// if(request.headers("Accept") != null) {
// List<String> acceptedContentTypes = Arrays.asList(request.headers("Accept").split(","));
// if(acceptedContentTypes.contains("application/json")) {
// return ContentType.JSON;
// }
// if(acceptedContentTypes.contains("text/csv")) {
// return ContentType.CSV;
// }
// }
//
// // No format specified, so default to JSON
// return ContentType.JSON;
// }
//
//
// protected final JsonConverter jsonConverter;
// protected final CsvResponseTransformer csvResponseTransformer;
//
// public RouteHelper(JsonConverter jsonConverter, CsvResponseTransformer csvResponseTransformer) {
// this.jsonConverter = jsonConverter;
// this.csvResponseTransformer = csvResponseTransformer;
// }
//
// public void publishRouteSet(HttpVerb verb, DataType dataType, String path, Route route) {
// // Publish a set of routes with or without a slash and with a provided format
// publishSingleRoute(verb, dataType, path, route);
// publishSingleRoute(verb, dataType, path + "/", route);
// publishSingleRoute(verb, dataType, path + ".json", route);
// publishSingleRoute(verb, dataType, path + ".csv", route);
// }
//
// public void publishOptionsRouteSet(String path) {
// // Always return empty response with CORS headers
// Route route = (request, response) -> { return ""; };
//
// options(path, route);
// options(path + "/", route);
// options(path + ".json", route);
// options(path + ".csv", route);
// }
//
//
// // A wrapper route to deduce the correct content type
// protected class RouteWrapper implements Route {
// private DataType dataType;
// private Route route;
//
// public RouteWrapper(DataType dataType, Route route) {
// this.dataType = dataType;
// this.route = route;
// }
//
// public Object handle(Request request, Response response) {
// ContentType contentType = RouteHelper.determineContentType(request);
// return evaluateAndFormatResponse(contentType, route, request, response);
// }
//
//
// private String evaluateAndFormatResponse(ContentType contentType, Route route, Request request, Response response) {
// // Set the content type after the evaluation to not mess up the content type of errors
// String body;
// switch(contentType) {
// case CSV:
// body = csvResponseTransformer.render(dataType, route.handle(request, response));
// response.type("text/csv");
// break;
// case JSON:
// body = jsonConverter.render(dataType, route.handle(request, response));
// response.type("application/json");
// break;
// default:
// throw new IllegalArgumentException("Unknown content type");
// }
// return body;
// }
// }
//
// private void publishSingleRoute(HttpVerb verb, DataType dataType, String path, Route route) {
// RouteWrapper routeWrapper = new RouteWrapper(dataType, route);
//
// switch (verb) {
// case GET:
// get(path, routeWrapper);
// break;
// case POST:
// post(path, routeWrapper);
// break;
// case PUT:
// put(path, routeWrapper);
// break;
// case DELETE:
// delete(path, routeWrapper);
// break;
// default:
// throw new RuntimeException("Unknown verb " + verb);
// }
// }
// }
| import org.cri.redmetrics.model.Entity;
import org.cri.redmetrics.util.RouteHelper;
import spark.ResponseTransformer;
import java.util.Collection; | package org.cri.redmetrics.json;
public interface JsonConverter<E extends Entity> extends ResponseTransformer {
E parse(String json);
Collection<E> parseCollection(String json);
// Remove the "throws Exception" declaration
@Override
public String render(Object model);
| // Path: src/main/java/org/cri/redmetrics/model/Entity.java
// @Data
// public abstract class Entity {
//
// public static UUID parseId(String id) {
// return UUID.fromString(id);
// }
//
// @DatabaseField(generatedId = true)
// private UUID id;
//
// @DatabaseField(columnDefinition = "text")
// private String customData;
//
// }
//
// Path: src/main/java/org/cri/redmetrics/util/RouteHelper.java
// public class RouteHelper {
//
// public enum HttpVerb {
// GET,
// POST,
// PUT,
// DELETE,
// OPTIONS
// }
//
// public enum ContentType {
// JSON,
// CSV
// }
//
// public enum DataType {
// ENTITY,
// ENTITY_OR_ID_LIST,
// ENTITY_LIST_OR_RESULTS_PAGE,
// BIN_COUNT_LIST
// }
//
// public static ContentType determineContentType(Request request) {
// // If the user requests a format in the URL
// if(request.url().endsWith(".json")) {
// return ContentType.JSON;
// }
// else if(request.url().endsWith(".csv")) {
// return ContentType.CSV;
// }
//
// // If the user requests a format in the query string
// if(request.queryMap("format").hasValue()) {
// if ("json".equalsIgnoreCase(request.queryMap("format").value())) {
// return ContentType.JSON;
// }
// if ("csv".equalsIgnoreCase(request.queryMap("format").value())) {
// return ContentType.CSV;
// }
//
// throw new IllegalArgumentException("Incorrect format requested. Only CSV or JSON is recognized");
// }
//
// // If the user requests a format in the header
// if(request.headers("Accept") != null) {
// List<String> acceptedContentTypes = Arrays.asList(request.headers("Accept").split(","));
// if(acceptedContentTypes.contains("application/json")) {
// return ContentType.JSON;
// }
// if(acceptedContentTypes.contains("text/csv")) {
// return ContentType.CSV;
// }
// }
//
// // No format specified, so default to JSON
// return ContentType.JSON;
// }
//
//
// protected final JsonConverter jsonConverter;
// protected final CsvResponseTransformer csvResponseTransformer;
//
// public RouteHelper(JsonConverter jsonConverter, CsvResponseTransformer csvResponseTransformer) {
// this.jsonConverter = jsonConverter;
// this.csvResponseTransformer = csvResponseTransformer;
// }
//
// public void publishRouteSet(HttpVerb verb, DataType dataType, String path, Route route) {
// // Publish a set of routes with or without a slash and with a provided format
// publishSingleRoute(verb, dataType, path, route);
// publishSingleRoute(verb, dataType, path + "/", route);
// publishSingleRoute(verb, dataType, path + ".json", route);
// publishSingleRoute(verb, dataType, path + ".csv", route);
// }
//
// public void publishOptionsRouteSet(String path) {
// // Always return empty response with CORS headers
// Route route = (request, response) -> { return ""; };
//
// options(path, route);
// options(path + "/", route);
// options(path + ".json", route);
// options(path + ".csv", route);
// }
//
//
// // A wrapper route to deduce the correct content type
// protected class RouteWrapper implements Route {
// private DataType dataType;
// private Route route;
//
// public RouteWrapper(DataType dataType, Route route) {
// this.dataType = dataType;
// this.route = route;
// }
//
// public Object handle(Request request, Response response) {
// ContentType contentType = RouteHelper.determineContentType(request);
// return evaluateAndFormatResponse(contentType, route, request, response);
// }
//
//
// private String evaluateAndFormatResponse(ContentType contentType, Route route, Request request, Response response) {
// // Set the content type after the evaluation to not mess up the content type of errors
// String body;
// switch(contentType) {
// case CSV:
// body = csvResponseTransformer.render(dataType, route.handle(request, response));
// response.type("text/csv");
// break;
// case JSON:
// body = jsonConverter.render(dataType, route.handle(request, response));
// response.type("application/json");
// break;
// default:
// throw new IllegalArgumentException("Unknown content type");
// }
// return body;
// }
// }
//
// private void publishSingleRoute(HttpVerb verb, DataType dataType, String path, Route route) {
// RouteWrapper routeWrapper = new RouteWrapper(dataType, route);
//
// switch (verb) {
// case GET:
// get(path, routeWrapper);
// break;
// case POST:
// post(path, routeWrapper);
// break;
// case PUT:
// put(path, routeWrapper);
// break;
// case DELETE:
// delete(path, routeWrapper);
// break;
// default:
// throw new RuntimeException("Unknown verb " + verb);
// }
// }
// }
// Path: src/main/java/org/cri/redmetrics/json/JsonConverter.java
import org.cri.redmetrics.model.Entity;
import org.cri.redmetrics.util.RouteHelper;
import spark.ResponseTransformer;
import java.util.Collection;
package org.cri.redmetrics.json;
public interface JsonConverter<E extends Entity> extends ResponseTransformer {
E parse(String json);
Collection<E> parseCollection(String json);
// Remove the "throws Exception" declaration
@Override
public String render(Object model);
| public String render(RouteHelper.DataType dataType, Object model); |
CyberCRI/RedMetrics | src/main/java/org/cri/redmetrics/model/ProgressData.java | // Path: src/main/java/org/cri/redmetrics/db/LtreePersister.java
// public class LtreePersister extends StringType {
//
// private static final LtreePersister SINGLETON = new LtreePersister();
//
// private LtreePersister() {
// super(SqlType.OTHER, new Class<?>[]{String[].class});
// }
//
// public static LtreePersister getSingleton() {
// return SINGLETON;
// }
//
//
// @Override
// public Object javaToSqlArg(FieldType fieldType, Object javaObject) {
// return javaObject;
// }
//
// @Override
// public Object sqlArgToJava(FieldType fieldType, Object sqlArg, int columnPos) {
// return sqlArg;
// }
// }
| import com.j256.ormlite.field.DatabaseField;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.cri.redmetrics.db.LtreePersister;
import java.util.Date; | package org.cri.redmetrics.model;
@Data
@EqualsAndHashCode(callSuper = true)
public abstract class ProgressData extends Entity {
@DatabaseField(
canBeNull = false,
foreign = true,
columnDefinition = "VARCHAR, FOREIGN KEY (\"gameVersion_id\") REFERENCES game_versions(id)")
private GameVersion gameVersion;
@DatabaseField(
canBeNull = false,
foreign = true,
columnDefinition = "VARCHAR, FOREIGN KEY (player_id) REFERENCES players(id)")
private Player player;
@DatabaseField(canBeNull = false)
private Date serverTime = new Date();
@DatabaseField
private Date userTime;
| // Path: src/main/java/org/cri/redmetrics/db/LtreePersister.java
// public class LtreePersister extends StringType {
//
// private static final LtreePersister SINGLETON = new LtreePersister();
//
// private LtreePersister() {
// super(SqlType.OTHER, new Class<?>[]{String[].class});
// }
//
// public static LtreePersister getSingleton() {
// return SINGLETON;
// }
//
//
// @Override
// public Object javaToSqlArg(FieldType fieldType, Object javaObject) {
// return javaObject;
// }
//
// @Override
// public Object sqlArgToJava(FieldType fieldType, Object sqlArg, int columnPos) {
// return sqlArg;
// }
// }
// Path: src/main/java/org/cri/redmetrics/model/ProgressData.java
import com.j256.ormlite.field.DatabaseField;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.cri.redmetrics.db.LtreePersister;
import java.util.Date;
package org.cri.redmetrics.model;
@Data
@EqualsAndHashCode(callSuper = true)
public abstract class ProgressData extends Entity {
@DatabaseField(
canBeNull = false,
foreign = true,
columnDefinition = "VARCHAR, FOREIGN KEY (\"gameVersion_id\") REFERENCES game_versions(id)")
private GameVersion gameVersion;
@DatabaseField(
canBeNull = false,
foreign = true,
columnDefinition = "VARCHAR, FOREIGN KEY (player_id) REFERENCES players(id)")
private Player player;
@DatabaseField(canBeNull = false)
private Date serverTime = new Date();
@DatabaseField
private Date userTime;
| @DatabaseField(persisterClass = LtreePersister.class, columnDefinition = "ltree") |
CyberCRI/RedMetrics | src/main/java/org/cri/redmetrics/Main.java | // Path: src/main/java/org/cri/configurator/Config.java
// public interface Config<K, V extends Serializable> {
//
// public void put(K key, V value);
//
// public V get(String K);
//
// public void read(Path path) throws IOException;
//
// public void write(Path path) throws IOException;
//
// }
//
// Path: src/main/java/org/cri/redmetrics/db/Db.java
// public class Db {
//
// public static final Class[] ENTITY_TYPES = {
// Event.class,
// Snapshot.class,
// Game.class,
// GameVersion.class,
// Group.class,
// Player.class};
//
// private final String URL;
// private final String user;
// private final String password;
//
//
// public Db(String databaseURL, String user, String password) {
// this.URL = databaseURL;
// this.user = user;
// this.password = password;
//
// }
//
// public JdbcConnectionSource newConnectionSource() throws SQLException {
// return new JdbcConnectionSource(URL, user, password);
// }
//
// }
| import org.cri.configurator.Config;
import org.cri.redmetrics.db.Db;
import java.sql.SQLException; | package org.cri.redmetrics;
public class Main {
public static void main(String[] args) throws SQLException { | // Path: src/main/java/org/cri/configurator/Config.java
// public interface Config<K, V extends Serializable> {
//
// public void put(K key, V value);
//
// public V get(String K);
//
// public void read(Path path) throws IOException;
//
// public void write(Path path) throws IOException;
//
// }
//
// Path: src/main/java/org/cri/redmetrics/db/Db.java
// public class Db {
//
// public static final Class[] ENTITY_TYPES = {
// Event.class,
// Snapshot.class,
// Game.class,
// GameVersion.class,
// Group.class,
// Player.class};
//
// private final String URL;
// private final String user;
// private final String password;
//
//
// public Db(String databaseURL, String user, String password) {
// this.URL = databaseURL;
// this.user = user;
// this.password = password;
//
// }
//
// public JdbcConnectionSource newConnectionSource() throws SQLException {
// return new JdbcConnectionSource(URL, user, password);
// }
//
// }
// Path: src/main/java/org/cri/redmetrics/Main.java
import org.cri.configurator.Config;
import org.cri.redmetrics.db.Db;
import java.sql.SQLException;
package org.cri.redmetrics;
public class Main {
public static void main(String[] args) throws SQLException { | Config<String, String> config = ConfigHelper.getDefaultConfig(); |
CyberCRI/RedMetrics | src/main/java/org/cri/redmetrics/Main.java | // Path: src/main/java/org/cri/configurator/Config.java
// public interface Config<K, V extends Serializable> {
//
// public void put(K key, V value);
//
// public V get(String K);
//
// public void read(Path path) throws IOException;
//
// public void write(Path path) throws IOException;
//
// }
//
// Path: src/main/java/org/cri/redmetrics/db/Db.java
// public class Db {
//
// public static final Class[] ENTITY_TYPES = {
// Event.class,
// Snapshot.class,
// Game.class,
// GameVersion.class,
// Group.class,
// Player.class};
//
// private final String URL;
// private final String user;
// private final String password;
//
//
// public Db(String databaseURL, String user, String password) {
// this.URL = databaseURL;
// this.user = user;
// this.password = password;
//
// }
//
// public JdbcConnectionSource newConnectionSource() throws SQLException {
// return new JdbcConnectionSource(URL, user, password);
// }
//
// }
| import org.cri.configurator.Config;
import org.cri.redmetrics.db.Db;
import java.sql.SQLException; | package org.cri.redmetrics;
public class Main {
public static void main(String[] args) throws SQLException {
Config<String, String> config = ConfigHelper.getDefaultConfig();
| // Path: src/main/java/org/cri/configurator/Config.java
// public interface Config<K, V extends Serializable> {
//
// public void put(K key, V value);
//
// public V get(String K);
//
// public void read(Path path) throws IOException;
//
// public void write(Path path) throws IOException;
//
// }
//
// Path: src/main/java/org/cri/redmetrics/db/Db.java
// public class Db {
//
// public static final Class[] ENTITY_TYPES = {
// Event.class,
// Snapshot.class,
// Game.class,
// GameVersion.class,
// Group.class,
// Player.class};
//
// private final String URL;
// private final String user;
// private final String password;
//
//
// public Db(String databaseURL, String user, String password) {
// this.URL = databaseURL;
// this.user = user;
// this.password = password;
//
// }
//
// public JdbcConnectionSource newConnectionSource() throws SQLException {
// return new JdbcConnectionSource(URL, user, password);
// }
//
// }
// Path: src/main/java/org/cri/redmetrics/Main.java
import org.cri.configurator.Config;
import org.cri.redmetrics.db.Db;
import java.sql.SQLException;
package org.cri.redmetrics;
public class Main {
public static void main(String[] args) throws SQLException {
Config<String, String> config = ConfigHelper.getDefaultConfig();
| Db db = new Db(config.get("databaseURL"), config.get("dbusername"), config.get("dbassword")); |
CyberCRI/RedMetrics | src/main/java/org/cri/redmetrics/util/RouteHelper.java | // Path: src/main/java/org/cri/redmetrics/csv/CsvResponseTransformer.java
// public class CsvResponseTransformer<E extends Entity> implements ResponseTransformer {
//
// CsvEntityConverter<E> csvEntityConverter;
//
// public CsvResponseTransformer(CsvEntityConverter<E> csvEntityConverter) {
// this.csvEntityConverter = csvEntityConverter;
// }
//
// // TODO: remove this unused method?
// @Override
// public String render(Object model) {
// return "";
// }
//
// public String render(RouteHelper.DataType dataType, Object data) {
// // Write into a String
// StringWriter stringWriter = new StringWriter();
// CSVWriter csvWriter = new CSVWriter(stringWriter); // Defaults to CSV with double-quotes
//
// // Depending on the data passed, call the right method to serialize it
// // All data needs to be converted into lists
// switch(dataType) {
// case ENTITY:
// writeEntity(csvWriter, (E) data);
// break;
// case ENTITY_LIST_OR_RESULTS_PAGE:
// if(data instanceof List)
// csvEntityConverter.write(csvWriter, (List<E>) data);
// else
// csvEntityConverter.write(csvWriter, ((ResultsPage<E>) data).results);
// break;
// case ENTITY_OR_ID_LIST:
// if(data instanceof Entity) {
// writeEntity(csvWriter, (E) data);
// } else {
// writeIdList(csvWriter, (UUID[]) data);
// }
// break;
// }
//
// // Return whatever the StringWriter has buffered
// try {
// csvWriter.close();
// return stringWriter.toString();
// } catch(IOException e) {
// throw new RuntimeException("Cannot write to CSV", e);
// }
// }
//
// // Write single column of ids
// public void writeIdList(CSVWriter csvWriter, UUID[] uuidList) {
// csvWriter.writeNext(new String[]{ "id" });
// Arrays.stream(uuidList).forEach((uuid) -> csvWriter.writeNext(new String[]{ uuid.toString() }));
// }
//
// public void writeEntity(CSVWriter csvWriter, E entity) {
// List<E> singleElementList = new ArrayList<E>();
// singleElementList.add(entity);
//
// csvEntityConverter.write(csvWriter, singleElementList);
// }
//
// }
//
// Path: src/main/java/org/cri/redmetrics/json/JsonConverter.java
// public interface JsonConverter<E extends Entity> extends ResponseTransformer {
//
// E parse(String json);
//
// Collection<E> parseCollection(String json);
//
// // Remove the "throws Exception" declaration
// @Override
// public String render(Object model);
//
// public String render(RouteHelper.DataType dataType, Object model);
// }
| import org.cri.redmetrics.csv.CsvResponseTransformer;
import org.cri.redmetrics.json.JsonConverter;
import spark.Request;
import spark.Response;
import spark.Route;
import java.util.Arrays;
import java.util.List;
import static spark.Spark.*; | }
// If the user requests a format in the query string
if(request.queryMap("format").hasValue()) {
if ("json".equalsIgnoreCase(request.queryMap("format").value())) {
return ContentType.JSON;
}
if ("csv".equalsIgnoreCase(request.queryMap("format").value())) {
return ContentType.CSV;
}
throw new IllegalArgumentException("Incorrect format requested. Only CSV or JSON is recognized");
}
// If the user requests a format in the header
if(request.headers("Accept") != null) {
List<String> acceptedContentTypes = Arrays.asList(request.headers("Accept").split(","));
if(acceptedContentTypes.contains("application/json")) {
return ContentType.JSON;
}
if(acceptedContentTypes.contains("text/csv")) {
return ContentType.CSV;
}
}
// No format specified, so default to JSON
return ContentType.JSON;
}
| // Path: src/main/java/org/cri/redmetrics/csv/CsvResponseTransformer.java
// public class CsvResponseTransformer<E extends Entity> implements ResponseTransformer {
//
// CsvEntityConverter<E> csvEntityConverter;
//
// public CsvResponseTransformer(CsvEntityConverter<E> csvEntityConverter) {
// this.csvEntityConverter = csvEntityConverter;
// }
//
// // TODO: remove this unused method?
// @Override
// public String render(Object model) {
// return "";
// }
//
// public String render(RouteHelper.DataType dataType, Object data) {
// // Write into a String
// StringWriter stringWriter = new StringWriter();
// CSVWriter csvWriter = new CSVWriter(stringWriter); // Defaults to CSV with double-quotes
//
// // Depending on the data passed, call the right method to serialize it
// // All data needs to be converted into lists
// switch(dataType) {
// case ENTITY:
// writeEntity(csvWriter, (E) data);
// break;
// case ENTITY_LIST_OR_RESULTS_PAGE:
// if(data instanceof List)
// csvEntityConverter.write(csvWriter, (List<E>) data);
// else
// csvEntityConverter.write(csvWriter, ((ResultsPage<E>) data).results);
// break;
// case ENTITY_OR_ID_LIST:
// if(data instanceof Entity) {
// writeEntity(csvWriter, (E) data);
// } else {
// writeIdList(csvWriter, (UUID[]) data);
// }
// break;
// }
//
// // Return whatever the StringWriter has buffered
// try {
// csvWriter.close();
// return stringWriter.toString();
// } catch(IOException e) {
// throw new RuntimeException("Cannot write to CSV", e);
// }
// }
//
// // Write single column of ids
// public void writeIdList(CSVWriter csvWriter, UUID[] uuidList) {
// csvWriter.writeNext(new String[]{ "id" });
// Arrays.stream(uuidList).forEach((uuid) -> csvWriter.writeNext(new String[]{ uuid.toString() }));
// }
//
// public void writeEntity(CSVWriter csvWriter, E entity) {
// List<E> singleElementList = new ArrayList<E>();
// singleElementList.add(entity);
//
// csvEntityConverter.write(csvWriter, singleElementList);
// }
//
// }
//
// Path: src/main/java/org/cri/redmetrics/json/JsonConverter.java
// public interface JsonConverter<E extends Entity> extends ResponseTransformer {
//
// E parse(String json);
//
// Collection<E> parseCollection(String json);
//
// // Remove the "throws Exception" declaration
// @Override
// public String render(Object model);
//
// public String render(RouteHelper.DataType dataType, Object model);
// }
// Path: src/main/java/org/cri/redmetrics/util/RouteHelper.java
import org.cri.redmetrics.csv.CsvResponseTransformer;
import org.cri.redmetrics.json.JsonConverter;
import spark.Request;
import spark.Response;
import spark.Route;
import java.util.Arrays;
import java.util.List;
import static spark.Spark.*;
}
// If the user requests a format in the query string
if(request.queryMap("format").hasValue()) {
if ("json".equalsIgnoreCase(request.queryMap("format").value())) {
return ContentType.JSON;
}
if ("csv".equalsIgnoreCase(request.queryMap("format").value())) {
return ContentType.CSV;
}
throw new IllegalArgumentException("Incorrect format requested. Only CSV or JSON is recognized");
}
// If the user requests a format in the header
if(request.headers("Accept") != null) {
List<String> acceptedContentTypes = Arrays.asList(request.headers("Accept").split(","));
if(acceptedContentTypes.contains("application/json")) {
return ContentType.JSON;
}
if(acceptedContentTypes.contains("text/csv")) {
return ContentType.CSV;
}
}
// No format specified, so default to JSON
return ContentType.JSON;
}
| protected final JsonConverter jsonConverter; |
CyberCRI/RedMetrics | src/main/java/org/cri/redmetrics/util/RouteHelper.java | // Path: src/main/java/org/cri/redmetrics/csv/CsvResponseTransformer.java
// public class CsvResponseTransformer<E extends Entity> implements ResponseTransformer {
//
// CsvEntityConverter<E> csvEntityConverter;
//
// public CsvResponseTransformer(CsvEntityConverter<E> csvEntityConverter) {
// this.csvEntityConverter = csvEntityConverter;
// }
//
// // TODO: remove this unused method?
// @Override
// public String render(Object model) {
// return "";
// }
//
// public String render(RouteHelper.DataType dataType, Object data) {
// // Write into a String
// StringWriter stringWriter = new StringWriter();
// CSVWriter csvWriter = new CSVWriter(stringWriter); // Defaults to CSV with double-quotes
//
// // Depending on the data passed, call the right method to serialize it
// // All data needs to be converted into lists
// switch(dataType) {
// case ENTITY:
// writeEntity(csvWriter, (E) data);
// break;
// case ENTITY_LIST_OR_RESULTS_PAGE:
// if(data instanceof List)
// csvEntityConverter.write(csvWriter, (List<E>) data);
// else
// csvEntityConverter.write(csvWriter, ((ResultsPage<E>) data).results);
// break;
// case ENTITY_OR_ID_LIST:
// if(data instanceof Entity) {
// writeEntity(csvWriter, (E) data);
// } else {
// writeIdList(csvWriter, (UUID[]) data);
// }
// break;
// }
//
// // Return whatever the StringWriter has buffered
// try {
// csvWriter.close();
// return stringWriter.toString();
// } catch(IOException e) {
// throw new RuntimeException("Cannot write to CSV", e);
// }
// }
//
// // Write single column of ids
// public void writeIdList(CSVWriter csvWriter, UUID[] uuidList) {
// csvWriter.writeNext(new String[]{ "id" });
// Arrays.stream(uuidList).forEach((uuid) -> csvWriter.writeNext(new String[]{ uuid.toString() }));
// }
//
// public void writeEntity(CSVWriter csvWriter, E entity) {
// List<E> singleElementList = new ArrayList<E>();
// singleElementList.add(entity);
//
// csvEntityConverter.write(csvWriter, singleElementList);
// }
//
// }
//
// Path: src/main/java/org/cri/redmetrics/json/JsonConverter.java
// public interface JsonConverter<E extends Entity> extends ResponseTransformer {
//
// E parse(String json);
//
// Collection<E> parseCollection(String json);
//
// // Remove the "throws Exception" declaration
// @Override
// public String render(Object model);
//
// public String render(RouteHelper.DataType dataType, Object model);
// }
| import org.cri.redmetrics.csv.CsvResponseTransformer;
import org.cri.redmetrics.json.JsonConverter;
import spark.Request;
import spark.Response;
import spark.Route;
import java.util.Arrays;
import java.util.List;
import static spark.Spark.*; |
// If the user requests a format in the query string
if(request.queryMap("format").hasValue()) {
if ("json".equalsIgnoreCase(request.queryMap("format").value())) {
return ContentType.JSON;
}
if ("csv".equalsIgnoreCase(request.queryMap("format").value())) {
return ContentType.CSV;
}
throw new IllegalArgumentException("Incorrect format requested. Only CSV or JSON is recognized");
}
// If the user requests a format in the header
if(request.headers("Accept") != null) {
List<String> acceptedContentTypes = Arrays.asList(request.headers("Accept").split(","));
if(acceptedContentTypes.contains("application/json")) {
return ContentType.JSON;
}
if(acceptedContentTypes.contains("text/csv")) {
return ContentType.CSV;
}
}
// No format specified, so default to JSON
return ContentType.JSON;
}
protected final JsonConverter jsonConverter; | // Path: src/main/java/org/cri/redmetrics/csv/CsvResponseTransformer.java
// public class CsvResponseTransformer<E extends Entity> implements ResponseTransformer {
//
// CsvEntityConverter<E> csvEntityConverter;
//
// public CsvResponseTransformer(CsvEntityConverter<E> csvEntityConverter) {
// this.csvEntityConverter = csvEntityConverter;
// }
//
// // TODO: remove this unused method?
// @Override
// public String render(Object model) {
// return "";
// }
//
// public String render(RouteHelper.DataType dataType, Object data) {
// // Write into a String
// StringWriter stringWriter = new StringWriter();
// CSVWriter csvWriter = new CSVWriter(stringWriter); // Defaults to CSV with double-quotes
//
// // Depending on the data passed, call the right method to serialize it
// // All data needs to be converted into lists
// switch(dataType) {
// case ENTITY:
// writeEntity(csvWriter, (E) data);
// break;
// case ENTITY_LIST_OR_RESULTS_PAGE:
// if(data instanceof List)
// csvEntityConverter.write(csvWriter, (List<E>) data);
// else
// csvEntityConverter.write(csvWriter, ((ResultsPage<E>) data).results);
// break;
// case ENTITY_OR_ID_LIST:
// if(data instanceof Entity) {
// writeEntity(csvWriter, (E) data);
// } else {
// writeIdList(csvWriter, (UUID[]) data);
// }
// break;
// }
//
// // Return whatever the StringWriter has buffered
// try {
// csvWriter.close();
// return stringWriter.toString();
// } catch(IOException e) {
// throw new RuntimeException("Cannot write to CSV", e);
// }
// }
//
// // Write single column of ids
// public void writeIdList(CSVWriter csvWriter, UUID[] uuidList) {
// csvWriter.writeNext(new String[]{ "id" });
// Arrays.stream(uuidList).forEach((uuid) -> csvWriter.writeNext(new String[]{ uuid.toString() }));
// }
//
// public void writeEntity(CSVWriter csvWriter, E entity) {
// List<E> singleElementList = new ArrayList<E>();
// singleElementList.add(entity);
//
// csvEntityConverter.write(csvWriter, singleElementList);
// }
//
// }
//
// Path: src/main/java/org/cri/redmetrics/json/JsonConverter.java
// public interface JsonConverter<E extends Entity> extends ResponseTransformer {
//
// E parse(String json);
//
// Collection<E> parseCollection(String json);
//
// // Remove the "throws Exception" declaration
// @Override
// public String render(Object model);
//
// public String render(RouteHelper.DataType dataType, Object model);
// }
// Path: src/main/java/org/cri/redmetrics/util/RouteHelper.java
import org.cri.redmetrics.csv.CsvResponseTransformer;
import org.cri.redmetrics.json.JsonConverter;
import spark.Request;
import spark.Response;
import spark.Route;
import java.util.Arrays;
import java.util.List;
import static spark.Spark.*;
// If the user requests a format in the query string
if(request.queryMap("format").hasValue()) {
if ("json".equalsIgnoreCase(request.queryMap("format").value())) {
return ContentType.JSON;
}
if ("csv".equalsIgnoreCase(request.queryMap("format").value())) {
return ContentType.CSV;
}
throw new IllegalArgumentException("Incorrect format requested. Only CSV or JSON is recognized");
}
// If the user requests a format in the header
if(request.headers("Accept") != null) {
List<String> acceptedContentTypes = Arrays.asList(request.headers("Accept").split(","));
if(acceptedContentTypes.contains("application/json")) {
return ContentType.JSON;
}
if(acceptedContentTypes.contains("text/csv")) {
return ContentType.CSV;
}
}
// No format specified, so default to JSON
return ContentType.JSON;
}
protected final JsonConverter jsonConverter; | protected final CsvResponseTransformer csvResponseTransformer; |
CyberCRI/RedMetrics | src/main/java/org/cri/redmetrics/json/ProgressDataJsonConverter.java | // Path: src/main/java/org/cri/redmetrics/model/GameVersion.java
// @Data
// @DatabaseTable(tableName = "game_versions")
// @NoArgsConstructor
// @AllArgsConstructor
// @EqualsAndHashCode(callSuper = true)
// public class GameVersion extends Entity {
//
// @DatabaseField(
// canBeNull = false,
// foreign = true,
// columnDefinition = "VARCHAR, FOREIGN KEY (game_id) REFERENCES games(id)")
// private Game game;
//
// @DatabaseField(canBeNull = false)
// private String name;
//
// @DatabaseField
// private String author;
//
// @DatabaseField
// private String description;
//
// }
//
// Path: src/main/java/org/cri/redmetrics/model/Player.java
// @Data
// @DatabaseTable(tableName = "players")
// @NoArgsConstructor
// @AllArgsConstructor
// @EqualsAndHashCode(callSuper = true)
// public class Player extends Entity {
//
// @DatabaseField
// private Date birthDate;
//
// @DatabaseField
// private String region;
//
// @DatabaseField
// private String country;
//
// @DatabaseField
// private Gender gender;
//
// @DatabaseField(index = true)
// private String externalId;
//
// }
//
// Path: src/main/java/org/cri/redmetrics/model/ProgressData.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// public abstract class ProgressData extends Entity {
//
// @DatabaseField(
// canBeNull = false,
// foreign = true,
// columnDefinition = "VARCHAR, FOREIGN KEY (\"gameVersion_id\") REFERENCES game_versions(id)")
// private GameVersion gameVersion;
//
// @DatabaseField(
// canBeNull = false,
// foreign = true,
// columnDefinition = "VARCHAR, FOREIGN KEY (player_id) REFERENCES players(id)")
// private Player player;
//
// @DatabaseField(canBeNull = false)
// private Date serverTime = new Date();
//
// @DatabaseField
// private Date userTime;
//
// @DatabaseField(persisterClass = LtreePersister.class, columnDefinition = "ltree")
// private String section;
//
// @DatabaseField(canBeNull = false)
// private String type;
//
// }
| import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.cri.redmetrics.model.GameVersion;
import org.cri.redmetrics.model.Player;
import org.cri.redmetrics.model.ProgressData;
import java.util.UUID; | package org.cri.redmetrics.json;
public class ProgressDataJsonConverter<E extends ProgressData> extends EntityJsonConverter<E> {
ProgressDataJsonConverter(Class<E> entityType, Gson gson, JsonParser jsonParser) {
super(entityType, gson, jsonParser);
}
@Override
public E parse(String json) {
E progressData = super.parse(json);
JsonObject jsonObject = jsonParser.parse(json).getAsJsonObject();
// GAME VERSION
JsonElement gameVersionId = jsonObject.get("gameVersion");
if (gameVersionId != null) { | // Path: src/main/java/org/cri/redmetrics/model/GameVersion.java
// @Data
// @DatabaseTable(tableName = "game_versions")
// @NoArgsConstructor
// @AllArgsConstructor
// @EqualsAndHashCode(callSuper = true)
// public class GameVersion extends Entity {
//
// @DatabaseField(
// canBeNull = false,
// foreign = true,
// columnDefinition = "VARCHAR, FOREIGN KEY (game_id) REFERENCES games(id)")
// private Game game;
//
// @DatabaseField(canBeNull = false)
// private String name;
//
// @DatabaseField
// private String author;
//
// @DatabaseField
// private String description;
//
// }
//
// Path: src/main/java/org/cri/redmetrics/model/Player.java
// @Data
// @DatabaseTable(tableName = "players")
// @NoArgsConstructor
// @AllArgsConstructor
// @EqualsAndHashCode(callSuper = true)
// public class Player extends Entity {
//
// @DatabaseField
// private Date birthDate;
//
// @DatabaseField
// private String region;
//
// @DatabaseField
// private String country;
//
// @DatabaseField
// private Gender gender;
//
// @DatabaseField(index = true)
// private String externalId;
//
// }
//
// Path: src/main/java/org/cri/redmetrics/model/ProgressData.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// public abstract class ProgressData extends Entity {
//
// @DatabaseField(
// canBeNull = false,
// foreign = true,
// columnDefinition = "VARCHAR, FOREIGN KEY (\"gameVersion_id\") REFERENCES game_versions(id)")
// private GameVersion gameVersion;
//
// @DatabaseField(
// canBeNull = false,
// foreign = true,
// columnDefinition = "VARCHAR, FOREIGN KEY (player_id) REFERENCES players(id)")
// private Player player;
//
// @DatabaseField(canBeNull = false)
// private Date serverTime = new Date();
//
// @DatabaseField
// private Date userTime;
//
// @DatabaseField(persisterClass = LtreePersister.class, columnDefinition = "ltree")
// private String section;
//
// @DatabaseField(canBeNull = false)
// private String type;
//
// }
// Path: src/main/java/org/cri/redmetrics/json/ProgressDataJsonConverter.java
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.cri.redmetrics.model.GameVersion;
import org.cri.redmetrics.model.Player;
import org.cri.redmetrics.model.ProgressData;
import java.util.UUID;
package org.cri.redmetrics.json;
public class ProgressDataJsonConverter<E extends ProgressData> extends EntityJsonConverter<E> {
ProgressDataJsonConverter(Class<E> entityType, Gson gson, JsonParser jsonParser) {
super(entityType, gson, jsonParser);
}
@Override
public E parse(String json) {
E progressData = super.parse(json);
JsonObject jsonObject = jsonParser.parse(json).getAsJsonObject();
// GAME VERSION
JsonElement gameVersionId = jsonObject.get("gameVersion");
if (gameVersionId != null) { | GameVersion gameVersion = new GameVersion(); |
CyberCRI/RedMetrics | src/main/java/org/cri/redmetrics/json/ProgressDataJsonConverter.java | // Path: src/main/java/org/cri/redmetrics/model/GameVersion.java
// @Data
// @DatabaseTable(tableName = "game_versions")
// @NoArgsConstructor
// @AllArgsConstructor
// @EqualsAndHashCode(callSuper = true)
// public class GameVersion extends Entity {
//
// @DatabaseField(
// canBeNull = false,
// foreign = true,
// columnDefinition = "VARCHAR, FOREIGN KEY (game_id) REFERENCES games(id)")
// private Game game;
//
// @DatabaseField(canBeNull = false)
// private String name;
//
// @DatabaseField
// private String author;
//
// @DatabaseField
// private String description;
//
// }
//
// Path: src/main/java/org/cri/redmetrics/model/Player.java
// @Data
// @DatabaseTable(tableName = "players")
// @NoArgsConstructor
// @AllArgsConstructor
// @EqualsAndHashCode(callSuper = true)
// public class Player extends Entity {
//
// @DatabaseField
// private Date birthDate;
//
// @DatabaseField
// private String region;
//
// @DatabaseField
// private String country;
//
// @DatabaseField
// private Gender gender;
//
// @DatabaseField(index = true)
// private String externalId;
//
// }
//
// Path: src/main/java/org/cri/redmetrics/model/ProgressData.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// public abstract class ProgressData extends Entity {
//
// @DatabaseField(
// canBeNull = false,
// foreign = true,
// columnDefinition = "VARCHAR, FOREIGN KEY (\"gameVersion_id\") REFERENCES game_versions(id)")
// private GameVersion gameVersion;
//
// @DatabaseField(
// canBeNull = false,
// foreign = true,
// columnDefinition = "VARCHAR, FOREIGN KEY (player_id) REFERENCES players(id)")
// private Player player;
//
// @DatabaseField(canBeNull = false)
// private Date serverTime = new Date();
//
// @DatabaseField
// private Date userTime;
//
// @DatabaseField(persisterClass = LtreePersister.class, columnDefinition = "ltree")
// private String section;
//
// @DatabaseField(canBeNull = false)
// private String type;
//
// }
| import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.cri.redmetrics.model.GameVersion;
import org.cri.redmetrics.model.Player;
import org.cri.redmetrics.model.ProgressData;
import java.util.UUID; | package org.cri.redmetrics.json;
public class ProgressDataJsonConverter<E extends ProgressData> extends EntityJsonConverter<E> {
ProgressDataJsonConverter(Class<E> entityType, Gson gson, JsonParser jsonParser) {
super(entityType, gson, jsonParser);
}
@Override
public E parse(String json) {
E progressData = super.parse(json);
JsonObject jsonObject = jsonParser.parse(json).getAsJsonObject();
// GAME VERSION
JsonElement gameVersionId = jsonObject.get("gameVersion");
if (gameVersionId != null) {
GameVersion gameVersion = new GameVersion();
// TODO Make sure the progress data can update without overwriting gameVersion data
gameVersion.setId(UUID.fromString(gameVersionId.getAsString()));
progressData.setGameVersion(gameVersion);
}
// PLAYER
JsonElement playerId = jsonObject.get("player");
if (playerId != null) { | // Path: src/main/java/org/cri/redmetrics/model/GameVersion.java
// @Data
// @DatabaseTable(tableName = "game_versions")
// @NoArgsConstructor
// @AllArgsConstructor
// @EqualsAndHashCode(callSuper = true)
// public class GameVersion extends Entity {
//
// @DatabaseField(
// canBeNull = false,
// foreign = true,
// columnDefinition = "VARCHAR, FOREIGN KEY (game_id) REFERENCES games(id)")
// private Game game;
//
// @DatabaseField(canBeNull = false)
// private String name;
//
// @DatabaseField
// private String author;
//
// @DatabaseField
// private String description;
//
// }
//
// Path: src/main/java/org/cri/redmetrics/model/Player.java
// @Data
// @DatabaseTable(tableName = "players")
// @NoArgsConstructor
// @AllArgsConstructor
// @EqualsAndHashCode(callSuper = true)
// public class Player extends Entity {
//
// @DatabaseField
// private Date birthDate;
//
// @DatabaseField
// private String region;
//
// @DatabaseField
// private String country;
//
// @DatabaseField
// private Gender gender;
//
// @DatabaseField(index = true)
// private String externalId;
//
// }
//
// Path: src/main/java/org/cri/redmetrics/model/ProgressData.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// public abstract class ProgressData extends Entity {
//
// @DatabaseField(
// canBeNull = false,
// foreign = true,
// columnDefinition = "VARCHAR, FOREIGN KEY (\"gameVersion_id\") REFERENCES game_versions(id)")
// private GameVersion gameVersion;
//
// @DatabaseField(
// canBeNull = false,
// foreign = true,
// columnDefinition = "VARCHAR, FOREIGN KEY (player_id) REFERENCES players(id)")
// private Player player;
//
// @DatabaseField(canBeNull = false)
// private Date serverTime = new Date();
//
// @DatabaseField
// private Date userTime;
//
// @DatabaseField(persisterClass = LtreePersister.class, columnDefinition = "ltree")
// private String section;
//
// @DatabaseField(canBeNull = false)
// private String type;
//
// }
// Path: src/main/java/org/cri/redmetrics/json/ProgressDataJsonConverter.java
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.cri.redmetrics.model.GameVersion;
import org.cri.redmetrics.model.Player;
import org.cri.redmetrics.model.ProgressData;
import java.util.UUID;
package org.cri.redmetrics.json;
public class ProgressDataJsonConverter<E extends ProgressData> extends EntityJsonConverter<E> {
ProgressDataJsonConverter(Class<E> entityType, Gson gson, JsonParser jsonParser) {
super(entityType, gson, jsonParser);
}
@Override
public E parse(String json) {
E progressData = super.parse(json);
JsonObject jsonObject = jsonParser.parse(json).getAsJsonObject();
// GAME VERSION
JsonElement gameVersionId = jsonObject.get("gameVersion");
if (gameVersionId != null) {
GameVersion gameVersion = new GameVersion();
// TODO Make sure the progress data can update without overwriting gameVersion data
gameVersion.setId(UUID.fromString(gameVersionId.getAsString()));
progressData.setGameVersion(gameVersion);
}
// PLAYER
JsonElement playerId = jsonObject.get("player");
if (playerId != null) { | Player player = new Player(); |
CyberCRI/RedMetrics | src/main/java/org/cri/redmetrics/json/GameVersionJsonConverter.java | // Path: src/main/java/org/cri/redmetrics/model/Game.java
// @Data
// @DatabaseTable(tableName = "games")
// @NoArgsConstructor
// @AllArgsConstructor
// @EqualsAndHashCode(callSuper = true)
// public class Game extends Entity {
//
// @DatabaseField(dataType = DataType.UUID)
// private UUID adminKey;
//
// @DatabaseField(canBeNull = false)
// private String name;
//
// @DatabaseField
// private String author;
//
// @DatabaseField
// private String description;
//
// }
//
// Path: src/main/java/org/cri/redmetrics/model/GameVersion.java
// @Data
// @DatabaseTable(tableName = "game_versions")
// @NoArgsConstructor
// @AllArgsConstructor
// @EqualsAndHashCode(callSuper = true)
// public class GameVersion extends Entity {
//
// @DatabaseField(
// canBeNull = false,
// foreign = true,
// columnDefinition = "VARCHAR, FOREIGN KEY (game_id) REFERENCES games(id)")
// private Game game;
//
// @DatabaseField(canBeNull = false)
// private String name;
//
// @DatabaseField
// private String author;
//
// @DatabaseField
// private String description;
//
// }
| import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import org.cri.redmetrics.model.Game;
import org.cri.redmetrics.model.GameVersion;
import java.util.UUID; | package org.cri.redmetrics.json;
public class GameVersionJsonConverter extends EntityJsonConverter<GameVersion> {
@Inject
GameVersionJsonConverter(@Named("GameVersion") Gson gson, JsonParser jsonParser) {
super(GameVersion.class, gson, jsonParser);
}
@Override
public GameVersion parse(String json) {
GameVersion gameVersion = super.parse(json);
JsonObject jsonObject = jsonParser.parse(json).getAsJsonObject();
// GAME
JsonElement gameId = jsonObject.get("game");
if (gameId != null) { | // Path: src/main/java/org/cri/redmetrics/model/Game.java
// @Data
// @DatabaseTable(tableName = "games")
// @NoArgsConstructor
// @AllArgsConstructor
// @EqualsAndHashCode(callSuper = true)
// public class Game extends Entity {
//
// @DatabaseField(dataType = DataType.UUID)
// private UUID adminKey;
//
// @DatabaseField(canBeNull = false)
// private String name;
//
// @DatabaseField
// private String author;
//
// @DatabaseField
// private String description;
//
// }
//
// Path: src/main/java/org/cri/redmetrics/model/GameVersion.java
// @Data
// @DatabaseTable(tableName = "game_versions")
// @NoArgsConstructor
// @AllArgsConstructor
// @EqualsAndHashCode(callSuper = true)
// public class GameVersion extends Entity {
//
// @DatabaseField(
// canBeNull = false,
// foreign = true,
// columnDefinition = "VARCHAR, FOREIGN KEY (game_id) REFERENCES games(id)")
// private Game game;
//
// @DatabaseField(canBeNull = false)
// private String name;
//
// @DatabaseField
// private String author;
//
// @DatabaseField
// private String description;
//
// }
// Path: src/main/java/org/cri/redmetrics/json/GameVersionJsonConverter.java
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import org.cri.redmetrics.model.Game;
import org.cri.redmetrics.model.GameVersion;
import java.util.UUID;
package org.cri.redmetrics.json;
public class GameVersionJsonConverter extends EntityJsonConverter<GameVersion> {
@Inject
GameVersionJsonConverter(@Named("GameVersion") Gson gson, JsonParser jsonParser) {
super(GameVersion.class, gson, jsonParser);
}
@Override
public GameVersion parse(String json) {
GameVersion gameVersion = super.parse(json);
JsonObject jsonObject = jsonParser.parse(json).getAsJsonObject();
// GAME
JsonElement gameId = jsonObject.get("game");
if (gameId != null) { | Game game = new Game(); |
CyberCRI/RedMetrics | src/main/java/org/cri/redmetrics/model/Event.java | // Path: src/main/java/org/cri/redmetrics/db/IntegerArrayPersister.java
// public class IntegerArrayPersister extends StringType {
//
// private static final IntegerArrayPersister SINGLETON = new IntegerArrayPersister();
//
// private IntegerArrayPersister() {
// super(SqlType.OTHER, new Class<?>[]{Integer[].class});
// }
//
// public static IntegerArrayPersister getSingleton() {
// return SINGLETON;
// }
//
//
// @Override
// public Object javaToSqlArg(FieldType fieldType, Object javaObject) {
// Integer[] array = (Integer[]) javaObject;
//
// if (array == null) {
// return null;
// } else {
// String join = "";
// for (Integer i : array) {
// join += i + ",";
// }
// return "{" + join.substring(0, join.length() - 1) + "}";
// }
//
// }
//
// @Override
// public Object sqlArgToJava(FieldType fieldType, Object sqlArg, int columnPos) {
// String string = (String) sqlArg;
//
// if (string == null) {
// return null;
// } else {
// String[] strings = string.replaceAll("[{}]", "").split(",");
// Integer[] ints = new Integer[strings.length];
// for (int i = 0, length = strings.length; i < length; i++) {
// ints[i] = Integer.parseInt(strings[i]);
// }
// return ints;
// }
// }
// }
| import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.cri.redmetrics.db.IntegerArrayPersister; | package org.cri.redmetrics.model;
@Data
@DatabaseTable(tableName = "events")
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class Event extends ProgressData {
| // Path: src/main/java/org/cri/redmetrics/db/IntegerArrayPersister.java
// public class IntegerArrayPersister extends StringType {
//
// private static final IntegerArrayPersister SINGLETON = new IntegerArrayPersister();
//
// private IntegerArrayPersister() {
// super(SqlType.OTHER, new Class<?>[]{Integer[].class});
// }
//
// public static IntegerArrayPersister getSingleton() {
// return SINGLETON;
// }
//
//
// @Override
// public Object javaToSqlArg(FieldType fieldType, Object javaObject) {
// Integer[] array = (Integer[]) javaObject;
//
// if (array == null) {
// return null;
// } else {
// String join = "";
// for (Integer i : array) {
// join += i + ",";
// }
// return "{" + join.substring(0, join.length() - 1) + "}";
// }
//
// }
//
// @Override
// public Object sqlArgToJava(FieldType fieldType, Object sqlArg, int columnPos) {
// String string = (String) sqlArg;
//
// if (string == null) {
// return null;
// } else {
// String[] strings = string.replaceAll("[{}]", "").split(",");
// Integer[] ints = new Integer[strings.length];
// for (int i = 0, length = strings.length; i < length; i++) {
// ints[i] = Integer.parseInt(strings[i]);
// }
// return ints;
// }
// }
// }
// Path: src/main/java/org/cri/redmetrics/model/Event.java
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.cri.redmetrics.db.IntegerArrayPersister;
package org.cri.redmetrics.model;
@Data
@DatabaseTable(tableName = "events")
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class Event extends ProgressData {
| @DatabaseField(persisterClass = IntegerArrayPersister.class, columnDefinition = "integer[]") |
CyberCRI/RedMetrics | src/main/java/org/cri/redmetrics/dao/EntityDao.java | // Path: src/main/java/org/cri/redmetrics/model/Entity.java
// @Data
// public abstract class Entity {
//
// public static UUID parseId(String id) {
// return UUID.fromString(id);
// }
//
// @DatabaseField(generatedId = true)
// private UUID id;
//
// @DatabaseField(columnDefinition = "text")
// private String customData;
//
// }
//
// Path: src/main/java/org/cri/redmetrics/model/ResultsPage.java
// public class ResultsPage<E extends Entity> {
// public ResultsPage(long total, long page, long perPage, List<E> results) {
// this.total = total;
// this.page = page;
// this.perPage = perPage;
// this.results = results;
// }
//
// public long total;
// public long page;
// public long perPage;
// public List<E> results;
// }
| import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import org.cri.redmetrics.model.Entity;
import org.cri.redmetrics.model.ResultsPage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID; | }
}
public E update(E entity) {
try {
orm.update(entity);
return read(entity.getId());
} catch (SQLException e) {
throw new DbException(e);
}
}
public E delete(UUID id) {
try {
E entity = read(id);
orm.delete(entity);
return entity;
} catch (SQLException e) {
throw new DbException(e);
}
}
public List<E> listAll() {
try {
return orm.queryForAll();
} catch (SQLException e) {
throw new DbException(e);
}
}
| // Path: src/main/java/org/cri/redmetrics/model/Entity.java
// @Data
// public abstract class Entity {
//
// public static UUID parseId(String id) {
// return UUID.fromString(id);
// }
//
// @DatabaseField(generatedId = true)
// private UUID id;
//
// @DatabaseField(columnDefinition = "text")
// private String customData;
//
// }
//
// Path: src/main/java/org/cri/redmetrics/model/ResultsPage.java
// public class ResultsPage<E extends Entity> {
// public ResultsPage(long total, long page, long perPage, List<E> results) {
// this.total = total;
// this.page = page;
// this.perPage = perPage;
// this.results = results;
// }
//
// public long total;
// public long page;
// public long perPage;
// public List<E> results;
// }
// Path: src/main/java/org/cri/redmetrics/dao/EntityDao.java
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import org.cri.redmetrics.model.Entity;
import org.cri.redmetrics.model.ResultsPage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;
}
}
public E update(E entity) {
try {
orm.update(entity);
return read(entity.getId());
} catch (SQLException e) {
throw new DbException(e);
}
}
public E delete(UUID id) {
try {
E entity = read(id);
orm.delete(entity);
return entity;
} catch (SQLException e) {
throw new DbException(e);
}
}
public List<E> listAll() {
try {
return orm.queryForAll();
} catch (SQLException e) {
throw new DbException(e);
}
}
| public ResultsPage<E> list(long page, long perPage) { |
CyberCRI/RedMetrics | src/main/java/org/cri/redmetrics/controller/GameController.java | // Path: src/main/java/org/cri/redmetrics/csv/CsvEntityConverter.java
// public interface CsvEntityConverter<E extends Entity> {
//
// public void write(CSVWriter csvWriter, List<E> models);
//
// }
//
// Path: src/main/java/org/cri/redmetrics/dao/GameDao.java
// public class GameDao extends EntityDao<Game> {
//
// @Inject
// public GameDao(ConnectionSource connectionSource) throws SQLException {
// super(connectionSource, Game.class);
// }
//
// @Override
// public Game create(Game game) {
// if (game.getName() == null || game.getName().isEmpty())
// throw new InconsistentDataException("Game name is required");
// game.setAdminKey(UUID.randomUUID());
// return super.create(game);
// }
//
// }
//
// Path: src/main/java/org/cri/redmetrics/json/GameJsonConverter.java
// public class GameJsonConverter extends EntityJsonConverter<Game> {
//
// @Inject
// GameJsonConverter(Gson gson, JsonParser jsonParser) {
// super(Game.class, gson, jsonParser);
// }
//
// }
//
// Path: src/main/java/org/cri/redmetrics/model/Game.java
// @Data
// @DatabaseTable(tableName = "games")
// @NoArgsConstructor
// @AllArgsConstructor
// @EqualsAndHashCode(callSuper = true)
// public class Game extends Entity {
//
// @DatabaseField(dataType = DataType.UUID)
// private UUID adminKey;
//
// @DatabaseField(canBeNull = false)
// private String name;
//
// @DatabaseField
// private String author;
//
// @DatabaseField
// private String description;
//
// }
//
// Path: src/main/java/org/cri/redmetrics/model/ResultsPage.java
// public class ResultsPage<E extends Entity> {
// public ResultsPage(long total, long page, long perPage, List<E> results) {
// this.total = total;
// this.page = page;
// this.perPage = perPage;
// this.results = results;
// }
//
// public long total;
// public long page;
// public long perPage;
// public List<E> results;
// }
| import com.google.inject.Inject;
import org.cri.redmetrics.csv.CsvEntityConverter;
import org.cri.redmetrics.dao.GameDao;
import org.cri.redmetrics.json.GameJsonConverter;
import org.cri.redmetrics.model.Game;
import org.cri.redmetrics.model.ResultsPage;
import spark.Request;
import java.util.UUID; | package org.cri.redmetrics.controller;
public class GameController extends Controller<Game, GameDao> {
@Inject | // Path: src/main/java/org/cri/redmetrics/csv/CsvEntityConverter.java
// public interface CsvEntityConverter<E extends Entity> {
//
// public void write(CSVWriter csvWriter, List<E> models);
//
// }
//
// Path: src/main/java/org/cri/redmetrics/dao/GameDao.java
// public class GameDao extends EntityDao<Game> {
//
// @Inject
// public GameDao(ConnectionSource connectionSource) throws SQLException {
// super(connectionSource, Game.class);
// }
//
// @Override
// public Game create(Game game) {
// if (game.getName() == null || game.getName().isEmpty())
// throw new InconsistentDataException("Game name is required");
// game.setAdminKey(UUID.randomUUID());
// return super.create(game);
// }
//
// }
//
// Path: src/main/java/org/cri/redmetrics/json/GameJsonConverter.java
// public class GameJsonConverter extends EntityJsonConverter<Game> {
//
// @Inject
// GameJsonConverter(Gson gson, JsonParser jsonParser) {
// super(Game.class, gson, jsonParser);
// }
//
// }
//
// Path: src/main/java/org/cri/redmetrics/model/Game.java
// @Data
// @DatabaseTable(tableName = "games")
// @NoArgsConstructor
// @AllArgsConstructor
// @EqualsAndHashCode(callSuper = true)
// public class Game extends Entity {
//
// @DatabaseField(dataType = DataType.UUID)
// private UUID adminKey;
//
// @DatabaseField(canBeNull = false)
// private String name;
//
// @DatabaseField
// private String author;
//
// @DatabaseField
// private String description;
//
// }
//
// Path: src/main/java/org/cri/redmetrics/model/ResultsPage.java
// public class ResultsPage<E extends Entity> {
// public ResultsPage(long total, long page, long perPage, List<E> results) {
// this.total = total;
// this.page = page;
// this.perPage = perPage;
// this.results = results;
// }
//
// public long total;
// public long page;
// public long perPage;
// public List<E> results;
// }
// Path: src/main/java/org/cri/redmetrics/controller/GameController.java
import com.google.inject.Inject;
import org.cri.redmetrics.csv.CsvEntityConverter;
import org.cri.redmetrics.dao.GameDao;
import org.cri.redmetrics.json.GameJsonConverter;
import org.cri.redmetrics.model.Game;
import org.cri.redmetrics.model.ResultsPage;
import spark.Request;
import java.util.UUID;
package org.cri.redmetrics.controller;
public class GameController extends Controller<Game, GameDao> {
@Inject | GameController(GameDao dao, GameJsonConverter jsonConverter, CsvEntityConverter<Game> csvEntityConverter) { |
CyberCRI/RedMetrics | src/main/java/org/cri/redmetrics/controller/GameController.java | // Path: src/main/java/org/cri/redmetrics/csv/CsvEntityConverter.java
// public interface CsvEntityConverter<E extends Entity> {
//
// public void write(CSVWriter csvWriter, List<E> models);
//
// }
//
// Path: src/main/java/org/cri/redmetrics/dao/GameDao.java
// public class GameDao extends EntityDao<Game> {
//
// @Inject
// public GameDao(ConnectionSource connectionSource) throws SQLException {
// super(connectionSource, Game.class);
// }
//
// @Override
// public Game create(Game game) {
// if (game.getName() == null || game.getName().isEmpty())
// throw new InconsistentDataException("Game name is required");
// game.setAdminKey(UUID.randomUUID());
// return super.create(game);
// }
//
// }
//
// Path: src/main/java/org/cri/redmetrics/json/GameJsonConverter.java
// public class GameJsonConverter extends EntityJsonConverter<Game> {
//
// @Inject
// GameJsonConverter(Gson gson, JsonParser jsonParser) {
// super(Game.class, gson, jsonParser);
// }
//
// }
//
// Path: src/main/java/org/cri/redmetrics/model/Game.java
// @Data
// @DatabaseTable(tableName = "games")
// @NoArgsConstructor
// @AllArgsConstructor
// @EqualsAndHashCode(callSuper = true)
// public class Game extends Entity {
//
// @DatabaseField(dataType = DataType.UUID)
// private UUID adminKey;
//
// @DatabaseField(canBeNull = false)
// private String name;
//
// @DatabaseField
// private String author;
//
// @DatabaseField
// private String description;
//
// }
//
// Path: src/main/java/org/cri/redmetrics/model/ResultsPage.java
// public class ResultsPage<E extends Entity> {
// public ResultsPage(long total, long page, long perPage, List<E> results) {
// this.total = total;
// this.page = page;
// this.perPage = perPage;
// this.results = results;
// }
//
// public long total;
// public long page;
// public long perPage;
// public List<E> results;
// }
| import com.google.inject.Inject;
import org.cri.redmetrics.csv.CsvEntityConverter;
import org.cri.redmetrics.dao.GameDao;
import org.cri.redmetrics.json.GameJsonConverter;
import org.cri.redmetrics.model.Game;
import org.cri.redmetrics.model.ResultsPage;
import spark.Request;
import java.util.UUID; | package org.cri.redmetrics.controller;
public class GameController extends Controller<Game, GameDao> {
@Inject | // Path: src/main/java/org/cri/redmetrics/csv/CsvEntityConverter.java
// public interface CsvEntityConverter<E extends Entity> {
//
// public void write(CSVWriter csvWriter, List<E> models);
//
// }
//
// Path: src/main/java/org/cri/redmetrics/dao/GameDao.java
// public class GameDao extends EntityDao<Game> {
//
// @Inject
// public GameDao(ConnectionSource connectionSource) throws SQLException {
// super(connectionSource, Game.class);
// }
//
// @Override
// public Game create(Game game) {
// if (game.getName() == null || game.getName().isEmpty())
// throw new InconsistentDataException("Game name is required");
// game.setAdminKey(UUID.randomUUID());
// return super.create(game);
// }
//
// }
//
// Path: src/main/java/org/cri/redmetrics/json/GameJsonConverter.java
// public class GameJsonConverter extends EntityJsonConverter<Game> {
//
// @Inject
// GameJsonConverter(Gson gson, JsonParser jsonParser) {
// super(Game.class, gson, jsonParser);
// }
//
// }
//
// Path: src/main/java/org/cri/redmetrics/model/Game.java
// @Data
// @DatabaseTable(tableName = "games")
// @NoArgsConstructor
// @AllArgsConstructor
// @EqualsAndHashCode(callSuper = true)
// public class Game extends Entity {
//
// @DatabaseField(dataType = DataType.UUID)
// private UUID adminKey;
//
// @DatabaseField(canBeNull = false)
// private String name;
//
// @DatabaseField
// private String author;
//
// @DatabaseField
// private String description;
//
// }
//
// Path: src/main/java/org/cri/redmetrics/model/ResultsPage.java
// public class ResultsPage<E extends Entity> {
// public ResultsPage(long total, long page, long perPage, List<E> results) {
// this.total = total;
// this.page = page;
// this.perPage = perPage;
// this.results = results;
// }
//
// public long total;
// public long page;
// public long perPage;
// public List<E> results;
// }
// Path: src/main/java/org/cri/redmetrics/controller/GameController.java
import com.google.inject.Inject;
import org.cri.redmetrics.csv.CsvEntityConverter;
import org.cri.redmetrics.dao.GameDao;
import org.cri.redmetrics.json.GameJsonConverter;
import org.cri.redmetrics.model.Game;
import org.cri.redmetrics.model.ResultsPage;
import spark.Request;
import java.util.UUID;
package org.cri.redmetrics.controller;
public class GameController extends Controller<Game, GameDao> {
@Inject | GameController(GameDao dao, GameJsonConverter jsonConverter, CsvEntityConverter<Game> csvEntityConverter) { |
CyberCRI/RedMetrics | src/main/java/org/cri/redmetrics/controller/GameController.java | // Path: src/main/java/org/cri/redmetrics/csv/CsvEntityConverter.java
// public interface CsvEntityConverter<E extends Entity> {
//
// public void write(CSVWriter csvWriter, List<E> models);
//
// }
//
// Path: src/main/java/org/cri/redmetrics/dao/GameDao.java
// public class GameDao extends EntityDao<Game> {
//
// @Inject
// public GameDao(ConnectionSource connectionSource) throws SQLException {
// super(connectionSource, Game.class);
// }
//
// @Override
// public Game create(Game game) {
// if (game.getName() == null || game.getName().isEmpty())
// throw new InconsistentDataException("Game name is required");
// game.setAdminKey(UUID.randomUUID());
// return super.create(game);
// }
//
// }
//
// Path: src/main/java/org/cri/redmetrics/json/GameJsonConverter.java
// public class GameJsonConverter extends EntityJsonConverter<Game> {
//
// @Inject
// GameJsonConverter(Gson gson, JsonParser jsonParser) {
// super(Game.class, gson, jsonParser);
// }
//
// }
//
// Path: src/main/java/org/cri/redmetrics/model/Game.java
// @Data
// @DatabaseTable(tableName = "games")
// @NoArgsConstructor
// @AllArgsConstructor
// @EqualsAndHashCode(callSuper = true)
// public class Game extends Entity {
//
// @DatabaseField(dataType = DataType.UUID)
// private UUID adminKey;
//
// @DatabaseField(canBeNull = false)
// private String name;
//
// @DatabaseField
// private String author;
//
// @DatabaseField
// private String description;
//
// }
//
// Path: src/main/java/org/cri/redmetrics/model/ResultsPage.java
// public class ResultsPage<E extends Entity> {
// public ResultsPage(long total, long page, long perPage, List<E> results) {
// this.total = total;
// this.page = page;
// this.perPage = perPage;
// this.results = results;
// }
//
// public long total;
// public long page;
// public long perPage;
// public List<E> results;
// }
| import com.google.inject.Inject;
import org.cri.redmetrics.csv.CsvEntityConverter;
import org.cri.redmetrics.dao.GameDao;
import org.cri.redmetrics.json.GameJsonConverter;
import org.cri.redmetrics.model.Game;
import org.cri.redmetrics.model.ResultsPage;
import spark.Request;
import java.util.UUID; | package org.cri.redmetrics.controller;
public class GameController extends Controller<Game, GameDao> {
@Inject
GameController(GameDao dao, GameJsonConverter jsonConverter, CsvEntityConverter<Game> csvEntityConverter) {
super("game", dao, jsonConverter, csvEntityConverter);
}
@Override
protected Game read(UUID id) {
Game game = super.read(id);
if (game != null) game.setAdminKey(null);
return game;
}
@Override | // Path: src/main/java/org/cri/redmetrics/csv/CsvEntityConverter.java
// public interface CsvEntityConverter<E extends Entity> {
//
// public void write(CSVWriter csvWriter, List<E> models);
//
// }
//
// Path: src/main/java/org/cri/redmetrics/dao/GameDao.java
// public class GameDao extends EntityDao<Game> {
//
// @Inject
// public GameDao(ConnectionSource connectionSource) throws SQLException {
// super(connectionSource, Game.class);
// }
//
// @Override
// public Game create(Game game) {
// if (game.getName() == null || game.getName().isEmpty())
// throw new InconsistentDataException("Game name is required");
// game.setAdminKey(UUID.randomUUID());
// return super.create(game);
// }
//
// }
//
// Path: src/main/java/org/cri/redmetrics/json/GameJsonConverter.java
// public class GameJsonConverter extends EntityJsonConverter<Game> {
//
// @Inject
// GameJsonConverter(Gson gson, JsonParser jsonParser) {
// super(Game.class, gson, jsonParser);
// }
//
// }
//
// Path: src/main/java/org/cri/redmetrics/model/Game.java
// @Data
// @DatabaseTable(tableName = "games")
// @NoArgsConstructor
// @AllArgsConstructor
// @EqualsAndHashCode(callSuper = true)
// public class Game extends Entity {
//
// @DatabaseField(dataType = DataType.UUID)
// private UUID adminKey;
//
// @DatabaseField(canBeNull = false)
// private String name;
//
// @DatabaseField
// private String author;
//
// @DatabaseField
// private String description;
//
// }
//
// Path: src/main/java/org/cri/redmetrics/model/ResultsPage.java
// public class ResultsPage<E extends Entity> {
// public ResultsPage(long total, long page, long perPage, List<E> results) {
// this.total = total;
// this.page = page;
// this.perPage = perPage;
// this.results = results;
// }
//
// public long total;
// public long page;
// public long perPage;
// public List<E> results;
// }
// Path: src/main/java/org/cri/redmetrics/controller/GameController.java
import com.google.inject.Inject;
import org.cri.redmetrics.csv.CsvEntityConverter;
import org.cri.redmetrics.dao.GameDao;
import org.cri.redmetrics.json.GameJsonConverter;
import org.cri.redmetrics.model.Game;
import org.cri.redmetrics.model.ResultsPage;
import spark.Request;
import java.util.UUID;
package org.cri.redmetrics.controller;
public class GameController extends Controller<Game, GameDao> {
@Inject
GameController(GameDao dao, GameJsonConverter jsonConverter, CsvEntityConverter<Game> csvEntityConverter) {
super("game", dao, jsonConverter, csvEntityConverter);
}
@Override
protected Game read(UUID id) {
Game game = super.read(id);
if (game != null) game.setAdminKey(null);
return game;
}
@Override | protected ResultsPage<Game> list(Request request, long start, long count) { |
CyberCRI/RedMetrics | src/test/java/org/cri/redmetrics/EventBackendTest.java | // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/EventBackend.java
// public class EventBackend extends ProgressDataBackend<TestEvent> {
//
// EventBackend() {
// super("event", TestEvent.class);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestEvent.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestEvent extends TestProgressData {
//
// @Key
// private String type;
//
// @Key
// private Integer[] coordinates;
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGameVersion extends TestEntity {
//
// @Key
// private String game;
//
// @Key
// private String name = "v1";
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestPlayer.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestPlayer extends TestEntity {
//
// @Key
// private String birthDate;
//
// @Key
// private String region;
//
// @Key
// private String country;
//
// @Key
// private String gender;
//
// @Key
// private String externalId;
// }
//
// Path: src/test/java/org/cri/redmetrics/util/DateUtils.java
// public class DateUtils {
//
// // ISO 8601 Extended Format
// private static final DateTimeFormatter DATE_FORMATTER =
// DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(DateTimeZone.UTC);
//
// public static String print(DateTime date) {
// return DATE_FORMATTER.print(date);
// }
//
// public static String now() {
// return print(new DateTime());
// }
//
// }
| import com.google.api.client.http.HttpResponseException;
import com.google.api.client.json.GenericJson;
import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.EventBackend;
import org.cri.redmetrics.model.TestEvent;
import org.cri.redmetrics.model.TestGameVersion;
import org.cri.redmetrics.model.TestPlayer;
import org.cri.redmetrics.util.DateUtils;
import org.joda.time.DateTime;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.failBecauseExceptionWasNotThrown; | package org.cri.redmetrics;
public class EventBackendTest {
static final EventBackend events = Backends.EVENT;
| // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/EventBackend.java
// public class EventBackend extends ProgressDataBackend<TestEvent> {
//
// EventBackend() {
// super("event", TestEvent.class);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestEvent.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestEvent extends TestProgressData {
//
// @Key
// private String type;
//
// @Key
// private Integer[] coordinates;
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGameVersion extends TestEntity {
//
// @Key
// private String game;
//
// @Key
// private String name = "v1";
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestPlayer.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestPlayer extends TestEntity {
//
// @Key
// private String birthDate;
//
// @Key
// private String region;
//
// @Key
// private String country;
//
// @Key
// private String gender;
//
// @Key
// private String externalId;
// }
//
// Path: src/test/java/org/cri/redmetrics/util/DateUtils.java
// public class DateUtils {
//
// // ISO 8601 Extended Format
// private static final DateTimeFormatter DATE_FORMATTER =
// DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(DateTimeZone.UTC);
//
// public static String print(DateTime date) {
// return DATE_FORMATTER.print(date);
// }
//
// public static String now() {
// return print(new DateTime());
// }
//
// }
// Path: src/test/java/org/cri/redmetrics/EventBackendTest.java
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.json.GenericJson;
import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.EventBackend;
import org.cri.redmetrics.model.TestEvent;
import org.cri.redmetrics.model.TestGameVersion;
import org.cri.redmetrics.model.TestPlayer;
import org.cri.redmetrics.util.DateUtils;
import org.joda.time.DateTime;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.failBecauseExceptionWasNotThrown;
package org.cri.redmetrics;
public class EventBackendTest {
static final EventBackend events = Backends.EVENT;
| TestGameVersion gameVersion = Backends.newSavedGameVersion(); |
CyberCRI/RedMetrics | src/test/java/org/cri/redmetrics/EventBackendTest.java | // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/EventBackend.java
// public class EventBackend extends ProgressDataBackend<TestEvent> {
//
// EventBackend() {
// super("event", TestEvent.class);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestEvent.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestEvent extends TestProgressData {
//
// @Key
// private String type;
//
// @Key
// private Integer[] coordinates;
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGameVersion extends TestEntity {
//
// @Key
// private String game;
//
// @Key
// private String name = "v1";
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestPlayer.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestPlayer extends TestEntity {
//
// @Key
// private String birthDate;
//
// @Key
// private String region;
//
// @Key
// private String country;
//
// @Key
// private String gender;
//
// @Key
// private String externalId;
// }
//
// Path: src/test/java/org/cri/redmetrics/util/DateUtils.java
// public class DateUtils {
//
// // ISO 8601 Extended Format
// private static final DateTimeFormatter DATE_FORMATTER =
// DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(DateTimeZone.UTC);
//
// public static String print(DateTime date) {
// return DATE_FORMATTER.print(date);
// }
//
// public static String now() {
// return print(new DateTime());
// }
//
// }
| import com.google.api.client.http.HttpResponseException;
import com.google.api.client.json.GenericJson;
import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.EventBackend;
import org.cri.redmetrics.model.TestEvent;
import org.cri.redmetrics.model.TestGameVersion;
import org.cri.redmetrics.model.TestPlayer;
import org.cri.redmetrics.util.DateUtils;
import org.joda.time.DateTime;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.failBecauseExceptionWasNotThrown; | package org.cri.redmetrics;
public class EventBackendTest {
static final EventBackend events = Backends.EVENT;
TestGameVersion gameVersion = Backends.newSavedGameVersion(); | // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/EventBackend.java
// public class EventBackend extends ProgressDataBackend<TestEvent> {
//
// EventBackend() {
// super("event", TestEvent.class);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestEvent.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestEvent extends TestProgressData {
//
// @Key
// private String type;
//
// @Key
// private Integer[] coordinates;
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGameVersion extends TestEntity {
//
// @Key
// private String game;
//
// @Key
// private String name = "v1";
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestPlayer.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestPlayer extends TestEntity {
//
// @Key
// private String birthDate;
//
// @Key
// private String region;
//
// @Key
// private String country;
//
// @Key
// private String gender;
//
// @Key
// private String externalId;
// }
//
// Path: src/test/java/org/cri/redmetrics/util/DateUtils.java
// public class DateUtils {
//
// // ISO 8601 Extended Format
// private static final DateTimeFormatter DATE_FORMATTER =
// DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(DateTimeZone.UTC);
//
// public static String print(DateTime date) {
// return DATE_FORMATTER.print(date);
// }
//
// public static String now() {
// return print(new DateTime());
// }
//
// }
// Path: src/test/java/org/cri/redmetrics/EventBackendTest.java
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.json.GenericJson;
import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.EventBackend;
import org.cri.redmetrics.model.TestEvent;
import org.cri.redmetrics.model.TestGameVersion;
import org.cri.redmetrics.model.TestPlayer;
import org.cri.redmetrics.util.DateUtils;
import org.joda.time.DateTime;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.failBecauseExceptionWasNotThrown;
package org.cri.redmetrics;
public class EventBackendTest {
static final EventBackend events = Backends.EVENT;
TestGameVersion gameVersion = Backends.newSavedGameVersion(); | TestPlayer player = Backends.newSavedPlayer(); |
CyberCRI/RedMetrics | src/test/java/org/cri/redmetrics/EventBackendTest.java | // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/EventBackend.java
// public class EventBackend extends ProgressDataBackend<TestEvent> {
//
// EventBackend() {
// super("event", TestEvent.class);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestEvent.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestEvent extends TestProgressData {
//
// @Key
// private String type;
//
// @Key
// private Integer[] coordinates;
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGameVersion extends TestEntity {
//
// @Key
// private String game;
//
// @Key
// private String name = "v1";
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestPlayer.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestPlayer extends TestEntity {
//
// @Key
// private String birthDate;
//
// @Key
// private String region;
//
// @Key
// private String country;
//
// @Key
// private String gender;
//
// @Key
// private String externalId;
// }
//
// Path: src/test/java/org/cri/redmetrics/util/DateUtils.java
// public class DateUtils {
//
// // ISO 8601 Extended Format
// private static final DateTimeFormatter DATE_FORMATTER =
// DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(DateTimeZone.UTC);
//
// public static String print(DateTime date) {
// return DATE_FORMATTER.print(date);
// }
//
// public static String now() {
// return print(new DateTime());
// }
//
// }
| import com.google.api.client.http.HttpResponseException;
import com.google.api.client.json.GenericJson;
import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.EventBackend;
import org.cri.redmetrics.model.TestEvent;
import org.cri.redmetrics.model.TestGameVersion;
import org.cri.redmetrics.model.TestPlayer;
import org.cri.redmetrics.util.DateUtils;
import org.joda.time.DateTime;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.failBecauseExceptionWasNotThrown; | package org.cri.redmetrics;
public class EventBackendTest {
static final EventBackend events = Backends.EVENT;
TestGameVersion gameVersion = Backends.newSavedGameVersion();
TestPlayer player = Backends.newSavedPlayer(); | // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/EventBackend.java
// public class EventBackend extends ProgressDataBackend<TestEvent> {
//
// EventBackend() {
// super("event", TestEvent.class);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestEvent.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestEvent extends TestProgressData {
//
// @Key
// private String type;
//
// @Key
// private Integer[] coordinates;
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGameVersion extends TestEntity {
//
// @Key
// private String game;
//
// @Key
// private String name = "v1";
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestPlayer.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestPlayer extends TestEntity {
//
// @Key
// private String birthDate;
//
// @Key
// private String region;
//
// @Key
// private String country;
//
// @Key
// private String gender;
//
// @Key
// private String externalId;
// }
//
// Path: src/test/java/org/cri/redmetrics/util/DateUtils.java
// public class DateUtils {
//
// // ISO 8601 Extended Format
// private static final DateTimeFormatter DATE_FORMATTER =
// DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(DateTimeZone.UTC);
//
// public static String print(DateTime date) {
// return DATE_FORMATTER.print(date);
// }
//
// public static String now() {
// return print(new DateTime());
// }
//
// }
// Path: src/test/java/org/cri/redmetrics/EventBackendTest.java
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.json.GenericJson;
import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.EventBackend;
import org.cri.redmetrics.model.TestEvent;
import org.cri.redmetrics.model.TestGameVersion;
import org.cri.redmetrics.model.TestPlayer;
import org.cri.redmetrics.util.DateUtils;
import org.joda.time.DateTime;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.failBecauseExceptionWasNotThrown;
package org.cri.redmetrics;
public class EventBackendTest {
static final EventBackend events = Backends.EVENT;
TestGameVersion gameVersion = Backends.newSavedGameVersion();
TestPlayer player = Backends.newSavedPlayer(); | TestEvent event; |
CyberCRI/RedMetrics | src/test/java/org/cri/redmetrics/EventBackendTest.java | // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/EventBackend.java
// public class EventBackend extends ProgressDataBackend<TestEvent> {
//
// EventBackend() {
// super("event", TestEvent.class);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestEvent.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestEvent extends TestProgressData {
//
// @Key
// private String type;
//
// @Key
// private Integer[] coordinates;
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGameVersion extends TestEntity {
//
// @Key
// private String game;
//
// @Key
// private String name = "v1";
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestPlayer.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestPlayer extends TestEntity {
//
// @Key
// private String birthDate;
//
// @Key
// private String region;
//
// @Key
// private String country;
//
// @Key
// private String gender;
//
// @Key
// private String externalId;
// }
//
// Path: src/test/java/org/cri/redmetrics/util/DateUtils.java
// public class DateUtils {
//
// // ISO 8601 Extended Format
// private static final DateTimeFormatter DATE_FORMATTER =
// DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(DateTimeZone.UTC);
//
// public static String print(DateTime date) {
// return DATE_FORMATTER.print(date);
// }
//
// public static String now() {
// return print(new DateTime());
// }
//
// }
| import com.google.api.client.http.HttpResponseException;
import com.google.api.client.json.GenericJson;
import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.EventBackend;
import org.cri.redmetrics.model.TestEvent;
import org.cri.redmetrics.model.TestGameVersion;
import org.cri.redmetrics.model.TestPlayer;
import org.cri.redmetrics.util.DateUtils;
import org.joda.time.DateTime;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.failBecauseExceptionWasNotThrown; | resetEvent();
saveEvent();
List<TestEvent> foundEvents = events.search()
.before(afterFirstSave)
.withGameVersion(gameVersion.getId())
.execute();
assertThat(foundEvents).hasSize(1);
}
@Test
public void findsAfterServerTime() throws IOException {
resetEvent(); // Should have been called by TestNG, but the test will strangely fail without this line
try {
Thread.sleep(1001); // Wait one second
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
DateTime beforeCreation = new DateTime();
saveEvent();
List<TestEvent> foundEvents = events.search().after(beforeCreation).execute();
assertThat(foundEvents).hasSize(1);
}
@Test
public void findsBeforeUserTime() throws IOException {
resetGameVersion();
DateTime time = new DateTime();
| // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/EventBackend.java
// public class EventBackend extends ProgressDataBackend<TestEvent> {
//
// EventBackend() {
// super("event", TestEvent.class);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestEvent.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestEvent extends TestProgressData {
//
// @Key
// private String type;
//
// @Key
// private Integer[] coordinates;
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGameVersion extends TestEntity {
//
// @Key
// private String game;
//
// @Key
// private String name = "v1";
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestPlayer.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestPlayer extends TestEntity {
//
// @Key
// private String birthDate;
//
// @Key
// private String region;
//
// @Key
// private String country;
//
// @Key
// private String gender;
//
// @Key
// private String externalId;
// }
//
// Path: src/test/java/org/cri/redmetrics/util/DateUtils.java
// public class DateUtils {
//
// // ISO 8601 Extended Format
// private static final DateTimeFormatter DATE_FORMATTER =
// DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(DateTimeZone.UTC);
//
// public static String print(DateTime date) {
// return DATE_FORMATTER.print(date);
// }
//
// public static String now() {
// return print(new DateTime());
// }
//
// }
// Path: src/test/java/org/cri/redmetrics/EventBackendTest.java
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.json.GenericJson;
import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.EventBackend;
import org.cri.redmetrics.model.TestEvent;
import org.cri.redmetrics.model.TestGameVersion;
import org.cri.redmetrics.model.TestPlayer;
import org.cri.redmetrics.util.DateUtils;
import org.joda.time.DateTime;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.failBecauseExceptionWasNotThrown;
resetEvent();
saveEvent();
List<TestEvent> foundEvents = events.search()
.before(afterFirstSave)
.withGameVersion(gameVersion.getId())
.execute();
assertThat(foundEvents).hasSize(1);
}
@Test
public void findsAfterServerTime() throws IOException {
resetEvent(); // Should have been called by TestNG, but the test will strangely fail without this line
try {
Thread.sleep(1001); // Wait one second
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
DateTime beforeCreation = new DateTime();
saveEvent();
List<TestEvent> foundEvents = events.search().after(beforeCreation).execute();
assertThat(foundEvents).hasSize(1);
}
@Test
public void findsBeforeUserTime() throws IOException {
resetGameVersion();
DateTime time = new DateTime();
| event.setUserTime(DateUtils.print(time.minusSeconds(1))); |
CyberCRI/RedMetrics | src/test/java/org/cri/redmetrics/SnapshotBackendTest.java | // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/SnapshotBackend.java
// public class SnapshotBackend extends ProgressDataBackend<TestSnapshot> {
//
// SnapshotBackend() {
// super("snapshot", TestSnapshot.class);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGameVersion extends TestEntity {
//
// @Key
// private String game;
//
// @Key
// private String name = "v1";
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestPlayer.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestPlayer extends TestEntity {
//
// @Key
// private String birthDate;
//
// @Key
// private String region;
//
// @Key
// private String country;
//
// @Key
// private String gender;
//
// @Key
// private String externalId;
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestSnapshot.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestSnapshot extends TestProgressData {
//
// }
| import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.SnapshotBackend;
import org.cri.redmetrics.model.TestGameVersion;
import org.cri.redmetrics.model.TestPlayer;
import org.cri.redmetrics.model.TestSnapshot;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import static org.fest.assertions.api.Assertions.assertThat; | package org.cri.redmetrics;
public class SnapshotBackendTest {
static final SnapshotBackend snapshots = Backends.SNAPSHOT;
| // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/SnapshotBackend.java
// public class SnapshotBackend extends ProgressDataBackend<TestSnapshot> {
//
// SnapshotBackend() {
// super("snapshot", TestSnapshot.class);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGameVersion extends TestEntity {
//
// @Key
// private String game;
//
// @Key
// private String name = "v1";
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestPlayer.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestPlayer extends TestEntity {
//
// @Key
// private String birthDate;
//
// @Key
// private String region;
//
// @Key
// private String country;
//
// @Key
// private String gender;
//
// @Key
// private String externalId;
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestSnapshot.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestSnapshot extends TestProgressData {
//
// }
// Path: src/test/java/org/cri/redmetrics/SnapshotBackendTest.java
import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.SnapshotBackend;
import org.cri.redmetrics.model.TestGameVersion;
import org.cri.redmetrics.model.TestPlayer;
import org.cri.redmetrics.model.TestSnapshot;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import static org.fest.assertions.api.Assertions.assertThat;
package org.cri.redmetrics;
public class SnapshotBackendTest {
static final SnapshotBackend snapshots = Backends.SNAPSHOT;
| TestGameVersion gameVersion; |
CyberCRI/RedMetrics | src/test/java/org/cri/redmetrics/SnapshotBackendTest.java | // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/SnapshotBackend.java
// public class SnapshotBackend extends ProgressDataBackend<TestSnapshot> {
//
// SnapshotBackend() {
// super("snapshot", TestSnapshot.class);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGameVersion extends TestEntity {
//
// @Key
// private String game;
//
// @Key
// private String name = "v1";
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestPlayer.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestPlayer extends TestEntity {
//
// @Key
// private String birthDate;
//
// @Key
// private String region;
//
// @Key
// private String country;
//
// @Key
// private String gender;
//
// @Key
// private String externalId;
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestSnapshot.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestSnapshot extends TestProgressData {
//
// }
| import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.SnapshotBackend;
import org.cri.redmetrics.model.TestGameVersion;
import org.cri.redmetrics.model.TestPlayer;
import org.cri.redmetrics.model.TestSnapshot;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import static org.fest.assertions.api.Assertions.assertThat; | package org.cri.redmetrics;
public class SnapshotBackendTest {
static final SnapshotBackend snapshots = Backends.SNAPSHOT;
TestGameVersion gameVersion; | // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/SnapshotBackend.java
// public class SnapshotBackend extends ProgressDataBackend<TestSnapshot> {
//
// SnapshotBackend() {
// super("snapshot", TestSnapshot.class);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGameVersion extends TestEntity {
//
// @Key
// private String game;
//
// @Key
// private String name = "v1";
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestPlayer.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestPlayer extends TestEntity {
//
// @Key
// private String birthDate;
//
// @Key
// private String region;
//
// @Key
// private String country;
//
// @Key
// private String gender;
//
// @Key
// private String externalId;
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestSnapshot.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestSnapshot extends TestProgressData {
//
// }
// Path: src/test/java/org/cri/redmetrics/SnapshotBackendTest.java
import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.SnapshotBackend;
import org.cri.redmetrics.model.TestGameVersion;
import org.cri.redmetrics.model.TestPlayer;
import org.cri.redmetrics.model.TestSnapshot;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import static org.fest.assertions.api.Assertions.assertThat;
package org.cri.redmetrics;
public class SnapshotBackendTest {
static final SnapshotBackend snapshots = Backends.SNAPSHOT;
TestGameVersion gameVersion; | TestPlayer player; |
CyberCRI/RedMetrics | src/test/java/org/cri/redmetrics/SnapshotBackendTest.java | // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/SnapshotBackend.java
// public class SnapshotBackend extends ProgressDataBackend<TestSnapshot> {
//
// SnapshotBackend() {
// super("snapshot", TestSnapshot.class);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGameVersion extends TestEntity {
//
// @Key
// private String game;
//
// @Key
// private String name = "v1";
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestPlayer.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestPlayer extends TestEntity {
//
// @Key
// private String birthDate;
//
// @Key
// private String region;
//
// @Key
// private String country;
//
// @Key
// private String gender;
//
// @Key
// private String externalId;
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestSnapshot.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestSnapshot extends TestProgressData {
//
// }
| import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.SnapshotBackend;
import org.cri.redmetrics.model.TestGameVersion;
import org.cri.redmetrics.model.TestPlayer;
import org.cri.redmetrics.model.TestSnapshot;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import static org.fest.assertions.api.Assertions.assertThat; | package org.cri.redmetrics;
public class SnapshotBackendTest {
static final SnapshotBackend snapshots = Backends.SNAPSHOT;
TestGameVersion gameVersion;
TestPlayer player; | // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/SnapshotBackend.java
// public class SnapshotBackend extends ProgressDataBackend<TestSnapshot> {
//
// SnapshotBackend() {
// super("snapshot", TestSnapshot.class);
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestGameVersion.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestGameVersion extends TestEntity {
//
// @Key
// private String game;
//
// @Key
// private String name = "v1";
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestPlayer.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestPlayer extends TestEntity {
//
// @Key
// private String birthDate;
//
// @Key
// private String region;
//
// @Key
// private String country;
//
// @Key
// private String gender;
//
// @Key
// private String externalId;
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestSnapshot.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestSnapshot extends TestProgressData {
//
// }
// Path: src/test/java/org/cri/redmetrics/SnapshotBackendTest.java
import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.SnapshotBackend;
import org.cri.redmetrics.model.TestGameVersion;
import org.cri.redmetrics.model.TestPlayer;
import org.cri.redmetrics.model.TestSnapshot;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import static org.fest.assertions.api.Assertions.assertThat;
package org.cri.redmetrics;
public class SnapshotBackendTest {
static final SnapshotBackend snapshots = Backends.SNAPSHOT;
TestGameVersion gameVersion;
TestPlayer player; | TestSnapshot snapshot; |
CyberCRI/RedMetrics | src/main/java/org/cri/redmetrics/ConfigHelper.java | // Path: src/main/java/org/cri/configurator/Config.java
// public interface Config<K, V extends Serializable> {
//
// public void put(K key, V value);
//
// public V get(String K);
//
// public void read(Path path) throws IOException;
//
// public void write(Path path) throws IOException;
//
// }
//
// Path: src/main/java/org/cri/configurator/Configs.java
// public class Configs {
//
// public static Config getSimpleConfig(Path path, String ... requiredOptions) throws IOException {
// SimpleLinuxLikeConfig config = new SimpleLinuxLikeConfig();
// config.read(path);
//
// Arrays.asList(requiredOptions).forEach(option -> {
// if(!config.config.containsKey(option)){
// throw new IllegalStateException("Missing property : " + option);
// }
// });
//
// return config;
//
// }
//
// private static class SimpleLinuxLikeConfig implements Config<String, String> {
//
// private final HashMap<String, String> config = new HashMap<>();
//
// public SimpleLinuxLikeConfig() {
// }
//
// @Override
// public void put(String key, String value) {
// config.put(key, value);
// }
//
// @Override
// public String get(String K) {
// return config.get(K);
// }
//
// @Override
// public void read(Path path) throws IOException {
// Files.lines(path).filter(line -> !(line.startsWith("#") ||
// line.isEmpty()))
// .forEach(line -> {
// String[] splittedLine = line.split(" ");
// if (splittedLine.length < 2) {
// String error = "Error parsing the file";
// if (splittedLine.length == 1) {
// throw new IllegalArgumentException(error
// + " : missing value near key "
// + splittedLine[0]);
// }
// }
// config.put(splittedLine[0], splittedLine[1]);
// });
// }
//
// @Override
// public void write(Path path) throws IOException {
// Files.write(path,
// config.entrySet()
// .stream()
// .map(entry -> entry.getKey() + " " + entry.getValue()).collect(Collectors.toList()),
// StandardOpenOption.CREATE);
// }
// }
// }
| import org.cri.configurator.Config;
import org.cri.configurator.Configs;
import java.io.IOException;
import java.nio.file.Paths; | package org.cri.redmetrics;
/**
* Created by himmelattack on 23/02/15.
*/
public class ConfigHelper {
public static Config<String, String> getDefaultConfig() {
Config<String, String> config = null;
String requiredOptions[] = {"databaseURL", "listenPort", "dbusername", "dbassword", "hostName"};
try { | // Path: src/main/java/org/cri/configurator/Config.java
// public interface Config<K, V extends Serializable> {
//
// public void put(K key, V value);
//
// public V get(String K);
//
// public void read(Path path) throws IOException;
//
// public void write(Path path) throws IOException;
//
// }
//
// Path: src/main/java/org/cri/configurator/Configs.java
// public class Configs {
//
// public static Config getSimpleConfig(Path path, String ... requiredOptions) throws IOException {
// SimpleLinuxLikeConfig config = new SimpleLinuxLikeConfig();
// config.read(path);
//
// Arrays.asList(requiredOptions).forEach(option -> {
// if(!config.config.containsKey(option)){
// throw new IllegalStateException("Missing property : " + option);
// }
// });
//
// return config;
//
// }
//
// private static class SimpleLinuxLikeConfig implements Config<String, String> {
//
// private final HashMap<String, String> config = new HashMap<>();
//
// public SimpleLinuxLikeConfig() {
// }
//
// @Override
// public void put(String key, String value) {
// config.put(key, value);
// }
//
// @Override
// public String get(String K) {
// return config.get(K);
// }
//
// @Override
// public void read(Path path) throws IOException {
// Files.lines(path).filter(line -> !(line.startsWith("#") ||
// line.isEmpty()))
// .forEach(line -> {
// String[] splittedLine = line.split(" ");
// if (splittedLine.length < 2) {
// String error = "Error parsing the file";
// if (splittedLine.length == 1) {
// throw new IllegalArgumentException(error
// + " : missing value near key "
// + splittedLine[0]);
// }
// }
// config.put(splittedLine[0], splittedLine[1]);
// });
// }
//
// @Override
// public void write(Path path) throws IOException {
// Files.write(path,
// config.entrySet()
// .stream()
// .map(entry -> entry.getKey() + " " + entry.getValue()).collect(Collectors.toList()),
// StandardOpenOption.CREATE);
// }
// }
// }
// Path: src/main/java/org/cri/redmetrics/ConfigHelper.java
import org.cri.configurator.Config;
import org.cri.configurator.Configs;
import java.io.IOException;
import java.nio.file.Paths;
package org.cri.redmetrics;
/**
* Created by himmelattack on 23/02/15.
*/
public class ConfigHelper {
public static Config<String, String> getDefaultConfig() {
Config<String, String> config = null;
String requiredOptions[] = {"databaseURL", "listenPort", "dbusername", "dbassword", "hostName"};
try { | config = Configs.getSimpleConfig(Paths.get("./redmetrics.conf"), requiredOptions); |
CyberCRI/RedMetrics | src/test/java/org/cri/redmetrics/PlayerBackendTest.java | // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/PlayerBackend.java
// public class PlayerBackend extends HttpBackend<TestPlayer> {
//
// PlayerBackend() {
// super("player", TestPlayer.class);
// }
// }
//
// Path: src/test/java/org/cri/redmetrics/model/Players.java
// public class Players {
//
// public static TestPlayer newJohnSnow() {
// return new PlayerBuilder().withNewRandomExternalId().withGender(Gender.MALE).withRegion("South").withCountry("The North").build();
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestPlayer.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestPlayer extends TestEntity {
//
// @Key
// private String birthDate;
//
// @Key
// private String region;
//
// @Key
// private String country;
//
// @Key
// private String gender;
//
// @Key
// private String externalId;
// }
| import com.google.api.client.http.HttpResponseException;
import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.PlayerBackend;
import org.cri.redmetrics.model.Players;
import org.cri.redmetrics.model.TestPlayer;
import org.testng.annotations.Test;
import java.io.IOException;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.failBecauseExceptionWasNotThrown; | package org.cri.redmetrics;
public class PlayerBackendTest {
final PlayerBackend players = Backends.PLAYER;
// CREATE
@Test
public void canCreatePlayer() throws IOException { | // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/PlayerBackend.java
// public class PlayerBackend extends HttpBackend<TestPlayer> {
//
// PlayerBackend() {
// super("player", TestPlayer.class);
// }
// }
//
// Path: src/test/java/org/cri/redmetrics/model/Players.java
// public class Players {
//
// public static TestPlayer newJohnSnow() {
// return new PlayerBuilder().withNewRandomExternalId().withGender(Gender.MALE).withRegion("South").withCountry("The North").build();
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestPlayer.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestPlayer extends TestEntity {
//
// @Key
// private String birthDate;
//
// @Key
// private String region;
//
// @Key
// private String country;
//
// @Key
// private String gender;
//
// @Key
// private String externalId;
// }
// Path: src/test/java/org/cri/redmetrics/PlayerBackendTest.java
import com.google.api.client.http.HttpResponseException;
import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.PlayerBackend;
import org.cri.redmetrics.model.Players;
import org.cri.redmetrics.model.TestPlayer;
import org.testng.annotations.Test;
import java.io.IOException;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.failBecauseExceptionWasNotThrown;
package org.cri.redmetrics;
public class PlayerBackendTest {
final PlayerBackend players = Backends.PLAYER;
// CREATE
@Test
public void canCreatePlayer() throws IOException { | TestPlayer johnSnow = Players.newJohnSnow(); |
CyberCRI/RedMetrics | src/test/java/org/cri/redmetrics/PlayerBackendTest.java | // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/PlayerBackend.java
// public class PlayerBackend extends HttpBackend<TestPlayer> {
//
// PlayerBackend() {
// super("player", TestPlayer.class);
// }
// }
//
// Path: src/test/java/org/cri/redmetrics/model/Players.java
// public class Players {
//
// public static TestPlayer newJohnSnow() {
// return new PlayerBuilder().withNewRandomExternalId().withGender(Gender.MALE).withRegion("South").withCountry("The North").build();
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestPlayer.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestPlayer extends TestEntity {
//
// @Key
// private String birthDate;
//
// @Key
// private String region;
//
// @Key
// private String country;
//
// @Key
// private String gender;
//
// @Key
// private String externalId;
// }
| import com.google.api.client.http.HttpResponseException;
import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.PlayerBackend;
import org.cri.redmetrics.model.Players;
import org.cri.redmetrics.model.TestPlayer;
import org.testng.annotations.Test;
import java.io.IOException;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.failBecauseExceptionWasNotThrown; | package org.cri.redmetrics;
public class PlayerBackendTest {
final PlayerBackend players = Backends.PLAYER;
// CREATE
@Test
public void canCreatePlayer() throws IOException { | // Path: src/test/java/org/cri/redmetrics/backend/Backends.java
// public class Backends {
//
// public static final EventBackend EVENT = new EventBackend();
// public static final GameBackend GAME = new GameBackend();
// public static final GameVersionBackend GAME_VERSION = new GameVersionBackend();
// public static final GroupBackend GROUP = new GroupBackend();
// public static final PlayerBackend PLAYER = new PlayerBackend();
// public static final SnapshotBackend SNAPSHOT = new SnapshotBackend();
// private static int gameNo = 0;
//
// public static TestGame newSavedGame() {
//
// try {
// TestGame game = new TestGame();
// game.setName("My Test Game " + gameNo);
// ++gameNo;
// TestGame savedGame = GAME.post(game);
// return savedGame;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestGameVersion newSavedGameVersion() {
// try {
// TestGame game = newSavedGame();
// TestGameVersion gameVersion = new TestGameVersion();
// gameVersion.setGame(game.getId());
// gameVersion.setName("version 1");
// gameVersion = GAME_VERSION.post(gameVersion);
// return gameVersion;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static TestPlayer newSavedPlayer() {
// try {
// TestPlayer player = Players.newJohnSnow();
// TestPlayer savedPlayer = PLAYER.post(player);
// return savedPlayer;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/backend/PlayerBackend.java
// public class PlayerBackend extends HttpBackend<TestPlayer> {
//
// PlayerBackend() {
// super("player", TestPlayer.class);
// }
// }
//
// Path: src/test/java/org/cri/redmetrics/model/Players.java
// public class Players {
//
// public static TestPlayer newJohnSnow() {
// return new PlayerBuilder().withNewRandomExternalId().withGender(Gender.MALE).withRegion("South").withCountry("The North").build();
// }
//
// }
//
// Path: src/test/java/org/cri/redmetrics/model/TestPlayer.java
// @Data
// @EqualsAndHashCode(callSuper = true)
// @ToString(callSuper = true)
// public class TestPlayer extends TestEntity {
//
// @Key
// private String birthDate;
//
// @Key
// private String region;
//
// @Key
// private String country;
//
// @Key
// private String gender;
//
// @Key
// private String externalId;
// }
// Path: src/test/java/org/cri/redmetrics/PlayerBackendTest.java
import com.google.api.client.http.HttpResponseException;
import org.cri.redmetrics.backend.Backends;
import org.cri.redmetrics.backend.PlayerBackend;
import org.cri.redmetrics.model.Players;
import org.cri.redmetrics.model.TestPlayer;
import org.testng.annotations.Test;
import java.io.IOException;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.failBecauseExceptionWasNotThrown;
package org.cri.redmetrics;
public class PlayerBackendTest {
final PlayerBackend players = Backends.PLAYER;
// CREATE
@Test
public void canCreatePlayer() throws IOException { | TestPlayer johnSnow = Players.newJohnSnow(); |
CyberCRI/RedMetrics | src/main/java/org/cri/redmetrics/controller/GroupController.java | // Path: src/main/java/org/cri/redmetrics/csv/CsvEntityConverter.java
// public interface CsvEntityConverter<E extends Entity> {
//
// public void write(CSVWriter csvWriter, List<E> models);
//
// }
//
// Path: src/main/java/org/cri/redmetrics/dao/GroupDao.java
// public class GroupDao extends EntityDao<Group>{
//
// @Inject
// public GroupDao(ConnectionSource connectionSource) throws SQLException {
// super(connectionSource, Group.class);
// }
// }
//
// Path: src/main/java/org/cri/redmetrics/json/GroupJsonConverter.java
// public class GroupJsonConverter extends EntityJsonConverter<Group>{
//
// @Inject
// GroupJsonConverter(Gson gson, JsonParser jsonParser) {
// super(Group.class, gson, jsonParser);
// }
// }
//
// Path: src/main/java/org/cri/redmetrics/model/Group.java
// @Data
// @DatabaseTable(tableName = "groups")
// @NoArgsConstructor
// @AllArgsConstructor
// @EqualsAndHashCode(callSuper = true)
// public class Group extends Entity{
//
// @DatabaseField(canBeNull = false)
// private String name;
//
// @DatabaseField
// private String description;
//
// @DatabaseField
// private String creator;
//
// @DatabaseField
// private boolean open;
// }
| import com.google.inject.Inject;
import org.cri.redmetrics.csv.CsvEntityConverter;
import org.cri.redmetrics.dao.GroupDao;
import org.cri.redmetrics.json.GroupJsonConverter;
import org.cri.redmetrics.model.Group; |
package org.cri.redmetrics.controller;
public class GroupController extends Controller<Group, GroupDao>{
@Inject | // Path: src/main/java/org/cri/redmetrics/csv/CsvEntityConverter.java
// public interface CsvEntityConverter<E extends Entity> {
//
// public void write(CSVWriter csvWriter, List<E> models);
//
// }
//
// Path: src/main/java/org/cri/redmetrics/dao/GroupDao.java
// public class GroupDao extends EntityDao<Group>{
//
// @Inject
// public GroupDao(ConnectionSource connectionSource) throws SQLException {
// super(connectionSource, Group.class);
// }
// }
//
// Path: src/main/java/org/cri/redmetrics/json/GroupJsonConverter.java
// public class GroupJsonConverter extends EntityJsonConverter<Group>{
//
// @Inject
// GroupJsonConverter(Gson gson, JsonParser jsonParser) {
// super(Group.class, gson, jsonParser);
// }
// }
//
// Path: src/main/java/org/cri/redmetrics/model/Group.java
// @Data
// @DatabaseTable(tableName = "groups")
// @NoArgsConstructor
// @AllArgsConstructor
// @EqualsAndHashCode(callSuper = true)
// public class Group extends Entity{
//
// @DatabaseField(canBeNull = false)
// private String name;
//
// @DatabaseField
// private String description;
//
// @DatabaseField
// private String creator;
//
// @DatabaseField
// private boolean open;
// }
// Path: src/main/java/org/cri/redmetrics/controller/GroupController.java
import com.google.inject.Inject;
import org.cri.redmetrics.csv.CsvEntityConverter;
import org.cri.redmetrics.dao.GroupDao;
import org.cri.redmetrics.json.GroupJsonConverter;
import org.cri.redmetrics.model.Group;
package org.cri.redmetrics.controller;
public class GroupController extends Controller<Group, GroupDao>{
@Inject | GroupController(GroupDao dao, GroupJsonConverter jsonConverter, CsvEntityConverter<Group> csvEntityConverter) { |
CyberCRI/RedMetrics | src/main/java/org/cri/redmetrics/controller/GroupController.java | // Path: src/main/java/org/cri/redmetrics/csv/CsvEntityConverter.java
// public interface CsvEntityConverter<E extends Entity> {
//
// public void write(CSVWriter csvWriter, List<E> models);
//
// }
//
// Path: src/main/java/org/cri/redmetrics/dao/GroupDao.java
// public class GroupDao extends EntityDao<Group>{
//
// @Inject
// public GroupDao(ConnectionSource connectionSource) throws SQLException {
// super(connectionSource, Group.class);
// }
// }
//
// Path: src/main/java/org/cri/redmetrics/json/GroupJsonConverter.java
// public class GroupJsonConverter extends EntityJsonConverter<Group>{
//
// @Inject
// GroupJsonConverter(Gson gson, JsonParser jsonParser) {
// super(Group.class, gson, jsonParser);
// }
// }
//
// Path: src/main/java/org/cri/redmetrics/model/Group.java
// @Data
// @DatabaseTable(tableName = "groups")
// @NoArgsConstructor
// @AllArgsConstructor
// @EqualsAndHashCode(callSuper = true)
// public class Group extends Entity{
//
// @DatabaseField(canBeNull = false)
// private String name;
//
// @DatabaseField
// private String description;
//
// @DatabaseField
// private String creator;
//
// @DatabaseField
// private boolean open;
// }
| import com.google.inject.Inject;
import org.cri.redmetrics.csv.CsvEntityConverter;
import org.cri.redmetrics.dao.GroupDao;
import org.cri.redmetrics.json.GroupJsonConverter;
import org.cri.redmetrics.model.Group; |
package org.cri.redmetrics.controller;
public class GroupController extends Controller<Group, GroupDao>{
@Inject | // Path: src/main/java/org/cri/redmetrics/csv/CsvEntityConverter.java
// public interface CsvEntityConverter<E extends Entity> {
//
// public void write(CSVWriter csvWriter, List<E> models);
//
// }
//
// Path: src/main/java/org/cri/redmetrics/dao/GroupDao.java
// public class GroupDao extends EntityDao<Group>{
//
// @Inject
// public GroupDao(ConnectionSource connectionSource) throws SQLException {
// super(connectionSource, Group.class);
// }
// }
//
// Path: src/main/java/org/cri/redmetrics/json/GroupJsonConverter.java
// public class GroupJsonConverter extends EntityJsonConverter<Group>{
//
// @Inject
// GroupJsonConverter(Gson gson, JsonParser jsonParser) {
// super(Group.class, gson, jsonParser);
// }
// }
//
// Path: src/main/java/org/cri/redmetrics/model/Group.java
// @Data
// @DatabaseTable(tableName = "groups")
// @NoArgsConstructor
// @AllArgsConstructor
// @EqualsAndHashCode(callSuper = true)
// public class Group extends Entity{
//
// @DatabaseField(canBeNull = false)
// private String name;
//
// @DatabaseField
// private String description;
//
// @DatabaseField
// private String creator;
//
// @DatabaseField
// private boolean open;
// }
// Path: src/main/java/org/cri/redmetrics/controller/GroupController.java
import com.google.inject.Inject;
import org.cri.redmetrics.csv.CsvEntityConverter;
import org.cri.redmetrics.dao.GroupDao;
import org.cri.redmetrics.json.GroupJsonConverter;
import org.cri.redmetrics.model.Group;
package org.cri.redmetrics.controller;
public class GroupController extends Controller<Group, GroupDao>{
@Inject | GroupController(GroupDao dao, GroupJsonConverter jsonConverter, CsvEntityConverter<Group> csvEntityConverter) { |
arquillian/arquillian-governor | skipper/src/main/java/org/arquillian/extension/governor/skipper/config/SkipperConfigurator.java | // Path: spi/src/main/java/org/arquillian/extension/governor/spi/event/GovernorExtensionConfigured.java
// public class GovernorExtensionConfigured {
//
// }
| import org.arquillian.extension.governor.skipper.impl.SkipperReportHolder;
import org.arquillian.extension.governor.spi.event.GovernorExtensionConfigured;
import org.jboss.arquillian.config.descriptor.api.ArquillianDescriptor;
import org.jboss.arquillian.config.descriptor.api.ExtensionDef;
import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.InstanceProducer;
import org.jboss.arquillian.core.api.annotation.ApplicationScoped;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.core.api.annotation.Observes;
import org.jboss.arquillian.core.spi.ServiceLoader;
import java.util.logging.Level;
import java.util.logging.Logger; | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.arquillian.extension.governor.skipper.config;
/**
* @author <a href="mailto:smikloso@redhat.com">Stefan Miklosovic</a>
*/
public class SkipperConfigurator {
private static final Logger logger = Logger.getLogger(SkipperConfigurator.class.getName());
private static final String EXTENSION_NAME = "governor-skipper";
@Inject
private Instance<ServiceLoader> serviceLoader;
@Inject
@ApplicationScoped
private InstanceProducer<SkipperConfiguration> skipperConfiguration;
@Inject
@ApplicationScoped
private InstanceProducer<SkipperReportHolder> skipperReportHolder;
| // Path: spi/src/main/java/org/arquillian/extension/governor/spi/event/GovernorExtensionConfigured.java
// public class GovernorExtensionConfigured {
//
// }
// Path: skipper/src/main/java/org/arquillian/extension/governor/skipper/config/SkipperConfigurator.java
import org.arquillian.extension.governor.skipper.impl.SkipperReportHolder;
import org.arquillian.extension.governor.spi.event.GovernorExtensionConfigured;
import org.jboss.arquillian.config.descriptor.api.ArquillianDescriptor;
import org.jboss.arquillian.config.descriptor.api.ExtensionDef;
import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.InstanceProducer;
import org.jboss.arquillian.core.api.annotation.ApplicationScoped;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.core.api.annotation.Observes;
import org.jboss.arquillian.core.spi.ServiceLoader;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.arquillian.extension.governor.skipper.config;
/**
* @author <a href="mailto:smikloso@redhat.com">Stefan Miklosovic</a>
*/
public class SkipperConfigurator {
private static final Logger logger = Logger.getLogger(SkipperConfigurator.class.getName());
private static final String EXTENSION_NAME = "governor-skipper";
@Inject
private Instance<ServiceLoader> serviceLoader;
@Inject
@ApplicationScoped
private InstanceProducer<SkipperConfiguration> skipperConfiguration;
@Inject
@ApplicationScoped
private InstanceProducer<SkipperReportHolder> skipperReportHolder;
| public void onGovernorExtensionConfigured(@Observes GovernorExtensionConfigured event, ArquillianDescriptor arquillianDescriptor) throws Exception { |
arquillian/arquillian-governor | jira/src/main/java/org/arquillian/extension/governor/jira/configuration/JiraGovernorConfiguration.java | // Path: api/src/main/java/org/arquillian/extension/governor/api/Configuration.java
// public abstract class Configuration {
//
// private Map<String, String> configuration = new HashMap<String, String>();
//
// /**
// * @return configuration of extension
// */
// public Map<String, String> getConfiguration() {
// return this.configuration;
// }
//
// /**
// * Gets configuration from Arquillian descriptor and creates instance of it.
// *
// * @param configuration configuration of extension from arquillian.xml
// * @return this
// * @throws IllegalArgumentException if {@code configuration} is a null object
// */
// public Configuration setConfiguration(Map<String, String> configuration) {
// Validate.notNull(configuration, "Properties for configuration of Arquillian Governor extension can not be a null object!");
// this.configuration = configuration;
// return this;
// }
//
// /**
// * Gets value of {@code name} property. In case a value for such name does not exist or is a null object or an empty string,
// * {@code defaultValue} is returned.
// *
// * @param name name of a property you want to get the value of
// * @param defaultValue value returned in case {@code name} is a null string or it is empty
// * @return value of a {@code name} property of {@code defaultValue} when {@code name} is null or empty string
// * @throws IllegalArgumentException if {@code name} is a null object or an empty string or if {@code defaultValue} is a null
// * object
// */
// public String getProperty(String name, String defaultValue) throws IllegalStateException {
// Validate.notNullOrEmpty(name, "Unable to get the configuration value of null or empty configuration key");
// Validate.notNull(defaultValue, "Unable to set configuration value of " + name + " to null object.");
//
// final String found = getConfiguration().get(name);
//
// if (found == null || found.isEmpty()) {
// return defaultValue;
// } else {
// return found;
// }
// }
//
// /**
// * Sets some property.
// *
// * @param name acts as a key
// * @param value
// * @throws IllegalArgumentException if {@code name} is null or empty or {@code value} is null
// */
// public void setProperty(String name, String value) {
// Validate.notNullOrEmpty(name, "Name of property can not be a null object nor an empty string!");
// Validate.notNull(value, "Value of property can not be a null object!");
//
// configuration.put(name, value);
// }
//
// /**
// * Gets value of {@code name} property as defined in system variable or return to the {@code getProperty} method to
// * fetch the value from arquillian.xml
// *
// * @param name name of a property you want to get the value of
// * @param value value of a {@code name} property as defined in system variable or {@code defaultValue} in case it is
// * null or empty string
// * @param defaultValue value returned in case {@code name} is a null string or it is empty
// * @return value of a {@code name} property as defined in system variable or return to {@code getProperty} if none provided
// */
// protected String getSystemProperty(String name, String value, String defaultValue) {
// if (!value.equals(defaultValue)) {
// return value;
// } else {
// return getProperty(name, defaultValue);
// }
// }
//
// /**
// * Validates configuration.
// *
// * @throws GovernorConfigurationException when configuration of the extension is not valid
// */
// public abstract void validate() throws GovernorConfigurationException;
// }
//
// Path: api/src/main/java/org/arquillian/extension/governor/api/GovernorConfigurationException.java
// public class GovernorConfigurationException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public GovernorConfigurationException() {
// super();
// }
//
// public GovernorConfigurationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GovernorConfigurationException(String message) {
// super(message);
// }
//
// public GovernorConfigurationException(Throwable cause) {
// super(cause);
// }
//
// }
| import org.arquillian.extension.governor.api.Configuration;
import org.arquillian.extension.governor.api.GovernorConfigurationException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL; | }
public void setServer(String server) {
setProperty("server", server);
}
public boolean getForce() {
return Boolean.parseBoolean(getSystemProperty("force", Boolean.toString(force), "false"));
}
public void setForce(boolean force) {
setProperty("force", Boolean.toString(force));
}
public boolean getClosePassed() {
return Boolean.parseBoolean(getSystemProperty("closePassed", Boolean.toString(closePassed), "false"));
}
public void setClosePassed(boolean closePassed) {
setProperty("closePassed", Boolean.toString(closePassed));
}
public String getClosingMessage() {
return getProperty("closingMessage", DEFAULT_JIRA_CLOSING_MESSAGE);
}
public void setClosingMessage(String closingMessage) {
setProperty("closingMessage", closingMessage);
}
| // Path: api/src/main/java/org/arquillian/extension/governor/api/Configuration.java
// public abstract class Configuration {
//
// private Map<String, String> configuration = new HashMap<String, String>();
//
// /**
// * @return configuration of extension
// */
// public Map<String, String> getConfiguration() {
// return this.configuration;
// }
//
// /**
// * Gets configuration from Arquillian descriptor and creates instance of it.
// *
// * @param configuration configuration of extension from arquillian.xml
// * @return this
// * @throws IllegalArgumentException if {@code configuration} is a null object
// */
// public Configuration setConfiguration(Map<String, String> configuration) {
// Validate.notNull(configuration, "Properties for configuration of Arquillian Governor extension can not be a null object!");
// this.configuration = configuration;
// return this;
// }
//
// /**
// * Gets value of {@code name} property. In case a value for such name does not exist or is a null object or an empty string,
// * {@code defaultValue} is returned.
// *
// * @param name name of a property you want to get the value of
// * @param defaultValue value returned in case {@code name} is a null string or it is empty
// * @return value of a {@code name} property of {@code defaultValue} when {@code name} is null or empty string
// * @throws IllegalArgumentException if {@code name} is a null object or an empty string or if {@code defaultValue} is a null
// * object
// */
// public String getProperty(String name, String defaultValue) throws IllegalStateException {
// Validate.notNullOrEmpty(name, "Unable to get the configuration value of null or empty configuration key");
// Validate.notNull(defaultValue, "Unable to set configuration value of " + name + " to null object.");
//
// final String found = getConfiguration().get(name);
//
// if (found == null || found.isEmpty()) {
// return defaultValue;
// } else {
// return found;
// }
// }
//
// /**
// * Sets some property.
// *
// * @param name acts as a key
// * @param value
// * @throws IllegalArgumentException if {@code name} is null or empty or {@code value} is null
// */
// public void setProperty(String name, String value) {
// Validate.notNullOrEmpty(name, "Name of property can not be a null object nor an empty string!");
// Validate.notNull(value, "Value of property can not be a null object!");
//
// configuration.put(name, value);
// }
//
// /**
// * Gets value of {@code name} property as defined in system variable or return to the {@code getProperty} method to
// * fetch the value from arquillian.xml
// *
// * @param name name of a property you want to get the value of
// * @param value value of a {@code name} property as defined in system variable or {@code defaultValue} in case it is
// * null or empty string
// * @param defaultValue value returned in case {@code name} is a null string or it is empty
// * @return value of a {@code name} property as defined in system variable or return to {@code getProperty} if none provided
// */
// protected String getSystemProperty(String name, String value, String defaultValue) {
// if (!value.equals(defaultValue)) {
// return value;
// } else {
// return getProperty(name, defaultValue);
// }
// }
//
// /**
// * Validates configuration.
// *
// * @throws GovernorConfigurationException when configuration of the extension is not valid
// */
// public abstract void validate() throws GovernorConfigurationException;
// }
//
// Path: api/src/main/java/org/arquillian/extension/governor/api/GovernorConfigurationException.java
// public class GovernorConfigurationException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public GovernorConfigurationException() {
// super();
// }
//
// public GovernorConfigurationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GovernorConfigurationException(String message) {
// super(message);
// }
//
// public GovernorConfigurationException(Throwable cause) {
// super(cause);
// }
//
// }
// Path: jira/src/main/java/org/arquillian/extension/governor/jira/configuration/JiraGovernorConfiguration.java
import org.arquillian.extension.governor.api.Configuration;
import org.arquillian.extension.governor.api.GovernorConfigurationException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
}
public void setServer(String server) {
setProperty("server", server);
}
public boolean getForce() {
return Boolean.parseBoolean(getSystemProperty("force", Boolean.toString(force), "false"));
}
public void setForce(boolean force) {
setProperty("force", Boolean.toString(force));
}
public boolean getClosePassed() {
return Boolean.parseBoolean(getSystemProperty("closePassed", Boolean.toString(closePassed), "false"));
}
public void setClosePassed(boolean closePassed) {
setProperty("closePassed", Boolean.toString(closePassed));
}
public String getClosingMessage() {
return getProperty("closingMessage", DEFAULT_JIRA_CLOSING_MESSAGE);
}
public void setClosingMessage(String closingMessage) {
setProperty("closingMessage", closingMessage);
}
| public URL getServerURL() throws GovernorConfigurationException { |
arquillian/arquillian-governor | github/src/main/java/org/arquillian/extension/governor/github/configuration/GitHubGovernorConfiguration.java | // Path: api/src/main/java/org/arquillian/extension/governor/api/Configuration.java
// public abstract class Configuration {
//
// private Map<String, String> configuration = new HashMap<String, String>();
//
// /**
// * @return configuration of extension
// */
// public Map<String, String> getConfiguration() {
// return this.configuration;
// }
//
// /**
// * Gets configuration from Arquillian descriptor and creates instance of it.
// *
// * @param configuration configuration of extension from arquillian.xml
// * @return this
// * @throws IllegalArgumentException if {@code configuration} is a null object
// */
// public Configuration setConfiguration(Map<String, String> configuration) {
// Validate.notNull(configuration, "Properties for configuration of Arquillian Governor extension can not be a null object!");
// this.configuration = configuration;
// return this;
// }
//
// /**
// * Gets value of {@code name} property. In case a value for such name does not exist or is a null object or an empty string,
// * {@code defaultValue} is returned.
// *
// * @param name name of a property you want to get the value of
// * @param defaultValue value returned in case {@code name} is a null string or it is empty
// * @return value of a {@code name} property of {@code defaultValue} when {@code name} is null or empty string
// * @throws IllegalArgumentException if {@code name} is a null object or an empty string or if {@code defaultValue} is a null
// * object
// */
// public String getProperty(String name, String defaultValue) throws IllegalStateException {
// Validate.notNullOrEmpty(name, "Unable to get the configuration value of null or empty configuration key");
// Validate.notNull(defaultValue, "Unable to set configuration value of " + name + " to null object.");
//
// final String found = getConfiguration().get(name);
//
// if (found == null || found.isEmpty()) {
// return defaultValue;
// } else {
// return found;
// }
// }
//
// /**
// * Sets some property.
// *
// * @param name acts as a key
// * @param value
// * @throws IllegalArgumentException if {@code name} is null or empty or {@code value} is null
// */
// public void setProperty(String name, String value) {
// Validate.notNullOrEmpty(name, "Name of property can not be a null object nor an empty string!");
// Validate.notNull(value, "Value of property can not be a null object!");
//
// configuration.put(name, value);
// }
//
// /**
// * Gets value of {@code name} property as defined in system variable or return to the {@code getProperty} method to
// * fetch the value from arquillian.xml
// *
// * @param name name of a property you want to get the value of
// * @param value value of a {@code name} property as defined in system variable or {@code defaultValue} in case it is
// * null or empty string
// * @param defaultValue value returned in case {@code name} is a null string or it is empty
// * @return value of a {@code name} property as defined in system variable or return to {@code getProperty} if none provided
// */
// protected String getSystemProperty(String name, String value, String defaultValue) {
// if (!value.equals(defaultValue)) {
// return value;
// } else {
// return getProperty(name, defaultValue);
// }
// }
//
// /**
// * Validates configuration.
// *
// * @throws GovernorConfigurationException when configuration of the extension is not valid
// */
// public abstract void validate() throws GovernorConfigurationException;
// }
//
// Path: api/src/main/java/org/arquillian/extension/governor/api/GovernorConfigurationException.java
// public class GovernorConfigurationException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public GovernorConfigurationException() {
// super();
// }
//
// public GovernorConfigurationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GovernorConfigurationException(String message) {
// super(message);
// }
//
// public GovernorConfigurationException(Throwable cause) {
// super(cause);
// }
//
// }
| import org.arquillian.extension.governor.api.Configuration;
import org.arquillian.extension.governor.api.GovernorConfigurationException; |
public void setForce(boolean force) {
setProperty("force", Boolean.toString(force));
}
public boolean getClosePassed() {
return Boolean.parseBoolean(getSystemProperty("closePassed", Boolean.toString(closePassed), "false"));
}
public void setClosePassed(boolean closePassed) {
setProperty("closePassed", Boolean.toString(closePassed));
}
public String getClosingMessage() {
return getProperty("closingMessage", DEFAULT_GITHUB_CLOSING_MESSAGE);
}
public void setClosingMessage(String closingMessage) {
setProperty("closingMessage", closingMessage);
}
public String getDefaultGithubURL() {
return defaultGithubURL;
}
public void setDefaultGithubURL(String defaultGithubURL) {
this.defaultGithubURL = defaultGithubURL;
}
@Override | // Path: api/src/main/java/org/arquillian/extension/governor/api/Configuration.java
// public abstract class Configuration {
//
// private Map<String, String> configuration = new HashMap<String, String>();
//
// /**
// * @return configuration of extension
// */
// public Map<String, String> getConfiguration() {
// return this.configuration;
// }
//
// /**
// * Gets configuration from Arquillian descriptor and creates instance of it.
// *
// * @param configuration configuration of extension from arquillian.xml
// * @return this
// * @throws IllegalArgumentException if {@code configuration} is a null object
// */
// public Configuration setConfiguration(Map<String, String> configuration) {
// Validate.notNull(configuration, "Properties for configuration of Arquillian Governor extension can not be a null object!");
// this.configuration = configuration;
// return this;
// }
//
// /**
// * Gets value of {@code name} property. In case a value for such name does not exist or is a null object or an empty string,
// * {@code defaultValue} is returned.
// *
// * @param name name of a property you want to get the value of
// * @param defaultValue value returned in case {@code name} is a null string or it is empty
// * @return value of a {@code name} property of {@code defaultValue} when {@code name} is null or empty string
// * @throws IllegalArgumentException if {@code name} is a null object or an empty string or if {@code defaultValue} is a null
// * object
// */
// public String getProperty(String name, String defaultValue) throws IllegalStateException {
// Validate.notNullOrEmpty(name, "Unable to get the configuration value of null or empty configuration key");
// Validate.notNull(defaultValue, "Unable to set configuration value of " + name + " to null object.");
//
// final String found = getConfiguration().get(name);
//
// if (found == null || found.isEmpty()) {
// return defaultValue;
// } else {
// return found;
// }
// }
//
// /**
// * Sets some property.
// *
// * @param name acts as a key
// * @param value
// * @throws IllegalArgumentException if {@code name} is null or empty or {@code value} is null
// */
// public void setProperty(String name, String value) {
// Validate.notNullOrEmpty(name, "Name of property can not be a null object nor an empty string!");
// Validate.notNull(value, "Value of property can not be a null object!");
//
// configuration.put(name, value);
// }
//
// /**
// * Gets value of {@code name} property as defined in system variable or return to the {@code getProperty} method to
// * fetch the value from arquillian.xml
// *
// * @param name name of a property you want to get the value of
// * @param value value of a {@code name} property as defined in system variable or {@code defaultValue} in case it is
// * null or empty string
// * @param defaultValue value returned in case {@code name} is a null string or it is empty
// * @return value of a {@code name} property as defined in system variable or return to {@code getProperty} if none provided
// */
// protected String getSystemProperty(String name, String value, String defaultValue) {
// if (!value.equals(defaultValue)) {
// return value;
// } else {
// return getProperty(name, defaultValue);
// }
// }
//
// /**
// * Validates configuration.
// *
// * @throws GovernorConfigurationException when configuration of the extension is not valid
// */
// public abstract void validate() throws GovernorConfigurationException;
// }
//
// Path: api/src/main/java/org/arquillian/extension/governor/api/GovernorConfigurationException.java
// public class GovernorConfigurationException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public GovernorConfigurationException() {
// super();
// }
//
// public GovernorConfigurationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GovernorConfigurationException(String message) {
// super(message);
// }
//
// public GovernorConfigurationException(Throwable cause) {
// super(cause);
// }
//
// }
// Path: github/src/main/java/org/arquillian/extension/governor/github/configuration/GitHubGovernorConfiguration.java
import org.arquillian.extension.governor.api.Configuration;
import org.arquillian.extension.governor.api.GovernorConfigurationException;
public void setForce(boolean force) {
setProperty("force", Boolean.toString(force));
}
public boolean getClosePassed() {
return Boolean.parseBoolean(getSystemProperty("closePassed", Boolean.toString(closePassed), "false"));
}
public void setClosePassed(boolean closePassed) {
setProperty("closePassed", Boolean.toString(closePassed));
}
public String getClosingMessage() {
return getProperty("closingMessage", DEFAULT_GITHUB_CLOSING_MESSAGE);
}
public void setClosingMessage(String closingMessage) {
setProperty("closingMessage", closingMessage);
}
public String getDefaultGithubURL() {
return defaultGithubURL;
}
public void setDefaultGithubURL(String defaultGithubURL) {
this.defaultGithubURL = defaultGithubURL;
}
@Override | public void validate() throws GovernorConfigurationException { |
arquillian/arquillian-governor | redmine/src/main/java/org/arquillian/extension/governor/redmine/configuration/RedmineGovernorConfiguration.java | // Path: api/src/main/java/org/arquillian/extension/governor/api/Configuration.java
// public abstract class Configuration {
//
// private Map<String, String> configuration = new HashMap<String, String>();
//
// /**
// * @return configuration of extension
// */
// public Map<String, String> getConfiguration() {
// return this.configuration;
// }
//
// /**
// * Gets configuration from Arquillian descriptor and creates instance of it.
// *
// * @param configuration configuration of extension from arquillian.xml
// * @return this
// * @throws IllegalArgumentException if {@code configuration} is a null object
// */
// public Configuration setConfiguration(Map<String, String> configuration) {
// Validate.notNull(configuration, "Properties for configuration of Arquillian Governor extension can not be a null object!");
// this.configuration = configuration;
// return this;
// }
//
// /**
// * Gets value of {@code name} property. In case a value for such name does not exist or is a null object or an empty string,
// * {@code defaultValue} is returned.
// *
// * @param name name of a property you want to get the value of
// * @param defaultValue value returned in case {@code name} is a null string or it is empty
// * @return value of a {@code name} property of {@code defaultValue} when {@code name} is null or empty string
// * @throws IllegalArgumentException if {@code name} is a null object or an empty string or if {@code defaultValue} is a null
// * object
// */
// public String getProperty(String name, String defaultValue) throws IllegalStateException {
// Validate.notNullOrEmpty(name, "Unable to get the configuration value of null or empty configuration key");
// Validate.notNull(defaultValue, "Unable to set configuration value of " + name + " to null object.");
//
// final String found = getConfiguration().get(name);
//
// if (found == null || found.isEmpty()) {
// return defaultValue;
// } else {
// return found;
// }
// }
//
// /**
// * Sets some property.
// *
// * @param name acts as a key
// * @param value
// * @throws IllegalArgumentException if {@code name} is null or empty or {@code value} is null
// */
// public void setProperty(String name, String value) {
// Validate.notNullOrEmpty(name, "Name of property can not be a null object nor an empty string!");
// Validate.notNull(value, "Value of property can not be a null object!");
//
// configuration.put(name, value);
// }
//
// /**
// * Gets value of {@code name} property as defined in system variable or return to the {@code getProperty} method to
// * fetch the value from arquillian.xml
// *
// * @param name name of a property you want to get the value of
// * @param value value of a {@code name} property as defined in system variable or {@code defaultValue} in case it is
// * null or empty string
// * @param defaultValue value returned in case {@code name} is a null string or it is empty
// * @return value of a {@code name} property as defined in system variable or return to {@code getProperty} if none provided
// */
// protected String getSystemProperty(String name, String value, String defaultValue) {
// if (!value.equals(defaultValue)) {
// return value;
// } else {
// return getProperty(name, defaultValue);
// }
// }
//
// /**
// * Validates configuration.
// *
// * @throws GovernorConfigurationException when configuration of the extension is not valid
// */
// public abstract void validate() throws GovernorConfigurationException;
// }
//
// Path: api/src/main/java/org/arquillian/extension/governor/api/GovernorConfigurationException.java
// public class GovernorConfigurationException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public GovernorConfigurationException() {
// super();
// }
//
// public GovernorConfigurationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GovernorConfigurationException(String message) {
// super(message);
// }
//
// public GovernorConfigurationException(Throwable cause) {
// super(cause);
// }
//
// }
| import org.arquillian.extension.governor.api.Configuration;
import org.arquillian.extension.governor.api.GovernorConfigurationException; |
public void setClosePassed(boolean closePassed) {
setProperty("closePassed", Boolean.toString(closePassed));
}
public boolean getOpenFailed() {
return Boolean.parseBoolean(getSystemProperty("openFailed", Boolean.toString(openFailed), "false"));
}
public void setOpenFailed(boolean openFailed) {
setProperty("openFailed", Boolean.toString(openFailed));
}
public String getClosingMessage() {
return getProperty("closingMessage", DEFAULT_REDMINE_CLOSING_MESSAGE);
}
public void setClosingMessage(String closingMessage) {
setProperty("closingMessage", closingMessage);
}
public String getOpeningMessage() {
return getProperty("openingMessage", DEFAULT_REDMINE_OPENING_MESSAGE);
}
public void setOpeningMessage(String closingMessage) {
setProperty("openingMessage", closingMessage);
}
@Override | // Path: api/src/main/java/org/arquillian/extension/governor/api/Configuration.java
// public abstract class Configuration {
//
// private Map<String, String> configuration = new HashMap<String, String>();
//
// /**
// * @return configuration of extension
// */
// public Map<String, String> getConfiguration() {
// return this.configuration;
// }
//
// /**
// * Gets configuration from Arquillian descriptor and creates instance of it.
// *
// * @param configuration configuration of extension from arquillian.xml
// * @return this
// * @throws IllegalArgumentException if {@code configuration} is a null object
// */
// public Configuration setConfiguration(Map<String, String> configuration) {
// Validate.notNull(configuration, "Properties for configuration of Arquillian Governor extension can not be a null object!");
// this.configuration = configuration;
// return this;
// }
//
// /**
// * Gets value of {@code name} property. In case a value for such name does not exist or is a null object or an empty string,
// * {@code defaultValue} is returned.
// *
// * @param name name of a property you want to get the value of
// * @param defaultValue value returned in case {@code name} is a null string or it is empty
// * @return value of a {@code name} property of {@code defaultValue} when {@code name} is null or empty string
// * @throws IllegalArgumentException if {@code name} is a null object or an empty string or if {@code defaultValue} is a null
// * object
// */
// public String getProperty(String name, String defaultValue) throws IllegalStateException {
// Validate.notNullOrEmpty(name, "Unable to get the configuration value of null or empty configuration key");
// Validate.notNull(defaultValue, "Unable to set configuration value of " + name + " to null object.");
//
// final String found = getConfiguration().get(name);
//
// if (found == null || found.isEmpty()) {
// return defaultValue;
// } else {
// return found;
// }
// }
//
// /**
// * Sets some property.
// *
// * @param name acts as a key
// * @param value
// * @throws IllegalArgumentException if {@code name} is null or empty or {@code value} is null
// */
// public void setProperty(String name, String value) {
// Validate.notNullOrEmpty(name, "Name of property can not be a null object nor an empty string!");
// Validate.notNull(value, "Value of property can not be a null object!");
//
// configuration.put(name, value);
// }
//
// /**
// * Gets value of {@code name} property as defined in system variable or return to the {@code getProperty} method to
// * fetch the value from arquillian.xml
// *
// * @param name name of a property you want to get the value of
// * @param value value of a {@code name} property as defined in system variable or {@code defaultValue} in case it is
// * null or empty string
// * @param defaultValue value returned in case {@code name} is a null string or it is empty
// * @return value of a {@code name} property as defined in system variable or return to {@code getProperty} if none provided
// */
// protected String getSystemProperty(String name, String value, String defaultValue) {
// if (!value.equals(defaultValue)) {
// return value;
// } else {
// return getProperty(name, defaultValue);
// }
// }
//
// /**
// * Validates configuration.
// *
// * @throws GovernorConfigurationException when configuration of the extension is not valid
// */
// public abstract void validate() throws GovernorConfigurationException;
// }
//
// Path: api/src/main/java/org/arquillian/extension/governor/api/GovernorConfigurationException.java
// public class GovernorConfigurationException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public GovernorConfigurationException() {
// super();
// }
//
// public GovernorConfigurationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GovernorConfigurationException(String message) {
// super(message);
// }
//
// public GovernorConfigurationException(Throwable cause) {
// super(cause);
// }
//
// }
// Path: redmine/src/main/java/org/arquillian/extension/governor/redmine/configuration/RedmineGovernorConfiguration.java
import org.arquillian.extension.governor.api.Configuration;
import org.arquillian.extension.governor.api.GovernorConfigurationException;
public void setClosePassed(boolean closePassed) {
setProperty("closePassed", Boolean.toString(closePassed));
}
public boolean getOpenFailed() {
return Boolean.parseBoolean(getSystemProperty("openFailed", Boolean.toString(openFailed), "false"));
}
public void setOpenFailed(boolean openFailed) {
setProperty("openFailed", Boolean.toString(openFailed));
}
public String getClosingMessage() {
return getProperty("closingMessage", DEFAULT_REDMINE_CLOSING_MESSAGE);
}
public void setClosingMessage(String closingMessage) {
setProperty("closingMessage", closingMessage);
}
public String getOpeningMessage() {
return getProperty("openingMessage", DEFAULT_REDMINE_OPENING_MESSAGE);
}
public void setOpeningMessage(String closingMessage) {
setProperty("openingMessage", closingMessage);
}
@Override | public void validate() throws GovernorConfigurationException { |
arquillian/arquillian-governor | impl/src/main/java/org/arquillian/extension/governor/impl/GovernorTestClassScanner.java | // Path: api/src/main/java/org/arquillian/extension/governor/api/ClosePassedDecider.java
// public interface ClosePassedDecider {
//
// /**
// * Returns {@code Map} with annotations and their closable flags in the scope of the whole test suite.
// *
// * @return {@code Map} with annotations and their closable flags.
// */
// Map<Annotation, Boolean> get();
//
// /**
// * Sets the closable flag to the issue specified in {@code annotation} in the scope of related test method.
// *
// * @param annotation Governor annotation.
// * @param closeable if {@code true}, the issue specified in annotation can be closed.
// */
// void setClosable(Annotation annotation, boolean closeable);
//
// /**
// * Returns {@code true} if the issue specified in {@code annotation} can be closed in the scope of the whole test suite.
// *
// * @param annotation Governor annotation.
// * @return {@code true} if the issue specified in annotation can be closed, otherwise {@code false}.
// */
// boolean isCloseable(Annotation annotation);
// }
| import org.arquillian.extension.governor.api.ClosePassedDecider;
import org.arquillian.extension.governor.api.Governor;
import org.arquillian.extension.governor.api.GovernorRegistry;
import org.arquillian.extension.governor.configuration.GovernorConfiguration;
import org.arquillian.extension.governor.spi.GovernorProvider;
import org.arquillian.extension.governor.spi.event.DecideMethodExecutions;
import org.jboss.arquillian.core.api.Event;
import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.InstanceProducer;
import org.jboss.arquillian.core.api.annotation.ApplicationScoped;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.core.api.annotation.Observes;
import org.jboss.arquillian.core.spi.ServiceLoader;
import org.jboss.arquillian.core.spi.Validate;
import org.jboss.arquillian.test.spi.TestClass;
import org.jboss.arquillian.test.spi.event.suite.BeforeClass;
import org.jboss.arquillian.test.spi.event.suite.BeforeSuite;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set; | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.arquillian.extension.governor.impl;
/**
* @author <a href="mailto:smikloso@redhat.com">Stefan Miklosovic</a>
*/
public class GovernorTestClassScanner {
@Inject
@ApplicationScoped
private InstanceProducer<GovernorRegistry> governorRegistry;
@Inject
@ApplicationScoped | // Path: api/src/main/java/org/arquillian/extension/governor/api/ClosePassedDecider.java
// public interface ClosePassedDecider {
//
// /**
// * Returns {@code Map} with annotations and their closable flags in the scope of the whole test suite.
// *
// * @return {@code Map} with annotations and their closable flags.
// */
// Map<Annotation, Boolean> get();
//
// /**
// * Sets the closable flag to the issue specified in {@code annotation} in the scope of related test method.
// *
// * @param annotation Governor annotation.
// * @param closeable if {@code true}, the issue specified in annotation can be closed.
// */
// void setClosable(Annotation annotation, boolean closeable);
//
// /**
// * Returns {@code true} if the issue specified in {@code annotation} can be closed in the scope of the whole test suite.
// *
// * @param annotation Governor annotation.
// * @return {@code true} if the issue specified in annotation can be closed, otherwise {@code false}.
// */
// boolean isCloseable(Annotation annotation);
// }
// Path: impl/src/main/java/org/arquillian/extension/governor/impl/GovernorTestClassScanner.java
import org.arquillian.extension.governor.api.ClosePassedDecider;
import org.arquillian.extension.governor.api.Governor;
import org.arquillian.extension.governor.api.GovernorRegistry;
import org.arquillian.extension.governor.configuration.GovernorConfiguration;
import org.arquillian.extension.governor.spi.GovernorProvider;
import org.arquillian.extension.governor.spi.event.DecideMethodExecutions;
import org.jboss.arquillian.core.api.Event;
import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.InstanceProducer;
import org.jboss.arquillian.core.api.annotation.ApplicationScoped;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.core.api.annotation.Observes;
import org.jboss.arquillian.core.spi.ServiceLoader;
import org.jboss.arquillian.core.spi.Validate;
import org.jboss.arquillian.test.spi.TestClass;
import org.jboss.arquillian.test.spi.event.suite.BeforeClass;
import org.jboss.arquillian.test.spi.event.suite.BeforeSuite;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.arquillian.extension.governor.impl;
/**
* @author <a href="mailto:smikloso@redhat.com">Stefan Miklosovic</a>
*/
public class GovernorTestClassScanner {
@Inject
@ApplicationScoped
private InstanceProducer<GovernorRegistry> governorRegistry;
@Inject
@ApplicationScoped | private InstanceProducer<ClosePassedDecider> closePassedDecider; |
arquillian/arquillian-governor | impl/src/main/java/org/arquillian/extension/governor/configuration/GovernorConfigurator.java | // Path: api/src/main/java/org/arquillian/extension/governor/api/GovernorConfigurationException.java
// public class GovernorConfigurationException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public GovernorConfigurationException() {
// super();
// }
//
// public GovernorConfigurationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GovernorConfigurationException(String message) {
// super(message);
// }
//
// public GovernorConfigurationException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: spi/src/main/java/org/arquillian/extension/governor/spi/event/GovernorExtensionConfigured.java
// public class GovernorExtensionConfigured {
//
// }
| import org.arquillian.extension.governor.api.GovernorConfigurationException;
import org.arquillian.extension.governor.spi.event.GovernorExtensionConfigured;
import org.jboss.arquillian.config.descriptor.api.ArquillianDescriptor;
import org.jboss.arquillian.config.descriptor.api.ExtensionDef;
import org.jboss.arquillian.core.api.Event;
import org.jboss.arquillian.core.api.InstanceProducer;
import org.jboss.arquillian.core.api.annotation.ApplicationScoped;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.core.api.annotation.Observes;
import java.util.logging.Level;
import java.util.logging.Logger; | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.arquillian.extension.governor.configuration;
/**
* @author <a href="mailto:smikloso@redhat.com">Stefan Miklosovic</a>
*/
public class GovernorConfigurator {
private static final Logger logger = Logger.getLogger(GovernorConfigurator.class.getName());
private static final String EXTENSION_NAME = "governor";
@Inject
@ApplicationScoped
private InstanceProducer<GovernorConfiguration> governorConfiguration;
@Inject | // Path: api/src/main/java/org/arquillian/extension/governor/api/GovernorConfigurationException.java
// public class GovernorConfigurationException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public GovernorConfigurationException() {
// super();
// }
//
// public GovernorConfigurationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GovernorConfigurationException(String message) {
// super(message);
// }
//
// public GovernorConfigurationException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: spi/src/main/java/org/arquillian/extension/governor/spi/event/GovernorExtensionConfigured.java
// public class GovernorExtensionConfigured {
//
// }
// Path: impl/src/main/java/org/arquillian/extension/governor/configuration/GovernorConfigurator.java
import org.arquillian.extension.governor.api.GovernorConfigurationException;
import org.arquillian.extension.governor.spi.event.GovernorExtensionConfigured;
import org.jboss.arquillian.config.descriptor.api.ArquillianDescriptor;
import org.jboss.arquillian.config.descriptor.api.ExtensionDef;
import org.jboss.arquillian.core.api.Event;
import org.jboss.arquillian.core.api.InstanceProducer;
import org.jboss.arquillian.core.api.annotation.ApplicationScoped;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.core.api.annotation.Observes;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.arquillian.extension.governor.configuration;
/**
* @author <a href="mailto:smikloso@redhat.com">Stefan Miklosovic</a>
*/
public class GovernorConfigurator {
private static final Logger logger = Logger.getLogger(GovernorConfigurator.class.getName());
private static final String EXTENSION_NAME = "governor";
@Inject
@ApplicationScoped
private InstanceProducer<GovernorConfiguration> governorConfiguration;
@Inject | private Event<GovernorExtensionConfigured> governorExtensionConfiguredEvent; |
arquillian/arquillian-governor | impl/src/main/java/org/arquillian/extension/governor/configuration/GovernorConfigurator.java | // Path: api/src/main/java/org/arquillian/extension/governor/api/GovernorConfigurationException.java
// public class GovernorConfigurationException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public GovernorConfigurationException() {
// super();
// }
//
// public GovernorConfigurationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GovernorConfigurationException(String message) {
// super(message);
// }
//
// public GovernorConfigurationException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: spi/src/main/java/org/arquillian/extension/governor/spi/event/GovernorExtensionConfigured.java
// public class GovernorExtensionConfigured {
//
// }
| import org.arquillian.extension.governor.api.GovernorConfigurationException;
import org.arquillian.extension.governor.spi.event.GovernorExtensionConfigured;
import org.jboss.arquillian.config.descriptor.api.ArquillianDescriptor;
import org.jboss.arquillian.config.descriptor.api.ExtensionDef;
import org.jboss.arquillian.core.api.Event;
import org.jboss.arquillian.core.api.InstanceProducer;
import org.jboss.arquillian.core.api.annotation.ApplicationScoped;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.core.api.annotation.Observes;
import java.util.logging.Level;
import java.util.logging.Logger; | /*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.arquillian.extension.governor.configuration;
/**
* @author <a href="mailto:smikloso@redhat.com">Stefan Miklosovic</a>
*/
public class GovernorConfigurator {
private static final Logger logger = Logger.getLogger(GovernorConfigurator.class.getName());
private static final String EXTENSION_NAME = "governor";
@Inject
@ApplicationScoped
private InstanceProducer<GovernorConfiguration> governorConfiguration;
@Inject
private Event<GovernorExtensionConfigured> governorExtensionConfiguredEvent;
| // Path: api/src/main/java/org/arquillian/extension/governor/api/GovernorConfigurationException.java
// public class GovernorConfigurationException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public GovernorConfigurationException() {
// super();
// }
//
// public GovernorConfigurationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public GovernorConfigurationException(String message) {
// super(message);
// }
//
// public GovernorConfigurationException(Throwable cause) {
// super(cause);
// }
//
// }
//
// Path: spi/src/main/java/org/arquillian/extension/governor/spi/event/GovernorExtensionConfigured.java
// public class GovernorExtensionConfigured {
//
// }
// Path: impl/src/main/java/org/arquillian/extension/governor/configuration/GovernorConfigurator.java
import org.arquillian.extension.governor.api.GovernorConfigurationException;
import org.arquillian.extension.governor.spi.event.GovernorExtensionConfigured;
import org.jboss.arquillian.config.descriptor.api.ArquillianDescriptor;
import org.jboss.arquillian.config.descriptor.api.ExtensionDef;
import org.jboss.arquillian.core.api.Event;
import org.jboss.arquillian.core.api.InstanceProducer;
import org.jboss.arquillian.core.api.annotation.ApplicationScoped;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.core.api.annotation.Observes;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* JBoss, Home of Professional Open Source
* Copyright 2016, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.arquillian.extension.governor.configuration;
/**
* @author <a href="mailto:smikloso@redhat.com">Stefan Miklosovic</a>
*/
public class GovernorConfigurator {
private static final Logger logger = Logger.getLogger(GovernorConfigurator.class.getName());
private static final String EXTENSION_NAME = "governor";
@Inject
@ApplicationScoped
private InstanceProducer<GovernorConfiguration> governorConfiguration;
@Inject
private Event<GovernorExtensionConfigured> governorExtensionConfiguredEvent;
| public void onArquillianDescriptor(@Observes ArquillianDescriptor arquillianDescriptor) throws GovernorConfigurationException { |
njkremer/SqliteORM | src/com/njkremer/Sqlite/SqlExecutor.java | // Path: src/com/njkremer/Sqlite/JoinExecutor.java
// public enum JoinType {
// INNER("inner "),
// LEFT_OUTER("left outer "),
// RIGHT_OUTER("right outer ");
//
// JoinType(String sql) {
// this.sql = sql;
// }
//
// public String getSql() {
// return sql;
// }
//
// private String sql;
// }
//
// Path: src/com/njkremer/Sqlite/utils/DateUtils.java
// public class DateUtils {
//
// public static Date getDateFromDatabaseFormattedString(String iso8601DateString) throws DataConnectionException {
// try {
// return DATE_FORMAT.parse(iso8601DateString);
// }
// catch (ParseException e) {
// throw new DataConnectionException(String.format("Error could not parse a date from the supplied string '%s' make sure it's in the form 'yyyy-MM-dd HH:mm:ss'", iso8601DateString));
// }
// }
//
// public static String getDatabaseFormattedStringFromDate(Date date) {
// return DATE_FORMAT.format(date);
// }
//
// private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// }
//
// Path: src/com/njkremer/Sqlite/utils/SqliteUtils.java
// public class SqliteUtils {
// public static Class<?> getClass(Object object) {
// return AopUtils.getTargetClass(object);
// }
//
// public static String capitalize(String word) {
// return word.substring(0, 1).toUpperCase() + word.substring(1);
// }
//
// public static String lowercase(String word) {
// return word.substring(0, 1).toLowerCase() + word.substring(1);
// }
//
// public static boolean isEmpty(Object object) {
// if(object == null) {
// return true;
// }
// if (object instanceof String) {
// return ((String) object).trim().length() == 0;
// }
// else if (object instanceof Float) {
// return ((Float) object) == 0.0f;
// }
// else if (object instanceof Integer) {
// return ((Integer) object) == 0;
// }
// else if (object instanceof Long) {
// return ((Long) object) == 0l;
// }
// else if (object instanceof Double) {
// return ((Double) object) == 0.0d;
// }
// else if (object instanceof Boolean) {
// return ((Boolean) object) == false;
// }
// return false;
// }
// }
| import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;
import org.springframework.aop.framework.ProxyFactory;
import com.njkremer.Sqlite.Annotations.AutoIncrement;
import com.njkremer.Sqlite.Annotations.OneToMany;
import com.njkremer.Sqlite.Annotations.PrimaryKey;
import com.njkremer.Sqlite.JoinExecutor.JoinType;
import com.njkremer.Sqlite.utils.DateUtils;
import com.njkremer.Sqlite.utils.SqliteUtils; | package com.njkremer.Sqlite;
/**
* Used to continue a {@linkplain SqlStatement} to interact with the database.
*
* <p>Typically this class is not instantiated outright, instead use {@linkplain SqlStatement#select(Class)},
* {@linkplain SqlStatement#update(Object)}, {@linkplain SqlStatement#insert(Object)},
* {@linkplain SqlStatement#delete(Class)}, or {@linkplain SqlStatement#delete(Object)} to create an instance of
* this class.
*
* @param <T> A class that is a POJO that "maps" to a table in the database.
*/
public class SqlExecutor<T> {
/**
* Used for retrieving an Object out of the database.
*
* @param clazz A reference to the Object.class that you are retrieving from the database.
* @return A {@linkplain SqlExecutor} used for function chaining.
* @throws DataConnectionException
*/
public SqlExecutor<T> select(Class<T> clazz) throws DataConnectionException {
reset();
this.clazz = clazz;
queryParts.put(StatementParts.SELECT, String.format(SELECT, clazz.getSimpleName().toLowerCase()));
queryParts.put(StatementParts.FROM, String.format(FROM, clazz.getSimpleName().toLowerCase()));
statementType = StatementType.SELECT;
return this;
}
/**
* Used for updating an Object in the database.
*
* @param databaseObject An object that was queried from the database that has been updated.
* @return A {@linkplain SqlExecutor} used for function chaining.
* @throws DataConnectionException
*/
@SuppressWarnings("unchecked")
public SqlExecutor<T> update(Object databaseObject) throws DataConnectionException {
reset(); | // Path: src/com/njkremer/Sqlite/JoinExecutor.java
// public enum JoinType {
// INNER("inner "),
// LEFT_OUTER("left outer "),
// RIGHT_OUTER("right outer ");
//
// JoinType(String sql) {
// this.sql = sql;
// }
//
// public String getSql() {
// return sql;
// }
//
// private String sql;
// }
//
// Path: src/com/njkremer/Sqlite/utils/DateUtils.java
// public class DateUtils {
//
// public static Date getDateFromDatabaseFormattedString(String iso8601DateString) throws DataConnectionException {
// try {
// return DATE_FORMAT.parse(iso8601DateString);
// }
// catch (ParseException e) {
// throw new DataConnectionException(String.format("Error could not parse a date from the supplied string '%s' make sure it's in the form 'yyyy-MM-dd HH:mm:ss'", iso8601DateString));
// }
// }
//
// public static String getDatabaseFormattedStringFromDate(Date date) {
// return DATE_FORMAT.format(date);
// }
//
// private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// }
//
// Path: src/com/njkremer/Sqlite/utils/SqliteUtils.java
// public class SqliteUtils {
// public static Class<?> getClass(Object object) {
// return AopUtils.getTargetClass(object);
// }
//
// public static String capitalize(String word) {
// return word.substring(0, 1).toUpperCase() + word.substring(1);
// }
//
// public static String lowercase(String word) {
// return word.substring(0, 1).toLowerCase() + word.substring(1);
// }
//
// public static boolean isEmpty(Object object) {
// if(object == null) {
// return true;
// }
// if (object instanceof String) {
// return ((String) object).trim().length() == 0;
// }
// else if (object instanceof Float) {
// return ((Float) object) == 0.0f;
// }
// else if (object instanceof Integer) {
// return ((Integer) object) == 0;
// }
// else if (object instanceof Long) {
// return ((Long) object) == 0l;
// }
// else if (object instanceof Double) {
// return ((Double) object) == 0.0d;
// }
// else if (object instanceof Boolean) {
// return ((Boolean) object) == false;
// }
// return false;
// }
// }
// Path: src/com/njkremer/Sqlite/SqlExecutor.java
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;
import org.springframework.aop.framework.ProxyFactory;
import com.njkremer.Sqlite.Annotations.AutoIncrement;
import com.njkremer.Sqlite.Annotations.OneToMany;
import com.njkremer.Sqlite.Annotations.PrimaryKey;
import com.njkremer.Sqlite.JoinExecutor.JoinType;
import com.njkremer.Sqlite.utils.DateUtils;
import com.njkremer.Sqlite.utils.SqliteUtils;
package com.njkremer.Sqlite;
/**
* Used to continue a {@linkplain SqlStatement} to interact with the database.
*
* <p>Typically this class is not instantiated outright, instead use {@linkplain SqlStatement#select(Class)},
* {@linkplain SqlStatement#update(Object)}, {@linkplain SqlStatement#insert(Object)},
* {@linkplain SqlStatement#delete(Class)}, or {@linkplain SqlStatement#delete(Object)} to create an instance of
* this class.
*
* @param <T> A class that is a POJO that "maps" to a table in the database.
*/
public class SqlExecutor<T> {
/**
* Used for retrieving an Object out of the database.
*
* @param clazz A reference to the Object.class that you are retrieving from the database.
* @return A {@linkplain SqlExecutor} used for function chaining.
* @throws DataConnectionException
*/
public SqlExecutor<T> select(Class<T> clazz) throws DataConnectionException {
reset();
this.clazz = clazz;
queryParts.put(StatementParts.SELECT, String.format(SELECT, clazz.getSimpleName().toLowerCase()));
queryParts.put(StatementParts.FROM, String.format(FROM, clazz.getSimpleName().toLowerCase()));
statementType = StatementType.SELECT;
return this;
}
/**
* Used for updating an Object in the database.
*
* @param databaseObject An object that was queried from the database that has been updated.
* @return A {@linkplain SqlExecutor} used for function chaining.
* @throws DataConnectionException
*/
@SuppressWarnings("unchecked")
public SqlExecutor<T> update(Object databaseObject) throws DataConnectionException {
reset(); | clazz = (Class<T>) SqliteUtils.getClass(databaseObject); |
njkremer/SqliteORM | src/com/njkremer/Sqlite/SqlExecutor.java | // Path: src/com/njkremer/Sqlite/JoinExecutor.java
// public enum JoinType {
// INNER("inner "),
// LEFT_OUTER("left outer "),
// RIGHT_OUTER("right outer ");
//
// JoinType(String sql) {
// this.sql = sql;
// }
//
// public String getSql() {
// return sql;
// }
//
// private String sql;
// }
//
// Path: src/com/njkremer/Sqlite/utils/DateUtils.java
// public class DateUtils {
//
// public static Date getDateFromDatabaseFormattedString(String iso8601DateString) throws DataConnectionException {
// try {
// return DATE_FORMAT.parse(iso8601DateString);
// }
// catch (ParseException e) {
// throw new DataConnectionException(String.format("Error could not parse a date from the supplied string '%s' make sure it's in the form 'yyyy-MM-dd HH:mm:ss'", iso8601DateString));
// }
// }
//
// public static String getDatabaseFormattedStringFromDate(Date date) {
// return DATE_FORMAT.format(date);
// }
//
// private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// }
//
// Path: src/com/njkremer/Sqlite/utils/SqliteUtils.java
// public class SqliteUtils {
// public static Class<?> getClass(Object object) {
// return AopUtils.getTargetClass(object);
// }
//
// public static String capitalize(String word) {
// return word.substring(0, 1).toUpperCase() + word.substring(1);
// }
//
// public static String lowercase(String word) {
// return word.substring(0, 1).toLowerCase() + word.substring(1);
// }
//
// public static boolean isEmpty(Object object) {
// if(object == null) {
// return true;
// }
// if (object instanceof String) {
// return ((String) object).trim().length() == 0;
// }
// else if (object instanceof Float) {
// return ((Float) object) == 0.0f;
// }
// else if (object instanceof Integer) {
// return ((Integer) object) == 0;
// }
// else if (object instanceof Long) {
// return ((Long) object) == 0l;
// }
// else if (object instanceof Double) {
// return ((Double) object) == 0.0d;
// }
// else if (object instanceof Boolean) {
// return ((Boolean) object) == false;
// }
// return false;
// }
// }
| import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;
import org.springframework.aop.framework.ProxyFactory;
import com.njkremer.Sqlite.Annotations.AutoIncrement;
import com.njkremer.Sqlite.Annotations.OneToMany;
import com.njkremer.Sqlite.Annotations.PrimaryKey;
import com.njkremer.Sqlite.JoinExecutor.JoinType;
import com.njkremer.Sqlite.utils.DateUtils;
import com.njkremer.Sqlite.utils.SqliteUtils; | */
public SqlExecutor<T> join(Class<?> leftClazz, String leftField, Class<?> rightClazz, String rightField) {
if (firstJoin) {
queryParts.put(StatementParts.JOIN, "");
firstJoin = false;
}
this.joinExecutor.join(leftClazz, leftField, rightClazz, rightField);
String join = joinExecutor.getQuery();
queryParts.put(StatementParts.JOIN, queryParts.get(StatementParts.JOIN).concat(join));
return this;
}
/**
* Used to do a SQL Join with another POJO/Table, with specifying the {@linkplain JoinType}
*
* <p>A simple example of using joining to get all of a user's things, given the user's name:
*
* <p>
* <pre>
* new SqlStatement().select(Thing.class).join(User.class, "id", Thing.class, "userId")
* .where(User.class, "name").eq("Bob").getList()
*</pre>
*
* @param leftClazz The (left) class/table you're joining to.
* @param leftField The field in the left class/table you're joining on.
* @param rightClazz The (right) class/table you're joining from.
* @param rightField The field in the right class/table you're joining on.
* @param joinType The {@linkplain JoinType} that the join should use.
* @return A {@linkplain SqlExecutor} used for function chaining.
*/ | // Path: src/com/njkremer/Sqlite/JoinExecutor.java
// public enum JoinType {
// INNER("inner "),
// LEFT_OUTER("left outer "),
// RIGHT_OUTER("right outer ");
//
// JoinType(String sql) {
// this.sql = sql;
// }
//
// public String getSql() {
// return sql;
// }
//
// private String sql;
// }
//
// Path: src/com/njkremer/Sqlite/utils/DateUtils.java
// public class DateUtils {
//
// public static Date getDateFromDatabaseFormattedString(String iso8601DateString) throws DataConnectionException {
// try {
// return DATE_FORMAT.parse(iso8601DateString);
// }
// catch (ParseException e) {
// throw new DataConnectionException(String.format("Error could not parse a date from the supplied string '%s' make sure it's in the form 'yyyy-MM-dd HH:mm:ss'", iso8601DateString));
// }
// }
//
// public static String getDatabaseFormattedStringFromDate(Date date) {
// return DATE_FORMAT.format(date);
// }
//
// private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// }
//
// Path: src/com/njkremer/Sqlite/utils/SqliteUtils.java
// public class SqliteUtils {
// public static Class<?> getClass(Object object) {
// return AopUtils.getTargetClass(object);
// }
//
// public static String capitalize(String word) {
// return word.substring(0, 1).toUpperCase() + word.substring(1);
// }
//
// public static String lowercase(String word) {
// return word.substring(0, 1).toLowerCase() + word.substring(1);
// }
//
// public static boolean isEmpty(Object object) {
// if(object == null) {
// return true;
// }
// if (object instanceof String) {
// return ((String) object).trim().length() == 0;
// }
// else if (object instanceof Float) {
// return ((Float) object) == 0.0f;
// }
// else if (object instanceof Integer) {
// return ((Integer) object) == 0;
// }
// else if (object instanceof Long) {
// return ((Long) object) == 0l;
// }
// else if (object instanceof Double) {
// return ((Double) object) == 0.0d;
// }
// else if (object instanceof Boolean) {
// return ((Boolean) object) == false;
// }
// return false;
// }
// }
// Path: src/com/njkremer/Sqlite/SqlExecutor.java
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;
import org.springframework.aop.framework.ProxyFactory;
import com.njkremer.Sqlite.Annotations.AutoIncrement;
import com.njkremer.Sqlite.Annotations.OneToMany;
import com.njkremer.Sqlite.Annotations.PrimaryKey;
import com.njkremer.Sqlite.JoinExecutor.JoinType;
import com.njkremer.Sqlite.utils.DateUtils;
import com.njkremer.Sqlite.utils.SqliteUtils;
*/
public SqlExecutor<T> join(Class<?> leftClazz, String leftField, Class<?> rightClazz, String rightField) {
if (firstJoin) {
queryParts.put(StatementParts.JOIN, "");
firstJoin = false;
}
this.joinExecutor.join(leftClazz, leftField, rightClazz, rightField);
String join = joinExecutor.getQuery();
queryParts.put(StatementParts.JOIN, queryParts.get(StatementParts.JOIN).concat(join));
return this;
}
/**
* Used to do a SQL Join with another POJO/Table, with specifying the {@linkplain JoinType}
*
* <p>A simple example of using joining to get all of a user's things, given the user's name:
*
* <p>
* <pre>
* new SqlStatement().select(Thing.class).join(User.class, "id", Thing.class, "userId")
* .where(User.class, "name").eq("Bob").getList()
*</pre>
*
* @param leftClazz The (left) class/table you're joining to.
* @param leftField The field in the left class/table you're joining on.
* @param rightClazz The (right) class/table you're joining from.
* @param rightField The field in the right class/table you're joining on.
* @param joinType The {@linkplain JoinType} that the join should use.
* @return A {@linkplain SqlExecutor} used for function chaining.
*/ | public SqlExecutor<T> join(Class<?> leftClazz, String leftField, Class<?> rightClazz, String rightField, JoinType joinType) { |
njkremer/SqliteORM | src/com/njkremer/Sqlite/SqlExecutor.java | // Path: src/com/njkremer/Sqlite/JoinExecutor.java
// public enum JoinType {
// INNER("inner "),
// LEFT_OUTER("left outer "),
// RIGHT_OUTER("right outer ");
//
// JoinType(String sql) {
// this.sql = sql;
// }
//
// public String getSql() {
// return sql;
// }
//
// private String sql;
// }
//
// Path: src/com/njkremer/Sqlite/utils/DateUtils.java
// public class DateUtils {
//
// public static Date getDateFromDatabaseFormattedString(String iso8601DateString) throws DataConnectionException {
// try {
// return DATE_FORMAT.parse(iso8601DateString);
// }
// catch (ParseException e) {
// throw new DataConnectionException(String.format("Error could not parse a date from the supplied string '%s' make sure it's in the form 'yyyy-MM-dd HH:mm:ss'", iso8601DateString));
// }
// }
//
// public static String getDatabaseFormattedStringFromDate(Date date) {
// return DATE_FORMAT.format(date);
// }
//
// private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// }
//
// Path: src/com/njkremer/Sqlite/utils/SqliteUtils.java
// public class SqliteUtils {
// public static Class<?> getClass(Object object) {
// return AopUtils.getTargetClass(object);
// }
//
// public static String capitalize(String word) {
// return word.substring(0, 1).toUpperCase() + word.substring(1);
// }
//
// public static String lowercase(String word) {
// return word.substring(0, 1).toLowerCase() + word.substring(1);
// }
//
// public static boolean isEmpty(Object object) {
// if(object == null) {
// return true;
// }
// if (object instanceof String) {
// return ((String) object).trim().length() == 0;
// }
// else if (object instanceof Float) {
// return ((Float) object) == 0.0f;
// }
// else if (object instanceof Integer) {
// return ((Integer) object) == 0;
// }
// else if (object instanceof Long) {
// return ((Long) object) == 0l;
// }
// else if (object instanceof Double) {
// return ((Double) object) == 0.0d;
// }
// else if (object instanceof Boolean) {
// return ((Boolean) object) == false;
// }
// return false;
// }
// }
| import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;
import org.springframework.aop.framework.ProxyFactory;
import com.njkremer.Sqlite.Annotations.AutoIncrement;
import com.njkremer.Sqlite.Annotations.OneToMany;
import com.njkremer.Sqlite.Annotations.PrimaryKey;
import com.njkremer.Sqlite.JoinExecutor.JoinType;
import com.njkremer.Sqlite.utils.DateUtils;
import com.njkremer.Sqlite.utils.SqliteUtils; | // moving on.
}
}
}
fieldsString.append(") ");
valuesString.append(") ");
queryParts.put(StatementParts.INSERT, queryParts.get(StatementParts.INSERT).concat(fieldsString.toString()).concat(valuesString.toString()));
}
private void replaceValues() throws SQLException, DataConnectionException {
logger.trace(String.format(getQuery().replaceAll("%", "%%").replaceAll("\\?", "%s"), values.toArray()));
for (int i = 0; i < values.size(); i++) {
Object object = values.get(i);
if (object instanceof String) {
statement.setString(i + 1, (String) object);
}
else if (object instanceof Float) {
statement.setFloat(i + 1, (Float) object);
}
else if (object instanceof Integer) {
statement.setInt(i + 1, (Integer) object);
}
else if (object instanceof Long) {
statement.setLong(i + 1, (Long) object);
}
else if (object instanceof Double) {
statement.setDouble(i + 1, (Double) object);
}
else if (object instanceof Date) { | // Path: src/com/njkremer/Sqlite/JoinExecutor.java
// public enum JoinType {
// INNER("inner "),
// LEFT_OUTER("left outer "),
// RIGHT_OUTER("right outer ");
//
// JoinType(String sql) {
// this.sql = sql;
// }
//
// public String getSql() {
// return sql;
// }
//
// private String sql;
// }
//
// Path: src/com/njkremer/Sqlite/utils/DateUtils.java
// public class DateUtils {
//
// public static Date getDateFromDatabaseFormattedString(String iso8601DateString) throws DataConnectionException {
// try {
// return DATE_FORMAT.parse(iso8601DateString);
// }
// catch (ParseException e) {
// throw new DataConnectionException(String.format("Error could not parse a date from the supplied string '%s' make sure it's in the form 'yyyy-MM-dd HH:mm:ss'", iso8601DateString));
// }
// }
//
// public static String getDatabaseFormattedStringFromDate(Date date) {
// return DATE_FORMAT.format(date);
// }
//
// private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// }
//
// Path: src/com/njkremer/Sqlite/utils/SqliteUtils.java
// public class SqliteUtils {
// public static Class<?> getClass(Object object) {
// return AopUtils.getTargetClass(object);
// }
//
// public static String capitalize(String word) {
// return word.substring(0, 1).toUpperCase() + word.substring(1);
// }
//
// public static String lowercase(String word) {
// return word.substring(0, 1).toLowerCase() + word.substring(1);
// }
//
// public static boolean isEmpty(Object object) {
// if(object == null) {
// return true;
// }
// if (object instanceof String) {
// return ((String) object).trim().length() == 0;
// }
// else if (object instanceof Float) {
// return ((Float) object) == 0.0f;
// }
// else if (object instanceof Integer) {
// return ((Integer) object) == 0;
// }
// else if (object instanceof Long) {
// return ((Long) object) == 0l;
// }
// else if (object instanceof Double) {
// return ((Double) object) == 0.0d;
// }
// else if (object instanceof Boolean) {
// return ((Boolean) object) == false;
// }
// return false;
// }
// }
// Path: src/com/njkremer/Sqlite/SqlExecutor.java
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;
import org.springframework.aop.framework.ProxyFactory;
import com.njkremer.Sqlite.Annotations.AutoIncrement;
import com.njkremer.Sqlite.Annotations.OneToMany;
import com.njkremer.Sqlite.Annotations.PrimaryKey;
import com.njkremer.Sqlite.JoinExecutor.JoinType;
import com.njkremer.Sqlite.utils.DateUtils;
import com.njkremer.Sqlite.utils.SqliteUtils;
// moving on.
}
}
}
fieldsString.append(") ");
valuesString.append(") ");
queryParts.put(StatementParts.INSERT, queryParts.get(StatementParts.INSERT).concat(fieldsString.toString()).concat(valuesString.toString()));
}
private void replaceValues() throws SQLException, DataConnectionException {
logger.trace(String.format(getQuery().replaceAll("%", "%%").replaceAll("\\?", "%s"), values.toArray()));
for (int i = 0; i < values.size(); i++) {
Object object = values.get(i);
if (object instanceof String) {
statement.setString(i + 1, (String) object);
}
else if (object instanceof Float) {
statement.setFloat(i + 1, (Float) object);
}
else if (object instanceof Integer) {
statement.setInt(i + 1, (Integer) object);
}
else if (object instanceof Long) {
statement.setLong(i + 1, (Long) object);
}
else if (object instanceof Double) {
statement.setDouble(i + 1, (Double) object);
}
else if (object instanceof Date) { | String date = DateUtils.getDatabaseFormattedStringFromDate((Date) object); |
njkremer/SqliteORM | test/com/njkremer/Sqlite/TU_JoinExecutor.java | // Path: src/com/njkremer/Sqlite/JoinExecutor.java
// public class JoinExecutor {
//
// /**
// * User to represent various join types for a database.
// */
// public enum JoinType {
// INNER("inner "),
// LEFT_OUTER("left outer "),
// RIGHT_OUTER("right outer ");
//
// JoinType(String sql) {
// this.sql = sql;
// }
//
// public String getSql() {
// return sql;
// }
//
// private String sql;
// }
//
// public JoinExecutor join(Class<?> leftClazz, String leftField, Class<?> rightClazz, String rightField) {
// String rightClassName = rightClazz.getSimpleName().toLowerCase();
// String leftClassName = leftClazz.getSimpleName().toLowerCase();
// String joinTypeSql = "";
// if (joinType != null) {
// joinTypeSql = this.joinType.getSql();
// }
// query = String.format(JOIN, joinTypeSql, leftClassName, leftClassName, leftField, rightClassName, rightField);
// return this;
// }
//
// public void setJoinType(JoinType joinType) {
// this.joinType = joinType;
// }
//
// String getQuery() {
// return query;
// }
//
// private final static String JOIN = "%sjoin %s on %s.%s = %s.%s ";
// private JoinType joinType = null;
// private String query;
// }
//
// Path: src/com/njkremer/Sqlite/JoinExecutor.java
// public enum JoinType {
// INNER("inner "),
// LEFT_OUTER("left outer "),
// RIGHT_OUTER("right outer ");
//
// JoinType(String sql) {
// this.sql = sql;
// }
//
// public String getSql() {
// return sql;
// }
//
// private String sql;
// }
//
// Path: test/com/njkremer/Sqlite/TestClass/User.java
// public class User {
// @AutoIncrement
// @PrimaryKey
// private long id;
// private String name;
// private String password;
//
// @OneToMany("userId")
// private List<Thing> things;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public List<Thing> getThings() {
// return things;
// }
//
// public void setThings(List<Thing> things) {
// this.things = things;
// }
//
//
// }
//
// Path: test/com/njkremer/Sqlite/TestClass/UserAccessGroup.java
// public class UserAccessGroup {
//
// public long getUserId() {
// return userId;
// }
// public void setUserId(long userId) {
// this.userId = userId;
// }
// public long getGroupId() {
// return groupId;
// }
// public void setGroupId(long groupId) {
// this.groupId = groupId;
// }
//
// private long userId;
// private long groupId;
// }
| import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.njkremer.Sqlite.JoinExecutor;
import com.njkremer.Sqlite.JoinExecutor.JoinType;
import com.njkremer.Sqlite.TestClass.User;
import com.njkremer.Sqlite.TestClass.UserAccessGroup; | package com.njkremer.Sqlite;
public class TU_JoinExecutor {
@Test
public void testJoin() { | // Path: src/com/njkremer/Sqlite/JoinExecutor.java
// public class JoinExecutor {
//
// /**
// * User to represent various join types for a database.
// */
// public enum JoinType {
// INNER("inner "),
// LEFT_OUTER("left outer "),
// RIGHT_OUTER("right outer ");
//
// JoinType(String sql) {
// this.sql = sql;
// }
//
// public String getSql() {
// return sql;
// }
//
// private String sql;
// }
//
// public JoinExecutor join(Class<?> leftClazz, String leftField, Class<?> rightClazz, String rightField) {
// String rightClassName = rightClazz.getSimpleName().toLowerCase();
// String leftClassName = leftClazz.getSimpleName().toLowerCase();
// String joinTypeSql = "";
// if (joinType != null) {
// joinTypeSql = this.joinType.getSql();
// }
// query = String.format(JOIN, joinTypeSql, leftClassName, leftClassName, leftField, rightClassName, rightField);
// return this;
// }
//
// public void setJoinType(JoinType joinType) {
// this.joinType = joinType;
// }
//
// String getQuery() {
// return query;
// }
//
// private final static String JOIN = "%sjoin %s on %s.%s = %s.%s ";
// private JoinType joinType = null;
// private String query;
// }
//
// Path: src/com/njkremer/Sqlite/JoinExecutor.java
// public enum JoinType {
// INNER("inner "),
// LEFT_OUTER("left outer "),
// RIGHT_OUTER("right outer ");
//
// JoinType(String sql) {
// this.sql = sql;
// }
//
// public String getSql() {
// return sql;
// }
//
// private String sql;
// }
//
// Path: test/com/njkremer/Sqlite/TestClass/User.java
// public class User {
// @AutoIncrement
// @PrimaryKey
// private long id;
// private String name;
// private String password;
//
// @OneToMany("userId")
// private List<Thing> things;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public List<Thing> getThings() {
// return things;
// }
//
// public void setThings(List<Thing> things) {
// this.things = things;
// }
//
//
// }
//
// Path: test/com/njkremer/Sqlite/TestClass/UserAccessGroup.java
// public class UserAccessGroup {
//
// public long getUserId() {
// return userId;
// }
// public void setUserId(long userId) {
// this.userId = userId;
// }
// public long getGroupId() {
// return groupId;
// }
// public void setGroupId(long groupId) {
// this.groupId = groupId;
// }
//
// private long userId;
// private long groupId;
// }
// Path: test/com/njkremer/Sqlite/TU_JoinExecutor.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.njkremer.Sqlite.JoinExecutor;
import com.njkremer.Sqlite.JoinExecutor.JoinType;
import com.njkremer.Sqlite.TestClass.User;
import com.njkremer.Sqlite.TestClass.UserAccessGroup;
package com.njkremer.Sqlite;
public class TU_JoinExecutor {
@Test
public void testJoin() { | JoinExecutor joinExecutor = new JoinExecutor(); |
njkremer/SqliteORM | test/com/njkremer/Sqlite/TU_JoinExecutor.java | // Path: src/com/njkremer/Sqlite/JoinExecutor.java
// public class JoinExecutor {
//
// /**
// * User to represent various join types for a database.
// */
// public enum JoinType {
// INNER("inner "),
// LEFT_OUTER("left outer "),
// RIGHT_OUTER("right outer ");
//
// JoinType(String sql) {
// this.sql = sql;
// }
//
// public String getSql() {
// return sql;
// }
//
// private String sql;
// }
//
// public JoinExecutor join(Class<?> leftClazz, String leftField, Class<?> rightClazz, String rightField) {
// String rightClassName = rightClazz.getSimpleName().toLowerCase();
// String leftClassName = leftClazz.getSimpleName().toLowerCase();
// String joinTypeSql = "";
// if (joinType != null) {
// joinTypeSql = this.joinType.getSql();
// }
// query = String.format(JOIN, joinTypeSql, leftClassName, leftClassName, leftField, rightClassName, rightField);
// return this;
// }
//
// public void setJoinType(JoinType joinType) {
// this.joinType = joinType;
// }
//
// String getQuery() {
// return query;
// }
//
// private final static String JOIN = "%sjoin %s on %s.%s = %s.%s ";
// private JoinType joinType = null;
// private String query;
// }
//
// Path: src/com/njkremer/Sqlite/JoinExecutor.java
// public enum JoinType {
// INNER("inner "),
// LEFT_OUTER("left outer "),
// RIGHT_OUTER("right outer ");
//
// JoinType(String sql) {
// this.sql = sql;
// }
//
// public String getSql() {
// return sql;
// }
//
// private String sql;
// }
//
// Path: test/com/njkremer/Sqlite/TestClass/User.java
// public class User {
// @AutoIncrement
// @PrimaryKey
// private long id;
// private String name;
// private String password;
//
// @OneToMany("userId")
// private List<Thing> things;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public List<Thing> getThings() {
// return things;
// }
//
// public void setThings(List<Thing> things) {
// this.things = things;
// }
//
//
// }
//
// Path: test/com/njkremer/Sqlite/TestClass/UserAccessGroup.java
// public class UserAccessGroup {
//
// public long getUserId() {
// return userId;
// }
// public void setUserId(long userId) {
// this.userId = userId;
// }
// public long getGroupId() {
// return groupId;
// }
// public void setGroupId(long groupId) {
// this.groupId = groupId;
// }
//
// private long userId;
// private long groupId;
// }
| import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.njkremer.Sqlite.JoinExecutor;
import com.njkremer.Sqlite.JoinExecutor.JoinType;
import com.njkremer.Sqlite.TestClass.User;
import com.njkremer.Sqlite.TestClass.UserAccessGroup; | package com.njkremer.Sqlite;
public class TU_JoinExecutor {
@Test
public void testJoin() {
JoinExecutor joinExecutor = new JoinExecutor(); | // Path: src/com/njkremer/Sqlite/JoinExecutor.java
// public class JoinExecutor {
//
// /**
// * User to represent various join types for a database.
// */
// public enum JoinType {
// INNER("inner "),
// LEFT_OUTER("left outer "),
// RIGHT_OUTER("right outer ");
//
// JoinType(String sql) {
// this.sql = sql;
// }
//
// public String getSql() {
// return sql;
// }
//
// private String sql;
// }
//
// public JoinExecutor join(Class<?> leftClazz, String leftField, Class<?> rightClazz, String rightField) {
// String rightClassName = rightClazz.getSimpleName().toLowerCase();
// String leftClassName = leftClazz.getSimpleName().toLowerCase();
// String joinTypeSql = "";
// if (joinType != null) {
// joinTypeSql = this.joinType.getSql();
// }
// query = String.format(JOIN, joinTypeSql, leftClassName, leftClassName, leftField, rightClassName, rightField);
// return this;
// }
//
// public void setJoinType(JoinType joinType) {
// this.joinType = joinType;
// }
//
// String getQuery() {
// return query;
// }
//
// private final static String JOIN = "%sjoin %s on %s.%s = %s.%s ";
// private JoinType joinType = null;
// private String query;
// }
//
// Path: src/com/njkremer/Sqlite/JoinExecutor.java
// public enum JoinType {
// INNER("inner "),
// LEFT_OUTER("left outer "),
// RIGHT_OUTER("right outer ");
//
// JoinType(String sql) {
// this.sql = sql;
// }
//
// public String getSql() {
// return sql;
// }
//
// private String sql;
// }
//
// Path: test/com/njkremer/Sqlite/TestClass/User.java
// public class User {
// @AutoIncrement
// @PrimaryKey
// private long id;
// private String name;
// private String password;
//
// @OneToMany("userId")
// private List<Thing> things;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public List<Thing> getThings() {
// return things;
// }
//
// public void setThings(List<Thing> things) {
// this.things = things;
// }
//
//
// }
//
// Path: test/com/njkremer/Sqlite/TestClass/UserAccessGroup.java
// public class UserAccessGroup {
//
// public long getUserId() {
// return userId;
// }
// public void setUserId(long userId) {
// this.userId = userId;
// }
// public long getGroupId() {
// return groupId;
// }
// public void setGroupId(long groupId) {
// this.groupId = groupId;
// }
//
// private long userId;
// private long groupId;
// }
// Path: test/com/njkremer/Sqlite/TU_JoinExecutor.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.njkremer.Sqlite.JoinExecutor;
import com.njkremer.Sqlite.JoinExecutor.JoinType;
import com.njkremer.Sqlite.TestClass.User;
import com.njkremer.Sqlite.TestClass.UserAccessGroup;
package com.njkremer.Sqlite;
public class TU_JoinExecutor {
@Test
public void testJoin() {
JoinExecutor joinExecutor = new JoinExecutor(); | joinExecutor.join(UserAccessGroup.class, "userId", User.class, "id"); |
njkremer/SqliteORM | test/com/njkremer/Sqlite/TU_JoinExecutor.java | // Path: src/com/njkremer/Sqlite/JoinExecutor.java
// public class JoinExecutor {
//
// /**
// * User to represent various join types for a database.
// */
// public enum JoinType {
// INNER("inner "),
// LEFT_OUTER("left outer "),
// RIGHT_OUTER("right outer ");
//
// JoinType(String sql) {
// this.sql = sql;
// }
//
// public String getSql() {
// return sql;
// }
//
// private String sql;
// }
//
// public JoinExecutor join(Class<?> leftClazz, String leftField, Class<?> rightClazz, String rightField) {
// String rightClassName = rightClazz.getSimpleName().toLowerCase();
// String leftClassName = leftClazz.getSimpleName().toLowerCase();
// String joinTypeSql = "";
// if (joinType != null) {
// joinTypeSql = this.joinType.getSql();
// }
// query = String.format(JOIN, joinTypeSql, leftClassName, leftClassName, leftField, rightClassName, rightField);
// return this;
// }
//
// public void setJoinType(JoinType joinType) {
// this.joinType = joinType;
// }
//
// String getQuery() {
// return query;
// }
//
// private final static String JOIN = "%sjoin %s on %s.%s = %s.%s ";
// private JoinType joinType = null;
// private String query;
// }
//
// Path: src/com/njkremer/Sqlite/JoinExecutor.java
// public enum JoinType {
// INNER("inner "),
// LEFT_OUTER("left outer "),
// RIGHT_OUTER("right outer ");
//
// JoinType(String sql) {
// this.sql = sql;
// }
//
// public String getSql() {
// return sql;
// }
//
// private String sql;
// }
//
// Path: test/com/njkremer/Sqlite/TestClass/User.java
// public class User {
// @AutoIncrement
// @PrimaryKey
// private long id;
// private String name;
// private String password;
//
// @OneToMany("userId")
// private List<Thing> things;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public List<Thing> getThings() {
// return things;
// }
//
// public void setThings(List<Thing> things) {
// this.things = things;
// }
//
//
// }
//
// Path: test/com/njkremer/Sqlite/TestClass/UserAccessGroup.java
// public class UserAccessGroup {
//
// public long getUserId() {
// return userId;
// }
// public void setUserId(long userId) {
// this.userId = userId;
// }
// public long getGroupId() {
// return groupId;
// }
// public void setGroupId(long groupId) {
// this.groupId = groupId;
// }
//
// private long userId;
// private long groupId;
// }
| import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.njkremer.Sqlite.JoinExecutor;
import com.njkremer.Sqlite.JoinExecutor.JoinType;
import com.njkremer.Sqlite.TestClass.User;
import com.njkremer.Sqlite.TestClass.UserAccessGroup; | package com.njkremer.Sqlite;
public class TU_JoinExecutor {
@Test
public void testJoin() {
JoinExecutor joinExecutor = new JoinExecutor(); | // Path: src/com/njkremer/Sqlite/JoinExecutor.java
// public class JoinExecutor {
//
// /**
// * User to represent various join types for a database.
// */
// public enum JoinType {
// INNER("inner "),
// LEFT_OUTER("left outer "),
// RIGHT_OUTER("right outer ");
//
// JoinType(String sql) {
// this.sql = sql;
// }
//
// public String getSql() {
// return sql;
// }
//
// private String sql;
// }
//
// public JoinExecutor join(Class<?> leftClazz, String leftField, Class<?> rightClazz, String rightField) {
// String rightClassName = rightClazz.getSimpleName().toLowerCase();
// String leftClassName = leftClazz.getSimpleName().toLowerCase();
// String joinTypeSql = "";
// if (joinType != null) {
// joinTypeSql = this.joinType.getSql();
// }
// query = String.format(JOIN, joinTypeSql, leftClassName, leftClassName, leftField, rightClassName, rightField);
// return this;
// }
//
// public void setJoinType(JoinType joinType) {
// this.joinType = joinType;
// }
//
// String getQuery() {
// return query;
// }
//
// private final static String JOIN = "%sjoin %s on %s.%s = %s.%s ";
// private JoinType joinType = null;
// private String query;
// }
//
// Path: src/com/njkremer/Sqlite/JoinExecutor.java
// public enum JoinType {
// INNER("inner "),
// LEFT_OUTER("left outer "),
// RIGHT_OUTER("right outer ");
//
// JoinType(String sql) {
// this.sql = sql;
// }
//
// public String getSql() {
// return sql;
// }
//
// private String sql;
// }
//
// Path: test/com/njkremer/Sqlite/TestClass/User.java
// public class User {
// @AutoIncrement
// @PrimaryKey
// private long id;
// private String name;
// private String password;
//
// @OneToMany("userId")
// private List<Thing> things;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public List<Thing> getThings() {
// return things;
// }
//
// public void setThings(List<Thing> things) {
// this.things = things;
// }
//
//
// }
//
// Path: test/com/njkremer/Sqlite/TestClass/UserAccessGroup.java
// public class UserAccessGroup {
//
// public long getUserId() {
// return userId;
// }
// public void setUserId(long userId) {
// this.userId = userId;
// }
// public long getGroupId() {
// return groupId;
// }
// public void setGroupId(long groupId) {
// this.groupId = groupId;
// }
//
// private long userId;
// private long groupId;
// }
// Path: test/com/njkremer/Sqlite/TU_JoinExecutor.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.njkremer.Sqlite.JoinExecutor;
import com.njkremer.Sqlite.JoinExecutor.JoinType;
import com.njkremer.Sqlite.TestClass.User;
import com.njkremer.Sqlite.TestClass.UserAccessGroup;
package com.njkremer.Sqlite;
public class TU_JoinExecutor {
@Test
public void testJoin() {
JoinExecutor joinExecutor = new JoinExecutor(); | joinExecutor.join(UserAccessGroup.class, "userId", User.class, "id"); |
njkremer/SqliteORM | test/com/njkremer/Sqlite/TU_JoinExecutor.java | // Path: src/com/njkremer/Sqlite/JoinExecutor.java
// public class JoinExecutor {
//
// /**
// * User to represent various join types for a database.
// */
// public enum JoinType {
// INNER("inner "),
// LEFT_OUTER("left outer "),
// RIGHT_OUTER("right outer ");
//
// JoinType(String sql) {
// this.sql = sql;
// }
//
// public String getSql() {
// return sql;
// }
//
// private String sql;
// }
//
// public JoinExecutor join(Class<?> leftClazz, String leftField, Class<?> rightClazz, String rightField) {
// String rightClassName = rightClazz.getSimpleName().toLowerCase();
// String leftClassName = leftClazz.getSimpleName().toLowerCase();
// String joinTypeSql = "";
// if (joinType != null) {
// joinTypeSql = this.joinType.getSql();
// }
// query = String.format(JOIN, joinTypeSql, leftClassName, leftClassName, leftField, rightClassName, rightField);
// return this;
// }
//
// public void setJoinType(JoinType joinType) {
// this.joinType = joinType;
// }
//
// String getQuery() {
// return query;
// }
//
// private final static String JOIN = "%sjoin %s on %s.%s = %s.%s ";
// private JoinType joinType = null;
// private String query;
// }
//
// Path: src/com/njkremer/Sqlite/JoinExecutor.java
// public enum JoinType {
// INNER("inner "),
// LEFT_OUTER("left outer "),
// RIGHT_OUTER("right outer ");
//
// JoinType(String sql) {
// this.sql = sql;
// }
//
// public String getSql() {
// return sql;
// }
//
// private String sql;
// }
//
// Path: test/com/njkremer/Sqlite/TestClass/User.java
// public class User {
// @AutoIncrement
// @PrimaryKey
// private long id;
// private String name;
// private String password;
//
// @OneToMany("userId")
// private List<Thing> things;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public List<Thing> getThings() {
// return things;
// }
//
// public void setThings(List<Thing> things) {
// this.things = things;
// }
//
//
// }
//
// Path: test/com/njkremer/Sqlite/TestClass/UserAccessGroup.java
// public class UserAccessGroup {
//
// public long getUserId() {
// return userId;
// }
// public void setUserId(long userId) {
// this.userId = userId;
// }
// public long getGroupId() {
// return groupId;
// }
// public void setGroupId(long groupId) {
// this.groupId = groupId;
// }
//
// private long userId;
// private long groupId;
// }
| import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.njkremer.Sqlite.JoinExecutor;
import com.njkremer.Sqlite.JoinExecutor.JoinType;
import com.njkremer.Sqlite.TestClass.User;
import com.njkremer.Sqlite.TestClass.UserAccessGroup; | package com.njkremer.Sqlite;
public class TU_JoinExecutor {
@Test
public void testJoin() {
JoinExecutor joinExecutor = new JoinExecutor();
joinExecutor.join(UserAccessGroup.class, "userId", User.class, "id");
assertEquals("join useraccessgroup on useraccessgroup.userId = user.id ", joinExecutor.getQuery());
}
@Test
public void testInnerJoin() {
JoinExecutor joinExecutor = new JoinExecutor(); | // Path: src/com/njkremer/Sqlite/JoinExecutor.java
// public class JoinExecutor {
//
// /**
// * User to represent various join types for a database.
// */
// public enum JoinType {
// INNER("inner "),
// LEFT_OUTER("left outer "),
// RIGHT_OUTER("right outer ");
//
// JoinType(String sql) {
// this.sql = sql;
// }
//
// public String getSql() {
// return sql;
// }
//
// private String sql;
// }
//
// public JoinExecutor join(Class<?> leftClazz, String leftField, Class<?> rightClazz, String rightField) {
// String rightClassName = rightClazz.getSimpleName().toLowerCase();
// String leftClassName = leftClazz.getSimpleName().toLowerCase();
// String joinTypeSql = "";
// if (joinType != null) {
// joinTypeSql = this.joinType.getSql();
// }
// query = String.format(JOIN, joinTypeSql, leftClassName, leftClassName, leftField, rightClassName, rightField);
// return this;
// }
//
// public void setJoinType(JoinType joinType) {
// this.joinType = joinType;
// }
//
// String getQuery() {
// return query;
// }
//
// private final static String JOIN = "%sjoin %s on %s.%s = %s.%s ";
// private JoinType joinType = null;
// private String query;
// }
//
// Path: src/com/njkremer/Sqlite/JoinExecutor.java
// public enum JoinType {
// INNER("inner "),
// LEFT_OUTER("left outer "),
// RIGHT_OUTER("right outer ");
//
// JoinType(String sql) {
// this.sql = sql;
// }
//
// public String getSql() {
// return sql;
// }
//
// private String sql;
// }
//
// Path: test/com/njkremer/Sqlite/TestClass/User.java
// public class User {
// @AutoIncrement
// @PrimaryKey
// private long id;
// private String name;
// private String password;
//
// @OneToMany("userId")
// private List<Thing> things;
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public List<Thing> getThings() {
// return things;
// }
//
// public void setThings(List<Thing> things) {
// this.things = things;
// }
//
//
// }
//
// Path: test/com/njkremer/Sqlite/TestClass/UserAccessGroup.java
// public class UserAccessGroup {
//
// public long getUserId() {
// return userId;
// }
// public void setUserId(long userId) {
// this.userId = userId;
// }
// public long getGroupId() {
// return groupId;
// }
// public void setGroupId(long groupId) {
// this.groupId = groupId;
// }
//
// private long userId;
// private long groupId;
// }
// Path: test/com/njkremer/Sqlite/TU_JoinExecutor.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.njkremer.Sqlite.JoinExecutor;
import com.njkremer.Sqlite.JoinExecutor.JoinType;
import com.njkremer.Sqlite.TestClass.User;
import com.njkremer.Sqlite.TestClass.UserAccessGroup;
package com.njkremer.Sqlite;
public class TU_JoinExecutor {
@Test
public void testJoin() {
JoinExecutor joinExecutor = new JoinExecutor();
joinExecutor.join(UserAccessGroup.class, "userId", User.class, "id");
assertEquals("join useraccessgroup on useraccessgroup.userId = user.id ", joinExecutor.getQuery());
}
@Test
public void testInnerJoin() {
JoinExecutor joinExecutor = new JoinExecutor(); | joinExecutor.setJoinType(JoinType.INNER); |
njkremer/SqliteORM | test/com/njkremer/Sqlite/TU_ColumnExpression.java | // Path: src/com/njkremer/Sqlite/ColumnExpression.java
// public class ColumnExpression {
// public ColumnExpression() {
// queryParts.put(StatementParts.SELECT, SELECT);
// queryParts.put(StatementParts.COLUMN, "");
// }
//
// /**
// * Specify the column to limit you're resulting query by. A function (such as SQLite's <a
// * href="http://www.sqlite.org/lang_datefunc.html">Date/Time Functions</a>) can be used in the passed in string
// * too.
// *
// * @param columnString The column to query.
// * @return A {@link ColumnExpression} for function chaining.
// */
// public ColumnExpression column(String columnString) {
// queryParts.put(StatementParts.COLUMN, queryParts.get(StatementParts.COLUMN).concat(columnString + ", "));
// return this;
// }
//
// /**
// * Lets you alias a column if you want. This can be useful when using a function in the
// * {@linkplain #column(String)}.
// *
// * @param alias The name of the alias for the column.
// * @return A {@link ColumnExpression} for function chaining.
// */
// public ColumnExpression as(String alias) {
// String columns = queryParts.get(StatementParts.COLUMN);
// columns = columns.substring(0, columns.lastIndexOf(",")).concat(" ");
// queryParts.put(StatementParts.COLUMN, columns.concat(String.format(AS, alias)));
// return this;
// }
//
// /**
// * Allows you to specify making a query distinc, which will eliminate duplicate rows in the result set.
// *
// * @return A {@link ColumnExpression} for function chaining.
// */
// public ColumnExpression distinct() {
// queryParts.put(StatementParts.SELECT, SELECT + DISTINCT);
// return this;
// }
//
// /**
// * @return Returns the Sql Select String so far for the {@linkplain ColumnExpression}.
// */
// String getQuery() {
// StringBuilder builder = new StringBuilder();
// for (StatementParts key : queryParts.keySet()) {
// builder.append(queryParts.get(key));
// }
// String query = builder.toString();
// int commaIndex = query.lastIndexOf(",");
// int trimIndex = commaIndex == -1 ? query.length() : commaIndex;
// return query.substring(0, trimIndex).concat(" ");
// }
//
// private static final String SELECT = "select ";
// private static final String AS = "as %s, ";
// private static final String DISTINCT = "distinct ";
// private LinkedHashMap<StatementParts, String> queryParts = new LinkedHashMap<StatementParts, String>();
//
// }
| import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.njkremer.Sqlite.ColumnExpression; | package com.njkremer.Sqlite;
public class TU_ColumnExpression {
@Test
public void testQueryStringWithOneColumn() { | // Path: src/com/njkremer/Sqlite/ColumnExpression.java
// public class ColumnExpression {
// public ColumnExpression() {
// queryParts.put(StatementParts.SELECT, SELECT);
// queryParts.put(StatementParts.COLUMN, "");
// }
//
// /**
// * Specify the column to limit you're resulting query by. A function (such as SQLite's <a
// * href="http://www.sqlite.org/lang_datefunc.html">Date/Time Functions</a>) can be used in the passed in string
// * too.
// *
// * @param columnString The column to query.
// * @return A {@link ColumnExpression} for function chaining.
// */
// public ColumnExpression column(String columnString) {
// queryParts.put(StatementParts.COLUMN, queryParts.get(StatementParts.COLUMN).concat(columnString + ", "));
// return this;
// }
//
// /**
// * Lets you alias a column if you want. This can be useful when using a function in the
// * {@linkplain #column(String)}.
// *
// * @param alias The name of the alias for the column.
// * @return A {@link ColumnExpression} for function chaining.
// */
// public ColumnExpression as(String alias) {
// String columns = queryParts.get(StatementParts.COLUMN);
// columns = columns.substring(0, columns.lastIndexOf(",")).concat(" ");
// queryParts.put(StatementParts.COLUMN, columns.concat(String.format(AS, alias)));
// return this;
// }
//
// /**
// * Allows you to specify making a query distinc, which will eliminate duplicate rows in the result set.
// *
// * @return A {@link ColumnExpression} for function chaining.
// */
// public ColumnExpression distinct() {
// queryParts.put(StatementParts.SELECT, SELECT + DISTINCT);
// return this;
// }
//
// /**
// * @return Returns the Sql Select String so far for the {@linkplain ColumnExpression}.
// */
// String getQuery() {
// StringBuilder builder = new StringBuilder();
// for (StatementParts key : queryParts.keySet()) {
// builder.append(queryParts.get(key));
// }
// String query = builder.toString();
// int commaIndex = query.lastIndexOf(",");
// int trimIndex = commaIndex == -1 ? query.length() : commaIndex;
// return query.substring(0, trimIndex).concat(" ");
// }
//
// private static final String SELECT = "select ";
// private static final String AS = "as %s, ";
// private static final String DISTINCT = "distinct ";
// private LinkedHashMap<StatementParts, String> queryParts = new LinkedHashMap<StatementParts, String>();
//
// }
// Path: test/com/njkremer/Sqlite/TU_ColumnExpression.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.njkremer.Sqlite.ColumnExpression;
package com.njkremer.Sqlite;
public class TU_ColumnExpression {
@Test
public void testQueryStringWithOneColumn() { | ColumnExpression me = new ColumnExpression(); |
njkremer/SqliteORM | src/com/njkremer/Sqlite/Relationship.java | // Path: src/com/njkremer/Sqlite/utils/SqliteUtils.java
// public class SqliteUtils {
// public static Class<?> getClass(Object object) {
// return AopUtils.getTargetClass(object);
// }
//
// public static String capitalize(String word) {
// return word.substring(0, 1).toUpperCase() + word.substring(1);
// }
//
// public static String lowercase(String word) {
// return word.substring(0, 1).toLowerCase() + word.substring(1);
// }
//
// public static boolean isEmpty(Object object) {
// if(object == null) {
// return true;
// }
// if (object instanceof String) {
// return ((String) object).trim().length() == 0;
// }
// else if (object instanceof Float) {
// return ((Float) object) == 0.0f;
// }
// else if (object instanceof Integer) {
// return ((Integer) object) == 0;
// }
// else if (object instanceof Long) {
// return ((Long) object) == 0l;
// }
// else if (object instanceof Double) {
// return ((Double) object) == 0.0d;
// }
// else if (object instanceof Boolean) {
// return ((Boolean) object) == false;
// }
// return false;
// }
// }
| import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import com.njkremer.Sqlite.Annotations.OneToMany;
import com.njkremer.Sqlite.utils.SqliteUtils; | package com.njkremer.Sqlite;
public class Relationship {
public enum RelationshipType {
ONE_TO_MANY
}
public Relationship(Field field) throws DataConnectionException {
if(field.isAnnotationPresent(OneToMany.class)) {
type = RelationshipType.ONE_TO_MANY;
fk = ((OneToMany) field.getAnnotation(OneToMany.class)).value();
fieldName = field.getName();
ParameterizedType genericType = (ParameterizedType) field.getGenericType();
Type[] types = genericType.getActualTypeArguments();
relatedClassType = (Class<?>) types[0];
try {
fkClassType = relatedClassType.getDeclaredField(fk).getType();
}
catch (Exception e) {
throw new DataConnectionException(String.format("Error occured when trying to get foreign key's type. The foreign key of %s does not exist on %s", fk, relatedClassType));
}
}
}
public String getterName() { | // Path: src/com/njkremer/Sqlite/utils/SqliteUtils.java
// public class SqliteUtils {
// public static Class<?> getClass(Object object) {
// return AopUtils.getTargetClass(object);
// }
//
// public static String capitalize(String word) {
// return word.substring(0, 1).toUpperCase() + word.substring(1);
// }
//
// public static String lowercase(String word) {
// return word.substring(0, 1).toLowerCase() + word.substring(1);
// }
//
// public static boolean isEmpty(Object object) {
// if(object == null) {
// return true;
// }
// if (object instanceof String) {
// return ((String) object).trim().length() == 0;
// }
// else if (object instanceof Float) {
// return ((Float) object) == 0.0f;
// }
// else if (object instanceof Integer) {
// return ((Integer) object) == 0;
// }
// else if (object instanceof Long) {
// return ((Long) object) == 0l;
// }
// else if (object instanceof Double) {
// return ((Double) object) == 0.0d;
// }
// else if (object instanceof Boolean) {
// return ((Boolean) object) == false;
// }
// return false;
// }
// }
// Path: src/com/njkremer/Sqlite/Relationship.java
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import com.njkremer.Sqlite.Annotations.OneToMany;
import com.njkremer.Sqlite.utils.SqliteUtils;
package com.njkremer.Sqlite;
public class Relationship {
public enum RelationshipType {
ONE_TO_MANY
}
public Relationship(Field field) throws DataConnectionException {
if(field.isAnnotationPresent(OneToMany.class)) {
type = RelationshipType.ONE_TO_MANY;
fk = ((OneToMany) field.getAnnotation(OneToMany.class)).value();
fieldName = field.getName();
ParameterizedType genericType = (ParameterizedType) field.getGenericType();
Type[] types = genericType.getActualTypeArguments();
relatedClassType = (Class<?>) types[0];
try {
fkClassType = relatedClassType.getDeclaredField(fk).getType();
}
catch (Exception e) {
throw new DataConnectionException(String.format("Error occured when trying to get foreign key's type. The foreign key of %s does not exist on %s", fk, relatedClassType));
}
}
}
public String getterName() { | return "get" + SqliteUtils.capitalize(fieldName); |
justice-code/QiuQiu | plugin/src/main/java/org/eddy/xml/context/XmlDataContext.java | // Path: plugin/src/main/java/org/eddy/xml/UrlDtdPathResolver.java
// public class UrlDtdPathResolver implements EntityResolver {
// @Override
// public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
// if (systemId != null) {
// return new InputSource(Thread.currentThread().getContextClassLoader().getResourceAsStream("config/config.dtd"));
// }
// return null;
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/DataNode.java
// @Getter
// @Setter
// @ToString
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class DataNode {
//
// public static final String DATA_NODE_NAME = "data";
//
// /**
// * 库名
// */
// @NonNull
// private String schema;
//
// /**
// * 表名
// */
// @NonNull
// private String table;
//
// /**
// * 对比脚本
// */
// @NonNull
// private String script;
//
// private RuleNode ruleNode;
//
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/KeyColumn.java
// @Getter
// @Setter
// @ToString
// @AllArgsConstructor
// @NoArgsConstructor
// public class KeyColumn {
//
// /**
// * 客户端查询sql分库分表传入的表名
// */
// @NonNull
// private String table;
//
// /**
// * 客户端查询sql分库分表传入的列名
// */
// @NonNull
// private String column;
//
// /**
// * 客户端查询sql分库分表传入的列取值类型
// */
// @NonNull
// private String javaType;
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/rule/Comparator.java
// public abstract class Comparator {
//
// public abstract DataNode check(RuleNode ruleNode);
//
// public boolean script(String mapper, Object[] param, String script) {
// Objects.requireNonNull(script);
//
// Binding binding = new Binding();
// GroovyShell shell = new GroovyShell(binding);
// shell.setVariable("mapper", mapper);
// shell.setVariable("params", param);
// Object returnValue = shell.evaluate(script);
//
// return (boolean) returnValue;
// }
// }
| import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import org.eddy.xml.UrlDtdPathResolver;
import org.eddy.xml.data.DataNode;
import org.eddy.xml.data.KeyColumn;
import org.eddy.xml.data.RuleNode;
import org.eddy.xml.rule.Comparator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors; | package org.eddy.xml.context;
/**
* Created by eddy on 2017/5/2.
*/
@Getter
public class XmlDataContext {
private static final Logger logger = LoggerFactory.getLogger(XmlDataContext.class);
| // Path: plugin/src/main/java/org/eddy/xml/UrlDtdPathResolver.java
// public class UrlDtdPathResolver implements EntityResolver {
// @Override
// public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
// if (systemId != null) {
// return new InputSource(Thread.currentThread().getContextClassLoader().getResourceAsStream("config/config.dtd"));
// }
// return null;
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/DataNode.java
// @Getter
// @Setter
// @ToString
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class DataNode {
//
// public static final String DATA_NODE_NAME = "data";
//
// /**
// * 库名
// */
// @NonNull
// private String schema;
//
// /**
// * 表名
// */
// @NonNull
// private String table;
//
// /**
// * 对比脚本
// */
// @NonNull
// private String script;
//
// private RuleNode ruleNode;
//
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/KeyColumn.java
// @Getter
// @Setter
// @ToString
// @AllArgsConstructor
// @NoArgsConstructor
// public class KeyColumn {
//
// /**
// * 客户端查询sql分库分表传入的表名
// */
// @NonNull
// private String table;
//
// /**
// * 客户端查询sql分库分表传入的列名
// */
// @NonNull
// private String column;
//
// /**
// * 客户端查询sql分库分表传入的列取值类型
// */
// @NonNull
// private String javaType;
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/rule/Comparator.java
// public abstract class Comparator {
//
// public abstract DataNode check(RuleNode ruleNode);
//
// public boolean script(String mapper, Object[] param, String script) {
// Objects.requireNonNull(script);
//
// Binding binding = new Binding();
// GroovyShell shell = new GroovyShell(binding);
// shell.setVariable("mapper", mapper);
// shell.setVariable("params", param);
// Object returnValue = shell.evaluate(script);
//
// return (boolean) returnValue;
// }
// }
// Path: plugin/src/main/java/org/eddy/xml/context/XmlDataContext.java
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import org.eddy.xml.UrlDtdPathResolver;
import org.eddy.xml.data.DataNode;
import org.eddy.xml.data.KeyColumn;
import org.eddy.xml.data.RuleNode;
import org.eddy.xml.rule.Comparator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
package org.eddy.xml.context;
/**
* Created by eddy on 2017/5/2.
*/
@Getter
public class XmlDataContext {
private static final Logger logger = LoggerFactory.getLogger(XmlDataContext.class);
| private List<RuleNode> nodes; |
justice-code/QiuQiu | plugin/src/main/java/org/eddy/xml/context/XmlDataContext.java | // Path: plugin/src/main/java/org/eddy/xml/UrlDtdPathResolver.java
// public class UrlDtdPathResolver implements EntityResolver {
// @Override
// public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
// if (systemId != null) {
// return new InputSource(Thread.currentThread().getContextClassLoader().getResourceAsStream("config/config.dtd"));
// }
// return null;
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/DataNode.java
// @Getter
// @Setter
// @ToString
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class DataNode {
//
// public static final String DATA_NODE_NAME = "data";
//
// /**
// * 库名
// */
// @NonNull
// private String schema;
//
// /**
// * 表名
// */
// @NonNull
// private String table;
//
// /**
// * 对比脚本
// */
// @NonNull
// private String script;
//
// private RuleNode ruleNode;
//
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/KeyColumn.java
// @Getter
// @Setter
// @ToString
// @AllArgsConstructor
// @NoArgsConstructor
// public class KeyColumn {
//
// /**
// * 客户端查询sql分库分表传入的表名
// */
// @NonNull
// private String table;
//
// /**
// * 客户端查询sql分库分表传入的列名
// */
// @NonNull
// private String column;
//
// /**
// * 客户端查询sql分库分表传入的列取值类型
// */
// @NonNull
// private String javaType;
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/rule/Comparator.java
// public abstract class Comparator {
//
// public abstract DataNode check(RuleNode ruleNode);
//
// public boolean script(String mapper, Object[] param, String script) {
// Objects.requireNonNull(script);
//
// Binding binding = new Binding();
// GroovyShell shell = new GroovyShell(binding);
// shell.setVariable("mapper", mapper);
// shell.setVariable("params", param);
// Object returnValue = shell.evaluate(script);
//
// return (boolean) returnValue;
// }
// }
| import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import org.eddy.xml.UrlDtdPathResolver;
import org.eddy.xml.data.DataNode;
import org.eddy.xml.data.KeyColumn;
import org.eddy.xml.data.RuleNode;
import org.eddy.xml.rule.Comparator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors; | package org.eddy.xml.context;
/**
* Created by eddy on 2017/5/2.
*/
@Getter
public class XmlDataContext {
private static final Logger logger = LoggerFactory.getLogger(XmlDataContext.class);
private List<RuleNode> nodes;
private static XmlDataContext context = new XmlDataContext("rule/rule.xml");
public static XmlDataContext getContext() {
return context;
}
//**********************私有构造函数*************************
private XmlDataContext(String path) {
try {
this.nodes = loadXml(path);
} catch (Exception e) {
logger.error("parse xml error", e);
throw new RuntimeException("parse xml error", e);
}
}
//**********************解析xml*****************************
private List<RuleNode> loadXml(String path) throws Exception{
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder(); | // Path: plugin/src/main/java/org/eddy/xml/UrlDtdPathResolver.java
// public class UrlDtdPathResolver implements EntityResolver {
// @Override
// public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
// if (systemId != null) {
// return new InputSource(Thread.currentThread().getContextClassLoader().getResourceAsStream("config/config.dtd"));
// }
// return null;
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/DataNode.java
// @Getter
// @Setter
// @ToString
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class DataNode {
//
// public static final String DATA_NODE_NAME = "data";
//
// /**
// * 库名
// */
// @NonNull
// private String schema;
//
// /**
// * 表名
// */
// @NonNull
// private String table;
//
// /**
// * 对比脚本
// */
// @NonNull
// private String script;
//
// private RuleNode ruleNode;
//
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/KeyColumn.java
// @Getter
// @Setter
// @ToString
// @AllArgsConstructor
// @NoArgsConstructor
// public class KeyColumn {
//
// /**
// * 客户端查询sql分库分表传入的表名
// */
// @NonNull
// private String table;
//
// /**
// * 客户端查询sql分库分表传入的列名
// */
// @NonNull
// private String column;
//
// /**
// * 客户端查询sql分库分表传入的列取值类型
// */
// @NonNull
// private String javaType;
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/rule/Comparator.java
// public abstract class Comparator {
//
// public abstract DataNode check(RuleNode ruleNode);
//
// public boolean script(String mapper, Object[] param, String script) {
// Objects.requireNonNull(script);
//
// Binding binding = new Binding();
// GroovyShell shell = new GroovyShell(binding);
// shell.setVariable("mapper", mapper);
// shell.setVariable("params", param);
// Object returnValue = shell.evaluate(script);
//
// return (boolean) returnValue;
// }
// }
// Path: plugin/src/main/java/org/eddy/xml/context/XmlDataContext.java
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import org.eddy.xml.UrlDtdPathResolver;
import org.eddy.xml.data.DataNode;
import org.eddy.xml.data.KeyColumn;
import org.eddy.xml.data.RuleNode;
import org.eddy.xml.rule.Comparator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
package org.eddy.xml.context;
/**
* Created by eddy on 2017/5/2.
*/
@Getter
public class XmlDataContext {
private static final Logger logger = LoggerFactory.getLogger(XmlDataContext.class);
private List<RuleNode> nodes;
private static XmlDataContext context = new XmlDataContext("rule/rule.xml");
public static XmlDataContext getContext() {
return context;
}
//**********************私有构造函数*************************
private XmlDataContext(String path) {
try {
this.nodes = loadXml(path);
} catch (Exception e) {
logger.error("parse xml error", e);
throw new RuntimeException("parse xml error", e);
}
}
//**********************解析xml*****************************
private List<RuleNode> loadXml(String path) throws Exception{
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder(); | builder.setEntityResolver(new UrlDtdPathResolver()); |
justice-code/QiuQiu | plugin/src/main/java/org/eddy/xml/context/XmlDataContext.java | // Path: plugin/src/main/java/org/eddy/xml/UrlDtdPathResolver.java
// public class UrlDtdPathResolver implements EntityResolver {
// @Override
// public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
// if (systemId != null) {
// return new InputSource(Thread.currentThread().getContextClassLoader().getResourceAsStream("config/config.dtd"));
// }
// return null;
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/DataNode.java
// @Getter
// @Setter
// @ToString
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class DataNode {
//
// public static final String DATA_NODE_NAME = "data";
//
// /**
// * 库名
// */
// @NonNull
// private String schema;
//
// /**
// * 表名
// */
// @NonNull
// private String table;
//
// /**
// * 对比脚本
// */
// @NonNull
// private String script;
//
// private RuleNode ruleNode;
//
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/KeyColumn.java
// @Getter
// @Setter
// @ToString
// @AllArgsConstructor
// @NoArgsConstructor
// public class KeyColumn {
//
// /**
// * 客户端查询sql分库分表传入的表名
// */
// @NonNull
// private String table;
//
// /**
// * 客户端查询sql分库分表传入的列名
// */
// @NonNull
// private String column;
//
// /**
// * 客户端查询sql分库分表传入的列取值类型
// */
// @NonNull
// private String javaType;
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/rule/Comparator.java
// public abstract class Comparator {
//
// public abstract DataNode check(RuleNode ruleNode);
//
// public boolean script(String mapper, Object[] param, String script) {
// Objects.requireNonNull(script);
//
// Binding binding = new Binding();
// GroovyShell shell = new GroovyShell(binding);
// shell.setVariable("mapper", mapper);
// shell.setVariable("params", param);
// Object returnValue = shell.evaluate(script);
//
// return (boolean) returnValue;
// }
// }
| import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import org.eddy.xml.UrlDtdPathResolver;
import org.eddy.xml.data.DataNode;
import org.eddy.xml.data.KeyColumn;
import org.eddy.xml.data.RuleNode;
import org.eddy.xml.rule.Comparator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors; | private List<RuleNode> loadXml(String path) throws Exception{
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
builder.setEntityResolver(new UrlDtdPathResolver());
Document document = builder.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream(path));
List<RuleNode> results = new ArrayList<>();
NodeList rootChildren = document.getDocumentElement().getChildNodes();
for (int i = 0; i < rootChildren.getLength(); i++) {
Optional.ofNullable(parseNode(rootChildren.item(i))).ifPresent(node -> results.add(node));
}
return results.stream().filter(Objects::nonNull).collect(Collectors.toList());
}
private RuleNode parseNode(Node item) throws Exception{
// 节点非element节点 或 element节点name非rule, 则直接返回
if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), RuleNode.RULE_NODE_NAME)) {
return null;
}
Element ruleNode = (Element) item;
String table = ruleNode.getAttribute("table");
String column = ruleNode.getAttribute("column");
String javaType = ruleNode.getAttribute("javaType"); | // Path: plugin/src/main/java/org/eddy/xml/UrlDtdPathResolver.java
// public class UrlDtdPathResolver implements EntityResolver {
// @Override
// public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
// if (systemId != null) {
// return new InputSource(Thread.currentThread().getContextClassLoader().getResourceAsStream("config/config.dtd"));
// }
// return null;
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/DataNode.java
// @Getter
// @Setter
// @ToString
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class DataNode {
//
// public static final String DATA_NODE_NAME = "data";
//
// /**
// * 库名
// */
// @NonNull
// private String schema;
//
// /**
// * 表名
// */
// @NonNull
// private String table;
//
// /**
// * 对比脚本
// */
// @NonNull
// private String script;
//
// private RuleNode ruleNode;
//
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/KeyColumn.java
// @Getter
// @Setter
// @ToString
// @AllArgsConstructor
// @NoArgsConstructor
// public class KeyColumn {
//
// /**
// * 客户端查询sql分库分表传入的表名
// */
// @NonNull
// private String table;
//
// /**
// * 客户端查询sql分库分表传入的列名
// */
// @NonNull
// private String column;
//
// /**
// * 客户端查询sql分库分表传入的列取值类型
// */
// @NonNull
// private String javaType;
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/rule/Comparator.java
// public abstract class Comparator {
//
// public abstract DataNode check(RuleNode ruleNode);
//
// public boolean script(String mapper, Object[] param, String script) {
// Objects.requireNonNull(script);
//
// Binding binding = new Binding();
// GroovyShell shell = new GroovyShell(binding);
// shell.setVariable("mapper", mapper);
// shell.setVariable("params", param);
// Object returnValue = shell.evaluate(script);
//
// return (boolean) returnValue;
// }
// }
// Path: plugin/src/main/java/org/eddy/xml/context/XmlDataContext.java
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import org.eddy.xml.UrlDtdPathResolver;
import org.eddy.xml.data.DataNode;
import org.eddy.xml.data.KeyColumn;
import org.eddy.xml.data.RuleNode;
import org.eddy.xml.rule.Comparator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
private List<RuleNode> loadXml(String path) throws Exception{
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
builder.setEntityResolver(new UrlDtdPathResolver());
Document document = builder.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream(path));
List<RuleNode> results = new ArrayList<>();
NodeList rootChildren = document.getDocumentElement().getChildNodes();
for (int i = 0; i < rootChildren.getLength(); i++) {
Optional.ofNullable(parseNode(rootChildren.item(i))).ifPresent(node -> results.add(node));
}
return results.stream().filter(Objects::nonNull).collect(Collectors.toList());
}
private RuleNode parseNode(Node item) throws Exception{
// 节点非element节点 或 element节点name非rule, 则直接返回
if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), RuleNode.RULE_NODE_NAME)) {
return null;
}
Element ruleNode = (Element) item;
String table = ruleNode.getAttribute("table");
String column = ruleNode.getAttribute("column");
String javaType = ruleNode.getAttribute("javaType"); | KeyColumn keyColumn = new KeyColumn(table, column, javaType); |
justice-code/QiuQiu | plugin/src/main/java/org/eddy/xml/context/XmlDataContext.java | // Path: plugin/src/main/java/org/eddy/xml/UrlDtdPathResolver.java
// public class UrlDtdPathResolver implements EntityResolver {
// @Override
// public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
// if (systemId != null) {
// return new InputSource(Thread.currentThread().getContextClassLoader().getResourceAsStream("config/config.dtd"));
// }
// return null;
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/DataNode.java
// @Getter
// @Setter
// @ToString
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class DataNode {
//
// public static final String DATA_NODE_NAME = "data";
//
// /**
// * 库名
// */
// @NonNull
// private String schema;
//
// /**
// * 表名
// */
// @NonNull
// private String table;
//
// /**
// * 对比脚本
// */
// @NonNull
// private String script;
//
// private RuleNode ruleNode;
//
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/KeyColumn.java
// @Getter
// @Setter
// @ToString
// @AllArgsConstructor
// @NoArgsConstructor
// public class KeyColumn {
//
// /**
// * 客户端查询sql分库分表传入的表名
// */
// @NonNull
// private String table;
//
// /**
// * 客户端查询sql分库分表传入的列名
// */
// @NonNull
// private String column;
//
// /**
// * 客户端查询sql分库分表传入的列取值类型
// */
// @NonNull
// private String javaType;
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/rule/Comparator.java
// public abstract class Comparator {
//
// public abstract DataNode check(RuleNode ruleNode);
//
// public boolean script(String mapper, Object[] param, String script) {
// Objects.requireNonNull(script);
//
// Binding binding = new Binding();
// GroovyShell shell = new GroovyShell(binding);
// shell.setVariable("mapper", mapper);
// shell.setVariable("params", param);
// Object returnValue = shell.evaluate(script);
//
// return (boolean) returnValue;
// }
// }
| import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import org.eddy.xml.UrlDtdPathResolver;
import org.eddy.xml.data.DataNode;
import org.eddy.xml.data.KeyColumn;
import org.eddy.xml.data.RuleNode;
import org.eddy.xml.rule.Comparator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors; | builder.setEntityResolver(new UrlDtdPathResolver());
Document document = builder.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream(path));
List<RuleNode> results = new ArrayList<>();
NodeList rootChildren = document.getDocumentElement().getChildNodes();
for (int i = 0; i < rootChildren.getLength(); i++) {
Optional.ofNullable(parseNode(rootChildren.item(i))).ifPresent(node -> results.add(node));
}
return results.stream().filter(Objects::nonNull).collect(Collectors.toList());
}
private RuleNode parseNode(Node item) throws Exception{
// 节点非element节点 或 element节点name非rule, 则直接返回
if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), RuleNode.RULE_NODE_NAME)) {
return null;
}
Element ruleNode = (Element) item;
String table = ruleNode.getAttribute("table");
String column = ruleNode.getAttribute("column");
String javaType = ruleNode.getAttribute("javaType");
KeyColumn keyColumn = new KeyColumn(table, column, javaType);
String comparator = ruleNode.getAttribute("class"); | // Path: plugin/src/main/java/org/eddy/xml/UrlDtdPathResolver.java
// public class UrlDtdPathResolver implements EntityResolver {
// @Override
// public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
// if (systemId != null) {
// return new InputSource(Thread.currentThread().getContextClassLoader().getResourceAsStream("config/config.dtd"));
// }
// return null;
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/DataNode.java
// @Getter
// @Setter
// @ToString
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class DataNode {
//
// public static final String DATA_NODE_NAME = "data";
//
// /**
// * 库名
// */
// @NonNull
// private String schema;
//
// /**
// * 表名
// */
// @NonNull
// private String table;
//
// /**
// * 对比脚本
// */
// @NonNull
// private String script;
//
// private RuleNode ruleNode;
//
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/KeyColumn.java
// @Getter
// @Setter
// @ToString
// @AllArgsConstructor
// @NoArgsConstructor
// public class KeyColumn {
//
// /**
// * 客户端查询sql分库分表传入的表名
// */
// @NonNull
// private String table;
//
// /**
// * 客户端查询sql分库分表传入的列名
// */
// @NonNull
// private String column;
//
// /**
// * 客户端查询sql分库分表传入的列取值类型
// */
// @NonNull
// private String javaType;
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/rule/Comparator.java
// public abstract class Comparator {
//
// public abstract DataNode check(RuleNode ruleNode);
//
// public boolean script(String mapper, Object[] param, String script) {
// Objects.requireNonNull(script);
//
// Binding binding = new Binding();
// GroovyShell shell = new GroovyShell(binding);
// shell.setVariable("mapper", mapper);
// shell.setVariable("params", param);
// Object returnValue = shell.evaluate(script);
//
// return (boolean) returnValue;
// }
// }
// Path: plugin/src/main/java/org/eddy/xml/context/XmlDataContext.java
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import org.eddy.xml.UrlDtdPathResolver;
import org.eddy.xml.data.DataNode;
import org.eddy.xml.data.KeyColumn;
import org.eddy.xml.data.RuleNode;
import org.eddy.xml.rule.Comparator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
builder.setEntityResolver(new UrlDtdPathResolver());
Document document = builder.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream(path));
List<RuleNode> results = new ArrayList<>();
NodeList rootChildren = document.getDocumentElement().getChildNodes();
for (int i = 0; i < rootChildren.getLength(); i++) {
Optional.ofNullable(parseNode(rootChildren.item(i))).ifPresent(node -> results.add(node));
}
return results.stream().filter(Objects::nonNull).collect(Collectors.toList());
}
private RuleNode parseNode(Node item) throws Exception{
// 节点非element节点 或 element节点name非rule, 则直接返回
if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), RuleNode.RULE_NODE_NAME)) {
return null;
}
Element ruleNode = (Element) item;
String table = ruleNode.getAttribute("table");
String column = ruleNode.getAttribute("column");
String javaType = ruleNode.getAttribute("javaType");
KeyColumn keyColumn = new KeyColumn(table, column, javaType);
String comparator = ruleNode.getAttribute("class"); | Comparator comparatorClass = (Comparator) Class.forName(comparator).newInstance(); |
justice-code/QiuQiu | plugin/src/main/java/org/eddy/xml/context/XmlDataContext.java | // Path: plugin/src/main/java/org/eddy/xml/UrlDtdPathResolver.java
// public class UrlDtdPathResolver implements EntityResolver {
// @Override
// public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
// if (systemId != null) {
// return new InputSource(Thread.currentThread().getContextClassLoader().getResourceAsStream("config/config.dtd"));
// }
// return null;
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/DataNode.java
// @Getter
// @Setter
// @ToString
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class DataNode {
//
// public static final String DATA_NODE_NAME = "data";
//
// /**
// * 库名
// */
// @NonNull
// private String schema;
//
// /**
// * 表名
// */
// @NonNull
// private String table;
//
// /**
// * 对比脚本
// */
// @NonNull
// private String script;
//
// private RuleNode ruleNode;
//
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/KeyColumn.java
// @Getter
// @Setter
// @ToString
// @AllArgsConstructor
// @NoArgsConstructor
// public class KeyColumn {
//
// /**
// * 客户端查询sql分库分表传入的表名
// */
// @NonNull
// private String table;
//
// /**
// * 客户端查询sql分库分表传入的列名
// */
// @NonNull
// private String column;
//
// /**
// * 客户端查询sql分库分表传入的列取值类型
// */
// @NonNull
// private String javaType;
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/rule/Comparator.java
// public abstract class Comparator {
//
// public abstract DataNode check(RuleNode ruleNode);
//
// public boolean script(String mapper, Object[] param, String script) {
// Objects.requireNonNull(script);
//
// Binding binding = new Binding();
// GroovyShell shell = new GroovyShell(binding);
// shell.setVariable("mapper", mapper);
// shell.setVariable("params", param);
// Object returnValue = shell.evaluate(script);
//
// return (boolean) returnValue;
// }
// }
| import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import org.eddy.xml.UrlDtdPathResolver;
import org.eddy.xml.data.DataNode;
import org.eddy.xml.data.KeyColumn;
import org.eddy.xml.data.RuleNode;
import org.eddy.xml.rule.Comparator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors; | // 节点非element节点 或 element节点name非rule, 则直接返回
if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), RuleNode.RULE_NODE_NAME)) {
return null;
}
Element ruleNode = (Element) item;
String table = ruleNode.getAttribute("table");
String column = ruleNode.getAttribute("column");
String javaType = ruleNode.getAttribute("javaType");
KeyColumn keyColumn = new KeyColumn(table, column, javaType);
String comparator = ruleNode.getAttribute("class");
Comparator comparatorClass = (Comparator) Class.forName(comparator).newInstance();
RuleNode node = new RuleNode(keyColumn, comparatorClass);
NodeList ruleChildren = item.getChildNodes();
for (int i = 0; i < ruleChildren.getLength(); i++) {
Optional.ofNullable(parseData(ruleChildren.item(i))).ifPresent(dataNode -> {
node.add(dataNode);
dataNode.setRuleNode(node);
});
}
return node;
}
| // Path: plugin/src/main/java/org/eddy/xml/UrlDtdPathResolver.java
// public class UrlDtdPathResolver implements EntityResolver {
// @Override
// public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
// if (systemId != null) {
// return new InputSource(Thread.currentThread().getContextClassLoader().getResourceAsStream("config/config.dtd"));
// }
// return null;
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/DataNode.java
// @Getter
// @Setter
// @ToString
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class DataNode {
//
// public static final String DATA_NODE_NAME = "data";
//
// /**
// * 库名
// */
// @NonNull
// private String schema;
//
// /**
// * 表名
// */
// @NonNull
// private String table;
//
// /**
// * 对比脚本
// */
// @NonNull
// private String script;
//
// private RuleNode ruleNode;
//
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/KeyColumn.java
// @Getter
// @Setter
// @ToString
// @AllArgsConstructor
// @NoArgsConstructor
// public class KeyColumn {
//
// /**
// * 客户端查询sql分库分表传入的表名
// */
// @NonNull
// private String table;
//
// /**
// * 客户端查询sql分库分表传入的列名
// */
// @NonNull
// private String column;
//
// /**
// * 客户端查询sql分库分表传入的列取值类型
// */
// @NonNull
// private String javaType;
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/rule/Comparator.java
// public abstract class Comparator {
//
// public abstract DataNode check(RuleNode ruleNode);
//
// public boolean script(String mapper, Object[] param, String script) {
// Objects.requireNonNull(script);
//
// Binding binding = new Binding();
// GroovyShell shell = new GroovyShell(binding);
// shell.setVariable("mapper", mapper);
// shell.setVariable("params", param);
// Object returnValue = shell.evaluate(script);
//
// return (boolean) returnValue;
// }
// }
// Path: plugin/src/main/java/org/eddy/xml/context/XmlDataContext.java
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import org.eddy.xml.UrlDtdPathResolver;
import org.eddy.xml.data.DataNode;
import org.eddy.xml.data.KeyColumn;
import org.eddy.xml.data.RuleNode;
import org.eddy.xml.rule.Comparator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
// 节点非element节点 或 element节点name非rule, 则直接返回
if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), RuleNode.RULE_NODE_NAME)) {
return null;
}
Element ruleNode = (Element) item;
String table = ruleNode.getAttribute("table");
String column = ruleNode.getAttribute("column");
String javaType = ruleNode.getAttribute("javaType");
KeyColumn keyColumn = new KeyColumn(table, column, javaType);
String comparator = ruleNode.getAttribute("class");
Comparator comparatorClass = (Comparator) Class.forName(comparator).newInstance();
RuleNode node = new RuleNode(keyColumn, comparatorClass);
NodeList ruleChildren = item.getChildNodes();
for (int i = 0; i < ruleChildren.getLength(); i++) {
Optional.ofNullable(parseData(ruleChildren.item(i))).ifPresent(dataNode -> {
node.add(dataNode);
dataNode.setRuleNode(node);
});
}
return node;
}
| private DataNode parseData(Node item) throws Exception { |
justice-code/QiuQiu | plugin/src/test/java/org/eddy/ognl/OgnlTest.java | // Path: plugin/src/main/java/org/eddy/xml/context/XmlDataContext.java
// @Getter
// public class XmlDataContext {
//
// private static final Logger logger = LoggerFactory.getLogger(XmlDataContext.class);
//
// private List<RuleNode> nodes;
//
// private static XmlDataContext context = new XmlDataContext("rule/rule.xml");
//
//
// public static XmlDataContext getContext() {
// return context;
// }
//
// //**********************私有构造函数*************************
//
// private XmlDataContext(String path) {
// try {
// this.nodes = loadXml(path);
// } catch (Exception e) {
// logger.error("parse xml error", e);
// throw new RuntimeException("parse xml error", e);
// }
// }
//
// //**********************解析xml*****************************
//
// private List<RuleNode> loadXml(String path) throws Exception{
// DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
// DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
// builder.setEntityResolver(new UrlDtdPathResolver());
// Document document = builder.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream(path));
//
// List<RuleNode> results = new ArrayList<>();
//
// NodeList rootChildren = document.getDocumentElement().getChildNodes();
// for (int i = 0; i < rootChildren.getLength(); i++) {
//
// Optional.ofNullable(parseNode(rootChildren.item(i))).ifPresent(node -> results.add(node));
//
// }
//
// return results.stream().filter(Objects::nonNull).collect(Collectors.toList());
// }
//
// private RuleNode parseNode(Node item) throws Exception{
//
// // 节点非element节点 或 element节点name非rule, 则直接返回
// if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), RuleNode.RULE_NODE_NAME)) {
// return null;
// }
//
// Element ruleNode = (Element) item;
//
// String table = ruleNode.getAttribute("table");
// String column = ruleNode.getAttribute("column");
// String javaType = ruleNode.getAttribute("javaType");
// KeyColumn keyColumn = new KeyColumn(table, column, javaType);
//
// String comparator = ruleNode.getAttribute("class");
// Comparator comparatorClass = (Comparator) Class.forName(comparator).newInstance();
//
// RuleNode node = new RuleNode(keyColumn, comparatorClass);
//
// NodeList ruleChildren = item.getChildNodes();
// for (int i = 0; i < ruleChildren.getLength(); i++) {
//
// Optional.ofNullable(parseData(ruleChildren.item(i))).ifPresent(dataNode -> {
// node.add(dataNode);
// dataNode.setRuleNode(node);
// });
//
// }
//
// return node;
// }
//
// private DataNode parseData(Node item) throws Exception {
// // 节点非element节点 或 element节点name非data, 则直接返回
// if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), DataNode.DATA_NODE_NAME)) {
// return null;
// }
//
// Element dataElement = (Element) item;
// String schema = dataElement.getAttribute("schema");
// String table = dataElement.getAttribute("table");
// String script = dataElement.getAttribute("script");
//
// return new DataNode(schema, table, script);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
| import org.apache.ibatis.ognl.Ognl;
import org.apache.ibatis.ognl.OgnlException;
import org.apache.ibatis.parsing.PropertyParser;
import org.eddy.xml.context.XmlDataContext;
import org.eddy.xml.data.RuleNode;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties; | package org.eddy.ognl;
/**
* Created by eddy on 2017/6/9.
*/
public class OgnlTest {
@Test
public void test() throws OgnlException { | // Path: plugin/src/main/java/org/eddy/xml/context/XmlDataContext.java
// @Getter
// public class XmlDataContext {
//
// private static final Logger logger = LoggerFactory.getLogger(XmlDataContext.class);
//
// private List<RuleNode> nodes;
//
// private static XmlDataContext context = new XmlDataContext("rule/rule.xml");
//
//
// public static XmlDataContext getContext() {
// return context;
// }
//
// //**********************私有构造函数*************************
//
// private XmlDataContext(String path) {
// try {
// this.nodes = loadXml(path);
// } catch (Exception e) {
// logger.error("parse xml error", e);
// throw new RuntimeException("parse xml error", e);
// }
// }
//
// //**********************解析xml*****************************
//
// private List<RuleNode> loadXml(String path) throws Exception{
// DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
// DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
// builder.setEntityResolver(new UrlDtdPathResolver());
// Document document = builder.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream(path));
//
// List<RuleNode> results = new ArrayList<>();
//
// NodeList rootChildren = document.getDocumentElement().getChildNodes();
// for (int i = 0; i < rootChildren.getLength(); i++) {
//
// Optional.ofNullable(parseNode(rootChildren.item(i))).ifPresent(node -> results.add(node));
//
// }
//
// return results.stream().filter(Objects::nonNull).collect(Collectors.toList());
// }
//
// private RuleNode parseNode(Node item) throws Exception{
//
// // 节点非element节点 或 element节点name非rule, 则直接返回
// if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), RuleNode.RULE_NODE_NAME)) {
// return null;
// }
//
// Element ruleNode = (Element) item;
//
// String table = ruleNode.getAttribute("table");
// String column = ruleNode.getAttribute("column");
// String javaType = ruleNode.getAttribute("javaType");
// KeyColumn keyColumn = new KeyColumn(table, column, javaType);
//
// String comparator = ruleNode.getAttribute("class");
// Comparator comparatorClass = (Comparator) Class.forName(comparator).newInstance();
//
// RuleNode node = new RuleNode(keyColumn, comparatorClass);
//
// NodeList ruleChildren = item.getChildNodes();
// for (int i = 0; i < ruleChildren.getLength(); i++) {
//
// Optional.ofNullable(parseData(ruleChildren.item(i))).ifPresent(dataNode -> {
// node.add(dataNode);
// dataNode.setRuleNode(node);
// });
//
// }
//
// return node;
// }
//
// private DataNode parseData(Node item) throws Exception {
// // 节点非element节点 或 element节点name非data, 则直接返回
// if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), DataNode.DATA_NODE_NAME)) {
// return null;
// }
//
// Element dataElement = (Element) item;
// String schema = dataElement.getAttribute("schema");
// String table = dataElement.getAttribute("table");
// String script = dataElement.getAttribute("script");
//
// return new DataNode(schema, table, script);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
// Path: plugin/src/test/java/org/eddy/ognl/OgnlTest.java
import org.apache.ibatis.ognl.Ognl;
import org.apache.ibatis.ognl.OgnlException;
import org.apache.ibatis.parsing.PropertyParser;
import org.eddy.xml.context.XmlDataContext;
import org.eddy.xml.data.RuleNode;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
package org.eddy.ognl;
/**
* Created by eddy on 2017/6/9.
*/
public class OgnlTest {
@Test
public void test() throws OgnlException { | List<RuleNode> dataNodes = XmlDataContext.getContext().getNodes(); |
justice-code/QiuQiu | plugin/src/test/java/org/eddy/ognl/OgnlTest.java | // Path: plugin/src/main/java/org/eddy/xml/context/XmlDataContext.java
// @Getter
// public class XmlDataContext {
//
// private static final Logger logger = LoggerFactory.getLogger(XmlDataContext.class);
//
// private List<RuleNode> nodes;
//
// private static XmlDataContext context = new XmlDataContext("rule/rule.xml");
//
//
// public static XmlDataContext getContext() {
// return context;
// }
//
// //**********************私有构造函数*************************
//
// private XmlDataContext(String path) {
// try {
// this.nodes = loadXml(path);
// } catch (Exception e) {
// logger.error("parse xml error", e);
// throw new RuntimeException("parse xml error", e);
// }
// }
//
// //**********************解析xml*****************************
//
// private List<RuleNode> loadXml(String path) throws Exception{
// DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
// DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
// builder.setEntityResolver(new UrlDtdPathResolver());
// Document document = builder.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream(path));
//
// List<RuleNode> results = new ArrayList<>();
//
// NodeList rootChildren = document.getDocumentElement().getChildNodes();
// for (int i = 0; i < rootChildren.getLength(); i++) {
//
// Optional.ofNullable(parseNode(rootChildren.item(i))).ifPresent(node -> results.add(node));
//
// }
//
// return results.stream().filter(Objects::nonNull).collect(Collectors.toList());
// }
//
// private RuleNode parseNode(Node item) throws Exception{
//
// // 节点非element节点 或 element节点name非rule, 则直接返回
// if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), RuleNode.RULE_NODE_NAME)) {
// return null;
// }
//
// Element ruleNode = (Element) item;
//
// String table = ruleNode.getAttribute("table");
// String column = ruleNode.getAttribute("column");
// String javaType = ruleNode.getAttribute("javaType");
// KeyColumn keyColumn = new KeyColumn(table, column, javaType);
//
// String comparator = ruleNode.getAttribute("class");
// Comparator comparatorClass = (Comparator) Class.forName(comparator).newInstance();
//
// RuleNode node = new RuleNode(keyColumn, comparatorClass);
//
// NodeList ruleChildren = item.getChildNodes();
// for (int i = 0; i < ruleChildren.getLength(); i++) {
//
// Optional.ofNullable(parseData(ruleChildren.item(i))).ifPresent(dataNode -> {
// node.add(dataNode);
// dataNode.setRuleNode(node);
// });
//
// }
//
// return node;
// }
//
// private DataNode parseData(Node item) throws Exception {
// // 节点非element节点 或 element节点name非data, 则直接返回
// if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), DataNode.DATA_NODE_NAME)) {
// return null;
// }
//
// Element dataElement = (Element) item;
// String schema = dataElement.getAttribute("schema");
// String table = dataElement.getAttribute("table");
// String script = dataElement.getAttribute("script");
//
// return new DataNode(schema, table, script);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
| import org.apache.ibatis.ognl.Ognl;
import org.apache.ibatis.ognl.OgnlException;
import org.apache.ibatis.parsing.PropertyParser;
import org.eddy.xml.context.XmlDataContext;
import org.eddy.xml.data.RuleNode;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties; | package org.eddy.ognl;
/**
* Created by eddy on 2017/6/9.
*/
public class OgnlTest {
@Test
public void test() throws OgnlException { | // Path: plugin/src/main/java/org/eddy/xml/context/XmlDataContext.java
// @Getter
// public class XmlDataContext {
//
// private static final Logger logger = LoggerFactory.getLogger(XmlDataContext.class);
//
// private List<RuleNode> nodes;
//
// private static XmlDataContext context = new XmlDataContext("rule/rule.xml");
//
//
// public static XmlDataContext getContext() {
// return context;
// }
//
// //**********************私有构造函数*************************
//
// private XmlDataContext(String path) {
// try {
// this.nodes = loadXml(path);
// } catch (Exception e) {
// logger.error("parse xml error", e);
// throw new RuntimeException("parse xml error", e);
// }
// }
//
// //**********************解析xml*****************************
//
// private List<RuleNode> loadXml(String path) throws Exception{
// DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
// DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
// builder.setEntityResolver(new UrlDtdPathResolver());
// Document document = builder.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream(path));
//
// List<RuleNode> results = new ArrayList<>();
//
// NodeList rootChildren = document.getDocumentElement().getChildNodes();
// for (int i = 0; i < rootChildren.getLength(); i++) {
//
// Optional.ofNullable(parseNode(rootChildren.item(i))).ifPresent(node -> results.add(node));
//
// }
//
// return results.stream().filter(Objects::nonNull).collect(Collectors.toList());
// }
//
// private RuleNode parseNode(Node item) throws Exception{
//
// // 节点非element节点 或 element节点name非rule, 则直接返回
// if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), RuleNode.RULE_NODE_NAME)) {
// return null;
// }
//
// Element ruleNode = (Element) item;
//
// String table = ruleNode.getAttribute("table");
// String column = ruleNode.getAttribute("column");
// String javaType = ruleNode.getAttribute("javaType");
// KeyColumn keyColumn = new KeyColumn(table, column, javaType);
//
// String comparator = ruleNode.getAttribute("class");
// Comparator comparatorClass = (Comparator) Class.forName(comparator).newInstance();
//
// RuleNode node = new RuleNode(keyColumn, comparatorClass);
//
// NodeList ruleChildren = item.getChildNodes();
// for (int i = 0; i < ruleChildren.getLength(); i++) {
//
// Optional.ofNullable(parseData(ruleChildren.item(i))).ifPresent(dataNode -> {
// node.add(dataNode);
// dataNode.setRuleNode(node);
// });
//
// }
//
// return node;
// }
//
// private DataNode parseData(Node item) throws Exception {
// // 节点非element节点 或 element节点name非data, 则直接返回
// if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), DataNode.DATA_NODE_NAME)) {
// return null;
// }
//
// Element dataElement = (Element) item;
// String schema = dataElement.getAttribute("schema");
// String table = dataElement.getAttribute("table");
// String script = dataElement.getAttribute("script");
//
// return new DataNode(schema, table, script);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
// Path: plugin/src/test/java/org/eddy/ognl/OgnlTest.java
import org.apache.ibatis.ognl.Ognl;
import org.apache.ibatis.ognl.OgnlException;
import org.apache.ibatis.parsing.PropertyParser;
import org.eddy.xml.context.XmlDataContext;
import org.eddy.xml.data.RuleNode;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
package org.eddy.ognl;
/**
* Created by eddy on 2017/6/9.
*/
public class OgnlTest {
@Test
public void test() throws OgnlException { | List<RuleNode> dataNodes = XmlDataContext.getContext().getNodes(); |
justice-code/QiuQiu | plugin/src/main/java/org/eddy/xml/data/RuleNode.java | // Path: plugin/src/main/java/org/eddy/xml/rule/Comparator.java
// public abstract class Comparator {
//
// public abstract DataNode check(RuleNode ruleNode);
//
// public boolean script(String mapper, Object[] param, String script) {
// Objects.requireNonNull(script);
//
// Binding binding = new Binding();
// GroovyShell shell = new GroovyShell(binding);
// shell.setVariable("mapper", mapper);
// shell.setVariable("params", param);
// Object returnValue = shell.evaluate(script);
//
// return (boolean) returnValue;
// }
// }
| import lombok.*;
import org.eddy.xml.rule.Comparator;
import java.util.ArrayList;
import java.util.List; | package org.eddy.xml.data;
/**
* Created by eddy on 2017/6/8.
*/
@Getter
@Setter
@ToString(exclude = "dataNodes")
@NoArgsConstructor
@RequiredArgsConstructor
public class RuleNode {
public static final String RULE_NODE_NAME = "rule";
@NonNull
private KeyColumn keyColumn;
private List<DataNode> dataNodes = new ArrayList<>();
/**
* 比较器
*/
@NonNull | // Path: plugin/src/main/java/org/eddy/xml/rule/Comparator.java
// public abstract class Comparator {
//
// public abstract DataNode check(RuleNode ruleNode);
//
// public boolean script(String mapper, Object[] param, String script) {
// Objects.requireNonNull(script);
//
// Binding binding = new Binding();
// GroovyShell shell = new GroovyShell(binding);
// shell.setVariable("mapper", mapper);
// shell.setVariable("params", param);
// Object returnValue = shell.evaluate(script);
//
// return (boolean) returnValue;
// }
// }
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
import lombok.*;
import org.eddy.xml.rule.Comparator;
import java.util.ArrayList;
import java.util.List;
package org.eddy.xml.data;
/**
* Created by eddy on 2017/6/8.
*/
@Getter
@Setter
@ToString(exclude = "dataNodes")
@NoArgsConstructor
@RequiredArgsConstructor
public class RuleNode {
public static final String RULE_NODE_NAME = "rule";
@NonNull
private KeyColumn keyColumn;
private List<DataNode> dataNodes = new ArrayList<>();
/**
* 比较器
*/
@NonNull | private Comparator comparator; |
justice-code/QiuQiu | plugin/src/main/java/org/eddy/xml/rule/impl/UserComparator.java | // Path: plugin/src/main/java/org/eddy/sql/config/RequestHolder.java
// public class RequestHolder {
//
// private static ThreadLocal<SplitRequest> requestHolder = new NamedThreadLocal<>("sqlSplitRequest");
//
// public static void resetRequest() {
// requestHolder.remove();
// }
//
// public static void initRequestHolder(String mapper, String[] ognl) {
// requestHolder.set(new SplitRequest(mapper, ognl));
// }
//
// public static SplitRequest getRequest() {
// return requestHolder.get();
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/DataNode.java
// @Getter
// @Setter
// @ToString
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class DataNode {
//
// public static final String DATA_NODE_NAME = "data";
//
// /**
// * 库名
// */
// @NonNull
// private String schema;
//
// /**
// * 表名
// */
// @NonNull
// private String table;
//
// /**
// * 对比脚本
// */
// @NonNull
// private String script;
//
// private RuleNode ruleNode;
//
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/rule/Comparator.java
// public abstract class Comparator {
//
// public abstract DataNode check(RuleNode ruleNode);
//
// public boolean script(String mapper, Object[] param, String script) {
// Objects.requireNonNull(script);
//
// Binding binding = new Binding();
// GroovyShell shell = new GroovyShell(binding);
// shell.setVariable("mapper", mapper);
// shell.setVariable("params", param);
// Object returnValue = shell.evaluate(script);
//
// return (boolean) returnValue;
// }
// }
| import org.eddy.sql.config.RequestHolder;
import org.eddy.xml.data.DataNode;
import org.eddy.xml.data.RuleNode;
import org.eddy.xml.rule.Comparator;
import java.util.Optional; | package org.eddy.xml.rule.impl;
/**
* Created by eddy on 2017/6/16.
*/
public class UserComparator extends Comparator{
@Override | // Path: plugin/src/main/java/org/eddy/sql/config/RequestHolder.java
// public class RequestHolder {
//
// private static ThreadLocal<SplitRequest> requestHolder = new NamedThreadLocal<>("sqlSplitRequest");
//
// public static void resetRequest() {
// requestHolder.remove();
// }
//
// public static void initRequestHolder(String mapper, String[] ognl) {
// requestHolder.set(new SplitRequest(mapper, ognl));
// }
//
// public static SplitRequest getRequest() {
// return requestHolder.get();
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/DataNode.java
// @Getter
// @Setter
// @ToString
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class DataNode {
//
// public static final String DATA_NODE_NAME = "data";
//
// /**
// * 库名
// */
// @NonNull
// private String schema;
//
// /**
// * 表名
// */
// @NonNull
// private String table;
//
// /**
// * 对比脚本
// */
// @NonNull
// private String script;
//
// private RuleNode ruleNode;
//
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/rule/Comparator.java
// public abstract class Comparator {
//
// public abstract DataNode check(RuleNode ruleNode);
//
// public boolean script(String mapper, Object[] param, String script) {
// Objects.requireNonNull(script);
//
// Binding binding = new Binding();
// GroovyShell shell = new GroovyShell(binding);
// shell.setVariable("mapper", mapper);
// shell.setVariable("params", param);
// Object returnValue = shell.evaluate(script);
//
// return (boolean) returnValue;
// }
// }
// Path: plugin/src/main/java/org/eddy/xml/rule/impl/UserComparator.java
import org.eddy.sql.config.RequestHolder;
import org.eddy.xml.data.DataNode;
import org.eddy.xml.data.RuleNode;
import org.eddy.xml.rule.Comparator;
import java.util.Optional;
package org.eddy.xml.rule.impl;
/**
* Created by eddy on 2017/6/16.
*/
public class UserComparator extends Comparator{
@Override | public DataNode check(RuleNode ruleNode) { |
justice-code/QiuQiu | plugin/src/main/java/org/eddy/xml/rule/impl/UserComparator.java | // Path: plugin/src/main/java/org/eddy/sql/config/RequestHolder.java
// public class RequestHolder {
//
// private static ThreadLocal<SplitRequest> requestHolder = new NamedThreadLocal<>("sqlSplitRequest");
//
// public static void resetRequest() {
// requestHolder.remove();
// }
//
// public static void initRequestHolder(String mapper, String[] ognl) {
// requestHolder.set(new SplitRequest(mapper, ognl));
// }
//
// public static SplitRequest getRequest() {
// return requestHolder.get();
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/DataNode.java
// @Getter
// @Setter
// @ToString
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class DataNode {
//
// public static final String DATA_NODE_NAME = "data";
//
// /**
// * 库名
// */
// @NonNull
// private String schema;
//
// /**
// * 表名
// */
// @NonNull
// private String table;
//
// /**
// * 对比脚本
// */
// @NonNull
// private String script;
//
// private RuleNode ruleNode;
//
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/rule/Comparator.java
// public abstract class Comparator {
//
// public abstract DataNode check(RuleNode ruleNode);
//
// public boolean script(String mapper, Object[] param, String script) {
// Objects.requireNonNull(script);
//
// Binding binding = new Binding();
// GroovyShell shell = new GroovyShell(binding);
// shell.setVariable("mapper", mapper);
// shell.setVariable("params", param);
// Object returnValue = shell.evaluate(script);
//
// return (boolean) returnValue;
// }
// }
| import org.eddy.sql.config.RequestHolder;
import org.eddy.xml.data.DataNode;
import org.eddy.xml.data.RuleNode;
import org.eddy.xml.rule.Comparator;
import java.util.Optional; | package org.eddy.xml.rule.impl;
/**
* Created by eddy on 2017/6/16.
*/
public class UserComparator extends Comparator{
@Override | // Path: plugin/src/main/java/org/eddy/sql/config/RequestHolder.java
// public class RequestHolder {
//
// private static ThreadLocal<SplitRequest> requestHolder = new NamedThreadLocal<>("sqlSplitRequest");
//
// public static void resetRequest() {
// requestHolder.remove();
// }
//
// public static void initRequestHolder(String mapper, String[] ognl) {
// requestHolder.set(new SplitRequest(mapper, ognl));
// }
//
// public static SplitRequest getRequest() {
// return requestHolder.get();
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/DataNode.java
// @Getter
// @Setter
// @ToString
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class DataNode {
//
// public static final String DATA_NODE_NAME = "data";
//
// /**
// * 库名
// */
// @NonNull
// private String schema;
//
// /**
// * 表名
// */
// @NonNull
// private String table;
//
// /**
// * 对比脚本
// */
// @NonNull
// private String script;
//
// private RuleNode ruleNode;
//
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/rule/Comparator.java
// public abstract class Comparator {
//
// public abstract DataNode check(RuleNode ruleNode);
//
// public boolean script(String mapper, Object[] param, String script) {
// Objects.requireNonNull(script);
//
// Binding binding = new Binding();
// GroovyShell shell = new GroovyShell(binding);
// shell.setVariable("mapper", mapper);
// shell.setVariable("params", param);
// Object returnValue = shell.evaluate(script);
//
// return (boolean) returnValue;
// }
// }
// Path: plugin/src/main/java/org/eddy/xml/rule/impl/UserComparator.java
import org.eddy.sql.config.RequestHolder;
import org.eddy.xml.data.DataNode;
import org.eddy.xml.data.RuleNode;
import org.eddy.xml.rule.Comparator;
import java.util.Optional;
package org.eddy.xml.rule.impl;
/**
* Created by eddy on 2017/6/16.
*/
public class UserComparator extends Comparator{
@Override | public DataNode check(RuleNode ruleNode) { |
justice-code/QiuQiu | plugin/src/main/java/org/eddy/xml/rule/impl/UserComparator.java | // Path: plugin/src/main/java/org/eddy/sql/config/RequestHolder.java
// public class RequestHolder {
//
// private static ThreadLocal<SplitRequest> requestHolder = new NamedThreadLocal<>("sqlSplitRequest");
//
// public static void resetRequest() {
// requestHolder.remove();
// }
//
// public static void initRequestHolder(String mapper, String[] ognl) {
// requestHolder.set(new SplitRequest(mapper, ognl));
// }
//
// public static SplitRequest getRequest() {
// return requestHolder.get();
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/DataNode.java
// @Getter
// @Setter
// @ToString
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class DataNode {
//
// public static final String DATA_NODE_NAME = "data";
//
// /**
// * 库名
// */
// @NonNull
// private String schema;
//
// /**
// * 表名
// */
// @NonNull
// private String table;
//
// /**
// * 对比脚本
// */
// @NonNull
// private String script;
//
// private RuleNode ruleNode;
//
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/rule/Comparator.java
// public abstract class Comparator {
//
// public abstract DataNode check(RuleNode ruleNode);
//
// public boolean script(String mapper, Object[] param, String script) {
// Objects.requireNonNull(script);
//
// Binding binding = new Binding();
// GroovyShell shell = new GroovyShell(binding);
// shell.setVariable("mapper", mapper);
// shell.setVariable("params", param);
// Object returnValue = shell.evaluate(script);
//
// return (boolean) returnValue;
// }
// }
| import org.eddy.sql.config.RequestHolder;
import org.eddy.xml.data.DataNode;
import org.eddy.xml.data.RuleNode;
import org.eddy.xml.rule.Comparator;
import java.util.Optional; | package org.eddy.xml.rule.impl;
/**
* Created by eddy on 2017/6/16.
*/
public class UserComparator extends Comparator{
@Override
public DataNode check(RuleNode ruleNode) { | // Path: plugin/src/main/java/org/eddy/sql/config/RequestHolder.java
// public class RequestHolder {
//
// private static ThreadLocal<SplitRequest> requestHolder = new NamedThreadLocal<>("sqlSplitRequest");
//
// public static void resetRequest() {
// requestHolder.remove();
// }
//
// public static void initRequestHolder(String mapper, String[] ognl) {
// requestHolder.set(new SplitRequest(mapper, ognl));
// }
//
// public static SplitRequest getRequest() {
// return requestHolder.get();
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/DataNode.java
// @Getter
// @Setter
// @ToString
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class DataNode {
//
// public static final String DATA_NODE_NAME = "data";
//
// /**
// * 库名
// */
// @NonNull
// private String schema;
//
// /**
// * 表名
// */
// @NonNull
// private String table;
//
// /**
// * 对比脚本
// */
// @NonNull
// private String script;
//
// private RuleNode ruleNode;
//
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/rule/Comparator.java
// public abstract class Comparator {
//
// public abstract DataNode check(RuleNode ruleNode);
//
// public boolean script(String mapper, Object[] param, String script) {
// Objects.requireNonNull(script);
//
// Binding binding = new Binding();
// GroovyShell shell = new GroovyShell(binding);
// shell.setVariable("mapper", mapper);
// shell.setVariable("params", param);
// Object returnValue = shell.evaluate(script);
//
// return (boolean) returnValue;
// }
// }
// Path: plugin/src/main/java/org/eddy/xml/rule/impl/UserComparator.java
import org.eddy.sql.config.RequestHolder;
import org.eddy.xml.data.DataNode;
import org.eddy.xml.data.RuleNode;
import org.eddy.xml.rule.Comparator;
import java.util.Optional;
package org.eddy.xml.rule.impl;
/**
* Created by eddy on 2017/6/16.
*/
public class UserComparator extends Comparator{
@Override
public DataNode check(RuleNode ruleNode) { | Object[] param = RequestHolder.getRequest().getParam(); |
justice-code/QiuQiu | plugin/src/main/java/org/eddy/util/TableList.java | // Path: plugin/src/main/java/org/eddy/xml/context/XmlDataContext.java
// @Getter
// public class XmlDataContext {
//
// private static final Logger logger = LoggerFactory.getLogger(XmlDataContext.class);
//
// private List<RuleNode> nodes;
//
// private static XmlDataContext context = new XmlDataContext("rule/rule.xml");
//
//
// public static XmlDataContext getContext() {
// return context;
// }
//
// //**********************私有构造函数*************************
//
// private XmlDataContext(String path) {
// try {
// this.nodes = loadXml(path);
// } catch (Exception e) {
// logger.error("parse xml error", e);
// throw new RuntimeException("parse xml error", e);
// }
// }
//
// //**********************解析xml*****************************
//
// private List<RuleNode> loadXml(String path) throws Exception{
// DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
// DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
// builder.setEntityResolver(new UrlDtdPathResolver());
// Document document = builder.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream(path));
//
// List<RuleNode> results = new ArrayList<>();
//
// NodeList rootChildren = document.getDocumentElement().getChildNodes();
// for (int i = 0; i < rootChildren.getLength(); i++) {
//
// Optional.ofNullable(parseNode(rootChildren.item(i))).ifPresent(node -> results.add(node));
//
// }
//
// return results.stream().filter(Objects::nonNull).collect(Collectors.toList());
// }
//
// private RuleNode parseNode(Node item) throws Exception{
//
// // 节点非element节点 或 element节点name非rule, 则直接返回
// if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), RuleNode.RULE_NODE_NAME)) {
// return null;
// }
//
// Element ruleNode = (Element) item;
//
// String table = ruleNode.getAttribute("table");
// String column = ruleNode.getAttribute("column");
// String javaType = ruleNode.getAttribute("javaType");
// KeyColumn keyColumn = new KeyColumn(table, column, javaType);
//
// String comparator = ruleNode.getAttribute("class");
// Comparator comparatorClass = (Comparator) Class.forName(comparator).newInstance();
//
// RuleNode node = new RuleNode(keyColumn, comparatorClass);
//
// NodeList ruleChildren = item.getChildNodes();
// for (int i = 0; i < ruleChildren.getLength(); i++) {
//
// Optional.ofNullable(parseData(ruleChildren.item(i))).ifPresent(dataNode -> {
// node.add(dataNode);
// dataNode.setRuleNode(node);
// });
//
// }
//
// return node;
// }
//
// private DataNode parseData(Node item) throws Exception {
// // 节点非element节点 或 element节点name非data, 则直接返回
// if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), DataNode.DATA_NODE_NAME)) {
// return null;
// }
//
// Element dataElement = (Element) item;
// String schema = dataElement.getAttribute("schema");
// String table = dataElement.getAttribute("table");
// String script = dataElement.getAttribute("script");
//
// return new DataNode(schema, table, script);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
| import net.sf.jsqlparser.schema.Table;
import org.apache.commons.lang3.StringUtils;
import org.eddy.xml.context.XmlDataContext;
import org.eddy.xml.data.RuleNode;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Pattern; | package org.eddy.util;
/**
* Created by eddy on 2017/6/8.
*/
public class TableList {
private static Pattern pattern = Pattern.compile("'|\"|`");
private List<String> tables = new ArrayList<>();
public void add(Table table, Supplier holder) {
Objects.requireNonNull(holder);
tables.add(holder.getName(table));
replace(table);
}
private void replace(Table table) { | // Path: plugin/src/main/java/org/eddy/xml/context/XmlDataContext.java
// @Getter
// public class XmlDataContext {
//
// private static final Logger logger = LoggerFactory.getLogger(XmlDataContext.class);
//
// private List<RuleNode> nodes;
//
// private static XmlDataContext context = new XmlDataContext("rule/rule.xml");
//
//
// public static XmlDataContext getContext() {
// return context;
// }
//
// //**********************私有构造函数*************************
//
// private XmlDataContext(String path) {
// try {
// this.nodes = loadXml(path);
// } catch (Exception e) {
// logger.error("parse xml error", e);
// throw new RuntimeException("parse xml error", e);
// }
// }
//
// //**********************解析xml*****************************
//
// private List<RuleNode> loadXml(String path) throws Exception{
// DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
// DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
// builder.setEntityResolver(new UrlDtdPathResolver());
// Document document = builder.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream(path));
//
// List<RuleNode> results = new ArrayList<>();
//
// NodeList rootChildren = document.getDocumentElement().getChildNodes();
// for (int i = 0; i < rootChildren.getLength(); i++) {
//
// Optional.ofNullable(parseNode(rootChildren.item(i))).ifPresent(node -> results.add(node));
//
// }
//
// return results.stream().filter(Objects::nonNull).collect(Collectors.toList());
// }
//
// private RuleNode parseNode(Node item) throws Exception{
//
// // 节点非element节点 或 element节点name非rule, 则直接返回
// if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), RuleNode.RULE_NODE_NAME)) {
// return null;
// }
//
// Element ruleNode = (Element) item;
//
// String table = ruleNode.getAttribute("table");
// String column = ruleNode.getAttribute("column");
// String javaType = ruleNode.getAttribute("javaType");
// KeyColumn keyColumn = new KeyColumn(table, column, javaType);
//
// String comparator = ruleNode.getAttribute("class");
// Comparator comparatorClass = (Comparator) Class.forName(comparator).newInstance();
//
// RuleNode node = new RuleNode(keyColumn, comparatorClass);
//
// NodeList ruleChildren = item.getChildNodes();
// for (int i = 0; i < ruleChildren.getLength(); i++) {
//
// Optional.ofNullable(parseData(ruleChildren.item(i))).ifPresent(dataNode -> {
// node.add(dataNode);
// dataNode.setRuleNode(node);
// });
//
// }
//
// return node;
// }
//
// private DataNode parseData(Node item) throws Exception {
// // 节点非element节点 或 element节点name非data, 则直接返回
// if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), DataNode.DATA_NODE_NAME)) {
// return null;
// }
//
// Element dataElement = (Element) item;
// String schema = dataElement.getAttribute("schema");
// String table = dataElement.getAttribute("table");
// String script = dataElement.getAttribute("script");
//
// return new DataNode(schema, table, script);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
// Path: plugin/src/main/java/org/eddy/util/TableList.java
import net.sf.jsqlparser.schema.Table;
import org.apache.commons.lang3.StringUtils;
import org.eddy.xml.context.XmlDataContext;
import org.eddy.xml.data.RuleNode;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Pattern;
package org.eddy.util;
/**
* Created by eddy on 2017/6/8.
*/
public class TableList {
private static Pattern pattern = Pattern.compile("'|\"|`");
private List<String> tables = new ArrayList<>();
public void add(Table table, Supplier holder) {
Objects.requireNonNull(holder);
tables.add(holder.getName(table));
replace(table);
}
private void replace(Table table) { | XmlDataContext.getContext().getNodes().forEach(ruleNode -> { |
justice-code/QiuQiu | plugin/src/main/java/org/eddy/util/TableList.java | // Path: plugin/src/main/java/org/eddy/xml/context/XmlDataContext.java
// @Getter
// public class XmlDataContext {
//
// private static final Logger logger = LoggerFactory.getLogger(XmlDataContext.class);
//
// private List<RuleNode> nodes;
//
// private static XmlDataContext context = new XmlDataContext("rule/rule.xml");
//
//
// public static XmlDataContext getContext() {
// return context;
// }
//
// //**********************私有构造函数*************************
//
// private XmlDataContext(String path) {
// try {
// this.nodes = loadXml(path);
// } catch (Exception e) {
// logger.error("parse xml error", e);
// throw new RuntimeException("parse xml error", e);
// }
// }
//
// //**********************解析xml*****************************
//
// private List<RuleNode> loadXml(String path) throws Exception{
// DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
// DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
// builder.setEntityResolver(new UrlDtdPathResolver());
// Document document = builder.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream(path));
//
// List<RuleNode> results = new ArrayList<>();
//
// NodeList rootChildren = document.getDocumentElement().getChildNodes();
// for (int i = 0; i < rootChildren.getLength(); i++) {
//
// Optional.ofNullable(parseNode(rootChildren.item(i))).ifPresent(node -> results.add(node));
//
// }
//
// return results.stream().filter(Objects::nonNull).collect(Collectors.toList());
// }
//
// private RuleNode parseNode(Node item) throws Exception{
//
// // 节点非element节点 或 element节点name非rule, 则直接返回
// if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), RuleNode.RULE_NODE_NAME)) {
// return null;
// }
//
// Element ruleNode = (Element) item;
//
// String table = ruleNode.getAttribute("table");
// String column = ruleNode.getAttribute("column");
// String javaType = ruleNode.getAttribute("javaType");
// KeyColumn keyColumn = new KeyColumn(table, column, javaType);
//
// String comparator = ruleNode.getAttribute("class");
// Comparator comparatorClass = (Comparator) Class.forName(comparator).newInstance();
//
// RuleNode node = new RuleNode(keyColumn, comparatorClass);
//
// NodeList ruleChildren = item.getChildNodes();
// for (int i = 0; i < ruleChildren.getLength(); i++) {
//
// Optional.ofNullable(parseData(ruleChildren.item(i))).ifPresent(dataNode -> {
// node.add(dataNode);
// dataNode.setRuleNode(node);
// });
//
// }
//
// return node;
// }
//
// private DataNode parseData(Node item) throws Exception {
// // 节点非element节点 或 element节点name非data, 则直接返回
// if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), DataNode.DATA_NODE_NAME)) {
// return null;
// }
//
// Element dataElement = (Element) item;
// String schema = dataElement.getAttribute("schema");
// String table = dataElement.getAttribute("table");
// String script = dataElement.getAttribute("script");
//
// return new DataNode(schema, table, script);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
| import net.sf.jsqlparser.schema.Table;
import org.apache.commons.lang3.StringUtils;
import org.eddy.xml.context.XmlDataContext;
import org.eddy.xml.data.RuleNode;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Pattern; | package org.eddy.util;
/**
* Created by eddy on 2017/6/8.
*/
public class TableList {
private static Pattern pattern = Pattern.compile("'|\"|`");
private List<String> tables = new ArrayList<>();
public void add(Table table, Supplier holder) {
Objects.requireNonNull(holder);
tables.add(holder.getName(table));
replace(table);
}
private void replace(Table table) {
XmlDataContext.getContext().getNodes().forEach(ruleNode -> {
if (! checkTableName(table, ruleNode)) {
return;
}
Optional.ofNullable(ruleNode.getComparator().check(ruleNode)).ifPresent(node -> {
table.setName(node.getTable());
table.setSchemaName(node.getSchema());
});
});
}
/**
* 表名对比方法
* @param table
* @param ruleNode
* @return true:对比通过,需要替换表名
*/ | // Path: plugin/src/main/java/org/eddy/xml/context/XmlDataContext.java
// @Getter
// public class XmlDataContext {
//
// private static final Logger logger = LoggerFactory.getLogger(XmlDataContext.class);
//
// private List<RuleNode> nodes;
//
// private static XmlDataContext context = new XmlDataContext("rule/rule.xml");
//
//
// public static XmlDataContext getContext() {
// return context;
// }
//
// //**********************私有构造函数*************************
//
// private XmlDataContext(String path) {
// try {
// this.nodes = loadXml(path);
// } catch (Exception e) {
// logger.error("parse xml error", e);
// throw new RuntimeException("parse xml error", e);
// }
// }
//
// //**********************解析xml*****************************
//
// private List<RuleNode> loadXml(String path) throws Exception{
// DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
// DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
// builder.setEntityResolver(new UrlDtdPathResolver());
// Document document = builder.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream(path));
//
// List<RuleNode> results = new ArrayList<>();
//
// NodeList rootChildren = document.getDocumentElement().getChildNodes();
// for (int i = 0; i < rootChildren.getLength(); i++) {
//
// Optional.ofNullable(parseNode(rootChildren.item(i))).ifPresent(node -> results.add(node));
//
// }
//
// return results.stream().filter(Objects::nonNull).collect(Collectors.toList());
// }
//
// private RuleNode parseNode(Node item) throws Exception{
//
// // 节点非element节点 或 element节点name非rule, 则直接返回
// if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), RuleNode.RULE_NODE_NAME)) {
// return null;
// }
//
// Element ruleNode = (Element) item;
//
// String table = ruleNode.getAttribute("table");
// String column = ruleNode.getAttribute("column");
// String javaType = ruleNode.getAttribute("javaType");
// KeyColumn keyColumn = new KeyColumn(table, column, javaType);
//
// String comparator = ruleNode.getAttribute("class");
// Comparator comparatorClass = (Comparator) Class.forName(comparator).newInstance();
//
// RuleNode node = new RuleNode(keyColumn, comparatorClass);
//
// NodeList ruleChildren = item.getChildNodes();
// for (int i = 0; i < ruleChildren.getLength(); i++) {
//
// Optional.ofNullable(parseData(ruleChildren.item(i))).ifPresent(dataNode -> {
// node.add(dataNode);
// dataNode.setRuleNode(node);
// });
//
// }
//
// return node;
// }
//
// private DataNode parseData(Node item) throws Exception {
// // 节点非element节点 或 element节点name非data, 则直接返回
// if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), DataNode.DATA_NODE_NAME)) {
// return null;
// }
//
// Element dataElement = (Element) item;
// String schema = dataElement.getAttribute("schema");
// String table = dataElement.getAttribute("table");
// String script = dataElement.getAttribute("script");
//
// return new DataNode(schema, table, script);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
// Path: plugin/src/main/java/org/eddy/util/TableList.java
import net.sf.jsqlparser.schema.Table;
import org.apache.commons.lang3.StringUtils;
import org.eddy.xml.context.XmlDataContext;
import org.eddy.xml.data.RuleNode;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Pattern;
package org.eddy.util;
/**
* Created by eddy on 2017/6/8.
*/
public class TableList {
private static Pattern pattern = Pattern.compile("'|\"|`");
private List<String> tables = new ArrayList<>();
public void add(Table table, Supplier holder) {
Objects.requireNonNull(holder);
tables.add(holder.getName(table));
replace(table);
}
private void replace(Table table) {
XmlDataContext.getContext().getNodes().forEach(ruleNode -> {
if (! checkTableName(table, ruleNode)) {
return;
}
Optional.ofNullable(ruleNode.getComparator().check(ruleNode)).ifPresent(node -> {
table.setName(node.getTable());
table.setSchemaName(node.getSchema());
});
});
}
/**
* 表名对比方法
* @param table
* @param ruleNode
* @return true:对比通过,需要替换表名
*/ | private boolean checkTableName(Table table, RuleNode ruleNode) { |
justice-code/QiuQiu | plugin/src/test/java/org/eddy/xml/XmlTest.java | // Path: plugin/src/main/java/org/eddy/xml/context/XmlDataContext.java
// @Getter
// public class XmlDataContext {
//
// private static final Logger logger = LoggerFactory.getLogger(XmlDataContext.class);
//
// private List<RuleNode> nodes;
//
// private static XmlDataContext context = new XmlDataContext("rule/rule.xml");
//
//
// public static XmlDataContext getContext() {
// return context;
// }
//
// //**********************私有构造函数*************************
//
// private XmlDataContext(String path) {
// try {
// this.nodes = loadXml(path);
// } catch (Exception e) {
// logger.error("parse xml error", e);
// throw new RuntimeException("parse xml error", e);
// }
// }
//
// //**********************解析xml*****************************
//
// private List<RuleNode> loadXml(String path) throws Exception{
// DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
// DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
// builder.setEntityResolver(new UrlDtdPathResolver());
// Document document = builder.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream(path));
//
// List<RuleNode> results = new ArrayList<>();
//
// NodeList rootChildren = document.getDocumentElement().getChildNodes();
// for (int i = 0; i < rootChildren.getLength(); i++) {
//
// Optional.ofNullable(parseNode(rootChildren.item(i))).ifPresent(node -> results.add(node));
//
// }
//
// return results.stream().filter(Objects::nonNull).collect(Collectors.toList());
// }
//
// private RuleNode parseNode(Node item) throws Exception{
//
// // 节点非element节点 或 element节点name非rule, 则直接返回
// if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), RuleNode.RULE_NODE_NAME)) {
// return null;
// }
//
// Element ruleNode = (Element) item;
//
// String table = ruleNode.getAttribute("table");
// String column = ruleNode.getAttribute("column");
// String javaType = ruleNode.getAttribute("javaType");
// KeyColumn keyColumn = new KeyColumn(table, column, javaType);
//
// String comparator = ruleNode.getAttribute("class");
// Comparator comparatorClass = (Comparator) Class.forName(comparator).newInstance();
//
// RuleNode node = new RuleNode(keyColumn, comparatorClass);
//
// NodeList ruleChildren = item.getChildNodes();
// for (int i = 0; i < ruleChildren.getLength(); i++) {
//
// Optional.ofNullable(parseData(ruleChildren.item(i))).ifPresent(dataNode -> {
// node.add(dataNode);
// dataNode.setRuleNode(node);
// });
//
// }
//
// return node;
// }
//
// private DataNode parseData(Node item) throws Exception {
// // 节点非element节点 或 element节点name非data, 则直接返回
// if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), DataNode.DATA_NODE_NAME)) {
// return null;
// }
//
// Element dataElement = (Element) item;
// String schema = dataElement.getAttribute("schema");
// String table = dataElement.getAttribute("table");
// String script = dataElement.getAttribute("script");
//
// return new DataNode(schema, table, script);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/DataNode.java
// @Getter
// @Setter
// @ToString
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class DataNode {
//
// public static final String DATA_NODE_NAME = "data";
//
// /**
// * 库名
// */
// @NonNull
// private String schema;
//
// /**
// * 表名
// */
// @NonNull
// private String table;
//
// /**
// * 对比脚本
// */
// @NonNull
// private String script;
//
// private RuleNode ruleNode;
//
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
| import org.eddy.xml.context.XmlDataContext;
import org.eddy.xml.data.DataNode;
import org.eddy.xml.data.RuleNode;
import org.junit.Assert;
import org.junit.Test;
import java.util.List; | package org.eddy.xml;
/**
* Created by eddy on 2017/5/3.
*/
public class XmlTest {
@Test
public void test() { | // Path: plugin/src/main/java/org/eddy/xml/context/XmlDataContext.java
// @Getter
// public class XmlDataContext {
//
// private static final Logger logger = LoggerFactory.getLogger(XmlDataContext.class);
//
// private List<RuleNode> nodes;
//
// private static XmlDataContext context = new XmlDataContext("rule/rule.xml");
//
//
// public static XmlDataContext getContext() {
// return context;
// }
//
// //**********************私有构造函数*************************
//
// private XmlDataContext(String path) {
// try {
// this.nodes = loadXml(path);
// } catch (Exception e) {
// logger.error("parse xml error", e);
// throw new RuntimeException("parse xml error", e);
// }
// }
//
// //**********************解析xml*****************************
//
// private List<RuleNode> loadXml(String path) throws Exception{
// DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
// DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
// builder.setEntityResolver(new UrlDtdPathResolver());
// Document document = builder.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream(path));
//
// List<RuleNode> results = new ArrayList<>();
//
// NodeList rootChildren = document.getDocumentElement().getChildNodes();
// for (int i = 0; i < rootChildren.getLength(); i++) {
//
// Optional.ofNullable(parseNode(rootChildren.item(i))).ifPresent(node -> results.add(node));
//
// }
//
// return results.stream().filter(Objects::nonNull).collect(Collectors.toList());
// }
//
// private RuleNode parseNode(Node item) throws Exception{
//
// // 节点非element节点 或 element节点name非rule, 则直接返回
// if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), RuleNode.RULE_NODE_NAME)) {
// return null;
// }
//
// Element ruleNode = (Element) item;
//
// String table = ruleNode.getAttribute("table");
// String column = ruleNode.getAttribute("column");
// String javaType = ruleNode.getAttribute("javaType");
// KeyColumn keyColumn = new KeyColumn(table, column, javaType);
//
// String comparator = ruleNode.getAttribute("class");
// Comparator comparatorClass = (Comparator) Class.forName(comparator).newInstance();
//
// RuleNode node = new RuleNode(keyColumn, comparatorClass);
//
// NodeList ruleChildren = item.getChildNodes();
// for (int i = 0; i < ruleChildren.getLength(); i++) {
//
// Optional.ofNullable(parseData(ruleChildren.item(i))).ifPresent(dataNode -> {
// node.add(dataNode);
// dataNode.setRuleNode(node);
// });
//
// }
//
// return node;
// }
//
// private DataNode parseData(Node item) throws Exception {
// // 节点非element节点 或 element节点name非data, 则直接返回
// if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), DataNode.DATA_NODE_NAME)) {
// return null;
// }
//
// Element dataElement = (Element) item;
// String schema = dataElement.getAttribute("schema");
// String table = dataElement.getAttribute("table");
// String script = dataElement.getAttribute("script");
//
// return new DataNode(schema, table, script);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/DataNode.java
// @Getter
// @Setter
// @ToString
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class DataNode {
//
// public static final String DATA_NODE_NAME = "data";
//
// /**
// * 库名
// */
// @NonNull
// private String schema;
//
// /**
// * 表名
// */
// @NonNull
// private String table;
//
// /**
// * 对比脚本
// */
// @NonNull
// private String script;
//
// private RuleNode ruleNode;
//
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
// Path: plugin/src/test/java/org/eddy/xml/XmlTest.java
import org.eddy.xml.context.XmlDataContext;
import org.eddy.xml.data.DataNode;
import org.eddy.xml.data.RuleNode;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
package org.eddy.xml;
/**
* Created by eddy on 2017/5/3.
*/
public class XmlTest {
@Test
public void test() { | List<RuleNode> dataNodes = XmlDataContext.getContext().getNodes(); |
justice-code/QiuQiu | plugin/src/test/java/org/eddy/xml/XmlTest.java | // Path: plugin/src/main/java/org/eddy/xml/context/XmlDataContext.java
// @Getter
// public class XmlDataContext {
//
// private static final Logger logger = LoggerFactory.getLogger(XmlDataContext.class);
//
// private List<RuleNode> nodes;
//
// private static XmlDataContext context = new XmlDataContext("rule/rule.xml");
//
//
// public static XmlDataContext getContext() {
// return context;
// }
//
// //**********************私有构造函数*************************
//
// private XmlDataContext(String path) {
// try {
// this.nodes = loadXml(path);
// } catch (Exception e) {
// logger.error("parse xml error", e);
// throw new RuntimeException("parse xml error", e);
// }
// }
//
// //**********************解析xml*****************************
//
// private List<RuleNode> loadXml(String path) throws Exception{
// DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
// DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
// builder.setEntityResolver(new UrlDtdPathResolver());
// Document document = builder.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream(path));
//
// List<RuleNode> results = new ArrayList<>();
//
// NodeList rootChildren = document.getDocumentElement().getChildNodes();
// for (int i = 0; i < rootChildren.getLength(); i++) {
//
// Optional.ofNullable(parseNode(rootChildren.item(i))).ifPresent(node -> results.add(node));
//
// }
//
// return results.stream().filter(Objects::nonNull).collect(Collectors.toList());
// }
//
// private RuleNode parseNode(Node item) throws Exception{
//
// // 节点非element节点 或 element节点name非rule, 则直接返回
// if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), RuleNode.RULE_NODE_NAME)) {
// return null;
// }
//
// Element ruleNode = (Element) item;
//
// String table = ruleNode.getAttribute("table");
// String column = ruleNode.getAttribute("column");
// String javaType = ruleNode.getAttribute("javaType");
// KeyColumn keyColumn = new KeyColumn(table, column, javaType);
//
// String comparator = ruleNode.getAttribute("class");
// Comparator comparatorClass = (Comparator) Class.forName(comparator).newInstance();
//
// RuleNode node = new RuleNode(keyColumn, comparatorClass);
//
// NodeList ruleChildren = item.getChildNodes();
// for (int i = 0; i < ruleChildren.getLength(); i++) {
//
// Optional.ofNullable(parseData(ruleChildren.item(i))).ifPresent(dataNode -> {
// node.add(dataNode);
// dataNode.setRuleNode(node);
// });
//
// }
//
// return node;
// }
//
// private DataNode parseData(Node item) throws Exception {
// // 节点非element节点 或 element节点name非data, 则直接返回
// if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), DataNode.DATA_NODE_NAME)) {
// return null;
// }
//
// Element dataElement = (Element) item;
// String schema = dataElement.getAttribute("schema");
// String table = dataElement.getAttribute("table");
// String script = dataElement.getAttribute("script");
//
// return new DataNode(schema, table, script);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/DataNode.java
// @Getter
// @Setter
// @ToString
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class DataNode {
//
// public static final String DATA_NODE_NAME = "data";
//
// /**
// * 库名
// */
// @NonNull
// private String schema;
//
// /**
// * 表名
// */
// @NonNull
// private String table;
//
// /**
// * 对比脚本
// */
// @NonNull
// private String script;
//
// private RuleNode ruleNode;
//
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
| import org.eddy.xml.context.XmlDataContext;
import org.eddy.xml.data.DataNode;
import org.eddy.xml.data.RuleNode;
import org.junit.Assert;
import org.junit.Test;
import java.util.List; | package org.eddy.xml;
/**
* Created by eddy on 2017/5/3.
*/
public class XmlTest {
@Test
public void test() { | // Path: plugin/src/main/java/org/eddy/xml/context/XmlDataContext.java
// @Getter
// public class XmlDataContext {
//
// private static final Logger logger = LoggerFactory.getLogger(XmlDataContext.class);
//
// private List<RuleNode> nodes;
//
// private static XmlDataContext context = new XmlDataContext("rule/rule.xml");
//
//
// public static XmlDataContext getContext() {
// return context;
// }
//
// //**********************私有构造函数*************************
//
// private XmlDataContext(String path) {
// try {
// this.nodes = loadXml(path);
// } catch (Exception e) {
// logger.error("parse xml error", e);
// throw new RuntimeException("parse xml error", e);
// }
// }
//
// //**********************解析xml*****************************
//
// private List<RuleNode> loadXml(String path) throws Exception{
// DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
// DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
// builder.setEntityResolver(new UrlDtdPathResolver());
// Document document = builder.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream(path));
//
// List<RuleNode> results = new ArrayList<>();
//
// NodeList rootChildren = document.getDocumentElement().getChildNodes();
// for (int i = 0; i < rootChildren.getLength(); i++) {
//
// Optional.ofNullable(parseNode(rootChildren.item(i))).ifPresent(node -> results.add(node));
//
// }
//
// return results.stream().filter(Objects::nonNull).collect(Collectors.toList());
// }
//
// private RuleNode parseNode(Node item) throws Exception{
//
// // 节点非element节点 或 element节点name非rule, 则直接返回
// if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), RuleNode.RULE_NODE_NAME)) {
// return null;
// }
//
// Element ruleNode = (Element) item;
//
// String table = ruleNode.getAttribute("table");
// String column = ruleNode.getAttribute("column");
// String javaType = ruleNode.getAttribute("javaType");
// KeyColumn keyColumn = new KeyColumn(table, column, javaType);
//
// String comparator = ruleNode.getAttribute("class");
// Comparator comparatorClass = (Comparator) Class.forName(comparator).newInstance();
//
// RuleNode node = new RuleNode(keyColumn, comparatorClass);
//
// NodeList ruleChildren = item.getChildNodes();
// for (int i = 0; i < ruleChildren.getLength(); i++) {
//
// Optional.ofNullable(parseData(ruleChildren.item(i))).ifPresent(dataNode -> {
// node.add(dataNode);
// dataNode.setRuleNode(node);
// });
//
// }
//
// return node;
// }
//
// private DataNode parseData(Node item) throws Exception {
// // 节点非element节点 或 element节点name非data, 则直接返回
// if (item.getNodeType() != Node.ELEMENT_NODE || !StringUtils.equals(item.getNodeName(), DataNode.DATA_NODE_NAME)) {
// return null;
// }
//
// Element dataElement = (Element) item;
// String schema = dataElement.getAttribute("schema");
// String table = dataElement.getAttribute("table");
// String script = dataElement.getAttribute("script");
//
// return new DataNode(schema, table, script);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/DataNode.java
// @Getter
// @Setter
// @ToString
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class DataNode {
//
// public static final String DATA_NODE_NAME = "data";
//
// /**
// * 库名
// */
// @NonNull
// private String schema;
//
// /**
// * 表名
// */
// @NonNull
// private String table;
//
// /**
// * 对比脚本
// */
// @NonNull
// private String script;
//
// private RuleNode ruleNode;
//
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
// Path: plugin/src/test/java/org/eddy/xml/XmlTest.java
import org.eddy.xml.context.XmlDataContext;
import org.eddy.xml.data.DataNode;
import org.eddy.xml.data.RuleNode;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
package org.eddy.xml;
/**
* Created by eddy on 2017/5/3.
*/
public class XmlTest {
@Test
public void test() { | List<RuleNode> dataNodes = XmlDataContext.getContext().getNodes(); |
justice-code/QiuQiu | plugin/src/main/java/org/eddy/sql/split/ReplaceTablesNamesFinder.java | // Path: plugin/src/main/java/org/eddy/util/TableList.java
// public class TableList {
//
// private static Pattern pattern = Pattern.compile("'|\"|`");
//
// private List<String> tables = new ArrayList<>();
//
// public void add(Table table, Supplier holder) {
// Objects.requireNonNull(holder);
// tables.add(holder.getName(table));
// replace(table);
// }
//
// private void replace(Table table) {
// XmlDataContext.getContext().getNodes().forEach(ruleNode -> {
// if (! checkTableName(table, ruleNode)) {
// return;
// }
// Optional.ofNullable(ruleNode.getComparator().check(ruleNode)).ifPresent(node -> {
// table.setName(node.getTable());
// table.setSchemaName(node.getSchema());
// });
// });
// }
//
// /**
// * 表名对比方法
// * @param table
// * @param ruleNode
// * @return true:对比通过,需要替换表名
// */
// private boolean checkTableName(Table table, RuleNode ruleNode) {
// String queryTable = pattern.matcher(table.getName()).replaceAll("");
// return StringUtils.equalsIgnoreCase(queryTable, ruleNode.sourceTable());
// }
//
// public boolean contains(String tableName) {
// // return tables.contains(tableName);
// return false;
// }
//
// public List<String> result() {
// return tables;
// }
//
// }
| import net.sf.jsqlparser.expression.*;
import net.sf.jsqlparser.expression.operators.arithmetic.*;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.conditional.OrExpression;
import net.sf.jsqlparser.expression.operators.relational.*;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.delete.Delete;
import net.sf.jsqlparser.statement.insert.Insert;
import net.sf.jsqlparser.statement.replace.Replace;
import net.sf.jsqlparser.statement.select.*;
import net.sf.jsqlparser.statement.update.Update;
import java.util.ArrayList;
import java.util.List;
import net.sf.jsqlparser.statement.SetStatement;
import net.sf.jsqlparser.statement.StatementVisitor;
import net.sf.jsqlparser.statement.Statements;
import net.sf.jsqlparser.statement.alter.Alter;
import net.sf.jsqlparser.statement.create.index.CreateIndex;
import net.sf.jsqlparser.statement.create.table.CreateTable;
import net.sf.jsqlparser.statement.create.view.CreateView;
import net.sf.jsqlparser.statement.drop.Drop;
import net.sf.jsqlparser.statement.execute.Execute;
import net.sf.jsqlparser.statement.merge.Merge;
import net.sf.jsqlparser.statement.truncate.Truncate;
import org.eddy.util.TableList; | package org.eddy.sql.split;
/**
* Find all used tables within an select statement.
*/
public class ReplaceTablesNamesFinder implements SelectVisitor, FromItemVisitor, ExpressionVisitor, ItemsListVisitor, SelectItemVisitor, StatementVisitor {
private static final String NOT_SUPPORTED_YET = "Not supported yet."; | // Path: plugin/src/main/java/org/eddy/util/TableList.java
// public class TableList {
//
// private static Pattern pattern = Pattern.compile("'|\"|`");
//
// private List<String> tables = new ArrayList<>();
//
// public void add(Table table, Supplier holder) {
// Objects.requireNonNull(holder);
// tables.add(holder.getName(table));
// replace(table);
// }
//
// private void replace(Table table) {
// XmlDataContext.getContext().getNodes().forEach(ruleNode -> {
// if (! checkTableName(table, ruleNode)) {
// return;
// }
// Optional.ofNullable(ruleNode.getComparator().check(ruleNode)).ifPresent(node -> {
// table.setName(node.getTable());
// table.setSchemaName(node.getSchema());
// });
// });
// }
//
// /**
// * 表名对比方法
// * @param table
// * @param ruleNode
// * @return true:对比通过,需要替换表名
// */
// private boolean checkTableName(Table table, RuleNode ruleNode) {
// String queryTable = pattern.matcher(table.getName()).replaceAll("");
// return StringUtils.equalsIgnoreCase(queryTable, ruleNode.sourceTable());
// }
//
// public boolean contains(String tableName) {
// // return tables.contains(tableName);
// return false;
// }
//
// public List<String> result() {
// return tables;
// }
//
// }
// Path: plugin/src/main/java/org/eddy/sql/split/ReplaceTablesNamesFinder.java
import net.sf.jsqlparser.expression.*;
import net.sf.jsqlparser.expression.operators.arithmetic.*;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.conditional.OrExpression;
import net.sf.jsqlparser.expression.operators.relational.*;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.delete.Delete;
import net.sf.jsqlparser.statement.insert.Insert;
import net.sf.jsqlparser.statement.replace.Replace;
import net.sf.jsqlparser.statement.select.*;
import net.sf.jsqlparser.statement.update.Update;
import java.util.ArrayList;
import java.util.List;
import net.sf.jsqlparser.statement.SetStatement;
import net.sf.jsqlparser.statement.StatementVisitor;
import net.sf.jsqlparser.statement.Statements;
import net.sf.jsqlparser.statement.alter.Alter;
import net.sf.jsqlparser.statement.create.index.CreateIndex;
import net.sf.jsqlparser.statement.create.table.CreateTable;
import net.sf.jsqlparser.statement.create.view.CreateView;
import net.sf.jsqlparser.statement.drop.Drop;
import net.sf.jsqlparser.statement.execute.Execute;
import net.sf.jsqlparser.statement.merge.Merge;
import net.sf.jsqlparser.statement.truncate.Truncate;
import org.eddy.util.TableList;
package org.eddy.sql.split;
/**
* Find all used tables within an select statement.
*/
public class ReplaceTablesNamesFinder implements SelectVisitor, FromItemVisitor, ExpressionVisitor, ItemsListVisitor, SelectItemVisitor, StatementVisitor {
private static final String NOT_SUPPORTED_YET = "Not supported yet."; | private TableList tables; |
justice-code/QiuQiu | plugin/src/main/java/org/eddy/xml/rule/impl/DefaultComparator.java | // Path: plugin/src/main/java/org/eddy/sql/config/RequestHolder.java
// public class RequestHolder {
//
// private static ThreadLocal<SplitRequest> requestHolder = new NamedThreadLocal<>("sqlSplitRequest");
//
// public static void resetRequest() {
// requestHolder.remove();
// }
//
// public static void initRequestHolder(String mapper, String[] ognl) {
// requestHolder.set(new SplitRequest(mapper, ognl));
// }
//
// public static SplitRequest getRequest() {
// return requestHolder.get();
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/DataNode.java
// @Getter
// @Setter
// @ToString
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class DataNode {
//
// public static final String DATA_NODE_NAME = "data";
//
// /**
// * 库名
// */
// @NonNull
// private String schema;
//
// /**
// * 表名
// */
// @NonNull
// private String table;
//
// /**
// * 对比脚本
// */
// @NonNull
// private String script;
//
// private RuleNode ruleNode;
//
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/rule/Comparator.java
// public abstract class Comparator {
//
// public abstract DataNode check(RuleNode ruleNode);
//
// public boolean script(String mapper, Object[] param, String script) {
// Objects.requireNonNull(script);
//
// Binding binding = new Binding();
// GroovyShell shell = new GroovyShell(binding);
// shell.setVariable("mapper", mapper);
// shell.setVariable("params", param);
// Object returnValue = shell.evaluate(script);
//
// return (boolean) returnValue;
// }
// }
| import org.eddy.sql.config.RequestHolder;
import org.eddy.xml.data.DataNode;
import org.eddy.xml.data.RuleNode;
import org.eddy.xml.rule.Comparator;
import java.util.Optional; | package org.eddy.xml.rule.impl;
/**
* Created by eddy on 2017/5/3.
*/
public class DefaultComparator extends Comparator {
@Override | // Path: plugin/src/main/java/org/eddy/sql/config/RequestHolder.java
// public class RequestHolder {
//
// private static ThreadLocal<SplitRequest> requestHolder = new NamedThreadLocal<>("sqlSplitRequest");
//
// public static void resetRequest() {
// requestHolder.remove();
// }
//
// public static void initRequestHolder(String mapper, String[] ognl) {
// requestHolder.set(new SplitRequest(mapper, ognl));
// }
//
// public static SplitRequest getRequest() {
// return requestHolder.get();
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/DataNode.java
// @Getter
// @Setter
// @ToString
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class DataNode {
//
// public static final String DATA_NODE_NAME = "data";
//
// /**
// * 库名
// */
// @NonNull
// private String schema;
//
// /**
// * 表名
// */
// @NonNull
// private String table;
//
// /**
// * 对比脚本
// */
// @NonNull
// private String script;
//
// private RuleNode ruleNode;
//
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/rule/Comparator.java
// public abstract class Comparator {
//
// public abstract DataNode check(RuleNode ruleNode);
//
// public boolean script(String mapper, Object[] param, String script) {
// Objects.requireNonNull(script);
//
// Binding binding = new Binding();
// GroovyShell shell = new GroovyShell(binding);
// shell.setVariable("mapper", mapper);
// shell.setVariable("params", param);
// Object returnValue = shell.evaluate(script);
//
// return (boolean) returnValue;
// }
// }
// Path: plugin/src/main/java/org/eddy/xml/rule/impl/DefaultComparator.java
import org.eddy.sql.config.RequestHolder;
import org.eddy.xml.data.DataNode;
import org.eddy.xml.data.RuleNode;
import org.eddy.xml.rule.Comparator;
import java.util.Optional;
package org.eddy.xml.rule.impl;
/**
* Created by eddy on 2017/5/3.
*/
public class DefaultComparator extends Comparator {
@Override | public DataNode check(RuleNode ruleNode) { |
justice-code/QiuQiu | plugin/src/main/java/org/eddy/xml/rule/impl/DefaultComparator.java | // Path: plugin/src/main/java/org/eddy/sql/config/RequestHolder.java
// public class RequestHolder {
//
// private static ThreadLocal<SplitRequest> requestHolder = new NamedThreadLocal<>("sqlSplitRequest");
//
// public static void resetRequest() {
// requestHolder.remove();
// }
//
// public static void initRequestHolder(String mapper, String[] ognl) {
// requestHolder.set(new SplitRequest(mapper, ognl));
// }
//
// public static SplitRequest getRequest() {
// return requestHolder.get();
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/DataNode.java
// @Getter
// @Setter
// @ToString
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class DataNode {
//
// public static final String DATA_NODE_NAME = "data";
//
// /**
// * 库名
// */
// @NonNull
// private String schema;
//
// /**
// * 表名
// */
// @NonNull
// private String table;
//
// /**
// * 对比脚本
// */
// @NonNull
// private String script;
//
// private RuleNode ruleNode;
//
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/rule/Comparator.java
// public abstract class Comparator {
//
// public abstract DataNode check(RuleNode ruleNode);
//
// public boolean script(String mapper, Object[] param, String script) {
// Objects.requireNonNull(script);
//
// Binding binding = new Binding();
// GroovyShell shell = new GroovyShell(binding);
// shell.setVariable("mapper", mapper);
// shell.setVariable("params", param);
// Object returnValue = shell.evaluate(script);
//
// return (boolean) returnValue;
// }
// }
| import org.eddy.sql.config.RequestHolder;
import org.eddy.xml.data.DataNode;
import org.eddy.xml.data.RuleNode;
import org.eddy.xml.rule.Comparator;
import java.util.Optional; | package org.eddy.xml.rule.impl;
/**
* Created by eddy on 2017/5/3.
*/
public class DefaultComparator extends Comparator {
@Override | // Path: plugin/src/main/java/org/eddy/sql/config/RequestHolder.java
// public class RequestHolder {
//
// private static ThreadLocal<SplitRequest> requestHolder = new NamedThreadLocal<>("sqlSplitRequest");
//
// public static void resetRequest() {
// requestHolder.remove();
// }
//
// public static void initRequestHolder(String mapper, String[] ognl) {
// requestHolder.set(new SplitRequest(mapper, ognl));
// }
//
// public static SplitRequest getRequest() {
// return requestHolder.get();
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/DataNode.java
// @Getter
// @Setter
// @ToString
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class DataNode {
//
// public static final String DATA_NODE_NAME = "data";
//
// /**
// * 库名
// */
// @NonNull
// private String schema;
//
// /**
// * 表名
// */
// @NonNull
// private String table;
//
// /**
// * 对比脚本
// */
// @NonNull
// private String script;
//
// private RuleNode ruleNode;
//
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/rule/Comparator.java
// public abstract class Comparator {
//
// public abstract DataNode check(RuleNode ruleNode);
//
// public boolean script(String mapper, Object[] param, String script) {
// Objects.requireNonNull(script);
//
// Binding binding = new Binding();
// GroovyShell shell = new GroovyShell(binding);
// shell.setVariable("mapper", mapper);
// shell.setVariable("params", param);
// Object returnValue = shell.evaluate(script);
//
// return (boolean) returnValue;
// }
// }
// Path: plugin/src/main/java/org/eddy/xml/rule/impl/DefaultComparator.java
import org.eddy.sql.config.RequestHolder;
import org.eddy.xml.data.DataNode;
import org.eddy.xml.data.RuleNode;
import org.eddy.xml.rule.Comparator;
import java.util.Optional;
package org.eddy.xml.rule.impl;
/**
* Created by eddy on 2017/5/3.
*/
public class DefaultComparator extends Comparator {
@Override | public DataNode check(RuleNode ruleNode) { |
justice-code/QiuQiu | plugin/src/main/java/org/eddy/xml/rule/impl/DefaultComparator.java | // Path: plugin/src/main/java/org/eddy/sql/config/RequestHolder.java
// public class RequestHolder {
//
// private static ThreadLocal<SplitRequest> requestHolder = new NamedThreadLocal<>("sqlSplitRequest");
//
// public static void resetRequest() {
// requestHolder.remove();
// }
//
// public static void initRequestHolder(String mapper, String[] ognl) {
// requestHolder.set(new SplitRequest(mapper, ognl));
// }
//
// public static SplitRequest getRequest() {
// return requestHolder.get();
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/DataNode.java
// @Getter
// @Setter
// @ToString
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class DataNode {
//
// public static final String DATA_NODE_NAME = "data";
//
// /**
// * 库名
// */
// @NonNull
// private String schema;
//
// /**
// * 表名
// */
// @NonNull
// private String table;
//
// /**
// * 对比脚本
// */
// @NonNull
// private String script;
//
// private RuleNode ruleNode;
//
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/rule/Comparator.java
// public abstract class Comparator {
//
// public abstract DataNode check(RuleNode ruleNode);
//
// public boolean script(String mapper, Object[] param, String script) {
// Objects.requireNonNull(script);
//
// Binding binding = new Binding();
// GroovyShell shell = new GroovyShell(binding);
// shell.setVariable("mapper", mapper);
// shell.setVariable("params", param);
// Object returnValue = shell.evaluate(script);
//
// return (boolean) returnValue;
// }
// }
| import org.eddy.sql.config.RequestHolder;
import org.eddy.xml.data.DataNode;
import org.eddy.xml.data.RuleNode;
import org.eddy.xml.rule.Comparator;
import java.util.Optional; | package org.eddy.xml.rule.impl;
/**
* Created by eddy on 2017/5/3.
*/
public class DefaultComparator extends Comparator {
@Override
public DataNode check(RuleNode ruleNode) { | // Path: plugin/src/main/java/org/eddy/sql/config/RequestHolder.java
// public class RequestHolder {
//
// private static ThreadLocal<SplitRequest> requestHolder = new NamedThreadLocal<>("sqlSplitRequest");
//
// public static void resetRequest() {
// requestHolder.remove();
// }
//
// public static void initRequestHolder(String mapper, String[] ognl) {
// requestHolder.set(new SplitRequest(mapper, ognl));
// }
//
// public static SplitRequest getRequest() {
// return requestHolder.get();
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/DataNode.java
// @Getter
// @Setter
// @ToString
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class DataNode {
//
// public static final String DATA_NODE_NAME = "data";
//
// /**
// * 库名
// */
// @NonNull
// private String schema;
//
// /**
// * 表名
// */
// @NonNull
// private String table;
//
// /**
// * 对比脚本
// */
// @NonNull
// private String script;
//
// private RuleNode ruleNode;
//
// }
//
// Path: plugin/src/main/java/org/eddy/xml/data/RuleNode.java
// @Getter
// @Setter
// @ToString(exclude = "dataNodes")
// @NoArgsConstructor
// @RequiredArgsConstructor
// public class RuleNode {
//
// public static final String RULE_NODE_NAME = "rule";
//
// @NonNull
// private KeyColumn keyColumn;
//
// private List<DataNode> dataNodes = new ArrayList<>();
//
// /**
// * 比较器
// */
// @NonNull
// private Comparator comparator;
//
// public String sourceTable() {
// return keyColumn.getTable();
// }
//
// public void add(DataNode dataNode) {
// dataNodes.add(dataNode);
// }
// }
//
// Path: plugin/src/main/java/org/eddy/xml/rule/Comparator.java
// public abstract class Comparator {
//
// public abstract DataNode check(RuleNode ruleNode);
//
// public boolean script(String mapper, Object[] param, String script) {
// Objects.requireNonNull(script);
//
// Binding binding = new Binding();
// GroovyShell shell = new GroovyShell(binding);
// shell.setVariable("mapper", mapper);
// shell.setVariable("params", param);
// Object returnValue = shell.evaluate(script);
//
// return (boolean) returnValue;
// }
// }
// Path: plugin/src/main/java/org/eddy/xml/rule/impl/DefaultComparator.java
import org.eddy.sql.config.RequestHolder;
import org.eddy.xml.data.DataNode;
import org.eddy.xml.data.RuleNode;
import org.eddy.xml.rule.Comparator;
import java.util.Optional;
package org.eddy.xml.rule.impl;
/**
* Created by eddy on 2017/5/3.
*/
public class DefaultComparator extends Comparator {
@Override
public DataNode check(RuleNode ruleNode) { | Object[] param = RequestHolder.getRequest().getParam(); |
justice-code/QiuQiu | plugin/src/main/java/org/eddy/aop/MapperAspect.java | // Path: plugin/src/main/java/org/eddy/sql/config/RequestHolder.java
// public class RequestHolder {
//
// private static ThreadLocal<SplitRequest> requestHolder = new NamedThreadLocal<>("sqlSplitRequest");
//
// public static void resetRequest() {
// requestHolder.remove();
// }
//
// public static void initRequestHolder(String mapper, String[] ognl) {
// requestHolder.set(new SplitRequest(mapper, ognl));
// }
//
// public static SplitRequest getRequest() {
// return requestHolder.get();
// }
// }
| import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.reflect.MethodSignature;
import org.eddy.sql.config.KeyParam;
import org.eddy.sql.config.RequestHolder;
import java.lang.reflect.Method; | package org.eddy.aop;
/**
* Created by eddy on 2017/6/14.
*/
public abstract class MapperAspect {
@Around("mapperCheckPoint()")
private Object around(ProceedingJoinPoint point) throws Throwable {
if(! check(point)) {
return point.proceed();
}
if (! (point.getSignature() instanceof MethodSignature)) {
return point.proceed();
}
MethodSignature methodSignature = (MethodSignature) point.getSignature();
Method method = methodSignature.getMethod();
if (! method.isAnnotationPresent(KeyParam.class)) {
return point.proceed();
}
KeyParam keyParam = method.getAnnotation(KeyParam.class);
String[] ognl = keyParam.value();
String mapper = method.getDeclaringClass().getSimpleName() + "." + method.getName(); | // Path: plugin/src/main/java/org/eddy/sql/config/RequestHolder.java
// public class RequestHolder {
//
// private static ThreadLocal<SplitRequest> requestHolder = new NamedThreadLocal<>("sqlSplitRequest");
//
// public static void resetRequest() {
// requestHolder.remove();
// }
//
// public static void initRequestHolder(String mapper, String[] ognl) {
// requestHolder.set(new SplitRequest(mapper, ognl));
// }
//
// public static SplitRequest getRequest() {
// return requestHolder.get();
// }
// }
// Path: plugin/src/main/java/org/eddy/aop/MapperAspect.java
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.reflect.MethodSignature;
import org.eddy.sql.config.KeyParam;
import org.eddy.sql.config.RequestHolder;
import java.lang.reflect.Method;
package org.eddy.aop;
/**
* Created by eddy on 2017/6/14.
*/
public abstract class MapperAspect {
@Around("mapperCheckPoint()")
private Object around(ProceedingJoinPoint point) throws Throwable {
if(! check(point)) {
return point.proceed();
}
if (! (point.getSignature() instanceof MethodSignature)) {
return point.proceed();
}
MethodSignature methodSignature = (MethodSignature) point.getSignature();
Method method = methodSignature.getMethod();
if (! method.isAnnotationPresent(KeyParam.class)) {
return point.proceed();
}
KeyParam keyParam = method.getAnnotation(KeyParam.class);
String[] ognl = keyParam.value();
String mapper = method.getDeclaringClass().getSimpleName() + "." + method.getName(); | RequestHolder.initRequestHolder(mapper, ognl); |
justice-code/QiuQiu | apply/src/test/java/org/eddy/UserTest.java | // Path: apply/src/main/java/org/eddy/dao/mapper/test/UserMapper.java
// @Mapper
// public interface UserMapper {
//
// @KeyParam("#root")
// List<User> selectById(Integer id);
//
// @KeyParam("#root")
// int insert(String name);
//
// @KeyParam("id")
// int update(User user);
//
// @KeyParam("#root")
// int delete(Integer id);
//
// @KeyParam({"begin", "end"})
// List<User> selectUsers(@Param("begin") Integer begin, @Param("end") Integer end);
// }
//
// Path: apply/src/main/java/org/eddy/model/User.java
// @Getter
// @Setter
// @AllArgsConstructor
// @NoArgsConstructor
// public class User {
//
// private Integer id;
// private String name;
// }
| import org.eddy.dao.mapper.test.UserMapper;
import org.eddy.model.User;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.List; | package org.eddy;
/**
* Created by eddy on 2017/6/6.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {ApplicationStart.class})
@ActiveProfiles(value="dev")
public class UserTest {
@Autowired | // Path: apply/src/main/java/org/eddy/dao/mapper/test/UserMapper.java
// @Mapper
// public interface UserMapper {
//
// @KeyParam("#root")
// List<User> selectById(Integer id);
//
// @KeyParam("#root")
// int insert(String name);
//
// @KeyParam("id")
// int update(User user);
//
// @KeyParam("#root")
// int delete(Integer id);
//
// @KeyParam({"begin", "end"})
// List<User> selectUsers(@Param("begin") Integer begin, @Param("end") Integer end);
// }
//
// Path: apply/src/main/java/org/eddy/model/User.java
// @Getter
// @Setter
// @AllArgsConstructor
// @NoArgsConstructor
// public class User {
//
// private Integer id;
// private String name;
// }
// Path: apply/src/test/java/org/eddy/UserTest.java
import org.eddy.dao.mapper.test.UserMapper;
import org.eddy.model.User;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
package org.eddy;
/**
* Created by eddy on 2017/6/6.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {ApplicationStart.class})
@ActiveProfiles(value="dev")
public class UserTest {
@Autowired | UserMapper userMapper; |
justice-code/QiuQiu | apply/src/test/java/org/eddy/UserTest.java | // Path: apply/src/main/java/org/eddy/dao/mapper/test/UserMapper.java
// @Mapper
// public interface UserMapper {
//
// @KeyParam("#root")
// List<User> selectById(Integer id);
//
// @KeyParam("#root")
// int insert(String name);
//
// @KeyParam("id")
// int update(User user);
//
// @KeyParam("#root")
// int delete(Integer id);
//
// @KeyParam({"begin", "end"})
// List<User> selectUsers(@Param("begin") Integer begin, @Param("end") Integer end);
// }
//
// Path: apply/src/main/java/org/eddy/model/User.java
// @Getter
// @Setter
// @AllArgsConstructor
// @NoArgsConstructor
// public class User {
//
// private Integer id;
// private String name;
// }
| import org.eddy.dao.mapper.test.UserMapper;
import org.eddy.model.User;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.List; | package org.eddy;
/**
* Created by eddy on 2017/6/6.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {ApplicationStart.class})
@ActiveProfiles(value="dev")
public class UserTest {
@Autowired
UserMapper userMapper;
@Test(expected = BadSqlGrammarException.class)
@Transactional
public void test() { | // Path: apply/src/main/java/org/eddy/dao/mapper/test/UserMapper.java
// @Mapper
// public interface UserMapper {
//
// @KeyParam("#root")
// List<User> selectById(Integer id);
//
// @KeyParam("#root")
// int insert(String name);
//
// @KeyParam("id")
// int update(User user);
//
// @KeyParam("#root")
// int delete(Integer id);
//
// @KeyParam({"begin", "end"})
// List<User> selectUsers(@Param("begin") Integer begin, @Param("end") Integer end);
// }
//
// Path: apply/src/main/java/org/eddy/model/User.java
// @Getter
// @Setter
// @AllArgsConstructor
// @NoArgsConstructor
// public class User {
//
// private Integer id;
// private String name;
// }
// Path: apply/src/test/java/org/eddy/UserTest.java
import org.eddy.dao.mapper.test.UserMapper;
import org.eddy.model.User;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
package org.eddy;
/**
* Created by eddy on 2017/6/6.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {ApplicationStart.class})
@ActiveProfiles(value="dev")
public class UserTest {
@Autowired
UserMapper userMapper;
@Test(expected = BadSqlGrammarException.class)
@Transactional
public void test() { | List<User> users = userMapper.selectById(2); |
justice-code/QiuQiu | apply/src/main/java/org/eddy/dao/mapper/test/UserMapper.java | // Path: apply/src/main/java/org/eddy/model/User.java
// @Getter
// @Setter
// @AllArgsConstructor
// @NoArgsConstructor
// public class User {
//
// private Integer id;
// private String name;
// }
| import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.eddy.model.User;
import org.eddy.sql.config.KeyParam;
import java.util.List; | package org.eddy.dao.mapper.test;
/**
* Created by eddy on 2016/12/10.
*/
@Mapper
public interface UserMapper {
@KeyParam("#root") | // Path: apply/src/main/java/org/eddy/model/User.java
// @Getter
// @Setter
// @AllArgsConstructor
// @NoArgsConstructor
// public class User {
//
// private Integer id;
// private String name;
// }
// Path: apply/src/main/java/org/eddy/dao/mapper/test/UserMapper.java
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.eddy.model.User;
import org.eddy.sql.config.KeyParam;
import java.util.List;
package org.eddy.dao.mapper.test;
/**
* Created by eddy on 2016/12/10.
*/
@Mapper
public interface UserMapper {
@KeyParam("#root") | List<User> selectById(Integer id); |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/model/api/ToastCallback.java | // Path: app/src/main/java/org/cnodejs/android/md/model/entity/ErrorResult.java
// public class ErrorResult extends Result {
//
// @NonNull
// public static ErrorResult from(@NonNull Response response) {
// ErrorResult errorResult = null;
// ResponseBody errorBody = response.errorBody();
// if (errorBody != null) {
// try {
// errorResult = EntityUtils.gson.fromJson(errorBody.string(), ErrorResult.class);
// } catch (Throwable ignored) {}
// }
// if (errorResult == null) {
// errorResult = new ErrorResult();
// errorResult.setSuccess(false);
// switch (response.code()) {
// case 400:
// errorResult.setMessage("非法请求");
// break;
// case 403:
// errorResult.setMessage("非法行为");
// break;
// case 404:
// errorResult.setMessage("未找到资源");
// break;
// case 405:
// errorResult.setMessage("非法请求方式");
// break;
// case 408:
// errorResult.setMessage("请求超时");
// break;
// case 500:
// errorResult.setMessage("服务器内部错误");
// break;
// case 502:
// errorResult.setMessage("服务器网关错误");
// break;
// case 504:
// errorResult.setMessage("服务器网关超时");
// break;
// default:
// errorResult.setMessage("未知响应:" + response.message());
// break;
// }
// }
// return errorResult;
// }
//
// @NonNull
// public static ErrorResult from(@NonNull Throwable t) {
// ErrorResult errorResult = new ErrorResult();
// errorResult.setSuccess(false);
// if (t instanceof UnknownHostException || t instanceof ConnectException) {
// errorResult.setMessage("网络无法连接");
// } else if (t instanceof NoRouteToHostException) {
// errorResult.setMessage("无法访问网络");
// } else if (t instanceof SocketTimeoutException) {
// errorResult.setMessage("网络访问超时");
// } else if (t instanceof JsonSyntaxException) {
// errorResult.setMessage("响应数据格式错误");
// } else {
// errorResult.setMessage("未知错误:" + t.getLocalizedMessage());
// }
// return errorResult;
// }
//
// @SerializedName("error_msg")
// private String message;
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/Result.java
// public class Result {
//
// private boolean success;
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ActivityUtils.java
// public final class ActivityUtils {
//
// private ActivityUtils() {}
//
// public static boolean isAlive(@Nullable Activity activity) {
// return activity != null && !(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && activity.isDestroyed()) && !activity.isFinishing();
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ToastUtils.java
// public final class ToastUtils {
//
// private volatile static ToastUtils singleton;
//
// public static ToastUtils with(@NonNull Context context) {
// if (singleton == null) {
// synchronized (ToastUtils.class) {
// if (singleton == null) {
// singleton = new ToastUtils(context);
// }
// }
// }
// return singleton;
// }
//
// private final Toast toast;
//
// @SuppressLint("ShowToast")
// private ToastUtils(@NonNull Context context) {
// toast = Toast.makeText(context.getApplicationContext(), null, Toast.LENGTH_SHORT);
// }
//
// public void show(CharSequence msg) {
// toast.setText(msg);
// toast.show();
// }
//
// public void show(@StringRes int resId) {
// toast.setText(resId);
// toast.show();
// }
//
// }
| import android.app.Activity;
import android.support.annotation.NonNull;
import org.cnodejs.android.md.model.entity.ErrorResult;
import org.cnodejs.android.md.model.entity.Result;
import org.cnodejs.android.md.ui.util.ActivityUtils;
import org.cnodejs.android.md.ui.util.ToastUtils;
import okhttp3.Headers; | package org.cnodejs.android.md.model.api;
public class ToastCallback<T extends Result> extends ForegroundCallback<T> {
public ToastCallback(@NonNull Activity activity) {
super(activity);
}
@Override | // Path: app/src/main/java/org/cnodejs/android/md/model/entity/ErrorResult.java
// public class ErrorResult extends Result {
//
// @NonNull
// public static ErrorResult from(@NonNull Response response) {
// ErrorResult errorResult = null;
// ResponseBody errorBody = response.errorBody();
// if (errorBody != null) {
// try {
// errorResult = EntityUtils.gson.fromJson(errorBody.string(), ErrorResult.class);
// } catch (Throwable ignored) {}
// }
// if (errorResult == null) {
// errorResult = new ErrorResult();
// errorResult.setSuccess(false);
// switch (response.code()) {
// case 400:
// errorResult.setMessage("非法请求");
// break;
// case 403:
// errorResult.setMessage("非法行为");
// break;
// case 404:
// errorResult.setMessage("未找到资源");
// break;
// case 405:
// errorResult.setMessage("非法请求方式");
// break;
// case 408:
// errorResult.setMessage("请求超时");
// break;
// case 500:
// errorResult.setMessage("服务器内部错误");
// break;
// case 502:
// errorResult.setMessage("服务器网关错误");
// break;
// case 504:
// errorResult.setMessage("服务器网关超时");
// break;
// default:
// errorResult.setMessage("未知响应:" + response.message());
// break;
// }
// }
// return errorResult;
// }
//
// @NonNull
// public static ErrorResult from(@NonNull Throwable t) {
// ErrorResult errorResult = new ErrorResult();
// errorResult.setSuccess(false);
// if (t instanceof UnknownHostException || t instanceof ConnectException) {
// errorResult.setMessage("网络无法连接");
// } else if (t instanceof NoRouteToHostException) {
// errorResult.setMessage("无法访问网络");
// } else if (t instanceof SocketTimeoutException) {
// errorResult.setMessage("网络访问超时");
// } else if (t instanceof JsonSyntaxException) {
// errorResult.setMessage("响应数据格式错误");
// } else {
// errorResult.setMessage("未知错误:" + t.getLocalizedMessage());
// }
// return errorResult;
// }
//
// @SerializedName("error_msg")
// private String message;
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/Result.java
// public class Result {
//
// private boolean success;
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ActivityUtils.java
// public final class ActivityUtils {
//
// private ActivityUtils() {}
//
// public static boolean isAlive(@Nullable Activity activity) {
// return activity != null && !(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && activity.isDestroyed()) && !activity.isFinishing();
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ToastUtils.java
// public final class ToastUtils {
//
// private volatile static ToastUtils singleton;
//
// public static ToastUtils with(@NonNull Context context) {
// if (singleton == null) {
// synchronized (ToastUtils.class) {
// if (singleton == null) {
// singleton = new ToastUtils(context);
// }
// }
// }
// return singleton;
// }
//
// private final Toast toast;
//
// @SuppressLint("ShowToast")
// private ToastUtils(@NonNull Context context) {
// toast = Toast.makeText(context.getApplicationContext(), null, Toast.LENGTH_SHORT);
// }
//
// public void show(CharSequence msg) {
// toast.setText(msg);
// toast.show();
// }
//
// public void show(@StringRes int resId) {
// toast.setText(resId);
// toast.show();
// }
//
// }
// Path: app/src/main/java/org/cnodejs/android/md/model/api/ToastCallback.java
import android.app.Activity;
import android.support.annotation.NonNull;
import org.cnodejs.android.md.model.entity.ErrorResult;
import org.cnodejs.android.md.model.entity.Result;
import org.cnodejs.android.md.ui.util.ActivityUtils;
import org.cnodejs.android.md.ui.util.ToastUtils;
import okhttp3.Headers;
package org.cnodejs.android.md.model.api;
public class ToastCallback<T extends Result> extends ForegroundCallback<T> {
public ToastCallback(@NonNull Activity activity) {
super(activity);
}
@Override | public boolean onResultError(int code, Headers headers, ErrorResult errorResult) { |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/model/api/ToastCallback.java | // Path: app/src/main/java/org/cnodejs/android/md/model/entity/ErrorResult.java
// public class ErrorResult extends Result {
//
// @NonNull
// public static ErrorResult from(@NonNull Response response) {
// ErrorResult errorResult = null;
// ResponseBody errorBody = response.errorBody();
// if (errorBody != null) {
// try {
// errorResult = EntityUtils.gson.fromJson(errorBody.string(), ErrorResult.class);
// } catch (Throwable ignored) {}
// }
// if (errorResult == null) {
// errorResult = new ErrorResult();
// errorResult.setSuccess(false);
// switch (response.code()) {
// case 400:
// errorResult.setMessage("非法请求");
// break;
// case 403:
// errorResult.setMessage("非法行为");
// break;
// case 404:
// errorResult.setMessage("未找到资源");
// break;
// case 405:
// errorResult.setMessage("非法请求方式");
// break;
// case 408:
// errorResult.setMessage("请求超时");
// break;
// case 500:
// errorResult.setMessage("服务器内部错误");
// break;
// case 502:
// errorResult.setMessage("服务器网关错误");
// break;
// case 504:
// errorResult.setMessage("服务器网关超时");
// break;
// default:
// errorResult.setMessage("未知响应:" + response.message());
// break;
// }
// }
// return errorResult;
// }
//
// @NonNull
// public static ErrorResult from(@NonNull Throwable t) {
// ErrorResult errorResult = new ErrorResult();
// errorResult.setSuccess(false);
// if (t instanceof UnknownHostException || t instanceof ConnectException) {
// errorResult.setMessage("网络无法连接");
// } else if (t instanceof NoRouteToHostException) {
// errorResult.setMessage("无法访问网络");
// } else if (t instanceof SocketTimeoutException) {
// errorResult.setMessage("网络访问超时");
// } else if (t instanceof JsonSyntaxException) {
// errorResult.setMessage("响应数据格式错误");
// } else {
// errorResult.setMessage("未知错误:" + t.getLocalizedMessage());
// }
// return errorResult;
// }
//
// @SerializedName("error_msg")
// private String message;
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/Result.java
// public class Result {
//
// private boolean success;
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ActivityUtils.java
// public final class ActivityUtils {
//
// private ActivityUtils() {}
//
// public static boolean isAlive(@Nullable Activity activity) {
// return activity != null && !(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && activity.isDestroyed()) && !activity.isFinishing();
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ToastUtils.java
// public final class ToastUtils {
//
// private volatile static ToastUtils singleton;
//
// public static ToastUtils with(@NonNull Context context) {
// if (singleton == null) {
// synchronized (ToastUtils.class) {
// if (singleton == null) {
// singleton = new ToastUtils(context);
// }
// }
// }
// return singleton;
// }
//
// private final Toast toast;
//
// @SuppressLint("ShowToast")
// private ToastUtils(@NonNull Context context) {
// toast = Toast.makeText(context.getApplicationContext(), null, Toast.LENGTH_SHORT);
// }
//
// public void show(CharSequence msg) {
// toast.setText(msg);
// toast.show();
// }
//
// public void show(@StringRes int resId) {
// toast.setText(resId);
// toast.show();
// }
//
// }
| import android.app.Activity;
import android.support.annotation.NonNull;
import org.cnodejs.android.md.model.entity.ErrorResult;
import org.cnodejs.android.md.model.entity.Result;
import org.cnodejs.android.md.ui.util.ActivityUtils;
import org.cnodejs.android.md.ui.util.ToastUtils;
import okhttp3.Headers; | package org.cnodejs.android.md.model.api;
public class ToastCallback<T extends Result> extends ForegroundCallback<T> {
public ToastCallback(@NonNull Activity activity) {
super(activity);
}
@Override
public boolean onResultError(int code, Headers headers, ErrorResult errorResult) {
return onAnyError(errorResult);
}
@Override
public boolean onCallException(Throwable t, ErrorResult errorResult) {
return onAnyError(errorResult);
}
public boolean onAnyError(ErrorResult errorResult) {
toastError(errorResult);
return false;
}
protected final void toastError(ErrorResult errorResult) {
Activity activity = getActivity(); | // Path: app/src/main/java/org/cnodejs/android/md/model/entity/ErrorResult.java
// public class ErrorResult extends Result {
//
// @NonNull
// public static ErrorResult from(@NonNull Response response) {
// ErrorResult errorResult = null;
// ResponseBody errorBody = response.errorBody();
// if (errorBody != null) {
// try {
// errorResult = EntityUtils.gson.fromJson(errorBody.string(), ErrorResult.class);
// } catch (Throwable ignored) {}
// }
// if (errorResult == null) {
// errorResult = new ErrorResult();
// errorResult.setSuccess(false);
// switch (response.code()) {
// case 400:
// errorResult.setMessage("非法请求");
// break;
// case 403:
// errorResult.setMessage("非法行为");
// break;
// case 404:
// errorResult.setMessage("未找到资源");
// break;
// case 405:
// errorResult.setMessage("非法请求方式");
// break;
// case 408:
// errorResult.setMessage("请求超时");
// break;
// case 500:
// errorResult.setMessage("服务器内部错误");
// break;
// case 502:
// errorResult.setMessage("服务器网关错误");
// break;
// case 504:
// errorResult.setMessage("服务器网关超时");
// break;
// default:
// errorResult.setMessage("未知响应:" + response.message());
// break;
// }
// }
// return errorResult;
// }
//
// @NonNull
// public static ErrorResult from(@NonNull Throwable t) {
// ErrorResult errorResult = new ErrorResult();
// errorResult.setSuccess(false);
// if (t instanceof UnknownHostException || t instanceof ConnectException) {
// errorResult.setMessage("网络无法连接");
// } else if (t instanceof NoRouteToHostException) {
// errorResult.setMessage("无法访问网络");
// } else if (t instanceof SocketTimeoutException) {
// errorResult.setMessage("网络访问超时");
// } else if (t instanceof JsonSyntaxException) {
// errorResult.setMessage("响应数据格式错误");
// } else {
// errorResult.setMessage("未知错误:" + t.getLocalizedMessage());
// }
// return errorResult;
// }
//
// @SerializedName("error_msg")
// private String message;
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/Result.java
// public class Result {
//
// private boolean success;
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ActivityUtils.java
// public final class ActivityUtils {
//
// private ActivityUtils() {}
//
// public static boolean isAlive(@Nullable Activity activity) {
// return activity != null && !(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && activity.isDestroyed()) && !activity.isFinishing();
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ToastUtils.java
// public final class ToastUtils {
//
// private volatile static ToastUtils singleton;
//
// public static ToastUtils with(@NonNull Context context) {
// if (singleton == null) {
// synchronized (ToastUtils.class) {
// if (singleton == null) {
// singleton = new ToastUtils(context);
// }
// }
// }
// return singleton;
// }
//
// private final Toast toast;
//
// @SuppressLint("ShowToast")
// private ToastUtils(@NonNull Context context) {
// toast = Toast.makeText(context.getApplicationContext(), null, Toast.LENGTH_SHORT);
// }
//
// public void show(CharSequence msg) {
// toast.setText(msg);
// toast.show();
// }
//
// public void show(@StringRes int resId) {
// toast.setText(resId);
// toast.show();
// }
//
// }
// Path: app/src/main/java/org/cnodejs/android/md/model/api/ToastCallback.java
import android.app.Activity;
import android.support.annotation.NonNull;
import org.cnodejs.android.md.model.entity.ErrorResult;
import org.cnodejs.android.md.model.entity.Result;
import org.cnodejs.android.md.ui.util.ActivityUtils;
import org.cnodejs.android.md.ui.util.ToastUtils;
import okhttp3.Headers;
package org.cnodejs.android.md.model.api;
public class ToastCallback<T extends Result> extends ForegroundCallback<T> {
public ToastCallback(@NonNull Activity activity) {
super(activity);
}
@Override
public boolean onResultError(int code, Headers headers, ErrorResult errorResult) {
return onAnyError(errorResult);
}
@Override
public boolean onCallException(Throwable t, ErrorResult errorResult) {
return onAnyError(errorResult);
}
public boolean onAnyError(ErrorResult errorResult) {
toastError(errorResult);
return false;
}
protected final void toastError(ErrorResult errorResult) {
Activity activity = getActivity(); | if (ActivityUtils.isAlive(activity)) { |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/model/api/ToastCallback.java | // Path: app/src/main/java/org/cnodejs/android/md/model/entity/ErrorResult.java
// public class ErrorResult extends Result {
//
// @NonNull
// public static ErrorResult from(@NonNull Response response) {
// ErrorResult errorResult = null;
// ResponseBody errorBody = response.errorBody();
// if (errorBody != null) {
// try {
// errorResult = EntityUtils.gson.fromJson(errorBody.string(), ErrorResult.class);
// } catch (Throwable ignored) {}
// }
// if (errorResult == null) {
// errorResult = new ErrorResult();
// errorResult.setSuccess(false);
// switch (response.code()) {
// case 400:
// errorResult.setMessage("非法请求");
// break;
// case 403:
// errorResult.setMessage("非法行为");
// break;
// case 404:
// errorResult.setMessage("未找到资源");
// break;
// case 405:
// errorResult.setMessage("非法请求方式");
// break;
// case 408:
// errorResult.setMessage("请求超时");
// break;
// case 500:
// errorResult.setMessage("服务器内部错误");
// break;
// case 502:
// errorResult.setMessage("服务器网关错误");
// break;
// case 504:
// errorResult.setMessage("服务器网关超时");
// break;
// default:
// errorResult.setMessage("未知响应:" + response.message());
// break;
// }
// }
// return errorResult;
// }
//
// @NonNull
// public static ErrorResult from(@NonNull Throwable t) {
// ErrorResult errorResult = new ErrorResult();
// errorResult.setSuccess(false);
// if (t instanceof UnknownHostException || t instanceof ConnectException) {
// errorResult.setMessage("网络无法连接");
// } else if (t instanceof NoRouteToHostException) {
// errorResult.setMessage("无法访问网络");
// } else if (t instanceof SocketTimeoutException) {
// errorResult.setMessage("网络访问超时");
// } else if (t instanceof JsonSyntaxException) {
// errorResult.setMessage("响应数据格式错误");
// } else {
// errorResult.setMessage("未知错误:" + t.getLocalizedMessage());
// }
// return errorResult;
// }
//
// @SerializedName("error_msg")
// private String message;
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/Result.java
// public class Result {
//
// private boolean success;
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ActivityUtils.java
// public final class ActivityUtils {
//
// private ActivityUtils() {}
//
// public static boolean isAlive(@Nullable Activity activity) {
// return activity != null && !(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && activity.isDestroyed()) && !activity.isFinishing();
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ToastUtils.java
// public final class ToastUtils {
//
// private volatile static ToastUtils singleton;
//
// public static ToastUtils with(@NonNull Context context) {
// if (singleton == null) {
// synchronized (ToastUtils.class) {
// if (singleton == null) {
// singleton = new ToastUtils(context);
// }
// }
// }
// return singleton;
// }
//
// private final Toast toast;
//
// @SuppressLint("ShowToast")
// private ToastUtils(@NonNull Context context) {
// toast = Toast.makeText(context.getApplicationContext(), null, Toast.LENGTH_SHORT);
// }
//
// public void show(CharSequence msg) {
// toast.setText(msg);
// toast.show();
// }
//
// public void show(@StringRes int resId) {
// toast.setText(resId);
// toast.show();
// }
//
// }
| import android.app.Activity;
import android.support.annotation.NonNull;
import org.cnodejs.android.md.model.entity.ErrorResult;
import org.cnodejs.android.md.model.entity.Result;
import org.cnodejs.android.md.ui.util.ActivityUtils;
import org.cnodejs.android.md.ui.util.ToastUtils;
import okhttp3.Headers; | package org.cnodejs.android.md.model.api;
public class ToastCallback<T extends Result> extends ForegroundCallback<T> {
public ToastCallback(@NonNull Activity activity) {
super(activity);
}
@Override
public boolean onResultError(int code, Headers headers, ErrorResult errorResult) {
return onAnyError(errorResult);
}
@Override
public boolean onCallException(Throwable t, ErrorResult errorResult) {
return onAnyError(errorResult);
}
public boolean onAnyError(ErrorResult errorResult) {
toastError(errorResult);
return false;
}
protected final void toastError(ErrorResult errorResult) {
Activity activity = getActivity();
if (ActivityUtils.isAlive(activity)) { | // Path: app/src/main/java/org/cnodejs/android/md/model/entity/ErrorResult.java
// public class ErrorResult extends Result {
//
// @NonNull
// public static ErrorResult from(@NonNull Response response) {
// ErrorResult errorResult = null;
// ResponseBody errorBody = response.errorBody();
// if (errorBody != null) {
// try {
// errorResult = EntityUtils.gson.fromJson(errorBody.string(), ErrorResult.class);
// } catch (Throwable ignored) {}
// }
// if (errorResult == null) {
// errorResult = new ErrorResult();
// errorResult.setSuccess(false);
// switch (response.code()) {
// case 400:
// errorResult.setMessage("非法请求");
// break;
// case 403:
// errorResult.setMessage("非法行为");
// break;
// case 404:
// errorResult.setMessage("未找到资源");
// break;
// case 405:
// errorResult.setMessage("非法请求方式");
// break;
// case 408:
// errorResult.setMessage("请求超时");
// break;
// case 500:
// errorResult.setMessage("服务器内部错误");
// break;
// case 502:
// errorResult.setMessage("服务器网关错误");
// break;
// case 504:
// errorResult.setMessage("服务器网关超时");
// break;
// default:
// errorResult.setMessage("未知响应:" + response.message());
// break;
// }
// }
// return errorResult;
// }
//
// @NonNull
// public static ErrorResult from(@NonNull Throwable t) {
// ErrorResult errorResult = new ErrorResult();
// errorResult.setSuccess(false);
// if (t instanceof UnknownHostException || t instanceof ConnectException) {
// errorResult.setMessage("网络无法连接");
// } else if (t instanceof NoRouteToHostException) {
// errorResult.setMessage("无法访问网络");
// } else if (t instanceof SocketTimeoutException) {
// errorResult.setMessage("网络访问超时");
// } else if (t instanceof JsonSyntaxException) {
// errorResult.setMessage("响应数据格式错误");
// } else {
// errorResult.setMessage("未知错误:" + t.getLocalizedMessage());
// }
// return errorResult;
// }
//
// @SerializedName("error_msg")
// private String message;
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/Result.java
// public class Result {
//
// private boolean success;
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ActivityUtils.java
// public final class ActivityUtils {
//
// private ActivityUtils() {}
//
// public static boolean isAlive(@Nullable Activity activity) {
// return activity != null && !(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && activity.isDestroyed()) && !activity.isFinishing();
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ToastUtils.java
// public final class ToastUtils {
//
// private volatile static ToastUtils singleton;
//
// public static ToastUtils with(@NonNull Context context) {
// if (singleton == null) {
// synchronized (ToastUtils.class) {
// if (singleton == null) {
// singleton = new ToastUtils(context);
// }
// }
// }
// return singleton;
// }
//
// private final Toast toast;
//
// @SuppressLint("ShowToast")
// private ToastUtils(@NonNull Context context) {
// toast = Toast.makeText(context.getApplicationContext(), null, Toast.LENGTH_SHORT);
// }
//
// public void show(CharSequence msg) {
// toast.setText(msg);
// toast.show();
// }
//
// public void show(@StringRes int resId) {
// toast.setText(resId);
// toast.show();
// }
//
// }
// Path: app/src/main/java/org/cnodejs/android/md/model/api/ToastCallback.java
import android.app.Activity;
import android.support.annotation.NonNull;
import org.cnodejs.android.md.model.entity.ErrorResult;
import org.cnodejs.android.md.model.entity.Result;
import org.cnodejs.android.md.ui.util.ActivityUtils;
import org.cnodejs.android.md.ui.util.ToastUtils;
import okhttp3.Headers;
package org.cnodejs.android.md.model.api;
public class ToastCallback<T extends Result> extends ForegroundCallback<T> {
public ToastCallback(@NonNull Activity activity) {
super(activity);
}
@Override
public boolean onResultError(int code, Headers headers, ErrorResult errorResult) {
return onAnyError(errorResult);
}
@Override
public boolean onCallException(Throwable t, ErrorResult errorResult) {
return onAnyError(errorResult);
}
public boolean onAnyError(ErrorResult errorResult) {
toastError(errorResult);
return false;
}
protected final void toastError(ErrorResult errorResult) {
Activity activity = getActivity();
if (ActivityUtils.isAlive(activity)) { | ToastUtils.with(activity).show(errorResult.getMessage()); |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/ui/dialog/AlertDialogUtils.java | // Path: app/src/main/java/org/cnodejs/android/md/model/storage/SettingShared.java
// public final class SettingShared {
//
// private SettingShared() {}
//
// private static final String TAG = "SettingShared";
//
// private static final String KEY_ENABLE_NOTIFICATION = "enableNotification";
// private static final String KEY_ENABLE_THEME_DARK = "enableThemeDark";
// private static final String KEY_ENABLE_TOPIC_DRAFT = "enableTopicDraft";
// private static final String KEY_ENABLE_TOPIC_SIGN = "enableTopicSign";
// private static final String KEY_TOPIC_SIGN_CONTENT = "topicSignContent";
// private static final String KEY_ENABLE_TOPIC_RENDER_COMPAT = "enableTopicRenderCompat";
// private static final String KEY_SHOW_TOPIC_RENDER_COMPAT_TIP = "showTopicRenderCompatTip";
//
// public static final String DEFAULT_TOPIC_SIGN_CONTENT = "来自酷炫的 [CNodeMD](https://github.com/TakWolf/CNode-Material-Design)";
//
// public static boolean isEnableNotification(@NonNull Context context) {
// return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_NOTIFICATION, true);
// }
//
// public static void setEnableNotification(@NonNull Context context, boolean enable) {
// SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_NOTIFICATION, enable);
// }
//
// public static boolean isEnableThemeDark(@NonNull Context context) {
// return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_THEME_DARK, false);
// }
//
// public static void setEnableThemeDark(@NonNull Context context, boolean enable) {
// SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_THEME_DARK, enable);
// }
//
// public static boolean isEnableTopicDraft(@NonNull Context context) {
// return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_DRAFT, true);
// }
//
// public static void setEnableTopicDraft(@NonNull Context context, boolean enable) {
// SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_DRAFT, enable);
// }
//
// public static boolean isEnableTopicSign(@NonNull Context context) {
// return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_SIGN, true);
// }
//
// public static void setEnableTopicSign(@NonNull Context context, boolean enable) {
// SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_SIGN, enable);
// }
//
// public static String getTopicSignContent(@NonNull Context context) {
// return SharedUtils.with(context, TAG).getString(KEY_TOPIC_SIGN_CONTENT, DEFAULT_TOPIC_SIGN_CONTENT);
// }
//
// public static void setTopicSignContent(@NonNull Context context, @Nullable String content) {
// SharedUtils.with(context, TAG).setString(KEY_TOPIC_SIGN_CONTENT, content);
// }
//
// public static boolean isEnableTopicRenderCompat(@NonNull Context context) {
// return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, true);
// }
//
// public static void setEnableTopicRenderCompat(@NonNull Context context, boolean enable) {
// SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, enable);
// }
//
// public static boolean isShowTopicRenderCompatTip(@NonNull Context context) {
// return SharedUtils.with(context, TAG).getBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, true);
// }
//
// public static void markShowTopicRenderCompatTip(@NonNull Context context) {
// SharedUtils.with(context, TAG).setBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, false);
// }
//
// }
| import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import org.cnodejs.android.md.R;
import org.cnodejs.android.md.model.storage.SettingShared; | package org.cnodejs.android.md.ui.dialog;
public final class AlertDialogUtils {
private AlertDialogUtils() {}
public static AlertDialog.Builder createBuilderWithAutoTheme(@NonNull Activity activity) { | // Path: app/src/main/java/org/cnodejs/android/md/model/storage/SettingShared.java
// public final class SettingShared {
//
// private SettingShared() {}
//
// private static final String TAG = "SettingShared";
//
// private static final String KEY_ENABLE_NOTIFICATION = "enableNotification";
// private static final String KEY_ENABLE_THEME_DARK = "enableThemeDark";
// private static final String KEY_ENABLE_TOPIC_DRAFT = "enableTopicDraft";
// private static final String KEY_ENABLE_TOPIC_SIGN = "enableTopicSign";
// private static final String KEY_TOPIC_SIGN_CONTENT = "topicSignContent";
// private static final String KEY_ENABLE_TOPIC_RENDER_COMPAT = "enableTopicRenderCompat";
// private static final String KEY_SHOW_TOPIC_RENDER_COMPAT_TIP = "showTopicRenderCompatTip";
//
// public static final String DEFAULT_TOPIC_SIGN_CONTENT = "来自酷炫的 [CNodeMD](https://github.com/TakWolf/CNode-Material-Design)";
//
// public static boolean isEnableNotification(@NonNull Context context) {
// return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_NOTIFICATION, true);
// }
//
// public static void setEnableNotification(@NonNull Context context, boolean enable) {
// SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_NOTIFICATION, enable);
// }
//
// public static boolean isEnableThemeDark(@NonNull Context context) {
// return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_THEME_DARK, false);
// }
//
// public static void setEnableThemeDark(@NonNull Context context, boolean enable) {
// SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_THEME_DARK, enable);
// }
//
// public static boolean isEnableTopicDraft(@NonNull Context context) {
// return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_DRAFT, true);
// }
//
// public static void setEnableTopicDraft(@NonNull Context context, boolean enable) {
// SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_DRAFT, enable);
// }
//
// public static boolean isEnableTopicSign(@NonNull Context context) {
// return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_SIGN, true);
// }
//
// public static void setEnableTopicSign(@NonNull Context context, boolean enable) {
// SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_SIGN, enable);
// }
//
// public static String getTopicSignContent(@NonNull Context context) {
// return SharedUtils.with(context, TAG).getString(KEY_TOPIC_SIGN_CONTENT, DEFAULT_TOPIC_SIGN_CONTENT);
// }
//
// public static void setTopicSignContent(@NonNull Context context, @Nullable String content) {
// SharedUtils.with(context, TAG).setString(KEY_TOPIC_SIGN_CONTENT, content);
// }
//
// public static boolean isEnableTopicRenderCompat(@NonNull Context context) {
// return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, true);
// }
//
// public static void setEnableTopicRenderCompat(@NonNull Context context, boolean enable) {
// SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, enable);
// }
//
// public static boolean isShowTopicRenderCompatTip(@NonNull Context context) {
// return SharedUtils.with(context, TAG).getBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, true);
// }
//
// public static void markShowTopicRenderCompatTip(@NonNull Context context) {
// SharedUtils.with(context, TAG).setBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, false);
// }
//
// }
// Path: app/src/main/java/org/cnodejs/android/md/ui/dialog/AlertDialogUtils.java
import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import org.cnodejs.android.md.R;
import org.cnodejs.android.md.model.storage.SettingShared;
package org.cnodejs.android.md.ui.dialog;
public final class AlertDialogUtils {
private AlertDialogUtils() {}
public static AlertDialog.Builder createBuilderWithAutoTheme(@NonNull Activity activity) { | return new AlertDialog.Builder(activity, SettingShared.isEnableThemeDark(activity) ? R.style.AppDialogDark_Alert : R.style.AppDialogLight_Alert); |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/ui/activity/LicenseActivity.java | // Path: app/src/main/java/org/cnodejs/android/md/ui/listener/NavigationFinishClickListener.java
// public class NavigationFinishClickListener implements View.OnClickListener {
//
// private final Activity activity;
//
// public NavigationFinishClickListener(@NonNull Activity activity) {
// this.activity = activity;
// }
//
// @Override
// public void onClick(View v) {
// ActivityCompat.finishAfterTransition(activity);
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ThemeUtils.java
// public final class ThemeUtils {
//
// private ThemeUtils() {}
//
// public static boolean configThemeBeforeOnCreate(@NonNull Activity activity, @StyleRes int light, @StyleRes int dark) {
// boolean enable = SettingShared.isEnableThemeDark(activity);
// activity.setTheme(enable ? dark : light);
// return enable;
// }
//
// public static void notifyThemeApply(@NonNull final Activity activity) {
// HandlerUtils.handler.post(new Runnable() {
//
// @Override
// public void run() {
// activity.recreate();
// }
//
// });
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ToastUtils.java
// public final class ToastUtils {
//
// private volatile static ToastUtils singleton;
//
// public static ToastUtils with(@NonNull Context context) {
// if (singleton == null) {
// synchronized (ToastUtils.class) {
// if (singleton == null) {
// singleton = new ToastUtils(context);
// }
// }
// }
// return singleton;
// }
//
// private final Toast toast;
//
// @SuppressLint("ShowToast")
// private ToastUtils(@NonNull Context context) {
// toast = Toast.makeText(context.getApplicationContext(), null, Toast.LENGTH_SHORT);
// }
//
// public void show(CharSequence msg) {
// toast.setText(msg);
// toast.show();
// }
//
// public void show(@StringRes int resId) {
// toast.setText(resId);
// toast.show();
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/util/ResUtils.java
// public final class ResUtils {
//
// private ResUtils() {}
//
// public static int getStatusBarHeight(@NonNull Context context) {
// int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
// return resourceId > 0 ? context.getResources().getDimensionPixelSize(resourceId) : 0;
// }
//
// @ColorInt
// public static int getThemeAttrColor(@NonNull Context context, @AttrRes int attr) {
// TypedArray a = context.obtainStyledAttributes(null, new int[]{attr});
// try {
// return a.getColor(0, 0);
// } finally {
// a.recycle();
// }
// }
//
// public static String getRawString(@NonNull Context context, @RawRes int rawId) throws IOException {
// InputStream is = context.getResources().openRawResource(rawId);
// BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
// StringBuilder sb = new StringBuilder();
// String line;
// while ((line = reader.readLine()) != null) {
// sb.append(line).append("\n");
// }
// if (sb.length() > 0) {
// sb.deleteCharAt(sb.length() - 1);
// }
// reader.close();
// return sb.toString();
// }
//
// }
| import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;
import org.cnodejs.android.md.R;
import org.cnodejs.android.md.ui.listener.NavigationFinishClickListener;
import org.cnodejs.android.md.ui.util.ThemeUtils;
import org.cnodejs.android.md.ui.util.ToastUtils;
import org.cnodejs.android.md.util.ResUtils;
import java.io.IOException;
import butterknife.BindView;
import butterknife.ButterKnife; | package org.cnodejs.android.md.ui.activity;
public class LicenseActivity extends StatusBarActivity {
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.tv_license)
TextView tvLicense;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) { | // Path: app/src/main/java/org/cnodejs/android/md/ui/listener/NavigationFinishClickListener.java
// public class NavigationFinishClickListener implements View.OnClickListener {
//
// private final Activity activity;
//
// public NavigationFinishClickListener(@NonNull Activity activity) {
// this.activity = activity;
// }
//
// @Override
// public void onClick(View v) {
// ActivityCompat.finishAfterTransition(activity);
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ThemeUtils.java
// public final class ThemeUtils {
//
// private ThemeUtils() {}
//
// public static boolean configThemeBeforeOnCreate(@NonNull Activity activity, @StyleRes int light, @StyleRes int dark) {
// boolean enable = SettingShared.isEnableThemeDark(activity);
// activity.setTheme(enable ? dark : light);
// return enable;
// }
//
// public static void notifyThemeApply(@NonNull final Activity activity) {
// HandlerUtils.handler.post(new Runnable() {
//
// @Override
// public void run() {
// activity.recreate();
// }
//
// });
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ToastUtils.java
// public final class ToastUtils {
//
// private volatile static ToastUtils singleton;
//
// public static ToastUtils with(@NonNull Context context) {
// if (singleton == null) {
// synchronized (ToastUtils.class) {
// if (singleton == null) {
// singleton = new ToastUtils(context);
// }
// }
// }
// return singleton;
// }
//
// private final Toast toast;
//
// @SuppressLint("ShowToast")
// private ToastUtils(@NonNull Context context) {
// toast = Toast.makeText(context.getApplicationContext(), null, Toast.LENGTH_SHORT);
// }
//
// public void show(CharSequence msg) {
// toast.setText(msg);
// toast.show();
// }
//
// public void show(@StringRes int resId) {
// toast.setText(resId);
// toast.show();
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/util/ResUtils.java
// public final class ResUtils {
//
// private ResUtils() {}
//
// public static int getStatusBarHeight(@NonNull Context context) {
// int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
// return resourceId > 0 ? context.getResources().getDimensionPixelSize(resourceId) : 0;
// }
//
// @ColorInt
// public static int getThemeAttrColor(@NonNull Context context, @AttrRes int attr) {
// TypedArray a = context.obtainStyledAttributes(null, new int[]{attr});
// try {
// return a.getColor(0, 0);
// } finally {
// a.recycle();
// }
// }
//
// public static String getRawString(@NonNull Context context, @RawRes int rawId) throws IOException {
// InputStream is = context.getResources().openRawResource(rawId);
// BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
// StringBuilder sb = new StringBuilder();
// String line;
// while ((line = reader.readLine()) != null) {
// sb.append(line).append("\n");
// }
// if (sb.length() > 0) {
// sb.deleteCharAt(sb.length() - 1);
// }
// reader.close();
// return sb.toString();
// }
//
// }
// Path: app/src/main/java/org/cnodejs/android/md/ui/activity/LicenseActivity.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;
import org.cnodejs.android.md.R;
import org.cnodejs.android.md.ui.listener.NavigationFinishClickListener;
import org.cnodejs.android.md.ui.util.ThemeUtils;
import org.cnodejs.android.md.ui.util.ToastUtils;
import org.cnodejs.android.md.util.ResUtils;
import java.io.IOException;
import butterknife.BindView;
import butterknife.ButterKnife;
package org.cnodejs.android.md.ui.activity;
public class LicenseActivity extends StatusBarActivity {
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.tv_license)
TextView tvLicense;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) { | ThemeUtils.configThemeBeforeOnCreate(this, R.style.AppThemeLight, R.style.AppThemeDark); |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/ui/activity/LicenseActivity.java | // Path: app/src/main/java/org/cnodejs/android/md/ui/listener/NavigationFinishClickListener.java
// public class NavigationFinishClickListener implements View.OnClickListener {
//
// private final Activity activity;
//
// public NavigationFinishClickListener(@NonNull Activity activity) {
// this.activity = activity;
// }
//
// @Override
// public void onClick(View v) {
// ActivityCompat.finishAfterTransition(activity);
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ThemeUtils.java
// public final class ThemeUtils {
//
// private ThemeUtils() {}
//
// public static boolean configThemeBeforeOnCreate(@NonNull Activity activity, @StyleRes int light, @StyleRes int dark) {
// boolean enable = SettingShared.isEnableThemeDark(activity);
// activity.setTheme(enable ? dark : light);
// return enable;
// }
//
// public static void notifyThemeApply(@NonNull final Activity activity) {
// HandlerUtils.handler.post(new Runnable() {
//
// @Override
// public void run() {
// activity.recreate();
// }
//
// });
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ToastUtils.java
// public final class ToastUtils {
//
// private volatile static ToastUtils singleton;
//
// public static ToastUtils with(@NonNull Context context) {
// if (singleton == null) {
// synchronized (ToastUtils.class) {
// if (singleton == null) {
// singleton = new ToastUtils(context);
// }
// }
// }
// return singleton;
// }
//
// private final Toast toast;
//
// @SuppressLint("ShowToast")
// private ToastUtils(@NonNull Context context) {
// toast = Toast.makeText(context.getApplicationContext(), null, Toast.LENGTH_SHORT);
// }
//
// public void show(CharSequence msg) {
// toast.setText(msg);
// toast.show();
// }
//
// public void show(@StringRes int resId) {
// toast.setText(resId);
// toast.show();
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/util/ResUtils.java
// public final class ResUtils {
//
// private ResUtils() {}
//
// public static int getStatusBarHeight(@NonNull Context context) {
// int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
// return resourceId > 0 ? context.getResources().getDimensionPixelSize(resourceId) : 0;
// }
//
// @ColorInt
// public static int getThemeAttrColor(@NonNull Context context, @AttrRes int attr) {
// TypedArray a = context.obtainStyledAttributes(null, new int[]{attr});
// try {
// return a.getColor(0, 0);
// } finally {
// a.recycle();
// }
// }
//
// public static String getRawString(@NonNull Context context, @RawRes int rawId) throws IOException {
// InputStream is = context.getResources().openRawResource(rawId);
// BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
// StringBuilder sb = new StringBuilder();
// String line;
// while ((line = reader.readLine()) != null) {
// sb.append(line).append("\n");
// }
// if (sb.length() > 0) {
// sb.deleteCharAt(sb.length() - 1);
// }
// reader.close();
// return sb.toString();
// }
//
// }
| import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;
import org.cnodejs.android.md.R;
import org.cnodejs.android.md.ui.listener.NavigationFinishClickListener;
import org.cnodejs.android.md.ui.util.ThemeUtils;
import org.cnodejs.android.md.ui.util.ToastUtils;
import org.cnodejs.android.md.util.ResUtils;
import java.io.IOException;
import butterknife.BindView;
import butterknife.ButterKnife; | package org.cnodejs.android.md.ui.activity;
public class LicenseActivity extends StatusBarActivity {
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.tv_license)
TextView tvLicense;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
ThemeUtils.configThemeBeforeOnCreate(this, R.style.AppThemeLight, R.style.AppThemeDark);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_license);
ButterKnife.bind(this);
| // Path: app/src/main/java/org/cnodejs/android/md/ui/listener/NavigationFinishClickListener.java
// public class NavigationFinishClickListener implements View.OnClickListener {
//
// private final Activity activity;
//
// public NavigationFinishClickListener(@NonNull Activity activity) {
// this.activity = activity;
// }
//
// @Override
// public void onClick(View v) {
// ActivityCompat.finishAfterTransition(activity);
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ThemeUtils.java
// public final class ThemeUtils {
//
// private ThemeUtils() {}
//
// public static boolean configThemeBeforeOnCreate(@NonNull Activity activity, @StyleRes int light, @StyleRes int dark) {
// boolean enable = SettingShared.isEnableThemeDark(activity);
// activity.setTheme(enable ? dark : light);
// return enable;
// }
//
// public static void notifyThemeApply(@NonNull final Activity activity) {
// HandlerUtils.handler.post(new Runnable() {
//
// @Override
// public void run() {
// activity.recreate();
// }
//
// });
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ToastUtils.java
// public final class ToastUtils {
//
// private volatile static ToastUtils singleton;
//
// public static ToastUtils with(@NonNull Context context) {
// if (singleton == null) {
// synchronized (ToastUtils.class) {
// if (singleton == null) {
// singleton = new ToastUtils(context);
// }
// }
// }
// return singleton;
// }
//
// private final Toast toast;
//
// @SuppressLint("ShowToast")
// private ToastUtils(@NonNull Context context) {
// toast = Toast.makeText(context.getApplicationContext(), null, Toast.LENGTH_SHORT);
// }
//
// public void show(CharSequence msg) {
// toast.setText(msg);
// toast.show();
// }
//
// public void show(@StringRes int resId) {
// toast.setText(resId);
// toast.show();
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/util/ResUtils.java
// public final class ResUtils {
//
// private ResUtils() {}
//
// public static int getStatusBarHeight(@NonNull Context context) {
// int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
// return resourceId > 0 ? context.getResources().getDimensionPixelSize(resourceId) : 0;
// }
//
// @ColorInt
// public static int getThemeAttrColor(@NonNull Context context, @AttrRes int attr) {
// TypedArray a = context.obtainStyledAttributes(null, new int[]{attr});
// try {
// return a.getColor(0, 0);
// } finally {
// a.recycle();
// }
// }
//
// public static String getRawString(@NonNull Context context, @RawRes int rawId) throws IOException {
// InputStream is = context.getResources().openRawResource(rawId);
// BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
// StringBuilder sb = new StringBuilder();
// String line;
// while ((line = reader.readLine()) != null) {
// sb.append(line).append("\n");
// }
// if (sb.length() > 0) {
// sb.deleteCharAt(sb.length() - 1);
// }
// reader.close();
// return sb.toString();
// }
//
// }
// Path: app/src/main/java/org/cnodejs/android/md/ui/activity/LicenseActivity.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;
import org.cnodejs.android.md.R;
import org.cnodejs.android.md.ui.listener.NavigationFinishClickListener;
import org.cnodejs.android.md.ui.util.ThemeUtils;
import org.cnodejs.android.md.ui.util.ToastUtils;
import org.cnodejs.android.md.util.ResUtils;
import java.io.IOException;
import butterknife.BindView;
import butterknife.ButterKnife;
package org.cnodejs.android.md.ui.activity;
public class LicenseActivity extends StatusBarActivity {
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.tv_license)
TextView tvLicense;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
ThemeUtils.configThemeBeforeOnCreate(this, R.style.AppThemeLight, R.style.AppThemeDark);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_license);
ButterKnife.bind(this);
| toolbar.setNavigationOnClickListener(new NavigationFinishClickListener(this)); |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/ui/activity/LicenseActivity.java | // Path: app/src/main/java/org/cnodejs/android/md/ui/listener/NavigationFinishClickListener.java
// public class NavigationFinishClickListener implements View.OnClickListener {
//
// private final Activity activity;
//
// public NavigationFinishClickListener(@NonNull Activity activity) {
// this.activity = activity;
// }
//
// @Override
// public void onClick(View v) {
// ActivityCompat.finishAfterTransition(activity);
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ThemeUtils.java
// public final class ThemeUtils {
//
// private ThemeUtils() {}
//
// public static boolean configThemeBeforeOnCreate(@NonNull Activity activity, @StyleRes int light, @StyleRes int dark) {
// boolean enable = SettingShared.isEnableThemeDark(activity);
// activity.setTheme(enable ? dark : light);
// return enable;
// }
//
// public static void notifyThemeApply(@NonNull final Activity activity) {
// HandlerUtils.handler.post(new Runnable() {
//
// @Override
// public void run() {
// activity.recreate();
// }
//
// });
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ToastUtils.java
// public final class ToastUtils {
//
// private volatile static ToastUtils singleton;
//
// public static ToastUtils with(@NonNull Context context) {
// if (singleton == null) {
// synchronized (ToastUtils.class) {
// if (singleton == null) {
// singleton = new ToastUtils(context);
// }
// }
// }
// return singleton;
// }
//
// private final Toast toast;
//
// @SuppressLint("ShowToast")
// private ToastUtils(@NonNull Context context) {
// toast = Toast.makeText(context.getApplicationContext(), null, Toast.LENGTH_SHORT);
// }
//
// public void show(CharSequence msg) {
// toast.setText(msg);
// toast.show();
// }
//
// public void show(@StringRes int resId) {
// toast.setText(resId);
// toast.show();
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/util/ResUtils.java
// public final class ResUtils {
//
// private ResUtils() {}
//
// public static int getStatusBarHeight(@NonNull Context context) {
// int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
// return resourceId > 0 ? context.getResources().getDimensionPixelSize(resourceId) : 0;
// }
//
// @ColorInt
// public static int getThemeAttrColor(@NonNull Context context, @AttrRes int attr) {
// TypedArray a = context.obtainStyledAttributes(null, new int[]{attr});
// try {
// return a.getColor(0, 0);
// } finally {
// a.recycle();
// }
// }
//
// public static String getRawString(@NonNull Context context, @RawRes int rawId) throws IOException {
// InputStream is = context.getResources().openRawResource(rawId);
// BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
// StringBuilder sb = new StringBuilder();
// String line;
// while ((line = reader.readLine()) != null) {
// sb.append(line).append("\n");
// }
// if (sb.length() > 0) {
// sb.deleteCharAt(sb.length() - 1);
// }
// reader.close();
// return sb.toString();
// }
//
// }
| import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;
import org.cnodejs.android.md.R;
import org.cnodejs.android.md.ui.listener.NavigationFinishClickListener;
import org.cnodejs.android.md.ui.util.ThemeUtils;
import org.cnodejs.android.md.ui.util.ToastUtils;
import org.cnodejs.android.md.util.ResUtils;
import java.io.IOException;
import butterknife.BindView;
import butterknife.ButterKnife; | package org.cnodejs.android.md.ui.activity;
public class LicenseActivity extends StatusBarActivity {
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.tv_license)
TextView tvLicense;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
ThemeUtils.configThemeBeforeOnCreate(this, R.style.AppThemeLight, R.style.AppThemeDark);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_license);
ButterKnife.bind(this);
toolbar.setNavigationOnClickListener(new NavigationFinishClickListener(this));
try { | // Path: app/src/main/java/org/cnodejs/android/md/ui/listener/NavigationFinishClickListener.java
// public class NavigationFinishClickListener implements View.OnClickListener {
//
// private final Activity activity;
//
// public NavigationFinishClickListener(@NonNull Activity activity) {
// this.activity = activity;
// }
//
// @Override
// public void onClick(View v) {
// ActivityCompat.finishAfterTransition(activity);
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ThemeUtils.java
// public final class ThemeUtils {
//
// private ThemeUtils() {}
//
// public static boolean configThemeBeforeOnCreate(@NonNull Activity activity, @StyleRes int light, @StyleRes int dark) {
// boolean enable = SettingShared.isEnableThemeDark(activity);
// activity.setTheme(enable ? dark : light);
// return enable;
// }
//
// public static void notifyThemeApply(@NonNull final Activity activity) {
// HandlerUtils.handler.post(new Runnable() {
//
// @Override
// public void run() {
// activity.recreate();
// }
//
// });
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ToastUtils.java
// public final class ToastUtils {
//
// private volatile static ToastUtils singleton;
//
// public static ToastUtils with(@NonNull Context context) {
// if (singleton == null) {
// synchronized (ToastUtils.class) {
// if (singleton == null) {
// singleton = new ToastUtils(context);
// }
// }
// }
// return singleton;
// }
//
// private final Toast toast;
//
// @SuppressLint("ShowToast")
// private ToastUtils(@NonNull Context context) {
// toast = Toast.makeText(context.getApplicationContext(), null, Toast.LENGTH_SHORT);
// }
//
// public void show(CharSequence msg) {
// toast.setText(msg);
// toast.show();
// }
//
// public void show(@StringRes int resId) {
// toast.setText(resId);
// toast.show();
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/util/ResUtils.java
// public final class ResUtils {
//
// private ResUtils() {}
//
// public static int getStatusBarHeight(@NonNull Context context) {
// int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
// return resourceId > 0 ? context.getResources().getDimensionPixelSize(resourceId) : 0;
// }
//
// @ColorInt
// public static int getThemeAttrColor(@NonNull Context context, @AttrRes int attr) {
// TypedArray a = context.obtainStyledAttributes(null, new int[]{attr});
// try {
// return a.getColor(0, 0);
// } finally {
// a.recycle();
// }
// }
//
// public static String getRawString(@NonNull Context context, @RawRes int rawId) throws IOException {
// InputStream is = context.getResources().openRawResource(rawId);
// BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
// StringBuilder sb = new StringBuilder();
// String line;
// while ((line = reader.readLine()) != null) {
// sb.append(line).append("\n");
// }
// if (sb.length() > 0) {
// sb.deleteCharAt(sb.length() - 1);
// }
// reader.close();
// return sb.toString();
// }
//
// }
// Path: app/src/main/java/org/cnodejs/android/md/ui/activity/LicenseActivity.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;
import org.cnodejs.android.md.R;
import org.cnodejs.android.md.ui.listener.NavigationFinishClickListener;
import org.cnodejs.android.md.ui.util.ThemeUtils;
import org.cnodejs.android.md.ui.util.ToastUtils;
import org.cnodejs.android.md.util.ResUtils;
import java.io.IOException;
import butterknife.BindView;
import butterknife.ButterKnife;
package org.cnodejs.android.md.ui.activity;
public class LicenseActivity extends StatusBarActivity {
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.tv_license)
TextView tvLicense;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
ThemeUtils.configThemeBeforeOnCreate(this, R.style.AppThemeLight, R.style.AppThemeDark);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_license);
ButterKnife.bind(this);
toolbar.setNavigationOnClickListener(new NavigationFinishClickListener(this));
try { | tvLicense.setText(ResUtils.getRawString(this, R.raw.open_source)); |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/ui/activity/LicenseActivity.java | // Path: app/src/main/java/org/cnodejs/android/md/ui/listener/NavigationFinishClickListener.java
// public class NavigationFinishClickListener implements View.OnClickListener {
//
// private final Activity activity;
//
// public NavigationFinishClickListener(@NonNull Activity activity) {
// this.activity = activity;
// }
//
// @Override
// public void onClick(View v) {
// ActivityCompat.finishAfterTransition(activity);
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ThemeUtils.java
// public final class ThemeUtils {
//
// private ThemeUtils() {}
//
// public static boolean configThemeBeforeOnCreate(@NonNull Activity activity, @StyleRes int light, @StyleRes int dark) {
// boolean enable = SettingShared.isEnableThemeDark(activity);
// activity.setTheme(enable ? dark : light);
// return enable;
// }
//
// public static void notifyThemeApply(@NonNull final Activity activity) {
// HandlerUtils.handler.post(new Runnable() {
//
// @Override
// public void run() {
// activity.recreate();
// }
//
// });
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ToastUtils.java
// public final class ToastUtils {
//
// private volatile static ToastUtils singleton;
//
// public static ToastUtils with(@NonNull Context context) {
// if (singleton == null) {
// synchronized (ToastUtils.class) {
// if (singleton == null) {
// singleton = new ToastUtils(context);
// }
// }
// }
// return singleton;
// }
//
// private final Toast toast;
//
// @SuppressLint("ShowToast")
// private ToastUtils(@NonNull Context context) {
// toast = Toast.makeText(context.getApplicationContext(), null, Toast.LENGTH_SHORT);
// }
//
// public void show(CharSequence msg) {
// toast.setText(msg);
// toast.show();
// }
//
// public void show(@StringRes int resId) {
// toast.setText(resId);
// toast.show();
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/util/ResUtils.java
// public final class ResUtils {
//
// private ResUtils() {}
//
// public static int getStatusBarHeight(@NonNull Context context) {
// int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
// return resourceId > 0 ? context.getResources().getDimensionPixelSize(resourceId) : 0;
// }
//
// @ColorInt
// public static int getThemeAttrColor(@NonNull Context context, @AttrRes int attr) {
// TypedArray a = context.obtainStyledAttributes(null, new int[]{attr});
// try {
// return a.getColor(0, 0);
// } finally {
// a.recycle();
// }
// }
//
// public static String getRawString(@NonNull Context context, @RawRes int rawId) throws IOException {
// InputStream is = context.getResources().openRawResource(rawId);
// BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
// StringBuilder sb = new StringBuilder();
// String line;
// while ((line = reader.readLine()) != null) {
// sb.append(line).append("\n");
// }
// if (sb.length() > 0) {
// sb.deleteCharAt(sb.length() - 1);
// }
// reader.close();
// return sb.toString();
// }
//
// }
| import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;
import org.cnodejs.android.md.R;
import org.cnodejs.android.md.ui.listener.NavigationFinishClickListener;
import org.cnodejs.android.md.ui.util.ThemeUtils;
import org.cnodejs.android.md.ui.util.ToastUtils;
import org.cnodejs.android.md.util.ResUtils;
import java.io.IOException;
import butterknife.BindView;
import butterknife.ButterKnife; | package org.cnodejs.android.md.ui.activity;
public class LicenseActivity extends StatusBarActivity {
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.tv_license)
TextView tvLicense;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
ThemeUtils.configThemeBeforeOnCreate(this, R.style.AppThemeLight, R.style.AppThemeDark);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_license);
ButterKnife.bind(this);
toolbar.setNavigationOnClickListener(new NavigationFinishClickListener(this));
try {
tvLicense.setText(ResUtils.getRawString(this, R.raw.open_source));
} catch (IOException e) {
tvLicense.setText(null); | // Path: app/src/main/java/org/cnodejs/android/md/ui/listener/NavigationFinishClickListener.java
// public class NavigationFinishClickListener implements View.OnClickListener {
//
// private final Activity activity;
//
// public NavigationFinishClickListener(@NonNull Activity activity) {
// this.activity = activity;
// }
//
// @Override
// public void onClick(View v) {
// ActivityCompat.finishAfterTransition(activity);
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ThemeUtils.java
// public final class ThemeUtils {
//
// private ThemeUtils() {}
//
// public static boolean configThemeBeforeOnCreate(@NonNull Activity activity, @StyleRes int light, @StyleRes int dark) {
// boolean enable = SettingShared.isEnableThemeDark(activity);
// activity.setTheme(enable ? dark : light);
// return enable;
// }
//
// public static void notifyThemeApply(@NonNull final Activity activity) {
// HandlerUtils.handler.post(new Runnable() {
//
// @Override
// public void run() {
// activity.recreate();
// }
//
// });
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ToastUtils.java
// public final class ToastUtils {
//
// private volatile static ToastUtils singleton;
//
// public static ToastUtils with(@NonNull Context context) {
// if (singleton == null) {
// synchronized (ToastUtils.class) {
// if (singleton == null) {
// singleton = new ToastUtils(context);
// }
// }
// }
// return singleton;
// }
//
// private final Toast toast;
//
// @SuppressLint("ShowToast")
// private ToastUtils(@NonNull Context context) {
// toast = Toast.makeText(context.getApplicationContext(), null, Toast.LENGTH_SHORT);
// }
//
// public void show(CharSequence msg) {
// toast.setText(msg);
// toast.show();
// }
//
// public void show(@StringRes int resId) {
// toast.setText(resId);
// toast.show();
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/util/ResUtils.java
// public final class ResUtils {
//
// private ResUtils() {}
//
// public static int getStatusBarHeight(@NonNull Context context) {
// int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
// return resourceId > 0 ? context.getResources().getDimensionPixelSize(resourceId) : 0;
// }
//
// @ColorInt
// public static int getThemeAttrColor(@NonNull Context context, @AttrRes int attr) {
// TypedArray a = context.obtainStyledAttributes(null, new int[]{attr});
// try {
// return a.getColor(0, 0);
// } finally {
// a.recycle();
// }
// }
//
// public static String getRawString(@NonNull Context context, @RawRes int rawId) throws IOException {
// InputStream is = context.getResources().openRawResource(rawId);
// BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
// StringBuilder sb = new StringBuilder();
// String line;
// while ((line = reader.readLine()) != null) {
// sb.append(line).append("\n");
// }
// if (sb.length() > 0) {
// sb.deleteCharAt(sb.length() - 1);
// }
// reader.close();
// return sb.toString();
// }
//
// }
// Path: app/src/main/java/org/cnodejs/android/md/ui/activity/LicenseActivity.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;
import org.cnodejs.android.md.R;
import org.cnodejs.android.md.ui.listener.NavigationFinishClickListener;
import org.cnodejs.android.md.ui.util.ThemeUtils;
import org.cnodejs.android.md.ui.util.ToastUtils;
import org.cnodejs.android.md.util.ResUtils;
import java.io.IOException;
import butterknife.BindView;
import butterknife.ButterKnife;
package org.cnodejs.android.md.ui.activity;
public class LicenseActivity extends StatusBarActivity {
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.tv_license)
TextView tvLicense;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
ThemeUtils.configThemeBeforeOnCreate(this, R.style.AppThemeLight, R.style.AppThemeDark);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_license);
ButterKnife.bind(this);
toolbar.setNavigationOnClickListener(new NavigationFinishClickListener(this));
try {
tvLicense.setText(ResUtils.getRawString(this, R.raw.open_source));
} catch (IOException e) {
tvLicense.setText(null); | ToastUtils.with(this).show("资源读取失败"); |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/model/entity/Author.java | // Path: app/src/main/java/org/cnodejs/android/md/util/FormatUtils.java
// public final class FormatUtils {
//
// private FormatUtils() {}
//
// /**
// * 获取最近时间字符串
// */
//
// private static final long MINUTE = 60 * 1000;
// private static final long HOUR = 60 * MINUTE;
// private static final long DAY = 24 * HOUR;
// private static final long WEEK = 7 * DAY;
// private static final long MONTH = 31 * DAY;
// private static final long YEAR = 12 * MONTH;
//
// public static String getRelativeTimeSpanString(@NonNull DateTime dateTime) {
// long offset = System.currentTimeMillis() - dateTime.getMillis();
// if (offset > YEAR) {
// return (offset / YEAR) + "年前";
// } else if (offset > MONTH) {
// return (offset / MONTH) + "个月前";
// } else if (offset > WEEK) {
// return (offset / WEEK) + "周前";
// } else if (offset > DAY) {
// return (offset / DAY) + "天前";
// } else if (offset > HOUR) {
// return (offset / HOUR) + "小时前";
// } else if (offset > MINUTE) {
// return (offset / MINUTE) + "分钟前";
// } else {
// return "刚刚";
// }
// }
//
// /**
// * 检测是否是用户accessToken
// */
// public static boolean isAccessToken(String accessToken) {
// if (TextUtils.isEmpty(accessToken)) {
// return false;
// } else {
// try {
// //noinspection ResultOfMethodCallIgnored
// UUID.fromString(accessToken);
// return true;
// } catch (Exception e) {
// return false;
// }
// }
// }
//
// /**
// * 修复头像地址的历史遗留问题
// */
// public static String getCompatAvatarUrl(String avatarUrl) {
// if (!TextUtils.isEmpty(avatarUrl) && avatarUrl.startsWith("//gravatar.com/avatar/")) {
// return "http:" + avatarUrl;
// } else {
// return avatarUrl;
// }
// }
//
// /**
// * 标准URL检测
// */
//
// public static boolean isUserLinkUrl(String url) {
// return !TextUtils.isEmpty(url) && url.startsWith(ApiDefine.USER_LINK_URL_PREFIX);
// }
//
// public static boolean isTopicLinkUrl(String url) {
// return !TextUtils.isEmpty(url) && url.startsWith(ApiDefine.TOPIC_LINK_URL_PREFIX);
// }
//
// /**
// * CNode兼容性的Markdown转换
// * '@'协议转换为'/user/'相对路径
// * 解析裸链接
// * 最外层包裹'<div class="markdown-text"></div>'
// * 尽可能的实现和服务端渲染相同的结果
// */
//
// private static final Markdown md = new Markdown();
//
// public static String renderMarkdown(String text) {
// // 保证text不为null
// text = TextUtils.isEmpty(text) ? "" : text;
// // 解析@协议
// text = text.replaceAll("@([\\w\\-]+)\\b(?![]<.])", "[@$1](" + ApiDefine.USER_PATH_PREFIX + "$1)");
// // 解析裸链接
// text = text + " ";
// text = text.replaceAll("((http|https|ftp)://[\\w\\-.:/?=&#%]+)(\\s)", "[$1]($1)$3");
// text = text.trim();
// // 渲染markdown
// try {
// StringWriter out = new StringWriter();
// md.transform(new StringReader(text), out);
// text = out.toString();
// } catch (ParseException e) {
// // nothing to do
// }
// // 添加样式容器
// return "<div class=\"markdown-text\">" + text + "</div>";
// }
//
// /**
// * CNode兼容性的Html处理
// * 过滤xss
// * 保留div的class属性,但是会清除其他非白名单属性
// * 通过baseUrl补全相对地址
// */
//
// private static final Cleaner cleaner = new Cleaner(Whitelist.relaxed().addAttributes("div", "class")); // 主要目的是保留最外层div的markdown-text属性
//
// public static Document handleHtml(String html) {
// // 保证html不为null
// html = TextUtils.isEmpty(html) ? "" : html;
// // 过滤xss
// return cleaner.clean(Jsoup.parseBodyFragment(html, ApiDefine.HOST_BASE_URL));
// }
//
// }
| import com.google.gson.annotations.SerializedName;
import org.cnodejs.android.md.util.FormatUtils; | package org.cnodejs.android.md.model.entity;
public class Author {
@SerializedName("loginname")
private String loginName;
@SerializedName("avatar_url")
private String avatarUrl;
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getAvatarUrl() { // 修复头像地址的历史遗留问题 | // Path: app/src/main/java/org/cnodejs/android/md/util/FormatUtils.java
// public final class FormatUtils {
//
// private FormatUtils() {}
//
// /**
// * 获取最近时间字符串
// */
//
// private static final long MINUTE = 60 * 1000;
// private static final long HOUR = 60 * MINUTE;
// private static final long DAY = 24 * HOUR;
// private static final long WEEK = 7 * DAY;
// private static final long MONTH = 31 * DAY;
// private static final long YEAR = 12 * MONTH;
//
// public static String getRelativeTimeSpanString(@NonNull DateTime dateTime) {
// long offset = System.currentTimeMillis() - dateTime.getMillis();
// if (offset > YEAR) {
// return (offset / YEAR) + "年前";
// } else if (offset > MONTH) {
// return (offset / MONTH) + "个月前";
// } else if (offset > WEEK) {
// return (offset / WEEK) + "周前";
// } else if (offset > DAY) {
// return (offset / DAY) + "天前";
// } else if (offset > HOUR) {
// return (offset / HOUR) + "小时前";
// } else if (offset > MINUTE) {
// return (offset / MINUTE) + "分钟前";
// } else {
// return "刚刚";
// }
// }
//
// /**
// * 检测是否是用户accessToken
// */
// public static boolean isAccessToken(String accessToken) {
// if (TextUtils.isEmpty(accessToken)) {
// return false;
// } else {
// try {
// //noinspection ResultOfMethodCallIgnored
// UUID.fromString(accessToken);
// return true;
// } catch (Exception e) {
// return false;
// }
// }
// }
//
// /**
// * 修复头像地址的历史遗留问题
// */
// public static String getCompatAvatarUrl(String avatarUrl) {
// if (!TextUtils.isEmpty(avatarUrl) && avatarUrl.startsWith("//gravatar.com/avatar/")) {
// return "http:" + avatarUrl;
// } else {
// return avatarUrl;
// }
// }
//
// /**
// * 标准URL检测
// */
//
// public static boolean isUserLinkUrl(String url) {
// return !TextUtils.isEmpty(url) && url.startsWith(ApiDefine.USER_LINK_URL_PREFIX);
// }
//
// public static boolean isTopicLinkUrl(String url) {
// return !TextUtils.isEmpty(url) && url.startsWith(ApiDefine.TOPIC_LINK_URL_PREFIX);
// }
//
// /**
// * CNode兼容性的Markdown转换
// * '@'协议转换为'/user/'相对路径
// * 解析裸链接
// * 最外层包裹'<div class="markdown-text"></div>'
// * 尽可能的实现和服务端渲染相同的结果
// */
//
// private static final Markdown md = new Markdown();
//
// public static String renderMarkdown(String text) {
// // 保证text不为null
// text = TextUtils.isEmpty(text) ? "" : text;
// // 解析@协议
// text = text.replaceAll("@([\\w\\-]+)\\b(?![]<.])", "[@$1](" + ApiDefine.USER_PATH_PREFIX + "$1)");
// // 解析裸链接
// text = text + " ";
// text = text.replaceAll("((http|https|ftp)://[\\w\\-.:/?=&#%]+)(\\s)", "[$1]($1)$3");
// text = text.trim();
// // 渲染markdown
// try {
// StringWriter out = new StringWriter();
// md.transform(new StringReader(text), out);
// text = out.toString();
// } catch (ParseException e) {
// // nothing to do
// }
// // 添加样式容器
// return "<div class=\"markdown-text\">" + text + "</div>";
// }
//
// /**
// * CNode兼容性的Html处理
// * 过滤xss
// * 保留div的class属性,但是会清除其他非白名单属性
// * 通过baseUrl补全相对地址
// */
//
// private static final Cleaner cleaner = new Cleaner(Whitelist.relaxed().addAttributes("div", "class")); // 主要目的是保留最外层div的markdown-text属性
//
// public static Document handleHtml(String html) {
// // 保证html不为null
// html = TextUtils.isEmpty(html) ? "" : html;
// // 过滤xss
// return cleaner.clean(Jsoup.parseBodyFragment(html, ApiDefine.HOST_BASE_URL));
// }
//
// }
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/Author.java
import com.google.gson.annotations.SerializedName;
import org.cnodejs.android.md.util.FormatUtils;
package org.cnodejs.android.md.model.entity;
public class Author {
@SerializedName("loginname")
private String loginName;
@SerializedName("avatar_url")
private String avatarUrl;
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getAvatarUrl() { // 修复头像地址的历史遗留问题 | return FormatUtils.getCompatAvatarUrl(avatarUrl); |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/ui/listener/FloatingActionButtonBehaviorListener.java | // Path: app/src/main/java/org/cnodejs/android/md/ui/widget/CNodeWebView.java
// public abstract class CNodeWebView extends WebView {
//
// private final WebViewClient webViewClient = new WebViewClient() {
//
// @Override
// public boolean shouldOverrideUrlLoading(WebView webView, String url) {
// if (!TextUtils.isEmpty(url) && !Navigator.openStandardLink(webView.getContext(), url)) {
// Navigator.openInBrowser(webView.getContext(), url);
// }
// return true;
// }
//
// @Override
// public void onPageFinished(WebView view, String url) {
// CNodeWebView.this.onPageFinished(url);
// }
//
// };
//
// private boolean darkTheme;
// private List<OnScrollListener> onScrollListenerList;
//
// public CNodeWebView(@NonNull Context context) {
// super(context);
// init(context, null, 0, 0);
// }
//
// public CNodeWebView(@NonNull Context context, @Nullable AttributeSet attrs) {
// super(context, attrs);
// init(context, attrs, 0, 0);
// }
//
// public CNodeWebView(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// init(context, attrs, defStyleAttr, 0);
// }
//
// @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
// public CNodeWebView(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {
// super(context, attrs, defStyleAttr, defStyleRes);
// init(context, attrs, defStyleAttr, defStyleRes);
// }
//
// @SuppressLint("SetJavaScriptEnabled")
// private void init(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {
// TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CNodeWebView, defStyleAttr, defStyleRes);
// darkTheme = a.getBoolean(R.styleable.CNodeWebView_darkTheme, false);
// a.recycle();
//
// getSettings().setJavaScriptEnabled(true);
// setWebViewClient(webViewClient);
// }
//
// public boolean isDarkTheme() {
// return darkTheme;
// }
//
// protected void onPageFinished(String url) {}
//
// @Override
// protected void onScrollChanged(int l, int t, int oldl, int oldt) {
// super.onScrollChanged(l, t, oldl, oldt);
// if (onScrollListenerList != null && onScrollListenerList.size() > 0) {
// for (OnScrollListener onScrollListener : onScrollListenerList) {
// onScrollListener.onScrollChanged(l, t, oldl, oldt);
// }
// }
// }
//
// public void addOnScrollListener(OnScrollListener listener) {
// if (onScrollListenerList == null) {
// onScrollListenerList = new ArrayList<>();
// }
// onScrollListenerList.add(listener);
// }
//
// public void removeOnScrollListener(OnScrollListener listener) {
// if (onScrollListenerList != null) {
// onScrollListenerList.remove(listener);
// }
// }
//
// public void clearOnScrollListeners() {
// if (onScrollListenerList != null) {
// onScrollListenerList.clear();
// }
// }
//
// public interface OnScrollListener {
//
// void onScrollChanged(int l, int t, int oldl, int oldt);
//
// }
//
// }
| import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.RecyclerView;
import org.cnodejs.android.md.ui.widget.CNodeWebView; | package org.cnodejs.android.md.ui.listener;
public final class FloatingActionButtonBehaviorListener {
private FloatingActionButtonBehaviorListener() {}
private static final int SCROLL_THRESHOLD = 4;
public static class ForRecyclerView extends RecyclerView.OnScrollListener {
private final FloatingActionButton floatingActionButton;
public ForRecyclerView(@NonNull FloatingActionButton floatingActionButton) {
this.floatingActionButton = floatingActionButton;
}
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
if (dy > SCROLL_THRESHOLD) {
floatingActionButton.hide();
} else if (dy < -SCROLL_THRESHOLD) {
floatingActionButton.show();
}
}
}
| // Path: app/src/main/java/org/cnodejs/android/md/ui/widget/CNodeWebView.java
// public abstract class CNodeWebView extends WebView {
//
// private final WebViewClient webViewClient = new WebViewClient() {
//
// @Override
// public boolean shouldOverrideUrlLoading(WebView webView, String url) {
// if (!TextUtils.isEmpty(url) && !Navigator.openStandardLink(webView.getContext(), url)) {
// Navigator.openInBrowser(webView.getContext(), url);
// }
// return true;
// }
//
// @Override
// public void onPageFinished(WebView view, String url) {
// CNodeWebView.this.onPageFinished(url);
// }
//
// };
//
// private boolean darkTheme;
// private List<OnScrollListener> onScrollListenerList;
//
// public CNodeWebView(@NonNull Context context) {
// super(context);
// init(context, null, 0, 0);
// }
//
// public CNodeWebView(@NonNull Context context, @Nullable AttributeSet attrs) {
// super(context, attrs);
// init(context, attrs, 0, 0);
// }
//
// public CNodeWebView(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// init(context, attrs, defStyleAttr, 0);
// }
//
// @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
// public CNodeWebView(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {
// super(context, attrs, defStyleAttr, defStyleRes);
// init(context, attrs, defStyleAttr, defStyleRes);
// }
//
// @SuppressLint("SetJavaScriptEnabled")
// private void init(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {
// TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CNodeWebView, defStyleAttr, defStyleRes);
// darkTheme = a.getBoolean(R.styleable.CNodeWebView_darkTheme, false);
// a.recycle();
//
// getSettings().setJavaScriptEnabled(true);
// setWebViewClient(webViewClient);
// }
//
// public boolean isDarkTheme() {
// return darkTheme;
// }
//
// protected void onPageFinished(String url) {}
//
// @Override
// protected void onScrollChanged(int l, int t, int oldl, int oldt) {
// super.onScrollChanged(l, t, oldl, oldt);
// if (onScrollListenerList != null && onScrollListenerList.size() > 0) {
// for (OnScrollListener onScrollListener : onScrollListenerList) {
// onScrollListener.onScrollChanged(l, t, oldl, oldt);
// }
// }
// }
//
// public void addOnScrollListener(OnScrollListener listener) {
// if (onScrollListenerList == null) {
// onScrollListenerList = new ArrayList<>();
// }
// onScrollListenerList.add(listener);
// }
//
// public void removeOnScrollListener(OnScrollListener listener) {
// if (onScrollListenerList != null) {
// onScrollListenerList.remove(listener);
// }
// }
//
// public void clearOnScrollListeners() {
// if (onScrollListenerList != null) {
// onScrollListenerList.clear();
// }
// }
//
// public interface OnScrollListener {
//
// void onScrollChanged(int l, int t, int oldl, int oldt);
//
// }
//
// }
// Path: app/src/main/java/org/cnodejs/android/md/ui/listener/FloatingActionButtonBehaviorListener.java
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.RecyclerView;
import org.cnodejs.android.md.ui.widget.CNodeWebView;
package org.cnodejs.android.md.ui.listener;
public final class FloatingActionButtonBehaviorListener {
private FloatingActionButtonBehaviorListener() {}
private static final int SCROLL_THRESHOLD = 4;
public static class ForRecyclerView extends RecyclerView.OnScrollListener {
private final FloatingActionButton floatingActionButton;
public ForRecyclerView(@NonNull FloatingActionButton floatingActionButton) {
this.floatingActionButton = floatingActionButton;
}
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
if (dy > SCROLL_THRESHOLD) {
floatingActionButton.hide();
} else if (dy < -SCROLL_THRESHOLD) {
floatingActionButton.show();
}
}
}
| public static class ForWebView implements CNodeWebView.OnScrollListener { |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/model/entity/User.java | // Path: app/src/main/java/org/cnodejs/android/md/util/FormatUtils.java
// public final class FormatUtils {
//
// private FormatUtils() {}
//
// /**
// * 获取最近时间字符串
// */
//
// private static final long MINUTE = 60 * 1000;
// private static final long HOUR = 60 * MINUTE;
// private static final long DAY = 24 * HOUR;
// private static final long WEEK = 7 * DAY;
// private static final long MONTH = 31 * DAY;
// private static final long YEAR = 12 * MONTH;
//
// public static String getRelativeTimeSpanString(@NonNull DateTime dateTime) {
// long offset = System.currentTimeMillis() - dateTime.getMillis();
// if (offset > YEAR) {
// return (offset / YEAR) + "年前";
// } else if (offset > MONTH) {
// return (offset / MONTH) + "个月前";
// } else if (offset > WEEK) {
// return (offset / WEEK) + "周前";
// } else if (offset > DAY) {
// return (offset / DAY) + "天前";
// } else if (offset > HOUR) {
// return (offset / HOUR) + "小时前";
// } else if (offset > MINUTE) {
// return (offset / MINUTE) + "分钟前";
// } else {
// return "刚刚";
// }
// }
//
// /**
// * 检测是否是用户accessToken
// */
// public static boolean isAccessToken(String accessToken) {
// if (TextUtils.isEmpty(accessToken)) {
// return false;
// } else {
// try {
// //noinspection ResultOfMethodCallIgnored
// UUID.fromString(accessToken);
// return true;
// } catch (Exception e) {
// return false;
// }
// }
// }
//
// /**
// * 修复头像地址的历史遗留问题
// */
// public static String getCompatAvatarUrl(String avatarUrl) {
// if (!TextUtils.isEmpty(avatarUrl) && avatarUrl.startsWith("//gravatar.com/avatar/")) {
// return "http:" + avatarUrl;
// } else {
// return avatarUrl;
// }
// }
//
// /**
// * 标准URL检测
// */
//
// public static boolean isUserLinkUrl(String url) {
// return !TextUtils.isEmpty(url) && url.startsWith(ApiDefine.USER_LINK_URL_PREFIX);
// }
//
// public static boolean isTopicLinkUrl(String url) {
// return !TextUtils.isEmpty(url) && url.startsWith(ApiDefine.TOPIC_LINK_URL_PREFIX);
// }
//
// /**
// * CNode兼容性的Markdown转换
// * '@'协议转换为'/user/'相对路径
// * 解析裸链接
// * 最外层包裹'<div class="markdown-text"></div>'
// * 尽可能的实现和服务端渲染相同的结果
// */
//
// private static final Markdown md = new Markdown();
//
// public static String renderMarkdown(String text) {
// // 保证text不为null
// text = TextUtils.isEmpty(text) ? "" : text;
// // 解析@协议
// text = text.replaceAll("@([\\w\\-]+)\\b(?![]<.])", "[@$1](" + ApiDefine.USER_PATH_PREFIX + "$1)");
// // 解析裸链接
// text = text + " ";
// text = text.replaceAll("((http|https|ftp)://[\\w\\-.:/?=&#%]+)(\\s)", "[$1]($1)$3");
// text = text.trim();
// // 渲染markdown
// try {
// StringWriter out = new StringWriter();
// md.transform(new StringReader(text), out);
// text = out.toString();
// } catch (ParseException e) {
// // nothing to do
// }
// // 添加样式容器
// return "<div class=\"markdown-text\">" + text + "</div>";
// }
//
// /**
// * CNode兼容性的Html处理
// * 过滤xss
// * 保留div的class属性,但是会清除其他非白名单属性
// * 通过baseUrl补全相对地址
// */
//
// private static final Cleaner cleaner = new Cleaner(Whitelist.relaxed().addAttributes("div", "class")); // 主要目的是保留最外层div的markdown-text属性
//
// public static Document handleHtml(String html) {
// // 保证html不为null
// html = TextUtils.isEmpty(html) ? "" : html;
// // 过滤xss
// return cleaner.clean(Jsoup.parseBodyFragment(html, ApiDefine.HOST_BASE_URL));
// }
//
// }
| import com.google.gson.annotations.SerializedName;
import org.cnodejs.android.md.util.FormatUtils;
import org.joda.time.DateTime;
import java.util.List; | package org.cnodejs.android.md.model.entity;
public class User {
@SerializedName("loginname")
private String loginName;
@SerializedName("avatar_url")
private String avatarUrl;
private String githubUsername;
@SerializedName("create_at")
private DateTime createAt;
private int score;
@SerializedName("recent_topics")
private List<TopicSimple> recentTopicList;
@SerializedName("recent_replies")
private List<TopicSimple> recentReplyList;
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getAvatarUrl() { // 修复头像地址的历史遗留问题 | // Path: app/src/main/java/org/cnodejs/android/md/util/FormatUtils.java
// public final class FormatUtils {
//
// private FormatUtils() {}
//
// /**
// * 获取最近时间字符串
// */
//
// private static final long MINUTE = 60 * 1000;
// private static final long HOUR = 60 * MINUTE;
// private static final long DAY = 24 * HOUR;
// private static final long WEEK = 7 * DAY;
// private static final long MONTH = 31 * DAY;
// private static final long YEAR = 12 * MONTH;
//
// public static String getRelativeTimeSpanString(@NonNull DateTime dateTime) {
// long offset = System.currentTimeMillis() - dateTime.getMillis();
// if (offset > YEAR) {
// return (offset / YEAR) + "年前";
// } else if (offset > MONTH) {
// return (offset / MONTH) + "个月前";
// } else if (offset > WEEK) {
// return (offset / WEEK) + "周前";
// } else if (offset > DAY) {
// return (offset / DAY) + "天前";
// } else if (offset > HOUR) {
// return (offset / HOUR) + "小时前";
// } else if (offset > MINUTE) {
// return (offset / MINUTE) + "分钟前";
// } else {
// return "刚刚";
// }
// }
//
// /**
// * 检测是否是用户accessToken
// */
// public static boolean isAccessToken(String accessToken) {
// if (TextUtils.isEmpty(accessToken)) {
// return false;
// } else {
// try {
// //noinspection ResultOfMethodCallIgnored
// UUID.fromString(accessToken);
// return true;
// } catch (Exception e) {
// return false;
// }
// }
// }
//
// /**
// * 修复头像地址的历史遗留问题
// */
// public static String getCompatAvatarUrl(String avatarUrl) {
// if (!TextUtils.isEmpty(avatarUrl) && avatarUrl.startsWith("//gravatar.com/avatar/")) {
// return "http:" + avatarUrl;
// } else {
// return avatarUrl;
// }
// }
//
// /**
// * 标准URL检测
// */
//
// public static boolean isUserLinkUrl(String url) {
// return !TextUtils.isEmpty(url) && url.startsWith(ApiDefine.USER_LINK_URL_PREFIX);
// }
//
// public static boolean isTopicLinkUrl(String url) {
// return !TextUtils.isEmpty(url) && url.startsWith(ApiDefine.TOPIC_LINK_URL_PREFIX);
// }
//
// /**
// * CNode兼容性的Markdown转换
// * '@'协议转换为'/user/'相对路径
// * 解析裸链接
// * 最外层包裹'<div class="markdown-text"></div>'
// * 尽可能的实现和服务端渲染相同的结果
// */
//
// private static final Markdown md = new Markdown();
//
// public static String renderMarkdown(String text) {
// // 保证text不为null
// text = TextUtils.isEmpty(text) ? "" : text;
// // 解析@协议
// text = text.replaceAll("@([\\w\\-]+)\\b(?![]<.])", "[@$1](" + ApiDefine.USER_PATH_PREFIX + "$1)");
// // 解析裸链接
// text = text + " ";
// text = text.replaceAll("((http|https|ftp)://[\\w\\-.:/?=&#%]+)(\\s)", "[$1]($1)$3");
// text = text.trim();
// // 渲染markdown
// try {
// StringWriter out = new StringWriter();
// md.transform(new StringReader(text), out);
// text = out.toString();
// } catch (ParseException e) {
// // nothing to do
// }
// // 添加样式容器
// return "<div class=\"markdown-text\">" + text + "</div>";
// }
//
// /**
// * CNode兼容性的Html处理
// * 过滤xss
// * 保留div的class属性,但是会清除其他非白名单属性
// * 通过baseUrl补全相对地址
// */
//
// private static final Cleaner cleaner = new Cleaner(Whitelist.relaxed().addAttributes("div", "class")); // 主要目的是保留最外层div的markdown-text属性
//
// public static Document handleHtml(String html) {
// // 保证html不为null
// html = TextUtils.isEmpty(html) ? "" : html;
// // 过滤xss
// return cleaner.clean(Jsoup.parseBodyFragment(html, ApiDefine.HOST_BASE_URL));
// }
//
// }
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/User.java
import com.google.gson.annotations.SerializedName;
import org.cnodejs.android.md.util.FormatUtils;
import org.joda.time.DateTime;
import java.util.List;
package org.cnodejs.android.md.model.entity;
public class User {
@SerializedName("loginname")
private String loginName;
@SerializedName("avatar_url")
private String avatarUrl;
private String githubUsername;
@SerializedName("create_at")
private DateTime createAt;
private int score;
@SerializedName("recent_topics")
private List<TopicSimple> recentTopicList;
@SerializedName("recent_replies")
private List<TopicSimple> recentReplyList;
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getAvatarUrl() { // 修复头像地址的历史遗留问题 | return FormatUtils.getCompatAvatarUrl(avatarUrl); |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/ui/activity/LaunchActivity.java | // Path: app/src/main/java/org/cnodejs/android/md/ui/util/ActivityUtils.java
// public final class ActivityUtils {
//
// private ActivityUtils() {}
//
// public static boolean isAlive(@Nullable Activity activity) {
// return activity != null && !(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && activity.isDestroyed()) && !activity.isFinishing();
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/util/HandlerUtils.java
// public final class HandlerUtils {
//
// private HandlerUtils() {}
//
// public static final Handler handler = new Handler(Looper.getMainLooper());
//
// }
| import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import org.cnodejs.android.md.R;
import org.cnodejs.android.md.ui.util.ActivityUtils;
import org.cnodejs.android.md.util.HandlerUtils; | package org.cnodejs.android.md.ui.activity;
public class LaunchActivity extends BaseActivity implements Runnable {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launch);
if (!isTaskRoot()) {
finish();
return;
}
| // Path: app/src/main/java/org/cnodejs/android/md/ui/util/ActivityUtils.java
// public final class ActivityUtils {
//
// private ActivityUtils() {}
//
// public static boolean isAlive(@Nullable Activity activity) {
// return activity != null && !(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && activity.isDestroyed()) && !activity.isFinishing();
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/util/HandlerUtils.java
// public final class HandlerUtils {
//
// private HandlerUtils() {}
//
// public static final Handler handler = new Handler(Looper.getMainLooper());
//
// }
// Path: app/src/main/java/org/cnodejs/android/md/ui/activity/LaunchActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import org.cnodejs.android.md.R;
import org.cnodejs.android.md.ui.util.ActivityUtils;
import org.cnodejs.android.md.util.HandlerUtils;
package org.cnodejs.android.md.ui.activity;
public class LaunchActivity extends BaseActivity implements Runnable {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launch);
if (!isTaskRoot()) {
finish();
return;
}
| HandlerUtils.handler.postDelayed(this, 1000); |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/ui/activity/LaunchActivity.java | // Path: app/src/main/java/org/cnodejs/android/md/ui/util/ActivityUtils.java
// public final class ActivityUtils {
//
// private ActivityUtils() {}
//
// public static boolean isAlive(@Nullable Activity activity) {
// return activity != null && !(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && activity.isDestroyed()) && !activity.isFinishing();
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/util/HandlerUtils.java
// public final class HandlerUtils {
//
// private HandlerUtils() {}
//
// public static final Handler handler = new Handler(Looper.getMainLooper());
//
// }
| import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import org.cnodejs.android.md.R;
import org.cnodejs.android.md.ui.util.ActivityUtils;
import org.cnodejs.android.md.util.HandlerUtils; | package org.cnodejs.android.md.ui.activity;
public class LaunchActivity extends BaseActivity implements Runnable {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launch);
if (!isTaskRoot()) {
finish();
return;
}
HandlerUtils.handler.postDelayed(this, 1000);
}
@Override
protected void onDestroy() {
HandlerUtils.handler.removeCallbacks(this);
super.onDestroy();
}
@Override
public void run() { | // Path: app/src/main/java/org/cnodejs/android/md/ui/util/ActivityUtils.java
// public final class ActivityUtils {
//
// private ActivityUtils() {}
//
// public static boolean isAlive(@Nullable Activity activity) {
// return activity != null && !(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && activity.isDestroyed()) && !activity.isFinishing();
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/util/HandlerUtils.java
// public final class HandlerUtils {
//
// private HandlerUtils() {}
//
// public static final Handler handler = new Handler(Looper.getMainLooper());
//
// }
// Path: app/src/main/java/org/cnodejs/android/md/ui/activity/LaunchActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import org.cnodejs.android.md.R;
import org.cnodejs.android.md.ui.util.ActivityUtils;
import org.cnodejs.android.md.util.HandlerUtils;
package org.cnodejs.android.md.ui.activity;
public class LaunchActivity extends BaseActivity implements Runnable {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launch);
if (!isTaskRoot()) {
finish();
return;
}
HandlerUtils.handler.postDelayed(this, 1000);
}
@Override
protected void onDestroy() {
HandlerUtils.handler.removeCallbacks(this);
super.onDestroy();
}
@Override
public void run() { | if (ActivityUtils.isAlive(this)) { |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/model/api/BackgroundCallback.java | // Path: app/src/main/java/org/cnodejs/android/md/model/entity/ErrorResult.java
// public class ErrorResult extends Result {
//
// @NonNull
// public static ErrorResult from(@NonNull Response response) {
// ErrorResult errorResult = null;
// ResponseBody errorBody = response.errorBody();
// if (errorBody != null) {
// try {
// errorResult = EntityUtils.gson.fromJson(errorBody.string(), ErrorResult.class);
// } catch (Throwable ignored) {}
// }
// if (errorResult == null) {
// errorResult = new ErrorResult();
// errorResult.setSuccess(false);
// switch (response.code()) {
// case 400:
// errorResult.setMessage("非法请求");
// break;
// case 403:
// errorResult.setMessage("非法行为");
// break;
// case 404:
// errorResult.setMessage("未找到资源");
// break;
// case 405:
// errorResult.setMessage("非法请求方式");
// break;
// case 408:
// errorResult.setMessage("请求超时");
// break;
// case 500:
// errorResult.setMessage("服务器内部错误");
// break;
// case 502:
// errorResult.setMessage("服务器网关错误");
// break;
// case 504:
// errorResult.setMessage("服务器网关超时");
// break;
// default:
// errorResult.setMessage("未知响应:" + response.message());
// break;
// }
// }
// return errorResult;
// }
//
// @NonNull
// public static ErrorResult from(@NonNull Throwable t) {
// ErrorResult errorResult = new ErrorResult();
// errorResult.setSuccess(false);
// if (t instanceof UnknownHostException || t instanceof ConnectException) {
// errorResult.setMessage("网络无法连接");
// } else if (t instanceof NoRouteToHostException) {
// errorResult.setMessage("无法访问网络");
// } else if (t instanceof SocketTimeoutException) {
// errorResult.setMessage("网络访问超时");
// } else if (t instanceof JsonSyntaxException) {
// errorResult.setMessage("响应数据格式错误");
// } else {
// errorResult.setMessage("未知错误:" + t.getLocalizedMessage());
// }
// return errorResult;
// }
//
// @SerializedName("error_msg")
// private String message;
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/Result.java
// public class Result {
//
// private boolean success;
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// }
| import android.support.annotation.NonNull;
import org.cnodejs.android.md.model.entity.ErrorResult;
import org.cnodejs.android.md.model.entity.Result;
import okhttp3.Headers;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response; | package org.cnodejs.android.md.model.api;
public class BackgroundCallback<T extends Result> implements Callback<T>, CallbackLifecycle<T> {
@Override
public final void onResponse(@NonNull Call<T> call, @NonNull Response<T> response) {
boolean interrupt;
if (response.isSuccessful()) {
interrupt = onResultOk(response.code(), response.headers(), response.body());
} else { | // Path: app/src/main/java/org/cnodejs/android/md/model/entity/ErrorResult.java
// public class ErrorResult extends Result {
//
// @NonNull
// public static ErrorResult from(@NonNull Response response) {
// ErrorResult errorResult = null;
// ResponseBody errorBody = response.errorBody();
// if (errorBody != null) {
// try {
// errorResult = EntityUtils.gson.fromJson(errorBody.string(), ErrorResult.class);
// } catch (Throwable ignored) {}
// }
// if (errorResult == null) {
// errorResult = new ErrorResult();
// errorResult.setSuccess(false);
// switch (response.code()) {
// case 400:
// errorResult.setMessage("非法请求");
// break;
// case 403:
// errorResult.setMessage("非法行为");
// break;
// case 404:
// errorResult.setMessage("未找到资源");
// break;
// case 405:
// errorResult.setMessage("非法请求方式");
// break;
// case 408:
// errorResult.setMessage("请求超时");
// break;
// case 500:
// errorResult.setMessage("服务器内部错误");
// break;
// case 502:
// errorResult.setMessage("服务器网关错误");
// break;
// case 504:
// errorResult.setMessage("服务器网关超时");
// break;
// default:
// errorResult.setMessage("未知响应:" + response.message());
// break;
// }
// }
// return errorResult;
// }
//
// @NonNull
// public static ErrorResult from(@NonNull Throwable t) {
// ErrorResult errorResult = new ErrorResult();
// errorResult.setSuccess(false);
// if (t instanceof UnknownHostException || t instanceof ConnectException) {
// errorResult.setMessage("网络无法连接");
// } else if (t instanceof NoRouteToHostException) {
// errorResult.setMessage("无法访问网络");
// } else if (t instanceof SocketTimeoutException) {
// errorResult.setMessage("网络访问超时");
// } else if (t instanceof JsonSyntaxException) {
// errorResult.setMessage("响应数据格式错误");
// } else {
// errorResult.setMessage("未知错误:" + t.getLocalizedMessage());
// }
// return errorResult;
// }
//
// @SerializedName("error_msg")
// private String message;
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/Result.java
// public class Result {
//
// private boolean success;
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// }
// Path: app/src/main/java/org/cnodejs/android/md/model/api/BackgroundCallback.java
import android.support.annotation.NonNull;
import org.cnodejs.android.md.model.entity.ErrorResult;
import org.cnodejs.android.md.model.entity.Result;
import okhttp3.Headers;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
package org.cnodejs.android.md.model.api;
public class BackgroundCallback<T extends Result> implements Callback<T>, CallbackLifecycle<T> {
@Override
public final void onResponse(@NonNull Call<T> call, @NonNull Response<T> response) {
boolean interrupt;
if (response.isSuccessful()) {
interrupt = onResultOk(response.code(), response.headers(), response.body());
} else { | interrupt = onResultError(response.code(), response.headers(), ErrorResult.from(response)); |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/ui/view/ITopicView.java | // Path: app/src/main/java/org/cnodejs/android/md/model/entity/Reply.java
// public class Reply {
//
// public enum UpAction {
// up,
// down
// }
//
// private String id;
//
// private Author author;
//
// private String content;
//
// @SerializedName("ups")
// private List<String> upList;
//
// @SerializedName("reply_id")
// private String replyId;
//
// @SerializedName("create_at")
// private DateTime createAt;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Author getAuthor() {
// return author;
// }
//
// public void setAuthor(Author author) {
// this.author = author;
// }
//
// public String getContent() {
// return content;
// }
//
// public void setContent(String content) {
// this.content = content;
// cleanContentCache();
// }
//
// public List<String> getUpList() {
// return upList;
// }
//
// public void setUpList(List<String> upList) {
// this.upList = upList;
// }
//
// public String getReplyId() {
// return replyId;
// }
//
// public void setReplyId(String replyId) {
// this.replyId = replyId;
// }
//
// public DateTime getCreateAt() {
// return createAt;
// }
//
// public void setCreateAt(DateTime createAt) {
// this.createAt = createAt;
// }
//
// /**
// * Html渲染缓存
// */
//
// @SerializedName("content_html")
// private String contentHtml;
//
// @SerializedName("content_summary")
// private String contentSummary;
//
// public void markSureHandleContent() {
// if (contentHtml == null || contentSummary == null) {
// Document document;
// if (ApiDefine.MD_RENDER) {
// document = FormatUtils.handleHtml(content);
// } else {
// document = FormatUtils.handleHtml(FormatUtils.renderMarkdown(content));
// }
// if (contentHtml == null) {
// contentHtml = document.body().html();
// }
// if (contentSummary == null) {
// contentSummary = document.body().text().trim();
// }
// }
// }
//
// public void cleanContentCache() {
// contentHtml = null;
// contentSummary = null;
// }
//
// public String getContentHtml() {
// markSureHandleContent();
// return contentHtml;
// }
//
// public String getContentSummary() {
// markSureHandleContent();
// return contentSummary;
// }
//
// public void setContentFromLocal(String content) {
// if (ApiDefine.MD_RENDER) {
// this.content = FormatUtils.renderMarkdown(content);
// } else {
// this.content = content;
// }
// cleanContentCache();
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/TopicWithReply.java
// public class TopicWithReply extends Topic {
//
// @SerializedName("is_collect")
// private boolean isCollect; // 是否收藏该话题,只有调用时带有 accesstoken 时,这个字段才有可能为 true
//
// @SerializedName("replies")
// private List<Reply> replyList;
//
// public boolean isCollect() {
// return isCollect;
// }
//
// public void setCollect(boolean collect) {
// isCollect = collect;
// }
//
// public List<Reply> getReplyList() {
// return replyList;
// }
//
// public void setReplyList(List<Reply> replyList) {
// this.replyList = replyList;
// }
//
// }
| import android.support.annotation.NonNull;
import org.cnodejs.android.md.model.entity.Reply;
import org.cnodejs.android.md.model.entity.TopicWithReply; | package org.cnodejs.android.md.ui.view;
public interface ITopicView {
void onGetTopicOk(@NonNull TopicWithReply topic);
void onGetTopicFinish();
| // Path: app/src/main/java/org/cnodejs/android/md/model/entity/Reply.java
// public class Reply {
//
// public enum UpAction {
// up,
// down
// }
//
// private String id;
//
// private Author author;
//
// private String content;
//
// @SerializedName("ups")
// private List<String> upList;
//
// @SerializedName("reply_id")
// private String replyId;
//
// @SerializedName("create_at")
// private DateTime createAt;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Author getAuthor() {
// return author;
// }
//
// public void setAuthor(Author author) {
// this.author = author;
// }
//
// public String getContent() {
// return content;
// }
//
// public void setContent(String content) {
// this.content = content;
// cleanContentCache();
// }
//
// public List<String> getUpList() {
// return upList;
// }
//
// public void setUpList(List<String> upList) {
// this.upList = upList;
// }
//
// public String getReplyId() {
// return replyId;
// }
//
// public void setReplyId(String replyId) {
// this.replyId = replyId;
// }
//
// public DateTime getCreateAt() {
// return createAt;
// }
//
// public void setCreateAt(DateTime createAt) {
// this.createAt = createAt;
// }
//
// /**
// * Html渲染缓存
// */
//
// @SerializedName("content_html")
// private String contentHtml;
//
// @SerializedName("content_summary")
// private String contentSummary;
//
// public void markSureHandleContent() {
// if (contentHtml == null || contentSummary == null) {
// Document document;
// if (ApiDefine.MD_RENDER) {
// document = FormatUtils.handleHtml(content);
// } else {
// document = FormatUtils.handleHtml(FormatUtils.renderMarkdown(content));
// }
// if (contentHtml == null) {
// contentHtml = document.body().html();
// }
// if (contentSummary == null) {
// contentSummary = document.body().text().trim();
// }
// }
// }
//
// public void cleanContentCache() {
// contentHtml = null;
// contentSummary = null;
// }
//
// public String getContentHtml() {
// markSureHandleContent();
// return contentHtml;
// }
//
// public String getContentSummary() {
// markSureHandleContent();
// return contentSummary;
// }
//
// public void setContentFromLocal(String content) {
// if (ApiDefine.MD_RENDER) {
// this.content = FormatUtils.renderMarkdown(content);
// } else {
// this.content = content;
// }
// cleanContentCache();
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/TopicWithReply.java
// public class TopicWithReply extends Topic {
//
// @SerializedName("is_collect")
// private boolean isCollect; // 是否收藏该话题,只有调用时带有 accesstoken 时,这个字段才有可能为 true
//
// @SerializedName("replies")
// private List<Reply> replyList;
//
// public boolean isCollect() {
// return isCollect;
// }
//
// public void setCollect(boolean collect) {
// isCollect = collect;
// }
//
// public List<Reply> getReplyList() {
// return replyList;
// }
//
// public void setReplyList(List<Reply> replyList) {
// this.replyList = replyList;
// }
//
// }
// Path: app/src/main/java/org/cnodejs/android/md/ui/view/ITopicView.java
import android.support.annotation.NonNull;
import org.cnodejs.android.md.model.entity.Reply;
import org.cnodejs.android.md.model.entity.TopicWithReply;
package org.cnodejs.android.md.ui.view;
public interface ITopicView {
void onGetTopicOk(@NonNull TopicWithReply topic);
void onGetTopicFinish();
| void appendReplyAndUpdateViews(@NonNull Reply reply); |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/model/storage/SettingShared.java | // Path: app/src/main/java/org/cnodejs/android/md/model/util/SharedUtils.java
// public final class SharedUtils {
//
// private SharedUtils() {}
//
// private static final String TAG = "SharedUtils";
//
// @NonNull
// public static SharedPreferencesWrapper with(@NonNull Context context, @NonNull String name) {
// return new SharedPreferencesWrapper(context.getSharedPreferences(DigestUtils.sha256.getHex(name), Context.MODE_PRIVATE));
// }
//
// public static class SharedPreferencesWrapper {
//
// private final SharedPreferences sharedPreferences;
//
// private SharedPreferencesWrapper(@NonNull SharedPreferences sharedPreferences) {
// this.sharedPreferences = sharedPreferences;
// }
//
// @NonNull
// public SharedPreferences getSharedPreferences() {
// return sharedPreferences;
// }
//
// @NonNull
// public SharedPreferencesWrapper clear() {
// sharedPreferences.edit().clear().apply();
// return this;
// }
//
// public String getString(@NonNull String key, @Nullable String defValue) {
// try {
// return sharedPreferences.getString(key, defValue);
// } catch (ClassCastException e) {
// Log.e(TAG, "Get string value error.", e);
// return defValue;
// }
// }
//
// @NonNull
// public SharedPreferencesWrapper setString(@NonNull String key, @Nullable String value) {
// sharedPreferences.edit().putString(key, value).apply();
// return this;
// }
//
// public boolean getBoolean(@NonNull String key, boolean defValue) {
// try {
// return sharedPreferences.getBoolean(key, defValue);
// } catch (ClassCastException e) {
// Log.e(TAG, "Get boolean value error.", e);
// return defValue;
// }
// }
//
// @NonNull
// public SharedPreferencesWrapper setBoolean(@NonNull String key, boolean value) {
// sharedPreferences.edit().putBoolean(key, value).apply();
// return this;
// }
//
// public float getFloat(@NonNull String key, float defValue) {
// try {
// return sharedPreferences.getFloat(key, defValue);
// } catch (ClassCastException e) {
// Log.e(TAG, "Get float value error.", e);
// return defValue;
// }
// }
//
// @NonNull
// public SharedPreferencesWrapper setFloat(@NonNull String key, float value) {
// sharedPreferences.edit().putFloat(key, value).apply();
// return this;
// }
//
// public int getInt(@NonNull String key, int defValue) {
// try {
// return sharedPreferences.getInt(key, defValue);
// } catch (ClassCastException e) {
// Log.e(TAG, "Get int value error.", e);
// return defValue;
// }
// }
//
// @NonNull
// public SharedPreferencesWrapper setInt(@NonNull String key, int value) {
// sharedPreferences.edit().putInt(key, value).apply();
// return this;
// }
//
// public long getLong(@NonNull String key, long defValue) {
// try {
// return sharedPreferences.getLong(key, defValue);
// } catch (ClassCastException e) {
// Log.e(TAG, "Get long value error.", e);
// return defValue;
// }
// }
//
// @NonNull
// public SharedPreferencesWrapper setLong(@NonNull String key, long value) {
// sharedPreferences.edit().putLong(key, value).apply();
// return this;
// }
//
// public <T> T getObject(@NonNull String key, @NonNull Type typeOfT) {
// String value = getString(key, null);
// if (value == null) {
// return null;
// } else {
// try {
// return EntityUtils.gson.fromJson(value, typeOfT);
// } catch (JsonParseException e) {
// Log.e(TAG, "Get object value error.", e);
// return null;
// }
// }
// }
//
// @NonNull
// public SharedPreferencesWrapper setObject(@NonNull String key, @Nullable Object value) {
// setString(key, value == null ? null : EntityUtils.gson.toJson(value));
// return this;
// }
//
// }
//
// }
| import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import org.cnodejs.android.md.model.util.SharedUtils; | package org.cnodejs.android.md.model.storage;
public final class SettingShared {
private SettingShared() {}
private static final String TAG = "SettingShared";
private static final String KEY_ENABLE_NOTIFICATION = "enableNotification";
private static final String KEY_ENABLE_THEME_DARK = "enableThemeDark";
private static final String KEY_ENABLE_TOPIC_DRAFT = "enableTopicDraft";
private static final String KEY_ENABLE_TOPIC_SIGN = "enableTopicSign";
private static final String KEY_TOPIC_SIGN_CONTENT = "topicSignContent";
private static final String KEY_ENABLE_TOPIC_RENDER_COMPAT = "enableTopicRenderCompat";
private static final String KEY_SHOW_TOPIC_RENDER_COMPAT_TIP = "showTopicRenderCompatTip";
public static final String DEFAULT_TOPIC_SIGN_CONTENT = "来自酷炫的 [CNodeMD](https://github.com/TakWolf/CNode-Material-Design)";
public static boolean isEnableNotification(@NonNull Context context) { | // Path: app/src/main/java/org/cnodejs/android/md/model/util/SharedUtils.java
// public final class SharedUtils {
//
// private SharedUtils() {}
//
// private static final String TAG = "SharedUtils";
//
// @NonNull
// public static SharedPreferencesWrapper with(@NonNull Context context, @NonNull String name) {
// return new SharedPreferencesWrapper(context.getSharedPreferences(DigestUtils.sha256.getHex(name), Context.MODE_PRIVATE));
// }
//
// public static class SharedPreferencesWrapper {
//
// private final SharedPreferences sharedPreferences;
//
// private SharedPreferencesWrapper(@NonNull SharedPreferences sharedPreferences) {
// this.sharedPreferences = sharedPreferences;
// }
//
// @NonNull
// public SharedPreferences getSharedPreferences() {
// return sharedPreferences;
// }
//
// @NonNull
// public SharedPreferencesWrapper clear() {
// sharedPreferences.edit().clear().apply();
// return this;
// }
//
// public String getString(@NonNull String key, @Nullable String defValue) {
// try {
// return sharedPreferences.getString(key, defValue);
// } catch (ClassCastException e) {
// Log.e(TAG, "Get string value error.", e);
// return defValue;
// }
// }
//
// @NonNull
// public SharedPreferencesWrapper setString(@NonNull String key, @Nullable String value) {
// sharedPreferences.edit().putString(key, value).apply();
// return this;
// }
//
// public boolean getBoolean(@NonNull String key, boolean defValue) {
// try {
// return sharedPreferences.getBoolean(key, defValue);
// } catch (ClassCastException e) {
// Log.e(TAG, "Get boolean value error.", e);
// return defValue;
// }
// }
//
// @NonNull
// public SharedPreferencesWrapper setBoolean(@NonNull String key, boolean value) {
// sharedPreferences.edit().putBoolean(key, value).apply();
// return this;
// }
//
// public float getFloat(@NonNull String key, float defValue) {
// try {
// return sharedPreferences.getFloat(key, defValue);
// } catch (ClassCastException e) {
// Log.e(TAG, "Get float value error.", e);
// return defValue;
// }
// }
//
// @NonNull
// public SharedPreferencesWrapper setFloat(@NonNull String key, float value) {
// sharedPreferences.edit().putFloat(key, value).apply();
// return this;
// }
//
// public int getInt(@NonNull String key, int defValue) {
// try {
// return sharedPreferences.getInt(key, defValue);
// } catch (ClassCastException e) {
// Log.e(TAG, "Get int value error.", e);
// return defValue;
// }
// }
//
// @NonNull
// public SharedPreferencesWrapper setInt(@NonNull String key, int value) {
// sharedPreferences.edit().putInt(key, value).apply();
// return this;
// }
//
// public long getLong(@NonNull String key, long defValue) {
// try {
// return sharedPreferences.getLong(key, defValue);
// } catch (ClassCastException e) {
// Log.e(TAG, "Get long value error.", e);
// return defValue;
// }
// }
//
// @NonNull
// public SharedPreferencesWrapper setLong(@NonNull String key, long value) {
// sharedPreferences.edit().putLong(key, value).apply();
// return this;
// }
//
// public <T> T getObject(@NonNull String key, @NonNull Type typeOfT) {
// String value = getString(key, null);
// if (value == null) {
// return null;
// } else {
// try {
// return EntityUtils.gson.fromJson(value, typeOfT);
// } catch (JsonParseException e) {
// Log.e(TAG, "Get object value error.", e);
// return null;
// }
// }
// }
//
// @NonNull
// public SharedPreferencesWrapper setObject(@NonNull String key, @Nullable Object value) {
// setString(key, value == null ? null : EntityUtils.gson.toJson(value));
// return this;
// }
//
// }
//
// }
// Path: app/src/main/java/org/cnodejs/android/md/model/storage/SettingShared.java
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import org.cnodejs.android.md.model.util.SharedUtils;
package org.cnodejs.android.md.model.storage;
public final class SettingShared {
private SettingShared() {}
private static final String TAG = "SettingShared";
private static final String KEY_ENABLE_NOTIFICATION = "enableNotification";
private static final String KEY_ENABLE_THEME_DARK = "enableThemeDark";
private static final String KEY_ENABLE_TOPIC_DRAFT = "enableTopicDraft";
private static final String KEY_ENABLE_TOPIC_SIGN = "enableTopicSign";
private static final String KEY_TOPIC_SIGN_CONTENT = "topicSignContent";
private static final String KEY_ENABLE_TOPIC_RENDER_COMPAT = "enableTopicRenderCompat";
private static final String KEY_SHOW_TOPIC_RENDER_COMPAT_TIP = "showTopicRenderCompatTip";
public static final String DEFAULT_TOPIC_SIGN_CONTENT = "来自酷炫的 [CNodeMD](https://github.com/TakWolf/CNode-Material-Design)";
public static boolean isEnableNotification(@NonNull Context context) { | return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_NOTIFICATION, true); |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/ui/widget/AdaptStatusBarView.java | // Path: app/src/main/java/org/cnodejs/android/md/util/ResUtils.java
// public final class ResUtils {
//
// private ResUtils() {}
//
// public static int getStatusBarHeight(@NonNull Context context) {
// int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
// return resourceId > 0 ? context.getResources().getDimensionPixelSize(resourceId) : 0;
// }
//
// @ColorInt
// public static int getThemeAttrColor(@NonNull Context context, @AttrRes int attr) {
// TypedArray a = context.obtainStyledAttributes(null, new int[]{attr});
// try {
// return a.getColor(0, 0);
// } finally {
// a.recycle();
// }
// }
//
// public static String getRawString(@NonNull Context context, @RawRes int rawId) throws IOException {
// InputStream is = context.getResources().openRawResource(rawId);
// BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
// StringBuilder sb = new StringBuilder();
// String line;
// while ((line = reader.readLine()) != null) {
// sb.append(line).append("\n");
// }
// if (sb.length() > 0) {
// sb.deleteCharAt(sb.length() - 1);
// }
// reader.close();
// return sb.toString();
// }
//
// }
| import android.content.Context;
import android.os.Build;
import android.support.annotation.AttrRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.annotation.StyleRes;
import android.util.AttributeSet;
import android.view.View;
import org.cnodejs.android.md.util.ResUtils; | package org.cnodejs.android.md.ui.widget;
public class AdaptStatusBarView extends View {
public AdaptStatusBarView(@NonNull Context context) {
super(context);
}
public AdaptStatusBarView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public AdaptStatusBarView(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public AdaptStatusBarView(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { | // Path: app/src/main/java/org/cnodejs/android/md/util/ResUtils.java
// public final class ResUtils {
//
// private ResUtils() {}
//
// public static int getStatusBarHeight(@NonNull Context context) {
// int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
// return resourceId > 0 ? context.getResources().getDimensionPixelSize(resourceId) : 0;
// }
//
// @ColorInt
// public static int getThemeAttrColor(@NonNull Context context, @AttrRes int attr) {
// TypedArray a = context.obtainStyledAttributes(null, new int[]{attr});
// try {
// return a.getColor(0, 0);
// } finally {
// a.recycle();
// }
// }
//
// public static String getRawString(@NonNull Context context, @RawRes int rawId) throws IOException {
// InputStream is = context.getResources().openRawResource(rawId);
// BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
// StringBuilder sb = new StringBuilder();
// String line;
// while ((line = reader.readLine()) != null) {
// sb.append(line).append("\n");
// }
// if (sb.length() > 0) {
// sb.deleteCharAt(sb.length() - 1);
// }
// reader.close();
// return sb.toString();
// }
//
// }
// Path: app/src/main/java/org/cnodejs/android/md/ui/widget/AdaptStatusBarView.java
import android.content.Context;
import android.os.Build;
import android.support.annotation.AttrRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.annotation.StyleRes;
import android.util.AttributeSet;
import android.view.View;
import org.cnodejs.android.md.util.ResUtils;
package org.cnodejs.android.md.ui.widget;
public class AdaptStatusBarView extends View {
public AdaptStatusBarView(@NonNull Context context) {
super(context);
}
public AdaptStatusBarView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public AdaptStatusBarView(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public AdaptStatusBarView(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { | setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), ResUtils.getStatusBarHeight(getContext())); |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/ui/holder/TopicSimpleListController.java | // Path: app/src/main/java/org/cnodejs/android/md/ui/adapter/TopicSimpleListAdapter.java
// public class TopicSimpleListAdapter extends RecyclerView.Adapter<TopicSimpleListAdapter.ViewHolder> {
//
// private final Activity activity;
// private final LayoutInflater inflater;
// private final List<TopicSimple> topicSimpleList = new ArrayList<>();
//
// public TopicSimpleListAdapter(@NonNull Activity activity) {
// this.activity = activity;
// inflater = LayoutInflater.from(activity);
// }
//
// public void setTopicSimpleListAndNotify(@NonNull List<TopicSimple> topicSimpleList) {
// this.topicSimpleList.clear();
// this.topicSimpleList.addAll(topicSimpleList);
// notifyDataSetChanged();
// }
//
// @Override
// public int getItemCount() {
// return topicSimpleList.size();
// }
//
// @NonNull
// @Override
// public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
// return new ViewHolder(inflater.inflate(R.layout.item_topic_simple, parent, false));
// }
//
// @Override
// public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
// holder.bind(topicSimpleList.get(position), position == topicSimpleList.size() - 1);
// }
//
// class ViewHolder extends RecyclerView.ViewHolder {
//
// @BindView(R.id.img_avatar)
// ImageView imgAvatar;
//
// @BindView(R.id.tv_title)
// TextView tvTitle;
//
// @BindView(R.id.tv_login_name)
// TextView tvLoginName;
//
// @BindView(R.id.tv_last_reply_time)
// TextView tvLastReplyTime;
//
// @BindView(R.id.icon_deep_line)
// View iconDeepLine;
//
// @BindView(R.id.icon_shadow_gap)
// View iconShadowGap;
//
// private TopicSimple topicSimple;
//
// ViewHolder(@NonNull View itemView) {
// super(itemView);
// ButterKnife.bind(this, itemView);
// }
//
// void bind(@NonNull TopicSimple topicSimple, boolean isTheLast) {
// this.topicSimple = topicSimple;
//
// tvTitle.setText(topicSimple.getTitle());
// GlideApp.with(activity).load(topicSimple.getAuthor().getAvatarUrl()).placeholder(R.drawable.image_placeholder).into(imgAvatar);
// tvLoginName.setText(topicSimple.getAuthor().getLoginName());
// tvLastReplyTime.setText(FormatUtils.getRelativeTimeSpanString(topicSimple.getLastReplyAt()));
// iconDeepLine.setVisibility(isTheLast ? View.GONE : View.VISIBLE);
// iconShadowGap.setVisibility(isTheLast ? View.VISIBLE : View.GONE);
// }
//
// @OnClick(R.id.img_avatar)
// void onBtnAvatarClick() {
// UserDetailActivity.startWithTransitionAnimation(activity, topicSimple.getAuthor().getLoginName(), imgAvatar, topicSimple.getAuthor().getAvatarUrl());
// }
//
// @OnClick(R.id.btn_item)
// void onBtnItemClick() {
// Navigator.TopicWithAutoCompat.start(activity, topicSimple.getId());
// }
//
// }
//
// }
| import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import org.cnodejs.android.md.R;
import org.cnodejs.android.md.model.entity.TopicSimple;
import org.cnodejs.android.md.ui.adapter.TopicSimpleListAdapter;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife; | package org.cnodejs.android.md.ui.holder;
public class TopicSimpleListController {
public static TopicSimpleListController assertType(@NonNull Object object) {
if (object instanceof TopicSimpleListController) {
return (TopicSimpleListController) object;
} else {
throw new AssertionError("Impossible controller type.");
}
}
@BindView(R.id.recycler_view)
RecyclerView recyclerView;
private final View contentView; | // Path: app/src/main/java/org/cnodejs/android/md/ui/adapter/TopicSimpleListAdapter.java
// public class TopicSimpleListAdapter extends RecyclerView.Adapter<TopicSimpleListAdapter.ViewHolder> {
//
// private final Activity activity;
// private final LayoutInflater inflater;
// private final List<TopicSimple> topicSimpleList = new ArrayList<>();
//
// public TopicSimpleListAdapter(@NonNull Activity activity) {
// this.activity = activity;
// inflater = LayoutInflater.from(activity);
// }
//
// public void setTopicSimpleListAndNotify(@NonNull List<TopicSimple> topicSimpleList) {
// this.topicSimpleList.clear();
// this.topicSimpleList.addAll(topicSimpleList);
// notifyDataSetChanged();
// }
//
// @Override
// public int getItemCount() {
// return topicSimpleList.size();
// }
//
// @NonNull
// @Override
// public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
// return new ViewHolder(inflater.inflate(R.layout.item_topic_simple, parent, false));
// }
//
// @Override
// public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
// holder.bind(topicSimpleList.get(position), position == topicSimpleList.size() - 1);
// }
//
// class ViewHolder extends RecyclerView.ViewHolder {
//
// @BindView(R.id.img_avatar)
// ImageView imgAvatar;
//
// @BindView(R.id.tv_title)
// TextView tvTitle;
//
// @BindView(R.id.tv_login_name)
// TextView tvLoginName;
//
// @BindView(R.id.tv_last_reply_time)
// TextView tvLastReplyTime;
//
// @BindView(R.id.icon_deep_line)
// View iconDeepLine;
//
// @BindView(R.id.icon_shadow_gap)
// View iconShadowGap;
//
// private TopicSimple topicSimple;
//
// ViewHolder(@NonNull View itemView) {
// super(itemView);
// ButterKnife.bind(this, itemView);
// }
//
// void bind(@NonNull TopicSimple topicSimple, boolean isTheLast) {
// this.topicSimple = topicSimple;
//
// tvTitle.setText(topicSimple.getTitle());
// GlideApp.with(activity).load(topicSimple.getAuthor().getAvatarUrl()).placeholder(R.drawable.image_placeholder).into(imgAvatar);
// tvLoginName.setText(topicSimple.getAuthor().getLoginName());
// tvLastReplyTime.setText(FormatUtils.getRelativeTimeSpanString(topicSimple.getLastReplyAt()));
// iconDeepLine.setVisibility(isTheLast ? View.GONE : View.VISIBLE);
// iconShadowGap.setVisibility(isTheLast ? View.VISIBLE : View.GONE);
// }
//
// @OnClick(R.id.img_avatar)
// void onBtnAvatarClick() {
// UserDetailActivity.startWithTransitionAnimation(activity, topicSimple.getAuthor().getLoginName(), imgAvatar, topicSimple.getAuthor().getAvatarUrl());
// }
//
// @OnClick(R.id.btn_item)
// void onBtnItemClick() {
// Navigator.TopicWithAutoCompat.start(activity, topicSimple.getId());
// }
//
// }
//
// }
// Path: app/src/main/java/org/cnodejs/android/md/ui/holder/TopicSimpleListController.java
import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import org.cnodejs.android.md.R;
import org.cnodejs.android.md.model.entity.TopicSimple;
import org.cnodejs.android.md.ui.adapter.TopicSimpleListAdapter;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
package org.cnodejs.android.md.ui.holder;
public class TopicSimpleListController {
public static TopicSimpleListController assertType(@NonNull Object object) {
if (object instanceof TopicSimpleListController) {
return (TopicSimpleListController) object;
} else {
throw new AssertionError("Impossible controller type.");
}
}
@BindView(R.id.recycler_view)
RecyclerView recyclerView;
private final View contentView; | private final TopicSimpleListAdapter adapter; |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/ui/activity/StandardLinkRouterActivity.java | // Path: app/src/main/java/org/cnodejs/android/md/ui/util/Navigator.java
// public final class Navigator {
//
// private Navigator() {}
//
// public static void openInMarket(@NonNull Context context) {
// Intent intent = new Intent(Intent.ACTION_VIEW);
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// intent.setData(Uri.parse("market://details?id=" + context.getPackageName()));
// if (intent.resolveActivity(context.getPackageManager()) != null) {
// context.startActivity(intent);
// } else {
// ToastUtils.with(context).show(R.string.no_market_install_in_system);
// }
// }
//
// public static void openInBrowser(@NonNull Context context, @NonNull String url) {
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// if (intent.resolveActivity(context.getPackageManager()) != null) {
// context.startActivity(intent);
// } else {
// ToastUtils.with(context).show(R.string.no_browser_install_in_system);
// }
// }
//
// public static void openEmail(@NonNull Context context, @NonNull String email, @NonNull String subject, @NonNull String text) {
// Intent intent = new Intent(Intent.ACTION_SENDTO);
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// intent.setData(Uri.parse("mailto:" + email));
// if (intent.resolveActivity(context.getPackageManager()) != null) {
// intent.putExtra(Intent.EXTRA_SUBJECT, subject);
// intent.putExtra(Intent.EXTRA_TEXT, text);
// context.startActivity(intent);
// } else {
// ToastUtils.with(context).show(R.string.no_email_client_install_in_system);
// }
// }
//
// public static void openShare(@NonNull Context context, @NonNull String text) {
// Intent intent = new Intent(Intent.ACTION_SEND);
// intent.setType("text/plain");
// intent.putExtra(Intent.EXTRA_TEXT, text);
// context.startActivity(Intent.createChooser(intent, context.getString(R.string.share)));
// }
//
// public static boolean openStandardLink(@NonNull Context context, @Nullable String url) {
// if (FormatUtils.isUserLinkUrl(url)) {
// UserDetailActivity.start(context, Uri.parse(url).getPath().replace(ApiDefine.USER_PATH_PREFIX, ""));
// return true;
// } else if (FormatUtils.isTopicLinkUrl(url)) {
// TopicWithAutoCompat.start(context, Uri.parse(url).getPath().replace(ApiDefine.TOPIC_PATH_PREFIX, ""));
// return true;
// } else {
// return false;
// }
// }
//
// public static final class TopicWithAutoCompat {
//
// private TopicWithAutoCompat() {}
//
// public static final String EXTRA_TOPIC_ID = "topicId";
// public static final String EXTRA_TOPIC = "topic";
//
// private static Class<?> getTargetClass(@NonNull Context context) {
// return SettingShared.isEnableTopicRenderCompat(context) ? TopicCompatActivity.class : TopicActivity.class;
// }
//
// public static void start(@NonNull Activity activity, @NonNull Topic topic) {
// Intent intent = new Intent(activity, getTargetClass(activity));
// intent.putExtra(EXTRA_TOPIC_ID, topic.getId());
// intent.putExtra(EXTRA_TOPIC, EntityUtils.gson.toJson(topic));
// activity.startActivity(intent);
// }
//
// public static void start(@NonNull Activity activity, String topicId) {
// Intent intent = new Intent(activity, getTargetClass(activity));
// intent.putExtra(EXTRA_TOPIC_ID, topicId);
// activity.startActivity(intent);
// }
//
// public static void start(@NonNull Context context, String topicId) {
// Intent intent = new Intent(context, getTargetClass(context));
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// intent.putExtra(EXTRA_TOPIC_ID, topicId);
// context.startActivity(intent);
// }
//
// }
//
// public static final class NotificationWithAutoCompat {
//
// private NotificationWithAutoCompat() {}
//
// private static Class<?> getTargetClass(@NonNull Context context) {
// return SettingShared.isEnableTopicRenderCompat(context) ? NotificationCompatActivity.class : NotificationActivity.class;
// }
//
// public static void start(@NonNull Activity activity) {
// activity.startActivity(new Intent(activity, getTargetClass(activity)));
// }
//
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ToastUtils.java
// public final class ToastUtils {
//
// private volatile static ToastUtils singleton;
//
// public static ToastUtils with(@NonNull Context context) {
// if (singleton == null) {
// synchronized (ToastUtils.class) {
// if (singleton == null) {
// singleton = new ToastUtils(context);
// }
// }
// }
// return singleton;
// }
//
// private final Toast toast;
//
// @SuppressLint("ShowToast")
// private ToastUtils(@NonNull Context context) {
// toast = Toast.makeText(context.getApplicationContext(), null, Toast.LENGTH_SHORT);
// }
//
// public void show(CharSequence msg) {
// toast.setText(msg);
// toast.show();
// }
//
// public void show(@StringRes int resId) {
// toast.setText(resId);
// toast.show();
// }
//
// }
| import android.os.Bundle;
import android.support.annotation.Nullable;
import org.cnodejs.android.md.R;
import org.cnodejs.android.md.ui.util.Navigator;
import org.cnodejs.android.md.ui.util.ToastUtils; | package org.cnodejs.android.md.ui.activity;
public class StandardLinkRouterActivity extends BaseActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState); | // Path: app/src/main/java/org/cnodejs/android/md/ui/util/Navigator.java
// public final class Navigator {
//
// private Navigator() {}
//
// public static void openInMarket(@NonNull Context context) {
// Intent intent = new Intent(Intent.ACTION_VIEW);
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// intent.setData(Uri.parse("market://details?id=" + context.getPackageName()));
// if (intent.resolveActivity(context.getPackageManager()) != null) {
// context.startActivity(intent);
// } else {
// ToastUtils.with(context).show(R.string.no_market_install_in_system);
// }
// }
//
// public static void openInBrowser(@NonNull Context context, @NonNull String url) {
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// if (intent.resolveActivity(context.getPackageManager()) != null) {
// context.startActivity(intent);
// } else {
// ToastUtils.with(context).show(R.string.no_browser_install_in_system);
// }
// }
//
// public static void openEmail(@NonNull Context context, @NonNull String email, @NonNull String subject, @NonNull String text) {
// Intent intent = new Intent(Intent.ACTION_SENDTO);
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// intent.setData(Uri.parse("mailto:" + email));
// if (intent.resolveActivity(context.getPackageManager()) != null) {
// intent.putExtra(Intent.EXTRA_SUBJECT, subject);
// intent.putExtra(Intent.EXTRA_TEXT, text);
// context.startActivity(intent);
// } else {
// ToastUtils.with(context).show(R.string.no_email_client_install_in_system);
// }
// }
//
// public static void openShare(@NonNull Context context, @NonNull String text) {
// Intent intent = new Intent(Intent.ACTION_SEND);
// intent.setType("text/plain");
// intent.putExtra(Intent.EXTRA_TEXT, text);
// context.startActivity(Intent.createChooser(intent, context.getString(R.string.share)));
// }
//
// public static boolean openStandardLink(@NonNull Context context, @Nullable String url) {
// if (FormatUtils.isUserLinkUrl(url)) {
// UserDetailActivity.start(context, Uri.parse(url).getPath().replace(ApiDefine.USER_PATH_PREFIX, ""));
// return true;
// } else if (FormatUtils.isTopicLinkUrl(url)) {
// TopicWithAutoCompat.start(context, Uri.parse(url).getPath().replace(ApiDefine.TOPIC_PATH_PREFIX, ""));
// return true;
// } else {
// return false;
// }
// }
//
// public static final class TopicWithAutoCompat {
//
// private TopicWithAutoCompat() {}
//
// public static final String EXTRA_TOPIC_ID = "topicId";
// public static final String EXTRA_TOPIC = "topic";
//
// private static Class<?> getTargetClass(@NonNull Context context) {
// return SettingShared.isEnableTopicRenderCompat(context) ? TopicCompatActivity.class : TopicActivity.class;
// }
//
// public static void start(@NonNull Activity activity, @NonNull Topic topic) {
// Intent intent = new Intent(activity, getTargetClass(activity));
// intent.putExtra(EXTRA_TOPIC_ID, topic.getId());
// intent.putExtra(EXTRA_TOPIC, EntityUtils.gson.toJson(topic));
// activity.startActivity(intent);
// }
//
// public static void start(@NonNull Activity activity, String topicId) {
// Intent intent = new Intent(activity, getTargetClass(activity));
// intent.putExtra(EXTRA_TOPIC_ID, topicId);
// activity.startActivity(intent);
// }
//
// public static void start(@NonNull Context context, String topicId) {
// Intent intent = new Intent(context, getTargetClass(context));
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// intent.putExtra(EXTRA_TOPIC_ID, topicId);
// context.startActivity(intent);
// }
//
// }
//
// public static final class NotificationWithAutoCompat {
//
// private NotificationWithAutoCompat() {}
//
// private static Class<?> getTargetClass(@NonNull Context context) {
// return SettingShared.isEnableTopicRenderCompat(context) ? NotificationCompatActivity.class : NotificationActivity.class;
// }
//
// public static void start(@NonNull Activity activity) {
// activity.startActivity(new Intent(activity, getTargetClass(activity)));
// }
//
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ToastUtils.java
// public final class ToastUtils {
//
// private volatile static ToastUtils singleton;
//
// public static ToastUtils with(@NonNull Context context) {
// if (singleton == null) {
// synchronized (ToastUtils.class) {
// if (singleton == null) {
// singleton = new ToastUtils(context);
// }
// }
// }
// return singleton;
// }
//
// private final Toast toast;
//
// @SuppressLint("ShowToast")
// private ToastUtils(@NonNull Context context) {
// toast = Toast.makeText(context.getApplicationContext(), null, Toast.LENGTH_SHORT);
// }
//
// public void show(CharSequence msg) {
// toast.setText(msg);
// toast.show();
// }
//
// public void show(@StringRes int resId) {
// toast.setText(resId);
// toast.show();
// }
//
// }
// Path: app/src/main/java/org/cnodejs/android/md/ui/activity/StandardLinkRouterActivity.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import org.cnodejs.android.md.R;
import org.cnodejs.android.md.ui.util.Navigator;
import org.cnodejs.android.md.ui.util.ToastUtils;
package org.cnodejs.android.md.ui.activity;
public class StandardLinkRouterActivity extends BaseActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState); | if (!Navigator.openStandardLink(this, getIntent().getDataString())) { |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/ui/activity/StandardLinkRouterActivity.java | // Path: app/src/main/java/org/cnodejs/android/md/ui/util/Navigator.java
// public final class Navigator {
//
// private Navigator() {}
//
// public static void openInMarket(@NonNull Context context) {
// Intent intent = new Intent(Intent.ACTION_VIEW);
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// intent.setData(Uri.parse("market://details?id=" + context.getPackageName()));
// if (intent.resolveActivity(context.getPackageManager()) != null) {
// context.startActivity(intent);
// } else {
// ToastUtils.with(context).show(R.string.no_market_install_in_system);
// }
// }
//
// public static void openInBrowser(@NonNull Context context, @NonNull String url) {
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// if (intent.resolveActivity(context.getPackageManager()) != null) {
// context.startActivity(intent);
// } else {
// ToastUtils.with(context).show(R.string.no_browser_install_in_system);
// }
// }
//
// public static void openEmail(@NonNull Context context, @NonNull String email, @NonNull String subject, @NonNull String text) {
// Intent intent = new Intent(Intent.ACTION_SENDTO);
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// intent.setData(Uri.parse("mailto:" + email));
// if (intent.resolveActivity(context.getPackageManager()) != null) {
// intent.putExtra(Intent.EXTRA_SUBJECT, subject);
// intent.putExtra(Intent.EXTRA_TEXT, text);
// context.startActivity(intent);
// } else {
// ToastUtils.with(context).show(R.string.no_email_client_install_in_system);
// }
// }
//
// public static void openShare(@NonNull Context context, @NonNull String text) {
// Intent intent = new Intent(Intent.ACTION_SEND);
// intent.setType("text/plain");
// intent.putExtra(Intent.EXTRA_TEXT, text);
// context.startActivity(Intent.createChooser(intent, context.getString(R.string.share)));
// }
//
// public static boolean openStandardLink(@NonNull Context context, @Nullable String url) {
// if (FormatUtils.isUserLinkUrl(url)) {
// UserDetailActivity.start(context, Uri.parse(url).getPath().replace(ApiDefine.USER_PATH_PREFIX, ""));
// return true;
// } else if (FormatUtils.isTopicLinkUrl(url)) {
// TopicWithAutoCompat.start(context, Uri.parse(url).getPath().replace(ApiDefine.TOPIC_PATH_PREFIX, ""));
// return true;
// } else {
// return false;
// }
// }
//
// public static final class TopicWithAutoCompat {
//
// private TopicWithAutoCompat() {}
//
// public static final String EXTRA_TOPIC_ID = "topicId";
// public static final String EXTRA_TOPIC = "topic";
//
// private static Class<?> getTargetClass(@NonNull Context context) {
// return SettingShared.isEnableTopicRenderCompat(context) ? TopicCompatActivity.class : TopicActivity.class;
// }
//
// public static void start(@NonNull Activity activity, @NonNull Topic topic) {
// Intent intent = new Intent(activity, getTargetClass(activity));
// intent.putExtra(EXTRA_TOPIC_ID, topic.getId());
// intent.putExtra(EXTRA_TOPIC, EntityUtils.gson.toJson(topic));
// activity.startActivity(intent);
// }
//
// public static void start(@NonNull Activity activity, String topicId) {
// Intent intent = new Intent(activity, getTargetClass(activity));
// intent.putExtra(EXTRA_TOPIC_ID, topicId);
// activity.startActivity(intent);
// }
//
// public static void start(@NonNull Context context, String topicId) {
// Intent intent = new Intent(context, getTargetClass(context));
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// intent.putExtra(EXTRA_TOPIC_ID, topicId);
// context.startActivity(intent);
// }
//
// }
//
// public static final class NotificationWithAutoCompat {
//
// private NotificationWithAutoCompat() {}
//
// private static Class<?> getTargetClass(@NonNull Context context) {
// return SettingShared.isEnableTopicRenderCompat(context) ? NotificationCompatActivity.class : NotificationActivity.class;
// }
//
// public static void start(@NonNull Activity activity) {
// activity.startActivity(new Intent(activity, getTargetClass(activity)));
// }
//
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ToastUtils.java
// public final class ToastUtils {
//
// private volatile static ToastUtils singleton;
//
// public static ToastUtils with(@NonNull Context context) {
// if (singleton == null) {
// synchronized (ToastUtils.class) {
// if (singleton == null) {
// singleton = new ToastUtils(context);
// }
// }
// }
// return singleton;
// }
//
// private final Toast toast;
//
// @SuppressLint("ShowToast")
// private ToastUtils(@NonNull Context context) {
// toast = Toast.makeText(context.getApplicationContext(), null, Toast.LENGTH_SHORT);
// }
//
// public void show(CharSequence msg) {
// toast.setText(msg);
// toast.show();
// }
//
// public void show(@StringRes int resId) {
// toast.setText(resId);
// toast.show();
// }
//
// }
| import android.os.Bundle;
import android.support.annotation.Nullable;
import org.cnodejs.android.md.R;
import org.cnodejs.android.md.ui.util.Navigator;
import org.cnodejs.android.md.ui.util.ToastUtils; | package org.cnodejs.android.md.ui.activity;
public class StandardLinkRouterActivity extends BaseActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!Navigator.openStandardLink(this, getIntent().getDataString())) { | // Path: app/src/main/java/org/cnodejs/android/md/ui/util/Navigator.java
// public final class Navigator {
//
// private Navigator() {}
//
// public static void openInMarket(@NonNull Context context) {
// Intent intent = new Intent(Intent.ACTION_VIEW);
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// intent.setData(Uri.parse("market://details?id=" + context.getPackageName()));
// if (intent.resolveActivity(context.getPackageManager()) != null) {
// context.startActivity(intent);
// } else {
// ToastUtils.with(context).show(R.string.no_market_install_in_system);
// }
// }
//
// public static void openInBrowser(@NonNull Context context, @NonNull String url) {
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// if (intent.resolveActivity(context.getPackageManager()) != null) {
// context.startActivity(intent);
// } else {
// ToastUtils.with(context).show(R.string.no_browser_install_in_system);
// }
// }
//
// public static void openEmail(@NonNull Context context, @NonNull String email, @NonNull String subject, @NonNull String text) {
// Intent intent = new Intent(Intent.ACTION_SENDTO);
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// intent.setData(Uri.parse("mailto:" + email));
// if (intent.resolveActivity(context.getPackageManager()) != null) {
// intent.putExtra(Intent.EXTRA_SUBJECT, subject);
// intent.putExtra(Intent.EXTRA_TEXT, text);
// context.startActivity(intent);
// } else {
// ToastUtils.with(context).show(R.string.no_email_client_install_in_system);
// }
// }
//
// public static void openShare(@NonNull Context context, @NonNull String text) {
// Intent intent = new Intent(Intent.ACTION_SEND);
// intent.setType("text/plain");
// intent.putExtra(Intent.EXTRA_TEXT, text);
// context.startActivity(Intent.createChooser(intent, context.getString(R.string.share)));
// }
//
// public static boolean openStandardLink(@NonNull Context context, @Nullable String url) {
// if (FormatUtils.isUserLinkUrl(url)) {
// UserDetailActivity.start(context, Uri.parse(url).getPath().replace(ApiDefine.USER_PATH_PREFIX, ""));
// return true;
// } else if (FormatUtils.isTopicLinkUrl(url)) {
// TopicWithAutoCompat.start(context, Uri.parse(url).getPath().replace(ApiDefine.TOPIC_PATH_PREFIX, ""));
// return true;
// } else {
// return false;
// }
// }
//
// public static final class TopicWithAutoCompat {
//
// private TopicWithAutoCompat() {}
//
// public static final String EXTRA_TOPIC_ID = "topicId";
// public static final String EXTRA_TOPIC = "topic";
//
// private static Class<?> getTargetClass(@NonNull Context context) {
// return SettingShared.isEnableTopicRenderCompat(context) ? TopicCompatActivity.class : TopicActivity.class;
// }
//
// public static void start(@NonNull Activity activity, @NonNull Topic topic) {
// Intent intent = new Intent(activity, getTargetClass(activity));
// intent.putExtra(EXTRA_TOPIC_ID, topic.getId());
// intent.putExtra(EXTRA_TOPIC, EntityUtils.gson.toJson(topic));
// activity.startActivity(intent);
// }
//
// public static void start(@NonNull Activity activity, String topicId) {
// Intent intent = new Intent(activity, getTargetClass(activity));
// intent.putExtra(EXTRA_TOPIC_ID, topicId);
// activity.startActivity(intent);
// }
//
// public static void start(@NonNull Context context, String topicId) {
// Intent intent = new Intent(context, getTargetClass(context));
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// intent.putExtra(EXTRA_TOPIC_ID, topicId);
// context.startActivity(intent);
// }
//
// }
//
// public static final class NotificationWithAutoCompat {
//
// private NotificationWithAutoCompat() {}
//
// private static Class<?> getTargetClass(@NonNull Context context) {
// return SettingShared.isEnableTopicRenderCompat(context) ? NotificationCompatActivity.class : NotificationActivity.class;
// }
//
// public static void start(@NonNull Activity activity) {
// activity.startActivity(new Intent(activity, getTargetClass(activity)));
// }
//
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ToastUtils.java
// public final class ToastUtils {
//
// private volatile static ToastUtils singleton;
//
// public static ToastUtils with(@NonNull Context context) {
// if (singleton == null) {
// synchronized (ToastUtils.class) {
// if (singleton == null) {
// singleton = new ToastUtils(context);
// }
// }
// }
// return singleton;
// }
//
// private final Toast toast;
//
// @SuppressLint("ShowToast")
// private ToastUtils(@NonNull Context context) {
// toast = Toast.makeText(context.getApplicationContext(), null, Toast.LENGTH_SHORT);
// }
//
// public void show(CharSequence msg) {
// toast.setText(msg);
// toast.show();
// }
//
// public void show(@StringRes int resId) {
// toast.setText(resId);
// toast.show();
// }
//
// }
// Path: app/src/main/java/org/cnodejs/android/md/ui/activity/StandardLinkRouterActivity.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import org.cnodejs.android.md.R;
import org.cnodejs.android.md.ui.util.Navigator;
import org.cnodejs.android.md.ui.util.ToastUtils;
package org.cnodejs.android.md.ui.activity;
public class StandardLinkRouterActivity extends BaseActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!Navigator.openStandardLink(this, getIntent().getDataString())) { | ToastUtils.with(this).show(R.string.invalid_link); |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/ui/activity/SettingActivity.java | // Path: app/src/main/java/org/cnodejs/android/md/model/storage/SettingShared.java
// public final class SettingShared {
//
// private SettingShared() {}
//
// private static final String TAG = "SettingShared";
//
// private static final String KEY_ENABLE_NOTIFICATION = "enableNotification";
// private static final String KEY_ENABLE_THEME_DARK = "enableThemeDark";
// private static final String KEY_ENABLE_TOPIC_DRAFT = "enableTopicDraft";
// private static final String KEY_ENABLE_TOPIC_SIGN = "enableTopicSign";
// private static final String KEY_TOPIC_SIGN_CONTENT = "topicSignContent";
// private static final String KEY_ENABLE_TOPIC_RENDER_COMPAT = "enableTopicRenderCompat";
// private static final String KEY_SHOW_TOPIC_RENDER_COMPAT_TIP = "showTopicRenderCompatTip";
//
// public static final String DEFAULT_TOPIC_SIGN_CONTENT = "来自酷炫的 [CNodeMD](https://github.com/TakWolf/CNode-Material-Design)";
//
// public static boolean isEnableNotification(@NonNull Context context) {
// return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_NOTIFICATION, true);
// }
//
// public static void setEnableNotification(@NonNull Context context, boolean enable) {
// SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_NOTIFICATION, enable);
// }
//
// public static boolean isEnableThemeDark(@NonNull Context context) {
// return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_THEME_DARK, false);
// }
//
// public static void setEnableThemeDark(@NonNull Context context, boolean enable) {
// SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_THEME_DARK, enable);
// }
//
// public static boolean isEnableTopicDraft(@NonNull Context context) {
// return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_DRAFT, true);
// }
//
// public static void setEnableTopicDraft(@NonNull Context context, boolean enable) {
// SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_DRAFT, enable);
// }
//
// public static boolean isEnableTopicSign(@NonNull Context context) {
// return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_SIGN, true);
// }
//
// public static void setEnableTopicSign(@NonNull Context context, boolean enable) {
// SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_SIGN, enable);
// }
//
// public static String getTopicSignContent(@NonNull Context context) {
// return SharedUtils.with(context, TAG).getString(KEY_TOPIC_SIGN_CONTENT, DEFAULT_TOPIC_SIGN_CONTENT);
// }
//
// public static void setTopicSignContent(@NonNull Context context, @Nullable String content) {
// SharedUtils.with(context, TAG).setString(KEY_TOPIC_SIGN_CONTENT, content);
// }
//
// public static boolean isEnableTopicRenderCompat(@NonNull Context context) {
// return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, true);
// }
//
// public static void setEnableTopicRenderCompat(@NonNull Context context, boolean enable) {
// SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, enable);
// }
//
// public static boolean isShowTopicRenderCompatTip(@NonNull Context context) {
// return SharedUtils.with(context, TAG).getBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, true);
// }
//
// public static void markShowTopicRenderCompatTip(@NonNull Context context) {
// SharedUtils.with(context, TAG).setBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, false);
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/listener/NavigationFinishClickListener.java
// public class NavigationFinishClickListener implements View.OnClickListener {
//
// private final Activity activity;
//
// public NavigationFinishClickListener(@NonNull Activity activity) {
// this.activity = activity;
// }
//
// @Override
// public void onClick(View v) {
// ActivityCompat.finishAfterTransition(activity);
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ThemeUtils.java
// public final class ThemeUtils {
//
// private ThemeUtils() {}
//
// public static boolean configThemeBeforeOnCreate(@NonNull Activity activity, @StyleRes int light, @StyleRes int dark) {
// boolean enable = SettingShared.isEnableThemeDark(activity);
// activity.setTheme(enable ? dark : light);
// return enable;
// }
//
// public static void notifyThemeApply(@NonNull final Activity activity) {
// HandlerUtils.handler.post(new Runnable() {
//
// @Override
// public void run() {
// activity.recreate();
// }
//
// });
// }
//
// }
| import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.SwitchCompat;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;
import org.cnodejs.android.md.R;
import org.cnodejs.android.md.model.storage.SettingShared;
import org.cnodejs.android.md.ui.listener.NavigationFinishClickListener;
import org.cnodejs.android.md.ui.util.ThemeUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick; | package org.cnodejs.android.md.ui.activity;
public class SettingActivity extends StatusBarActivity {
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.switch_notification)
SwitchCompat switchNotification;
@BindView(R.id.switch_theme_dark)
SwitchCompat switchThemeDark;
@BindView(R.id.switch_topic_draft)
SwitchCompat switchTopicDraft;
@BindView(R.id.switch_topic_sign)
SwitchCompat switchTopicSign;
@BindView(R.id.btn_modify_topic_sign)
TextView btnModifyTopicSign;
@BindView(R.id.switch_topic_render_compat)
SwitchCompat switchTopicRenderCompat;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) { | // Path: app/src/main/java/org/cnodejs/android/md/model/storage/SettingShared.java
// public final class SettingShared {
//
// private SettingShared() {}
//
// private static final String TAG = "SettingShared";
//
// private static final String KEY_ENABLE_NOTIFICATION = "enableNotification";
// private static final String KEY_ENABLE_THEME_DARK = "enableThemeDark";
// private static final String KEY_ENABLE_TOPIC_DRAFT = "enableTopicDraft";
// private static final String KEY_ENABLE_TOPIC_SIGN = "enableTopicSign";
// private static final String KEY_TOPIC_SIGN_CONTENT = "topicSignContent";
// private static final String KEY_ENABLE_TOPIC_RENDER_COMPAT = "enableTopicRenderCompat";
// private static final String KEY_SHOW_TOPIC_RENDER_COMPAT_TIP = "showTopicRenderCompatTip";
//
// public static final String DEFAULT_TOPIC_SIGN_CONTENT = "来自酷炫的 [CNodeMD](https://github.com/TakWolf/CNode-Material-Design)";
//
// public static boolean isEnableNotification(@NonNull Context context) {
// return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_NOTIFICATION, true);
// }
//
// public static void setEnableNotification(@NonNull Context context, boolean enable) {
// SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_NOTIFICATION, enable);
// }
//
// public static boolean isEnableThemeDark(@NonNull Context context) {
// return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_THEME_DARK, false);
// }
//
// public static void setEnableThemeDark(@NonNull Context context, boolean enable) {
// SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_THEME_DARK, enable);
// }
//
// public static boolean isEnableTopicDraft(@NonNull Context context) {
// return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_DRAFT, true);
// }
//
// public static void setEnableTopicDraft(@NonNull Context context, boolean enable) {
// SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_DRAFT, enable);
// }
//
// public static boolean isEnableTopicSign(@NonNull Context context) {
// return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_SIGN, true);
// }
//
// public static void setEnableTopicSign(@NonNull Context context, boolean enable) {
// SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_SIGN, enable);
// }
//
// public static String getTopicSignContent(@NonNull Context context) {
// return SharedUtils.with(context, TAG).getString(KEY_TOPIC_SIGN_CONTENT, DEFAULT_TOPIC_SIGN_CONTENT);
// }
//
// public static void setTopicSignContent(@NonNull Context context, @Nullable String content) {
// SharedUtils.with(context, TAG).setString(KEY_TOPIC_SIGN_CONTENT, content);
// }
//
// public static boolean isEnableTopicRenderCompat(@NonNull Context context) {
// return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, true);
// }
//
// public static void setEnableTopicRenderCompat(@NonNull Context context, boolean enable) {
// SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, enable);
// }
//
// public static boolean isShowTopicRenderCompatTip(@NonNull Context context) {
// return SharedUtils.with(context, TAG).getBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, true);
// }
//
// public static void markShowTopicRenderCompatTip(@NonNull Context context) {
// SharedUtils.with(context, TAG).setBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, false);
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/listener/NavigationFinishClickListener.java
// public class NavigationFinishClickListener implements View.OnClickListener {
//
// private final Activity activity;
//
// public NavigationFinishClickListener(@NonNull Activity activity) {
// this.activity = activity;
// }
//
// @Override
// public void onClick(View v) {
// ActivityCompat.finishAfterTransition(activity);
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ThemeUtils.java
// public final class ThemeUtils {
//
// private ThemeUtils() {}
//
// public static boolean configThemeBeforeOnCreate(@NonNull Activity activity, @StyleRes int light, @StyleRes int dark) {
// boolean enable = SettingShared.isEnableThemeDark(activity);
// activity.setTheme(enable ? dark : light);
// return enable;
// }
//
// public static void notifyThemeApply(@NonNull final Activity activity) {
// HandlerUtils.handler.post(new Runnable() {
//
// @Override
// public void run() {
// activity.recreate();
// }
//
// });
// }
//
// }
// Path: app/src/main/java/org/cnodejs/android/md/ui/activity/SettingActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.SwitchCompat;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;
import org.cnodejs.android.md.R;
import org.cnodejs.android.md.model.storage.SettingShared;
import org.cnodejs.android.md.ui.listener.NavigationFinishClickListener;
import org.cnodejs.android.md.ui.util.ThemeUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
package org.cnodejs.android.md.ui.activity;
public class SettingActivity extends StatusBarActivity {
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.switch_notification)
SwitchCompat switchNotification;
@BindView(R.id.switch_theme_dark)
SwitchCompat switchThemeDark;
@BindView(R.id.switch_topic_draft)
SwitchCompat switchTopicDraft;
@BindView(R.id.switch_topic_sign)
SwitchCompat switchTopicSign;
@BindView(R.id.btn_modify_topic_sign)
TextView btnModifyTopicSign;
@BindView(R.id.switch_topic_render_compat)
SwitchCompat switchTopicRenderCompat;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) { | ThemeUtils.configThemeBeforeOnCreate(this, R.style.AppThemeLight, R.style.AppThemeDark); |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/model/entity/ErrorResult.java | // Path: app/src/main/java/org/cnodejs/android/md/model/util/EntityUtils.java
// public final class EntityUtils {
//
// private EntityUtils() {}
//
// public static final Gson gson = new GsonBuilder()
// .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter())
// .create();
//
// private static class DateTimeTypeAdapter extends TypeAdapter<DateTime> {
//
// @Override
// public void write(JsonWriter out, DateTime dateTime) throws IOException {
// if (dateTime == null) {
// out.nullValue();
// } else {
// out.value(dateTime.toString());
// }
// }
//
// @Override
// public DateTime read(JsonReader in) throws IOException {
// if (in.peek() == JsonToken.NULL) {
// in.nextNull();
// return null;
// } else {
// return new DateTime(in.nextString());
// }
// }
//
// }
//
// }
| import android.support.annotation.NonNull;
import com.google.gson.JsonSyntaxException;
import com.google.gson.annotations.SerializedName;
import org.cnodejs.android.md.model.util.EntityUtils;
import java.net.ConnectException;
import java.net.NoRouteToHostException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import okhttp3.ResponseBody;
import retrofit2.Response; | package org.cnodejs.android.md.model.entity;
public class ErrorResult extends Result {
@NonNull
public static ErrorResult from(@NonNull Response response) {
ErrorResult errorResult = null;
ResponseBody errorBody = response.errorBody();
if (errorBody != null) {
try { | // Path: app/src/main/java/org/cnodejs/android/md/model/util/EntityUtils.java
// public final class EntityUtils {
//
// private EntityUtils() {}
//
// public static final Gson gson = new GsonBuilder()
// .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter())
// .create();
//
// private static class DateTimeTypeAdapter extends TypeAdapter<DateTime> {
//
// @Override
// public void write(JsonWriter out, DateTime dateTime) throws IOException {
// if (dateTime == null) {
// out.nullValue();
// } else {
// out.value(dateTime.toString());
// }
// }
//
// @Override
// public DateTime read(JsonReader in) throws IOException {
// if (in.peek() == JsonToken.NULL) {
// in.nextNull();
// return null;
// } else {
// return new DateTime(in.nextString());
// }
// }
//
// }
//
// }
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/ErrorResult.java
import android.support.annotation.NonNull;
import com.google.gson.JsonSyntaxException;
import com.google.gson.annotations.SerializedName;
import org.cnodejs.android.md.model.util.EntityUtils;
import java.net.ConnectException;
import java.net.NoRouteToHostException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import okhttp3.ResponseBody;
import retrofit2.Response;
package org.cnodejs.android.md.model.entity;
public class ErrorResult extends Result {
@NonNull
public static ErrorResult from(@NonNull Response response) {
ErrorResult errorResult = null;
ResponseBody errorBody = response.errorBody();
if (errorBody != null) {
try { | errorResult = EntityUtils.gson.fromJson(errorBody.string(), ErrorResult.class); |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/model/entity/LoginResult.java | // Path: app/src/main/java/org/cnodejs/android/md/util/FormatUtils.java
// public final class FormatUtils {
//
// private FormatUtils() {}
//
// /**
// * 获取最近时间字符串
// */
//
// private static final long MINUTE = 60 * 1000;
// private static final long HOUR = 60 * MINUTE;
// private static final long DAY = 24 * HOUR;
// private static final long WEEK = 7 * DAY;
// private static final long MONTH = 31 * DAY;
// private static final long YEAR = 12 * MONTH;
//
// public static String getRelativeTimeSpanString(@NonNull DateTime dateTime) {
// long offset = System.currentTimeMillis() - dateTime.getMillis();
// if (offset > YEAR) {
// return (offset / YEAR) + "年前";
// } else if (offset > MONTH) {
// return (offset / MONTH) + "个月前";
// } else if (offset > WEEK) {
// return (offset / WEEK) + "周前";
// } else if (offset > DAY) {
// return (offset / DAY) + "天前";
// } else if (offset > HOUR) {
// return (offset / HOUR) + "小时前";
// } else if (offset > MINUTE) {
// return (offset / MINUTE) + "分钟前";
// } else {
// return "刚刚";
// }
// }
//
// /**
// * 检测是否是用户accessToken
// */
// public static boolean isAccessToken(String accessToken) {
// if (TextUtils.isEmpty(accessToken)) {
// return false;
// } else {
// try {
// //noinspection ResultOfMethodCallIgnored
// UUID.fromString(accessToken);
// return true;
// } catch (Exception e) {
// return false;
// }
// }
// }
//
// /**
// * 修复头像地址的历史遗留问题
// */
// public static String getCompatAvatarUrl(String avatarUrl) {
// if (!TextUtils.isEmpty(avatarUrl) && avatarUrl.startsWith("//gravatar.com/avatar/")) {
// return "http:" + avatarUrl;
// } else {
// return avatarUrl;
// }
// }
//
// /**
// * 标准URL检测
// */
//
// public static boolean isUserLinkUrl(String url) {
// return !TextUtils.isEmpty(url) && url.startsWith(ApiDefine.USER_LINK_URL_PREFIX);
// }
//
// public static boolean isTopicLinkUrl(String url) {
// return !TextUtils.isEmpty(url) && url.startsWith(ApiDefine.TOPIC_LINK_URL_PREFIX);
// }
//
// /**
// * CNode兼容性的Markdown转换
// * '@'协议转换为'/user/'相对路径
// * 解析裸链接
// * 最外层包裹'<div class="markdown-text"></div>'
// * 尽可能的实现和服务端渲染相同的结果
// */
//
// private static final Markdown md = new Markdown();
//
// public static String renderMarkdown(String text) {
// // 保证text不为null
// text = TextUtils.isEmpty(text) ? "" : text;
// // 解析@协议
// text = text.replaceAll("@([\\w\\-]+)\\b(?![]<.])", "[@$1](" + ApiDefine.USER_PATH_PREFIX + "$1)");
// // 解析裸链接
// text = text + " ";
// text = text.replaceAll("((http|https|ftp)://[\\w\\-.:/?=&#%]+)(\\s)", "[$1]($1)$3");
// text = text.trim();
// // 渲染markdown
// try {
// StringWriter out = new StringWriter();
// md.transform(new StringReader(text), out);
// text = out.toString();
// } catch (ParseException e) {
// // nothing to do
// }
// // 添加样式容器
// return "<div class=\"markdown-text\">" + text + "</div>";
// }
//
// /**
// * CNode兼容性的Html处理
// * 过滤xss
// * 保留div的class属性,但是会清除其他非白名单属性
// * 通过baseUrl补全相对地址
// */
//
// private static final Cleaner cleaner = new Cleaner(Whitelist.relaxed().addAttributes("div", "class")); // 主要目的是保留最外层div的markdown-text属性
//
// public static Document handleHtml(String html) {
// // 保证html不为null
// html = TextUtils.isEmpty(html) ? "" : html;
// // 过滤xss
// return cleaner.clean(Jsoup.parseBodyFragment(html, ApiDefine.HOST_BASE_URL));
// }
//
// }
| import com.google.gson.annotations.SerializedName;
import org.cnodejs.android.md.util.FormatUtils; | package org.cnodejs.android.md.model.entity;
public class LoginResult extends Result {
private String id;
@SerializedName("loginname")
private String loginName;
@SerializedName("avatar_url")
private String avatarUrl;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getAvatarUrl() { // 修复头像地址的历史遗留问题 | // Path: app/src/main/java/org/cnodejs/android/md/util/FormatUtils.java
// public final class FormatUtils {
//
// private FormatUtils() {}
//
// /**
// * 获取最近时间字符串
// */
//
// private static final long MINUTE = 60 * 1000;
// private static final long HOUR = 60 * MINUTE;
// private static final long DAY = 24 * HOUR;
// private static final long WEEK = 7 * DAY;
// private static final long MONTH = 31 * DAY;
// private static final long YEAR = 12 * MONTH;
//
// public static String getRelativeTimeSpanString(@NonNull DateTime dateTime) {
// long offset = System.currentTimeMillis() - dateTime.getMillis();
// if (offset > YEAR) {
// return (offset / YEAR) + "年前";
// } else if (offset > MONTH) {
// return (offset / MONTH) + "个月前";
// } else if (offset > WEEK) {
// return (offset / WEEK) + "周前";
// } else if (offset > DAY) {
// return (offset / DAY) + "天前";
// } else if (offset > HOUR) {
// return (offset / HOUR) + "小时前";
// } else if (offset > MINUTE) {
// return (offset / MINUTE) + "分钟前";
// } else {
// return "刚刚";
// }
// }
//
// /**
// * 检测是否是用户accessToken
// */
// public static boolean isAccessToken(String accessToken) {
// if (TextUtils.isEmpty(accessToken)) {
// return false;
// } else {
// try {
// //noinspection ResultOfMethodCallIgnored
// UUID.fromString(accessToken);
// return true;
// } catch (Exception e) {
// return false;
// }
// }
// }
//
// /**
// * 修复头像地址的历史遗留问题
// */
// public static String getCompatAvatarUrl(String avatarUrl) {
// if (!TextUtils.isEmpty(avatarUrl) && avatarUrl.startsWith("//gravatar.com/avatar/")) {
// return "http:" + avatarUrl;
// } else {
// return avatarUrl;
// }
// }
//
// /**
// * 标准URL检测
// */
//
// public static boolean isUserLinkUrl(String url) {
// return !TextUtils.isEmpty(url) && url.startsWith(ApiDefine.USER_LINK_URL_PREFIX);
// }
//
// public static boolean isTopicLinkUrl(String url) {
// return !TextUtils.isEmpty(url) && url.startsWith(ApiDefine.TOPIC_LINK_URL_PREFIX);
// }
//
// /**
// * CNode兼容性的Markdown转换
// * '@'协议转换为'/user/'相对路径
// * 解析裸链接
// * 最外层包裹'<div class="markdown-text"></div>'
// * 尽可能的实现和服务端渲染相同的结果
// */
//
// private static final Markdown md = new Markdown();
//
// public static String renderMarkdown(String text) {
// // 保证text不为null
// text = TextUtils.isEmpty(text) ? "" : text;
// // 解析@协议
// text = text.replaceAll("@([\\w\\-]+)\\b(?![]<.])", "[@$1](" + ApiDefine.USER_PATH_PREFIX + "$1)");
// // 解析裸链接
// text = text + " ";
// text = text.replaceAll("((http|https|ftp)://[\\w\\-.:/?=&#%]+)(\\s)", "[$1]($1)$3");
// text = text.trim();
// // 渲染markdown
// try {
// StringWriter out = new StringWriter();
// md.transform(new StringReader(text), out);
// text = out.toString();
// } catch (ParseException e) {
// // nothing to do
// }
// // 添加样式容器
// return "<div class=\"markdown-text\">" + text + "</div>";
// }
//
// /**
// * CNode兼容性的Html处理
// * 过滤xss
// * 保留div的class属性,但是会清除其他非白名单属性
// * 通过baseUrl补全相对地址
// */
//
// private static final Cleaner cleaner = new Cleaner(Whitelist.relaxed().addAttributes("div", "class")); // 主要目的是保留最外层div的markdown-text属性
//
// public static Document handleHtml(String html) {
// // 保证html不为null
// html = TextUtils.isEmpty(html) ? "" : html;
// // 过滤xss
// return cleaner.clean(Jsoup.parseBodyFragment(html, ApiDefine.HOST_BASE_URL));
// }
//
// }
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/LoginResult.java
import com.google.gson.annotations.SerializedName;
import org.cnodejs.android.md.util.FormatUtils;
package org.cnodejs.android.md.model.entity;
public class LoginResult extends Result {
private String id;
@SerializedName("loginname")
private String loginName;
@SerializedName("avatar_url")
private String avatarUrl;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getAvatarUrl() { // 修复头像地址的历史遗留问题 | return FormatUtils.getCompatAvatarUrl(avatarUrl); |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/ui/activity/ImagePreviewActivity.java | // Path: app/src/main/java/org/cnodejs/android/md/ui/listener/NavigationFinishClickListener.java
// public class NavigationFinishClickListener implements View.OnClickListener {
//
// private final Activity activity;
//
// public NavigationFinishClickListener(@NonNull Activity activity) {
// this.activity = activity;
// }
//
// @Override
// public void onClick(View v) {
// ActivityCompat.finishAfterTransition(activity);
// }
//
// }
| import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.github.chrisbanes.photoview.PhotoView;
import com.pnikosis.materialishprogress.ProgressWheel;
import org.cnodejs.android.md.R;
import org.cnodejs.android.md.model.glide.GlideApp;
import org.cnodejs.android.md.ui.listener.NavigationFinishClickListener;
import butterknife.BindView;
import butterknife.ButterKnife; | package org.cnodejs.android.md.ui.activity;
public class ImagePreviewActivity extends StatusBarActivity {
private static final String EXTRA_IMAGE_URL = "imageUrl";
public static void start(@NonNull Context context, String imageUrl) {
Intent intent = new Intent(context, ImagePreviewActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(EXTRA_IMAGE_URL, imageUrl);
context.startActivity(intent);
}
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.photo_view)
PhotoView photoView;
@BindView(R.id.progress_wheel)
ProgressWheel progressWheel;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_preview);
ButterKnife.bind(this);
| // Path: app/src/main/java/org/cnodejs/android/md/ui/listener/NavigationFinishClickListener.java
// public class NavigationFinishClickListener implements View.OnClickListener {
//
// private final Activity activity;
//
// public NavigationFinishClickListener(@NonNull Activity activity) {
// this.activity = activity;
// }
//
// @Override
// public void onClick(View v) {
// ActivityCompat.finishAfterTransition(activity);
// }
//
// }
// Path: app/src/main/java/org/cnodejs/android/md/ui/activity/ImagePreviewActivity.java
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.github.chrisbanes.photoview.PhotoView;
import com.pnikosis.materialishprogress.ProgressWheel;
import org.cnodejs.android.md.R;
import org.cnodejs.android.md.model.glide.GlideApp;
import org.cnodejs.android.md.ui.listener.NavigationFinishClickListener;
import butterknife.BindView;
import butterknife.ButterKnife;
package org.cnodejs.android.md.ui.activity;
public class ImagePreviewActivity extends StatusBarActivity {
private static final String EXTRA_IMAGE_URL = "imageUrl";
public static void start(@NonNull Context context, String imageUrl) {
Intent intent = new Intent(context, ImagePreviewActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(EXTRA_IMAGE_URL, imageUrl);
context.startActivity(intent);
}
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.photo_view)
PhotoView photoView;
@BindView(R.id.progress_wheel)
ProgressWheel progressWheel;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_preview);
ButterKnife.bind(this);
| toolbar.setNavigationOnClickListener(new NavigationFinishClickListener(this)); |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/model/storage/TopicShared.java | // Path: app/src/main/java/org/cnodejs/android/md/model/util/SharedUtils.java
// public final class SharedUtils {
//
// private SharedUtils() {}
//
// private static final String TAG = "SharedUtils";
//
// @NonNull
// public static SharedPreferencesWrapper with(@NonNull Context context, @NonNull String name) {
// return new SharedPreferencesWrapper(context.getSharedPreferences(DigestUtils.sha256.getHex(name), Context.MODE_PRIVATE));
// }
//
// public static class SharedPreferencesWrapper {
//
// private final SharedPreferences sharedPreferences;
//
// private SharedPreferencesWrapper(@NonNull SharedPreferences sharedPreferences) {
// this.sharedPreferences = sharedPreferences;
// }
//
// @NonNull
// public SharedPreferences getSharedPreferences() {
// return sharedPreferences;
// }
//
// @NonNull
// public SharedPreferencesWrapper clear() {
// sharedPreferences.edit().clear().apply();
// return this;
// }
//
// public String getString(@NonNull String key, @Nullable String defValue) {
// try {
// return sharedPreferences.getString(key, defValue);
// } catch (ClassCastException e) {
// Log.e(TAG, "Get string value error.", e);
// return defValue;
// }
// }
//
// @NonNull
// public SharedPreferencesWrapper setString(@NonNull String key, @Nullable String value) {
// sharedPreferences.edit().putString(key, value).apply();
// return this;
// }
//
// public boolean getBoolean(@NonNull String key, boolean defValue) {
// try {
// return sharedPreferences.getBoolean(key, defValue);
// } catch (ClassCastException e) {
// Log.e(TAG, "Get boolean value error.", e);
// return defValue;
// }
// }
//
// @NonNull
// public SharedPreferencesWrapper setBoolean(@NonNull String key, boolean value) {
// sharedPreferences.edit().putBoolean(key, value).apply();
// return this;
// }
//
// public float getFloat(@NonNull String key, float defValue) {
// try {
// return sharedPreferences.getFloat(key, defValue);
// } catch (ClassCastException e) {
// Log.e(TAG, "Get float value error.", e);
// return defValue;
// }
// }
//
// @NonNull
// public SharedPreferencesWrapper setFloat(@NonNull String key, float value) {
// sharedPreferences.edit().putFloat(key, value).apply();
// return this;
// }
//
// public int getInt(@NonNull String key, int defValue) {
// try {
// return sharedPreferences.getInt(key, defValue);
// } catch (ClassCastException e) {
// Log.e(TAG, "Get int value error.", e);
// return defValue;
// }
// }
//
// @NonNull
// public SharedPreferencesWrapper setInt(@NonNull String key, int value) {
// sharedPreferences.edit().putInt(key, value).apply();
// return this;
// }
//
// public long getLong(@NonNull String key, long defValue) {
// try {
// return sharedPreferences.getLong(key, defValue);
// } catch (ClassCastException e) {
// Log.e(TAG, "Get long value error.", e);
// return defValue;
// }
// }
//
// @NonNull
// public SharedPreferencesWrapper setLong(@NonNull String key, long value) {
// sharedPreferences.edit().putLong(key, value).apply();
// return this;
// }
//
// public <T> T getObject(@NonNull String key, @NonNull Type typeOfT) {
// String value = getString(key, null);
// if (value == null) {
// return null;
// } else {
// try {
// return EntityUtils.gson.fromJson(value, typeOfT);
// } catch (JsonParseException e) {
// Log.e(TAG, "Get object value error.", e);
// return null;
// }
// }
// }
//
// @NonNull
// public SharedPreferencesWrapper setObject(@NonNull String key, @Nullable Object value) {
// setString(key, value == null ? null : EntityUtils.gson.toJson(value));
// return this;
// }
//
// }
//
// }
| import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import org.cnodejs.android.md.model.util.SharedUtils; | package org.cnodejs.android.md.model.storage;
public final class TopicShared {
private TopicShared() {}
private static final String TAG = "TopicShared";
private static String getSharedName(@NonNull Context context) {
return TAG + "@" + LoginShared.getId(context);
}
private static final String KEY_DRAFT_TAB_POSITION = "draftTabPosition";
private static final String KEY_DRAFT_TITLE = "draftTitle";
private static final String KEY_DRAFT_CONTENT = "draftContent";
public static void clear(@NonNull Context context) { | // Path: app/src/main/java/org/cnodejs/android/md/model/util/SharedUtils.java
// public final class SharedUtils {
//
// private SharedUtils() {}
//
// private static final String TAG = "SharedUtils";
//
// @NonNull
// public static SharedPreferencesWrapper with(@NonNull Context context, @NonNull String name) {
// return new SharedPreferencesWrapper(context.getSharedPreferences(DigestUtils.sha256.getHex(name), Context.MODE_PRIVATE));
// }
//
// public static class SharedPreferencesWrapper {
//
// private final SharedPreferences sharedPreferences;
//
// private SharedPreferencesWrapper(@NonNull SharedPreferences sharedPreferences) {
// this.sharedPreferences = sharedPreferences;
// }
//
// @NonNull
// public SharedPreferences getSharedPreferences() {
// return sharedPreferences;
// }
//
// @NonNull
// public SharedPreferencesWrapper clear() {
// sharedPreferences.edit().clear().apply();
// return this;
// }
//
// public String getString(@NonNull String key, @Nullable String defValue) {
// try {
// return sharedPreferences.getString(key, defValue);
// } catch (ClassCastException e) {
// Log.e(TAG, "Get string value error.", e);
// return defValue;
// }
// }
//
// @NonNull
// public SharedPreferencesWrapper setString(@NonNull String key, @Nullable String value) {
// sharedPreferences.edit().putString(key, value).apply();
// return this;
// }
//
// public boolean getBoolean(@NonNull String key, boolean defValue) {
// try {
// return sharedPreferences.getBoolean(key, defValue);
// } catch (ClassCastException e) {
// Log.e(TAG, "Get boolean value error.", e);
// return defValue;
// }
// }
//
// @NonNull
// public SharedPreferencesWrapper setBoolean(@NonNull String key, boolean value) {
// sharedPreferences.edit().putBoolean(key, value).apply();
// return this;
// }
//
// public float getFloat(@NonNull String key, float defValue) {
// try {
// return sharedPreferences.getFloat(key, defValue);
// } catch (ClassCastException e) {
// Log.e(TAG, "Get float value error.", e);
// return defValue;
// }
// }
//
// @NonNull
// public SharedPreferencesWrapper setFloat(@NonNull String key, float value) {
// sharedPreferences.edit().putFloat(key, value).apply();
// return this;
// }
//
// public int getInt(@NonNull String key, int defValue) {
// try {
// return sharedPreferences.getInt(key, defValue);
// } catch (ClassCastException e) {
// Log.e(TAG, "Get int value error.", e);
// return defValue;
// }
// }
//
// @NonNull
// public SharedPreferencesWrapper setInt(@NonNull String key, int value) {
// sharedPreferences.edit().putInt(key, value).apply();
// return this;
// }
//
// public long getLong(@NonNull String key, long defValue) {
// try {
// return sharedPreferences.getLong(key, defValue);
// } catch (ClassCastException e) {
// Log.e(TAG, "Get long value error.", e);
// return defValue;
// }
// }
//
// @NonNull
// public SharedPreferencesWrapper setLong(@NonNull String key, long value) {
// sharedPreferences.edit().putLong(key, value).apply();
// return this;
// }
//
// public <T> T getObject(@NonNull String key, @NonNull Type typeOfT) {
// String value = getString(key, null);
// if (value == null) {
// return null;
// } else {
// try {
// return EntityUtils.gson.fromJson(value, typeOfT);
// } catch (JsonParseException e) {
// Log.e(TAG, "Get object value error.", e);
// return null;
// }
// }
// }
//
// @NonNull
// public SharedPreferencesWrapper setObject(@NonNull String key, @Nullable Object value) {
// setString(key, value == null ? null : EntityUtils.gson.toJson(value));
// return this;
// }
//
// }
//
// }
// Path: app/src/main/java/org/cnodejs/android/md/model/storage/TopicShared.java
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import org.cnodejs.android.md.model.util.SharedUtils;
package org.cnodejs.android.md.model.storage;
public final class TopicShared {
private TopicShared() {}
private static final String TAG = "TopicShared";
private static String getSharedName(@NonNull Context context) {
return TAG + "@" + LoginShared.getId(context);
}
private static final String KEY_DRAFT_TAB_POSITION = "draftTabPosition";
private static final String KEY_DRAFT_TITLE = "draftTitle";
private static final String KEY_DRAFT_CONTENT = "draftContent";
public static void clear(@NonNull Context context) { | SharedUtils.with(context, getSharedName(context)).clear(); |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/ui/view/ILoginView.java | // Path: app/src/main/java/org/cnodejs/android/md/model/entity/LoginResult.java
// public class LoginResult extends Result {
//
// private String id;
//
// @SerializedName("loginname")
// private String loginName;
//
// @SerializedName("avatar_url")
// private String avatarUrl;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getLoginName() {
// return loginName;
// }
//
// public void setLoginName(String loginName) {
// this.loginName = loginName;
// }
//
// public String getAvatarUrl() { // 修复头像地址的历史遗留问题
// return FormatUtils.getCompatAvatarUrl(avatarUrl);
// }
//
// public void setAvatarUrl(String avatarUrl) {
// this.avatarUrl = avatarUrl;
// }
//
// }
| import android.support.annotation.NonNull;
import org.cnodejs.android.md.model.entity.LoginResult;
import retrofit2.Call; | package org.cnodejs.android.md.ui.view;
public interface ILoginView {
void onAccessTokenError(@NonNull String message);
| // Path: app/src/main/java/org/cnodejs/android/md/model/entity/LoginResult.java
// public class LoginResult extends Result {
//
// private String id;
//
// @SerializedName("loginname")
// private String loginName;
//
// @SerializedName("avatar_url")
// private String avatarUrl;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getLoginName() {
// return loginName;
// }
//
// public void setLoginName(String loginName) {
// this.loginName = loginName;
// }
//
// public String getAvatarUrl() { // 修复头像地址的历史遗留问题
// return FormatUtils.getCompatAvatarUrl(avatarUrl);
// }
//
// public void setAvatarUrl(String avatarUrl) {
// this.avatarUrl = avatarUrl;
// }
//
// }
// Path: app/src/main/java/org/cnodejs/android/md/ui/view/ILoginView.java
import android.support.annotation.NonNull;
import org.cnodejs.android.md.model.entity.LoginResult;
import retrofit2.Call;
package org.cnodejs.android.md.ui.view;
public interface ILoginView {
void onAccessTokenError(@NonNull String message);
| void onLoginOk(@NonNull String accessToken, @NonNull LoginResult loginResult); |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/app/AppController.java | // Path: app/src/main/java/org/cnodejs/android/md/ui/activity/CrashLogActivity.java
// public class CrashLogActivity extends StatusBarActivity implements Toolbar.OnMenuItemClickListener {
//
// private static final String EXTRA_E = "e";
//
// public static void start(@NonNull Context context, @NonNull Throwable e) {
// Intent intent = new Intent(context, CrashLogActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Bundle bundle = new Bundle();
// bundle.putSerializable(EXTRA_E, e);
// intent.putExtras(bundle);
// context.startActivity(intent);
// }
//
// @BindView(R.id.toolbar)
// Toolbar toolbar;
//
// @BindView(R.id.tv_info)
// TextView tvInfo;
//
// private String crashLog;
//
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// ThemeUtils.configThemeBeforeOnCreate(this, R.style.AppThemeLight, R.style.AppThemeDark);
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_crash_log);
// ButterKnife.bind(this);
//
// toolbar.setNavigationOnClickListener(new NavigationFinishClickListener(this));
// toolbar.inflateMenu(R.menu.crash_log);
// toolbar.setOnMenuItemClickListener(this);
//
// Throwable e = (Throwable) getIntent().getSerializableExtra(EXTRA_E);
//
// crashLog = "生产厂商:\n" +
// Build.MANUFACTURER + "\n\n" +
// "手机型号:\n" +
// Build.MODEL + "\n\n" +
// "系统版本:\n" +
// Build.VERSION.RELEASE + "\n\n" +
// "异常时间:\n" +
// new DateTime() + "\n\n" +
// "异常类型:\n" +
// e.getClass().getName() + "\n\n" +
// "异常信息:\n" +
// e.getMessage() + "\n\n" +
// "异常堆栈:\n" +
// Log.getStackTraceString(e);
//
// tvInfo.setText(crashLog);
// }
//
// @Override
// public boolean onMenuItemClick(MenuItem item) {
// switch (item.getItemId()) {
// case R.id.action_send:
// Navigator.openEmail(
// this,
// "takwolf@foxmail.com",
// "来自 CNodeMD-" + AboutActivity.VERSION_TEXT + " 的客户端崩溃日志",
// crashLog
// );
// return true;
// default:
// return false;
// }
// }
//
// }
| import android.app.Application;
import net.danlew.android.joda.JodaTimeAndroid;
import org.cnodejs.android.md.BuildConfig;
import org.cnodejs.android.md.ui.activity.CrashLogActivity; | package org.cnodejs.android.md.app;
public class AppController extends Application implements Thread.UncaughtExceptionHandler {
@Override
public void onCreate() {
super.onCreate();
JodaTimeAndroid.init(this);
if (!BuildConfig.DEBUG) {
Thread.setDefaultUncaughtExceptionHandler(this);
}
}
@Override
public void uncaughtException(Thread thread, Throwable e) { | // Path: app/src/main/java/org/cnodejs/android/md/ui/activity/CrashLogActivity.java
// public class CrashLogActivity extends StatusBarActivity implements Toolbar.OnMenuItemClickListener {
//
// private static final String EXTRA_E = "e";
//
// public static void start(@NonNull Context context, @NonNull Throwable e) {
// Intent intent = new Intent(context, CrashLogActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Bundle bundle = new Bundle();
// bundle.putSerializable(EXTRA_E, e);
// intent.putExtras(bundle);
// context.startActivity(intent);
// }
//
// @BindView(R.id.toolbar)
// Toolbar toolbar;
//
// @BindView(R.id.tv_info)
// TextView tvInfo;
//
// private String crashLog;
//
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// ThemeUtils.configThemeBeforeOnCreate(this, R.style.AppThemeLight, R.style.AppThemeDark);
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_crash_log);
// ButterKnife.bind(this);
//
// toolbar.setNavigationOnClickListener(new NavigationFinishClickListener(this));
// toolbar.inflateMenu(R.menu.crash_log);
// toolbar.setOnMenuItemClickListener(this);
//
// Throwable e = (Throwable) getIntent().getSerializableExtra(EXTRA_E);
//
// crashLog = "生产厂商:\n" +
// Build.MANUFACTURER + "\n\n" +
// "手机型号:\n" +
// Build.MODEL + "\n\n" +
// "系统版本:\n" +
// Build.VERSION.RELEASE + "\n\n" +
// "异常时间:\n" +
// new DateTime() + "\n\n" +
// "异常类型:\n" +
// e.getClass().getName() + "\n\n" +
// "异常信息:\n" +
// e.getMessage() + "\n\n" +
// "异常堆栈:\n" +
// Log.getStackTraceString(e);
//
// tvInfo.setText(crashLog);
// }
//
// @Override
// public boolean onMenuItemClick(MenuItem item) {
// switch (item.getItemId()) {
// case R.id.action_send:
// Navigator.openEmail(
// this,
// "takwolf@foxmail.com",
// "来自 CNodeMD-" + AboutActivity.VERSION_TEXT + " 的客户端崩溃日志",
// crashLog
// );
// return true;
// default:
// return false;
// }
// }
//
// }
// Path: app/src/main/java/org/cnodejs/android/md/app/AppController.java
import android.app.Application;
import net.danlew.android.joda.JodaTimeAndroid;
import org.cnodejs.android.md.BuildConfig;
import org.cnodejs.android.md.ui.activity.CrashLogActivity;
package org.cnodejs.android.md.app;
public class AppController extends Application implements Thread.UncaughtExceptionHandler {
@Override
public void onCreate() {
super.onCreate();
JodaTimeAndroid.init(this);
if (!BuildConfig.DEBUG) {
Thread.setDefaultUncaughtExceptionHandler(this);
}
}
@Override
public void uncaughtException(Thread thread, Throwable e) { | CrashLogActivity.start(this, e); |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/ui/widget/ContentWebView.java | // Path: app/src/main/java/org/cnodejs/android/md/ui/jsbridge/ImageJavascriptInterface.java
// public final class ImageJavascriptInterface {
//
// public static final String NAME = "imageBridge";
//
// private final Context context;
//
// public ImageJavascriptInterface(@NonNull Context context) {
// this.context = context.getApplicationContext();
// }
//
// @JavascriptInterface
// public void openImage(String imageUrl) {
// ImagePreviewActivity.start(context, imageUrl);
// }
//
// }
| import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.support.annotation.AttrRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.annotation.StyleRes;
import android.util.AttributeSet;
import org.cnodejs.android.md.ui.jsbridge.ImageJavascriptInterface; | package org.cnodejs.android.md.ui.widget;
public class ContentWebView extends CNodeWebView {
private static final String HTML_0 = "" +
"<!DOCTYPE html>\n" +
"<html>\n" +
"<head>\n" +
"<meta charset=\"UTF-8\">\n" +
"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\">\n";
private static final String LIGHT_THEME_CSS = "" +
"<link type=\"text/css\" rel=\"stylesheet\" href=\"" + "file:///android_asset/css/content_light.css" + "\">\n" +
"<link type=\"text/css\" rel=\"stylesheet\" href=\"" + "file:///android_asset/css/markdown_light.css" + "\">\n";
private static final String DARK_THEME_CSS = "" +
"<link type=\"text/css\" rel=\"stylesheet\" href=\"" + "file:///android_asset/css/content_dark.css" + "\">\n" +
"<link type=\"text/css\" rel=\"stylesheet\" href=\"" + "file:///android_asset/css/markdown_dark.css" + "\">\n";
private static final String HTML_1 = "" +
"</head>\n" +
"<body>\n" +
"<div id=\"markdown-container\">\n";
private static final String HTML_2 = "" +
"</div>\n" +
"<script>\n" +
"(function() {\n" +
" var markdownContainer = document.getElementById('markdown-container');\n" +
" markdownContainer.onclick = function (event) {\n" +
" if (event.target.nodeName === 'IMG') {\n" +
" if (event.target.parentNode.nodeName !== 'A') {\n" + | // Path: app/src/main/java/org/cnodejs/android/md/ui/jsbridge/ImageJavascriptInterface.java
// public final class ImageJavascriptInterface {
//
// public static final String NAME = "imageBridge";
//
// private final Context context;
//
// public ImageJavascriptInterface(@NonNull Context context) {
// this.context = context.getApplicationContext();
// }
//
// @JavascriptInterface
// public void openImage(String imageUrl) {
// ImagePreviewActivity.start(context, imageUrl);
// }
//
// }
// Path: app/src/main/java/org/cnodejs/android/md/ui/widget/ContentWebView.java
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.support.annotation.AttrRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.annotation.StyleRes;
import android.util.AttributeSet;
import org.cnodejs.android.md.ui.jsbridge.ImageJavascriptInterface;
package org.cnodejs.android.md.ui.widget;
public class ContentWebView extends CNodeWebView {
private static final String HTML_0 = "" +
"<!DOCTYPE html>\n" +
"<html>\n" +
"<head>\n" +
"<meta charset=\"UTF-8\">\n" +
"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\">\n";
private static final String LIGHT_THEME_CSS = "" +
"<link type=\"text/css\" rel=\"stylesheet\" href=\"" + "file:///android_asset/css/content_light.css" + "\">\n" +
"<link type=\"text/css\" rel=\"stylesheet\" href=\"" + "file:///android_asset/css/markdown_light.css" + "\">\n";
private static final String DARK_THEME_CSS = "" +
"<link type=\"text/css\" rel=\"stylesheet\" href=\"" + "file:///android_asset/css/content_dark.css" + "\">\n" +
"<link type=\"text/css\" rel=\"stylesheet\" href=\"" + "file:///android_asset/css/markdown_dark.css" + "\">\n";
private static final String HTML_1 = "" +
"</head>\n" +
"<body>\n" +
"<div id=\"markdown-container\">\n";
private static final String HTML_2 = "" +
"</div>\n" +
"<script>\n" +
"(function() {\n" +
" var markdownContainer = document.getElementById('markdown-container');\n" +
" markdownContainer.onclick = function (event) {\n" +
" if (event.target.nodeName === 'IMG') {\n" +
" if (event.target.parentNode.nodeName !== 'A') {\n" + | " window." + ImageJavascriptInterface.NAME + ".openImage(event.target.src);\n" + |
TakWolf/CNode-Material-Design | app/src/main/java/org/cnodejs/android/md/model/api/ForegroundCallback.java | // Path: app/src/main/java/org/cnodejs/android/md/model/entity/ErrorResult.java
// public class ErrorResult extends Result {
//
// @NonNull
// public static ErrorResult from(@NonNull Response response) {
// ErrorResult errorResult = null;
// ResponseBody errorBody = response.errorBody();
// if (errorBody != null) {
// try {
// errorResult = EntityUtils.gson.fromJson(errorBody.string(), ErrorResult.class);
// } catch (Throwable ignored) {}
// }
// if (errorResult == null) {
// errorResult = new ErrorResult();
// errorResult.setSuccess(false);
// switch (response.code()) {
// case 400:
// errorResult.setMessage("非法请求");
// break;
// case 403:
// errorResult.setMessage("非法行为");
// break;
// case 404:
// errorResult.setMessage("未找到资源");
// break;
// case 405:
// errorResult.setMessage("非法请求方式");
// break;
// case 408:
// errorResult.setMessage("请求超时");
// break;
// case 500:
// errorResult.setMessage("服务器内部错误");
// break;
// case 502:
// errorResult.setMessage("服务器网关错误");
// break;
// case 504:
// errorResult.setMessage("服务器网关超时");
// break;
// default:
// errorResult.setMessage("未知响应:" + response.message());
// break;
// }
// }
// return errorResult;
// }
//
// @NonNull
// public static ErrorResult from(@NonNull Throwable t) {
// ErrorResult errorResult = new ErrorResult();
// errorResult.setSuccess(false);
// if (t instanceof UnknownHostException || t instanceof ConnectException) {
// errorResult.setMessage("网络无法连接");
// } else if (t instanceof NoRouteToHostException) {
// errorResult.setMessage("无法访问网络");
// } else if (t instanceof SocketTimeoutException) {
// errorResult.setMessage("网络访问超时");
// } else if (t instanceof JsonSyntaxException) {
// errorResult.setMessage("响应数据格式错误");
// } else {
// errorResult.setMessage("未知错误:" + t.getLocalizedMessage());
// }
// return errorResult;
// }
//
// @SerializedName("error_msg")
// private String message;
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/Result.java
// public class Result {
//
// private boolean success;
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ActivityUtils.java
// public final class ActivityUtils {
//
// private ActivityUtils() {}
//
// public static boolean isAlive(@Nullable Activity activity) {
// return activity != null && !(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && activity.isDestroyed()) && !activity.isFinishing();
// }
//
// }
| import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import org.cnodejs.android.md.model.entity.ErrorResult;
import org.cnodejs.android.md.model.entity.Result;
import org.cnodejs.android.md.ui.util.ActivityUtils;
import java.lang.ref.WeakReference;
import okhttp3.Headers;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response; | package org.cnodejs.android.md.model.api;
public class ForegroundCallback<T extends Result> implements Callback<T>, CallbackLifecycle<T> {
private final WeakReference<Activity> activityWeakReference;
public ForegroundCallback(@NonNull Activity activity) {
activityWeakReference = new WeakReference<>(activity);
}
@Nullable
protected final Activity getActivity() {
return activityWeakReference.get();
}
@Override
public final void onResponse(@NonNull Call<T> call, @NonNull Response<T> response) {
Activity activity = getActivity(); | // Path: app/src/main/java/org/cnodejs/android/md/model/entity/ErrorResult.java
// public class ErrorResult extends Result {
//
// @NonNull
// public static ErrorResult from(@NonNull Response response) {
// ErrorResult errorResult = null;
// ResponseBody errorBody = response.errorBody();
// if (errorBody != null) {
// try {
// errorResult = EntityUtils.gson.fromJson(errorBody.string(), ErrorResult.class);
// } catch (Throwable ignored) {}
// }
// if (errorResult == null) {
// errorResult = new ErrorResult();
// errorResult.setSuccess(false);
// switch (response.code()) {
// case 400:
// errorResult.setMessage("非法请求");
// break;
// case 403:
// errorResult.setMessage("非法行为");
// break;
// case 404:
// errorResult.setMessage("未找到资源");
// break;
// case 405:
// errorResult.setMessage("非法请求方式");
// break;
// case 408:
// errorResult.setMessage("请求超时");
// break;
// case 500:
// errorResult.setMessage("服务器内部错误");
// break;
// case 502:
// errorResult.setMessage("服务器网关错误");
// break;
// case 504:
// errorResult.setMessage("服务器网关超时");
// break;
// default:
// errorResult.setMessage("未知响应:" + response.message());
// break;
// }
// }
// return errorResult;
// }
//
// @NonNull
// public static ErrorResult from(@NonNull Throwable t) {
// ErrorResult errorResult = new ErrorResult();
// errorResult.setSuccess(false);
// if (t instanceof UnknownHostException || t instanceof ConnectException) {
// errorResult.setMessage("网络无法连接");
// } else if (t instanceof NoRouteToHostException) {
// errorResult.setMessage("无法访问网络");
// } else if (t instanceof SocketTimeoutException) {
// errorResult.setMessage("网络访问超时");
// } else if (t instanceof JsonSyntaxException) {
// errorResult.setMessage("响应数据格式错误");
// } else {
// errorResult.setMessage("未知错误:" + t.getLocalizedMessage());
// }
// return errorResult;
// }
//
// @SerializedName("error_msg")
// private String message;
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/Result.java
// public class Result {
//
// private boolean success;
//
// public boolean isSuccess() {
// return success;
// }
//
// public void setSuccess(boolean success) {
// this.success = success;
// }
//
// }
//
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/ActivityUtils.java
// public final class ActivityUtils {
//
// private ActivityUtils() {}
//
// public static boolean isAlive(@Nullable Activity activity) {
// return activity != null && !(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && activity.isDestroyed()) && !activity.isFinishing();
// }
//
// }
// Path: app/src/main/java/org/cnodejs/android/md/model/api/ForegroundCallback.java
import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import org.cnodejs.android.md.model.entity.ErrorResult;
import org.cnodejs.android.md.model.entity.Result;
import org.cnodejs.android.md.ui.util.ActivityUtils;
import java.lang.ref.WeakReference;
import okhttp3.Headers;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
package org.cnodejs.android.md.model.api;
public class ForegroundCallback<T extends Result> implements Callback<T>, CallbackLifecycle<T> {
private final WeakReference<Activity> activityWeakReference;
public ForegroundCallback(@NonNull Activity activity) {
activityWeakReference = new WeakReference<>(activity);
}
@Nullable
protected final Activity getActivity() {
return activityWeakReference.get();
}
@Override
public final void onResponse(@NonNull Call<T> call, @NonNull Response<T> response) {
Activity activity = getActivity(); | if (ActivityUtils.isAlive(activity)) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.