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
juga999/easy-com-display
src/main/java/org/chorem/ecd/endpoint/PowerManagementEndpoint.java
// Path: src/main/java/org/chorem/ecd/service/PowerManagementService.java // @ApplicationScoped // public class PowerManagementService { // // private static final Logger logger = LoggerFactory.getLogger(PowerManagementService.class); // // @Inject // protected SettingsDao settingsDao; // // public TvTimes getTvTimes() { // return settingsDao.getTvTimes(); // } // // @TransactionRequired // public void setTvTimes(TvTimes tvTimes) { // validateTvTimes(tvTimes); // // settingsDao.setTvTimes(tvTimes); // } // // private void validateTvTimes(TvTimes tvTimes) throws InvalidArgumentException { // try { // LocalTime.parse(tvTimes.getWakeupTime()); // LocalTime.parse(tvTimes.getSleepTime()); // } catch(NullPointerException | DateTimeParseException e) { // logger.error(e.getMessage(), e); // throw new InvalidArgumentException("Les heures sont invalides"); // } // } // // } // // Path: src/main/java/org/chorem/ecd/model/settings/TvTimes.java // public class TvTimes { // // private String wakeupTime; // // private String sleepTime; // // public TvTimes() { // // } // // public TvTimes(String wakeupTime, String sleepTime) { // this.wakeupTime = wakeupTime; // this.sleepTime = sleepTime; // } // // public String getWakeupTime() { // return wakeupTime; // } // // public void setWakeupTime(String wakeupTime) { // this.wakeupTime = wakeupTime; // } // // public String getSleepTime() { // return sleepTime; // } // // public void setSleepTime(String sleepTime) { // this.sleepTime = sleepTime; // } // // }
import org.chorem.ecd.service.PowerManagementService; import org.chorem.ecd.model.settings.TvTimes; import spark.Request; import spark.Response; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject;
package org.chorem.ecd.endpoint; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class PowerManagementEndpoint extends Endpoint { @Inject
// Path: src/main/java/org/chorem/ecd/service/PowerManagementService.java // @ApplicationScoped // public class PowerManagementService { // // private static final Logger logger = LoggerFactory.getLogger(PowerManagementService.class); // // @Inject // protected SettingsDao settingsDao; // // public TvTimes getTvTimes() { // return settingsDao.getTvTimes(); // } // // @TransactionRequired // public void setTvTimes(TvTimes tvTimes) { // validateTvTimes(tvTimes); // // settingsDao.setTvTimes(tvTimes); // } // // private void validateTvTimes(TvTimes tvTimes) throws InvalidArgumentException { // try { // LocalTime.parse(tvTimes.getWakeupTime()); // LocalTime.parse(tvTimes.getSleepTime()); // } catch(NullPointerException | DateTimeParseException e) { // logger.error(e.getMessage(), e); // throw new InvalidArgumentException("Les heures sont invalides"); // } // } // // } // // Path: src/main/java/org/chorem/ecd/model/settings/TvTimes.java // public class TvTimes { // // private String wakeupTime; // // private String sleepTime; // // public TvTimes() { // // } // // public TvTimes(String wakeupTime, String sleepTime) { // this.wakeupTime = wakeupTime; // this.sleepTime = sleepTime; // } // // public String getWakeupTime() { // return wakeupTime; // } // // public void setWakeupTime(String wakeupTime) { // this.wakeupTime = wakeupTime; // } // // public String getSleepTime() { // return sleepTime; // } // // public void setSleepTime(String sleepTime) { // this.sleepTime = sleepTime; // } // // } // Path: src/main/java/org/chorem/ecd/endpoint/PowerManagementEndpoint.java import org.chorem.ecd.service.PowerManagementService; import org.chorem.ecd.model.settings.TvTimes; import spark.Request; import spark.Response; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; package org.chorem.ecd.endpoint; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class PowerManagementEndpoint extends Endpoint { @Inject
protected PowerManagementService powerManagementService;
juga999/easy-com-display
src/main/java/org/chorem/ecd/endpoint/PowerManagementEndpoint.java
// Path: src/main/java/org/chorem/ecd/service/PowerManagementService.java // @ApplicationScoped // public class PowerManagementService { // // private static final Logger logger = LoggerFactory.getLogger(PowerManagementService.class); // // @Inject // protected SettingsDao settingsDao; // // public TvTimes getTvTimes() { // return settingsDao.getTvTimes(); // } // // @TransactionRequired // public void setTvTimes(TvTimes tvTimes) { // validateTvTimes(tvTimes); // // settingsDao.setTvTimes(tvTimes); // } // // private void validateTvTimes(TvTimes tvTimes) throws InvalidArgumentException { // try { // LocalTime.parse(tvTimes.getWakeupTime()); // LocalTime.parse(tvTimes.getSleepTime()); // } catch(NullPointerException | DateTimeParseException e) { // logger.error(e.getMessage(), e); // throw new InvalidArgumentException("Les heures sont invalides"); // } // } // // } // // Path: src/main/java/org/chorem/ecd/model/settings/TvTimes.java // public class TvTimes { // // private String wakeupTime; // // private String sleepTime; // // public TvTimes() { // // } // // public TvTimes(String wakeupTime, String sleepTime) { // this.wakeupTime = wakeupTime; // this.sleepTime = sleepTime; // } // // public String getWakeupTime() { // return wakeupTime; // } // // public void setWakeupTime(String wakeupTime) { // this.wakeupTime = wakeupTime; // } // // public String getSleepTime() { // return sleepTime; // } // // public void setSleepTime(String sleepTime) { // this.sleepTime = sleepTime; // } // // }
import org.chorem.ecd.service.PowerManagementService; import org.chorem.ecd.model.settings.TvTimes; import spark.Request; import spark.Response; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject;
package org.chorem.ecd.endpoint; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class PowerManagementEndpoint extends Endpoint { @Inject protected PowerManagementService powerManagementService; @Override protected void init() { registerJsonProducer(ecdApiPath("/settings/tv-times"), this::getTvTimes); registerJsonConsumer(ecdApiPath("/settings/tv-times"), this::setTvTimes); } private Object getTvTimes(Request req, Response resp) { return powerManagementService.getTvTimes(); } private Object setTvTimes(Request req, Response resp) throws Exception {
// Path: src/main/java/org/chorem/ecd/service/PowerManagementService.java // @ApplicationScoped // public class PowerManagementService { // // private static final Logger logger = LoggerFactory.getLogger(PowerManagementService.class); // // @Inject // protected SettingsDao settingsDao; // // public TvTimes getTvTimes() { // return settingsDao.getTvTimes(); // } // // @TransactionRequired // public void setTvTimes(TvTimes tvTimes) { // validateTvTimes(tvTimes); // // settingsDao.setTvTimes(tvTimes); // } // // private void validateTvTimes(TvTimes tvTimes) throws InvalidArgumentException { // try { // LocalTime.parse(tvTimes.getWakeupTime()); // LocalTime.parse(tvTimes.getSleepTime()); // } catch(NullPointerException | DateTimeParseException e) { // logger.error(e.getMessage(), e); // throw new InvalidArgumentException("Les heures sont invalides"); // } // } // // } // // Path: src/main/java/org/chorem/ecd/model/settings/TvTimes.java // public class TvTimes { // // private String wakeupTime; // // private String sleepTime; // // public TvTimes() { // // } // // public TvTimes(String wakeupTime, String sleepTime) { // this.wakeupTime = wakeupTime; // this.sleepTime = sleepTime; // } // // public String getWakeupTime() { // return wakeupTime; // } // // public void setWakeupTime(String wakeupTime) { // this.wakeupTime = wakeupTime; // } // // public String getSleepTime() { // return sleepTime; // } // // public void setSleepTime(String sleepTime) { // this.sleepTime = sleepTime; // } // // } // Path: src/main/java/org/chorem/ecd/endpoint/PowerManagementEndpoint.java import org.chorem.ecd.service.PowerManagementService; import org.chorem.ecd.model.settings.TvTimes; import spark.Request; import spark.Response; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; package org.chorem.ecd.endpoint; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class PowerManagementEndpoint extends Endpoint { @Inject protected PowerManagementService powerManagementService; @Override protected void init() { registerJsonProducer(ecdApiPath("/settings/tv-times"), this::getTvTimes); registerJsonConsumer(ecdApiPath("/settings/tv-times"), this::setTvTimes); } private Object getTvTimes(Request req, Response resp) { return powerManagementService.getTvTimes(); } private Object setTvTimes(Request req, Response resp) throws Exception {
TvTimes tvTimes = getObject(req, TvTimes.class);
juga999/easy-com-display
src/main/java/org/chorem/ecd/App.java
// Path: src/main/java/org/chorem/ecd/exception/InvalidArgumentException.java // public class InvalidArgumentException extends RuntimeException { // // public InvalidArgumentException(String msg) { // super(msg); // } // // } // // Path: src/main/java/org/chorem/ecd/service/PeriodicTasksExecutorService.java // @Singleton // public class PeriodicTasksExecutorService { // // private static final Logger logger = LoggerFactory.getLogger(PeriodicTasksExecutorService.class); // // private ScheduledExecutorService executor = Executors.newScheduledThreadPool(4); // // private Map<String, ScheduledFuture<?>> taskFuturesMap = Maps.newConcurrentMap(); // // @PostConstruct // public void init() { // } // // @PreDestroy // public void shutdown() { // taskFuturesMap.forEach((name, future) -> { // future.cancel(false); // logger.info("Cancelled " + name); // }); // taskFuturesMap.clear(); // } // // public void schedule(EcdPeriodicTask task) { // ScheduledFuture<?> future; // if (taskFuturesMap.containsKey(task.getName())) { // future = taskFuturesMap.get(task.getName()); // future.cancel(false); // taskFuturesMap.remove(task.getName()); // } // future = executor.scheduleWithFixedDelay(task, 0, task.getPeriodicity(), task.getPeriodicityUnit()); // taskFuturesMap.put(task.getName(), future); // logger.info("Scheduled " + task.getName()); // } // }
import org.jboss.weld.environment.se.Weld; import org.jboss.weld.environment.se.WeldContainer; import org.chorem.ecd.exception.InvalidArgumentException; import org.chorem.ecd.service.PeriodicTasksExecutorService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import spark.Spark; import java.net.HttpURLConnection;
package org.chorem.ecd; public class App { private static final Logger logger = LoggerFactory.getLogger(App.class); public static void main(String args[]) throws Exception { Spark.threadPool(4); Spark.port(8084);
// Path: src/main/java/org/chorem/ecd/exception/InvalidArgumentException.java // public class InvalidArgumentException extends RuntimeException { // // public InvalidArgumentException(String msg) { // super(msg); // } // // } // // Path: src/main/java/org/chorem/ecd/service/PeriodicTasksExecutorService.java // @Singleton // public class PeriodicTasksExecutorService { // // private static final Logger logger = LoggerFactory.getLogger(PeriodicTasksExecutorService.class); // // private ScheduledExecutorService executor = Executors.newScheduledThreadPool(4); // // private Map<String, ScheduledFuture<?>> taskFuturesMap = Maps.newConcurrentMap(); // // @PostConstruct // public void init() { // } // // @PreDestroy // public void shutdown() { // taskFuturesMap.forEach((name, future) -> { // future.cancel(false); // logger.info("Cancelled " + name); // }); // taskFuturesMap.clear(); // } // // public void schedule(EcdPeriodicTask task) { // ScheduledFuture<?> future; // if (taskFuturesMap.containsKey(task.getName())) { // future = taskFuturesMap.get(task.getName()); // future.cancel(false); // taskFuturesMap.remove(task.getName()); // } // future = executor.scheduleWithFixedDelay(task, 0, task.getPeriodicity(), task.getPeriodicityUnit()); // taskFuturesMap.put(task.getName(), future); // logger.info("Scheduled " + task.getName()); // } // } // Path: src/main/java/org/chorem/ecd/App.java import org.jboss.weld.environment.se.Weld; import org.jboss.weld.environment.se.WeldContainer; import org.chorem.ecd.exception.InvalidArgumentException; import org.chorem.ecd.service.PeriodicTasksExecutorService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import spark.Spark; import java.net.HttpURLConnection; package org.chorem.ecd; public class App { private static final Logger logger = LoggerFactory.getLogger(App.class); public static void main(String args[]) throws Exception { Spark.threadPool(4); Spark.port(8084);
Spark.exception(InvalidArgumentException.class, (e, req, resp) -> {
juga999/easy-com-display
src/main/java/org/chorem/ecd/App.java
// Path: src/main/java/org/chorem/ecd/exception/InvalidArgumentException.java // public class InvalidArgumentException extends RuntimeException { // // public InvalidArgumentException(String msg) { // super(msg); // } // // } // // Path: src/main/java/org/chorem/ecd/service/PeriodicTasksExecutorService.java // @Singleton // public class PeriodicTasksExecutorService { // // private static final Logger logger = LoggerFactory.getLogger(PeriodicTasksExecutorService.class); // // private ScheduledExecutorService executor = Executors.newScheduledThreadPool(4); // // private Map<String, ScheduledFuture<?>> taskFuturesMap = Maps.newConcurrentMap(); // // @PostConstruct // public void init() { // } // // @PreDestroy // public void shutdown() { // taskFuturesMap.forEach((name, future) -> { // future.cancel(false); // logger.info("Cancelled " + name); // }); // taskFuturesMap.clear(); // } // // public void schedule(EcdPeriodicTask task) { // ScheduledFuture<?> future; // if (taskFuturesMap.containsKey(task.getName())) { // future = taskFuturesMap.get(task.getName()); // future.cancel(false); // taskFuturesMap.remove(task.getName()); // } // future = executor.scheduleWithFixedDelay(task, 0, task.getPeriodicity(), task.getPeriodicityUnit()); // taskFuturesMap.put(task.getName(), future); // logger.info("Scheduled " + task.getName()); // } // }
import org.jboss.weld.environment.se.Weld; import org.jboss.weld.environment.se.WeldContainer; import org.chorem.ecd.exception.InvalidArgumentException; import org.chorem.ecd.service.PeriodicTasksExecutorService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import spark.Spark; import java.net.HttpURLConnection;
package org.chorem.ecd; public class App { private static final Logger logger = LoggerFactory.getLogger(App.class); public static void main(String args[]) throws Exception { Spark.threadPool(4); Spark.port(8084); Spark.exception(InvalidArgumentException.class, (e, req, resp) -> { logger.error(e.getMessage(), e); resp.status(HttpURLConnection.HTTP_BAD_REQUEST); resp.type("application/json"); resp.body(String.format("{\"message\":\"%s\"}", e.getMessage())); }); Spark.staticFileLocation("/public"); Weld.newInstance().initialize();
// Path: src/main/java/org/chorem/ecd/exception/InvalidArgumentException.java // public class InvalidArgumentException extends RuntimeException { // // public InvalidArgumentException(String msg) { // super(msg); // } // // } // // Path: src/main/java/org/chorem/ecd/service/PeriodicTasksExecutorService.java // @Singleton // public class PeriodicTasksExecutorService { // // private static final Logger logger = LoggerFactory.getLogger(PeriodicTasksExecutorService.class); // // private ScheduledExecutorService executor = Executors.newScheduledThreadPool(4); // // private Map<String, ScheduledFuture<?>> taskFuturesMap = Maps.newConcurrentMap(); // // @PostConstruct // public void init() { // } // // @PreDestroy // public void shutdown() { // taskFuturesMap.forEach((name, future) -> { // future.cancel(false); // logger.info("Cancelled " + name); // }); // taskFuturesMap.clear(); // } // // public void schedule(EcdPeriodicTask task) { // ScheduledFuture<?> future; // if (taskFuturesMap.containsKey(task.getName())) { // future = taskFuturesMap.get(task.getName()); // future.cancel(false); // taskFuturesMap.remove(task.getName()); // } // future = executor.scheduleWithFixedDelay(task, 0, task.getPeriodicity(), task.getPeriodicityUnit()); // taskFuturesMap.put(task.getName(), future); // logger.info("Scheduled " + task.getName()); // } // } // Path: src/main/java/org/chorem/ecd/App.java import org.jboss.weld.environment.se.Weld; import org.jboss.weld.environment.se.WeldContainer; import org.chorem.ecd.exception.InvalidArgumentException; import org.chorem.ecd.service.PeriodicTasksExecutorService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import spark.Spark; import java.net.HttpURLConnection; package org.chorem.ecd; public class App { private static final Logger logger = LoggerFactory.getLogger(App.class); public static void main(String args[]) throws Exception { Spark.threadPool(4); Spark.port(8084); Spark.exception(InvalidArgumentException.class, (e, req, resp) -> { logger.error(e.getMessage(), e); resp.status(HttpURLConnection.HTTP_BAD_REQUEST); resp.type("application/json"); resp.body(String.format("{\"message\":\"%s\"}", e.getMessage())); }); Spark.staticFileLocation("/public"); Weld.newInstance().initialize();
WeldContainer.current().select(PeriodicTasksExecutorService.class).get();
juga999/easy-com-display
src/main/java/org/chorem/ecd/dao/EcdDataSource.java
// Path: src/main/java/org/chorem/ecd/EcdConfig.java // @ApplicationScoped // public class EcdConfig { // // private static final Logger logger = LoggerFactory.getLogger(EcdConfig.class); // // private final Properties props; // // public static final String STREAMS_DIR = "streams"; // public static final String NEWS_DIR = "news"; // public static final String WEATHER_DIR = "weather"; // // public EcdConfig() { // props = new Properties(); // try { // props.load(getClass().getClassLoader().getResourceAsStream("ecd.properties")); // } catch (IOException e) { // logger.error(e.getMessage(), e); // } // } // // public String getDataSourceUrl() { // return props.getProperty("ecd.datasource.url"); // } // // public String getDataSourceLogin() { // return props.getProperty("ecd.datasource.login"); // } // // public String getDataSourcePwd() { // return props.getProperty("ecd.datasource.pwd"); // } // // public String getApiPathPrefix() { // return "/api/ecd"; // } // // public String getMediaPathPrefix() { // return "/media/ecd"; // } // // public String getDataDir() { // return props.getProperty("ecd.data.dir"); // } // // public String getUploadDir() { return props.getProperty("ecd.upload.dir"); } // // public String getUnoconvCmd() { // return props.getProperty("ecd.cmd.unoconv"); // } // // public String getResizeCmd() { // return props.getProperty("ecd.cmd.resize"); // } // // public String getLocationSearchUrlFormat() { // return props.getProperty("ecd.location.searchUrlFormat"); // } // // public Integer getDefaultStreamTiming() { // return Integer.valueOf(props.getProperty("ecd.default.streamTiming")); // } // // public Path getStreamsPath() { // return Paths.get(getDataDir(), STREAMS_DIR); // } // // public Path getAggregatedNewsPath() { // return Paths.get(getDataDir(), NEWS_DIR, "aggregated.json"); // } // // public Path getWeatherForecastPath() { // return Paths.get(getDataDir(), WEATHER_DIR, "forecast.json"); // } // // }
import org.apache.tomcat.jdbc.pool.DataSource; import org.apache.tomcat.jdbc.pool.PoolProperties; import org.chorem.ecd.EcdConfig; import org.flywaydb.core.Flyway; import org.jooq.Configuration; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.Initialized; import javax.enterprise.event.Observes; import javax.inject.Inject; import java.util.Optional;
package org.chorem.ecd.dao; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class EcdDataSource { private static final Logger logger = LoggerFactory.getLogger(EcdDataSource.class); @Inject
// Path: src/main/java/org/chorem/ecd/EcdConfig.java // @ApplicationScoped // public class EcdConfig { // // private static final Logger logger = LoggerFactory.getLogger(EcdConfig.class); // // private final Properties props; // // public static final String STREAMS_DIR = "streams"; // public static final String NEWS_DIR = "news"; // public static final String WEATHER_DIR = "weather"; // // public EcdConfig() { // props = new Properties(); // try { // props.load(getClass().getClassLoader().getResourceAsStream("ecd.properties")); // } catch (IOException e) { // logger.error(e.getMessage(), e); // } // } // // public String getDataSourceUrl() { // return props.getProperty("ecd.datasource.url"); // } // // public String getDataSourceLogin() { // return props.getProperty("ecd.datasource.login"); // } // // public String getDataSourcePwd() { // return props.getProperty("ecd.datasource.pwd"); // } // // public String getApiPathPrefix() { // return "/api/ecd"; // } // // public String getMediaPathPrefix() { // return "/media/ecd"; // } // // public String getDataDir() { // return props.getProperty("ecd.data.dir"); // } // // public String getUploadDir() { return props.getProperty("ecd.upload.dir"); } // // public String getUnoconvCmd() { // return props.getProperty("ecd.cmd.unoconv"); // } // // public String getResizeCmd() { // return props.getProperty("ecd.cmd.resize"); // } // // public String getLocationSearchUrlFormat() { // return props.getProperty("ecd.location.searchUrlFormat"); // } // // public Integer getDefaultStreamTiming() { // return Integer.valueOf(props.getProperty("ecd.default.streamTiming")); // } // // public Path getStreamsPath() { // return Paths.get(getDataDir(), STREAMS_DIR); // } // // public Path getAggregatedNewsPath() { // return Paths.get(getDataDir(), NEWS_DIR, "aggregated.json"); // } // // public Path getWeatherForecastPath() { // return Paths.get(getDataDir(), WEATHER_DIR, "forecast.json"); // } // // } // Path: src/main/java/org/chorem/ecd/dao/EcdDataSource.java import org.apache.tomcat.jdbc.pool.DataSource; import org.apache.tomcat.jdbc.pool.PoolProperties; import org.chorem.ecd.EcdConfig; import org.flywaydb.core.Flyway; import org.jooq.Configuration; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.context.Initialized; import javax.enterprise.event.Observes; import javax.inject.Inject; import java.util.Optional; package org.chorem.ecd.dao; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class EcdDataSource { private static final Logger logger = LoggerFactory.getLogger(EcdDataSource.class); @Inject
protected EcdConfig ecdConfig;
juga999/easy-com-display
src/main/java/org/chorem/ecd/service/PowerManagementService.java
// Path: src/main/java/org/chorem/ecd/dao/SettingsDao.java // @ApplicationScoped // public class SettingsDao extends AbstractDao<Settings, Integer> { // // public SettingsDao() { // super(Settings.class, SETTINGS, SETTINGS.ID::eq); // } // // public TvTimes getTvTimes() { // DSLContext create = dataSource.getSqlContext(); // TvTimes result = create.select(SETTINGS.TV_TIMES).from(SETTINGS).where(SETTINGS.ID.eq(1)) // .fetchOptionalInto(String.class) // .map(json -> gson.fromJson(json, TvTimes.class)) // .orElse(new TvTimes()); // return result; // } // // public Location getLocation() { // DSLContext create = dataSource.getSqlContext(); // Location result = create.select(SETTINGS.LOCATION).from(SETTINGS).where(SETTINGS.ID.eq(1)) // .fetchOptionalInto(String.class) // .map(json -> gson.fromJson(json, Location.class)) // .orElse(new Location()); // return result; // } // // public void setTvTimes(TvTimes tvTimes) { // Object value = DSL.cast(gson.toJson(tvTimes), PostgresDataType.JSON); // DSLContext create = dataSource.getSqlContext(); // create.insertInto(SETTINGS, SETTINGS.ID, SETTINGS.TV_TIMES) // .values(1, value) // .onDuplicateKeyUpdate() // .set(SETTINGS.TV_TIMES, value) // .execute(); // } // // public void setLocation(Location location) { // Object value = DSL.cast(gson.toJson(location), PostgresDataType.JSON); // DSLContext create = dataSource.getSqlContext(); // create.insertInto(SETTINGS, SETTINGS.ID, SETTINGS.LOCATION) // .values(1, value) // .onDuplicateKeyUpdate() // .set(SETTINGS.LOCATION, value) // .execute(); // } // // @Override // protected RecordMapper<Record, Settings> getRecordMapper() { // throw new UnsupportedOperationException(); // } // // } // // Path: src/main/java/org/chorem/ecd/exception/InvalidArgumentException.java // public class InvalidArgumentException extends RuntimeException { // // public InvalidArgumentException(String msg) { // super(msg); // } // // } // // Path: src/main/java/org/chorem/ecd/model/settings/TvTimes.java // public class TvTimes { // // private String wakeupTime; // // private String sleepTime; // // public TvTimes() { // // } // // public TvTimes(String wakeupTime, String sleepTime) { // this.wakeupTime = wakeupTime; // this.sleepTime = sleepTime; // } // // public String getWakeupTime() { // return wakeupTime; // } // // public void setWakeupTime(String wakeupTime) { // this.wakeupTime = wakeupTime; // } // // public String getSleepTime() { // return sleepTime; // } // // public void setSleepTime(String sleepTime) { // this.sleepTime = sleepTime; // } // // }
import org.chorem.ecd.dao.SettingsDao; import org.chorem.ecd.dao.TransactionRequired; import org.chorem.ecd.exception.InvalidArgumentException; import org.chorem.ecd.model.settings.TvTimes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import java.time.LocalTime; import java.time.format.DateTimeParseException;
package org.chorem.ecd.service; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class PowerManagementService { private static final Logger logger = LoggerFactory.getLogger(PowerManagementService.class); @Inject
// Path: src/main/java/org/chorem/ecd/dao/SettingsDao.java // @ApplicationScoped // public class SettingsDao extends AbstractDao<Settings, Integer> { // // public SettingsDao() { // super(Settings.class, SETTINGS, SETTINGS.ID::eq); // } // // public TvTimes getTvTimes() { // DSLContext create = dataSource.getSqlContext(); // TvTimes result = create.select(SETTINGS.TV_TIMES).from(SETTINGS).where(SETTINGS.ID.eq(1)) // .fetchOptionalInto(String.class) // .map(json -> gson.fromJson(json, TvTimes.class)) // .orElse(new TvTimes()); // return result; // } // // public Location getLocation() { // DSLContext create = dataSource.getSqlContext(); // Location result = create.select(SETTINGS.LOCATION).from(SETTINGS).where(SETTINGS.ID.eq(1)) // .fetchOptionalInto(String.class) // .map(json -> gson.fromJson(json, Location.class)) // .orElse(new Location()); // return result; // } // // public void setTvTimes(TvTimes tvTimes) { // Object value = DSL.cast(gson.toJson(tvTimes), PostgresDataType.JSON); // DSLContext create = dataSource.getSqlContext(); // create.insertInto(SETTINGS, SETTINGS.ID, SETTINGS.TV_TIMES) // .values(1, value) // .onDuplicateKeyUpdate() // .set(SETTINGS.TV_TIMES, value) // .execute(); // } // // public void setLocation(Location location) { // Object value = DSL.cast(gson.toJson(location), PostgresDataType.JSON); // DSLContext create = dataSource.getSqlContext(); // create.insertInto(SETTINGS, SETTINGS.ID, SETTINGS.LOCATION) // .values(1, value) // .onDuplicateKeyUpdate() // .set(SETTINGS.LOCATION, value) // .execute(); // } // // @Override // protected RecordMapper<Record, Settings> getRecordMapper() { // throw new UnsupportedOperationException(); // } // // } // // Path: src/main/java/org/chorem/ecd/exception/InvalidArgumentException.java // public class InvalidArgumentException extends RuntimeException { // // public InvalidArgumentException(String msg) { // super(msg); // } // // } // // Path: src/main/java/org/chorem/ecd/model/settings/TvTimes.java // public class TvTimes { // // private String wakeupTime; // // private String sleepTime; // // public TvTimes() { // // } // // public TvTimes(String wakeupTime, String sleepTime) { // this.wakeupTime = wakeupTime; // this.sleepTime = sleepTime; // } // // public String getWakeupTime() { // return wakeupTime; // } // // public void setWakeupTime(String wakeupTime) { // this.wakeupTime = wakeupTime; // } // // public String getSleepTime() { // return sleepTime; // } // // public void setSleepTime(String sleepTime) { // this.sleepTime = sleepTime; // } // // } // Path: src/main/java/org/chorem/ecd/service/PowerManagementService.java import org.chorem.ecd.dao.SettingsDao; import org.chorem.ecd.dao.TransactionRequired; import org.chorem.ecd.exception.InvalidArgumentException; import org.chorem.ecd.model.settings.TvTimes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import java.time.LocalTime; import java.time.format.DateTimeParseException; package org.chorem.ecd.service; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class PowerManagementService { private static final Logger logger = LoggerFactory.getLogger(PowerManagementService.class); @Inject
protected SettingsDao settingsDao;
juga999/easy-com-display
src/main/java/org/chorem/ecd/service/PowerManagementService.java
// Path: src/main/java/org/chorem/ecd/dao/SettingsDao.java // @ApplicationScoped // public class SettingsDao extends AbstractDao<Settings, Integer> { // // public SettingsDao() { // super(Settings.class, SETTINGS, SETTINGS.ID::eq); // } // // public TvTimes getTvTimes() { // DSLContext create = dataSource.getSqlContext(); // TvTimes result = create.select(SETTINGS.TV_TIMES).from(SETTINGS).where(SETTINGS.ID.eq(1)) // .fetchOptionalInto(String.class) // .map(json -> gson.fromJson(json, TvTimes.class)) // .orElse(new TvTimes()); // return result; // } // // public Location getLocation() { // DSLContext create = dataSource.getSqlContext(); // Location result = create.select(SETTINGS.LOCATION).from(SETTINGS).where(SETTINGS.ID.eq(1)) // .fetchOptionalInto(String.class) // .map(json -> gson.fromJson(json, Location.class)) // .orElse(new Location()); // return result; // } // // public void setTvTimes(TvTimes tvTimes) { // Object value = DSL.cast(gson.toJson(tvTimes), PostgresDataType.JSON); // DSLContext create = dataSource.getSqlContext(); // create.insertInto(SETTINGS, SETTINGS.ID, SETTINGS.TV_TIMES) // .values(1, value) // .onDuplicateKeyUpdate() // .set(SETTINGS.TV_TIMES, value) // .execute(); // } // // public void setLocation(Location location) { // Object value = DSL.cast(gson.toJson(location), PostgresDataType.JSON); // DSLContext create = dataSource.getSqlContext(); // create.insertInto(SETTINGS, SETTINGS.ID, SETTINGS.LOCATION) // .values(1, value) // .onDuplicateKeyUpdate() // .set(SETTINGS.LOCATION, value) // .execute(); // } // // @Override // protected RecordMapper<Record, Settings> getRecordMapper() { // throw new UnsupportedOperationException(); // } // // } // // Path: src/main/java/org/chorem/ecd/exception/InvalidArgumentException.java // public class InvalidArgumentException extends RuntimeException { // // public InvalidArgumentException(String msg) { // super(msg); // } // // } // // Path: src/main/java/org/chorem/ecd/model/settings/TvTimes.java // public class TvTimes { // // private String wakeupTime; // // private String sleepTime; // // public TvTimes() { // // } // // public TvTimes(String wakeupTime, String sleepTime) { // this.wakeupTime = wakeupTime; // this.sleepTime = sleepTime; // } // // public String getWakeupTime() { // return wakeupTime; // } // // public void setWakeupTime(String wakeupTime) { // this.wakeupTime = wakeupTime; // } // // public String getSleepTime() { // return sleepTime; // } // // public void setSleepTime(String sleepTime) { // this.sleepTime = sleepTime; // } // // }
import org.chorem.ecd.dao.SettingsDao; import org.chorem.ecd.dao.TransactionRequired; import org.chorem.ecd.exception.InvalidArgumentException; import org.chorem.ecd.model.settings.TvTimes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import java.time.LocalTime; import java.time.format.DateTimeParseException;
package org.chorem.ecd.service; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class PowerManagementService { private static final Logger logger = LoggerFactory.getLogger(PowerManagementService.class); @Inject protected SettingsDao settingsDao;
// Path: src/main/java/org/chorem/ecd/dao/SettingsDao.java // @ApplicationScoped // public class SettingsDao extends AbstractDao<Settings, Integer> { // // public SettingsDao() { // super(Settings.class, SETTINGS, SETTINGS.ID::eq); // } // // public TvTimes getTvTimes() { // DSLContext create = dataSource.getSqlContext(); // TvTimes result = create.select(SETTINGS.TV_TIMES).from(SETTINGS).where(SETTINGS.ID.eq(1)) // .fetchOptionalInto(String.class) // .map(json -> gson.fromJson(json, TvTimes.class)) // .orElse(new TvTimes()); // return result; // } // // public Location getLocation() { // DSLContext create = dataSource.getSqlContext(); // Location result = create.select(SETTINGS.LOCATION).from(SETTINGS).where(SETTINGS.ID.eq(1)) // .fetchOptionalInto(String.class) // .map(json -> gson.fromJson(json, Location.class)) // .orElse(new Location()); // return result; // } // // public void setTvTimes(TvTimes tvTimes) { // Object value = DSL.cast(gson.toJson(tvTimes), PostgresDataType.JSON); // DSLContext create = dataSource.getSqlContext(); // create.insertInto(SETTINGS, SETTINGS.ID, SETTINGS.TV_TIMES) // .values(1, value) // .onDuplicateKeyUpdate() // .set(SETTINGS.TV_TIMES, value) // .execute(); // } // // public void setLocation(Location location) { // Object value = DSL.cast(gson.toJson(location), PostgresDataType.JSON); // DSLContext create = dataSource.getSqlContext(); // create.insertInto(SETTINGS, SETTINGS.ID, SETTINGS.LOCATION) // .values(1, value) // .onDuplicateKeyUpdate() // .set(SETTINGS.LOCATION, value) // .execute(); // } // // @Override // protected RecordMapper<Record, Settings> getRecordMapper() { // throw new UnsupportedOperationException(); // } // // } // // Path: src/main/java/org/chorem/ecd/exception/InvalidArgumentException.java // public class InvalidArgumentException extends RuntimeException { // // public InvalidArgumentException(String msg) { // super(msg); // } // // } // // Path: src/main/java/org/chorem/ecd/model/settings/TvTimes.java // public class TvTimes { // // private String wakeupTime; // // private String sleepTime; // // public TvTimes() { // // } // // public TvTimes(String wakeupTime, String sleepTime) { // this.wakeupTime = wakeupTime; // this.sleepTime = sleepTime; // } // // public String getWakeupTime() { // return wakeupTime; // } // // public void setWakeupTime(String wakeupTime) { // this.wakeupTime = wakeupTime; // } // // public String getSleepTime() { // return sleepTime; // } // // public void setSleepTime(String sleepTime) { // this.sleepTime = sleepTime; // } // // } // Path: src/main/java/org/chorem/ecd/service/PowerManagementService.java import org.chorem.ecd.dao.SettingsDao; import org.chorem.ecd.dao.TransactionRequired; import org.chorem.ecd.exception.InvalidArgumentException; import org.chorem.ecd.model.settings.TvTimes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import java.time.LocalTime; import java.time.format.DateTimeParseException; package org.chorem.ecd.service; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class PowerManagementService { private static final Logger logger = LoggerFactory.getLogger(PowerManagementService.class); @Inject protected SettingsDao settingsDao;
public TvTimes getTvTimes() {
juga999/easy-com-display
src/main/java/org/chorem/ecd/service/PowerManagementService.java
// Path: src/main/java/org/chorem/ecd/dao/SettingsDao.java // @ApplicationScoped // public class SettingsDao extends AbstractDao<Settings, Integer> { // // public SettingsDao() { // super(Settings.class, SETTINGS, SETTINGS.ID::eq); // } // // public TvTimes getTvTimes() { // DSLContext create = dataSource.getSqlContext(); // TvTimes result = create.select(SETTINGS.TV_TIMES).from(SETTINGS).where(SETTINGS.ID.eq(1)) // .fetchOptionalInto(String.class) // .map(json -> gson.fromJson(json, TvTimes.class)) // .orElse(new TvTimes()); // return result; // } // // public Location getLocation() { // DSLContext create = dataSource.getSqlContext(); // Location result = create.select(SETTINGS.LOCATION).from(SETTINGS).where(SETTINGS.ID.eq(1)) // .fetchOptionalInto(String.class) // .map(json -> gson.fromJson(json, Location.class)) // .orElse(new Location()); // return result; // } // // public void setTvTimes(TvTimes tvTimes) { // Object value = DSL.cast(gson.toJson(tvTimes), PostgresDataType.JSON); // DSLContext create = dataSource.getSqlContext(); // create.insertInto(SETTINGS, SETTINGS.ID, SETTINGS.TV_TIMES) // .values(1, value) // .onDuplicateKeyUpdate() // .set(SETTINGS.TV_TIMES, value) // .execute(); // } // // public void setLocation(Location location) { // Object value = DSL.cast(gson.toJson(location), PostgresDataType.JSON); // DSLContext create = dataSource.getSqlContext(); // create.insertInto(SETTINGS, SETTINGS.ID, SETTINGS.LOCATION) // .values(1, value) // .onDuplicateKeyUpdate() // .set(SETTINGS.LOCATION, value) // .execute(); // } // // @Override // protected RecordMapper<Record, Settings> getRecordMapper() { // throw new UnsupportedOperationException(); // } // // } // // Path: src/main/java/org/chorem/ecd/exception/InvalidArgumentException.java // public class InvalidArgumentException extends RuntimeException { // // public InvalidArgumentException(String msg) { // super(msg); // } // // } // // Path: src/main/java/org/chorem/ecd/model/settings/TvTimes.java // public class TvTimes { // // private String wakeupTime; // // private String sleepTime; // // public TvTimes() { // // } // // public TvTimes(String wakeupTime, String sleepTime) { // this.wakeupTime = wakeupTime; // this.sleepTime = sleepTime; // } // // public String getWakeupTime() { // return wakeupTime; // } // // public void setWakeupTime(String wakeupTime) { // this.wakeupTime = wakeupTime; // } // // public String getSleepTime() { // return sleepTime; // } // // public void setSleepTime(String sleepTime) { // this.sleepTime = sleepTime; // } // // }
import org.chorem.ecd.dao.SettingsDao; import org.chorem.ecd.dao.TransactionRequired; import org.chorem.ecd.exception.InvalidArgumentException; import org.chorem.ecd.model.settings.TvTimes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import java.time.LocalTime; import java.time.format.DateTimeParseException;
package org.chorem.ecd.service; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class PowerManagementService { private static final Logger logger = LoggerFactory.getLogger(PowerManagementService.class); @Inject protected SettingsDao settingsDao; public TvTimes getTvTimes() { return settingsDao.getTvTimes(); } @TransactionRequired public void setTvTimes(TvTimes tvTimes) { validateTvTimes(tvTimes); settingsDao.setTvTimes(tvTimes); }
// Path: src/main/java/org/chorem/ecd/dao/SettingsDao.java // @ApplicationScoped // public class SettingsDao extends AbstractDao<Settings, Integer> { // // public SettingsDao() { // super(Settings.class, SETTINGS, SETTINGS.ID::eq); // } // // public TvTimes getTvTimes() { // DSLContext create = dataSource.getSqlContext(); // TvTimes result = create.select(SETTINGS.TV_TIMES).from(SETTINGS).where(SETTINGS.ID.eq(1)) // .fetchOptionalInto(String.class) // .map(json -> gson.fromJson(json, TvTimes.class)) // .orElse(new TvTimes()); // return result; // } // // public Location getLocation() { // DSLContext create = dataSource.getSqlContext(); // Location result = create.select(SETTINGS.LOCATION).from(SETTINGS).where(SETTINGS.ID.eq(1)) // .fetchOptionalInto(String.class) // .map(json -> gson.fromJson(json, Location.class)) // .orElse(new Location()); // return result; // } // // public void setTvTimes(TvTimes tvTimes) { // Object value = DSL.cast(gson.toJson(tvTimes), PostgresDataType.JSON); // DSLContext create = dataSource.getSqlContext(); // create.insertInto(SETTINGS, SETTINGS.ID, SETTINGS.TV_TIMES) // .values(1, value) // .onDuplicateKeyUpdate() // .set(SETTINGS.TV_TIMES, value) // .execute(); // } // // public void setLocation(Location location) { // Object value = DSL.cast(gson.toJson(location), PostgresDataType.JSON); // DSLContext create = dataSource.getSqlContext(); // create.insertInto(SETTINGS, SETTINGS.ID, SETTINGS.LOCATION) // .values(1, value) // .onDuplicateKeyUpdate() // .set(SETTINGS.LOCATION, value) // .execute(); // } // // @Override // protected RecordMapper<Record, Settings> getRecordMapper() { // throw new UnsupportedOperationException(); // } // // } // // Path: src/main/java/org/chorem/ecd/exception/InvalidArgumentException.java // public class InvalidArgumentException extends RuntimeException { // // public InvalidArgumentException(String msg) { // super(msg); // } // // } // // Path: src/main/java/org/chorem/ecd/model/settings/TvTimes.java // public class TvTimes { // // private String wakeupTime; // // private String sleepTime; // // public TvTimes() { // // } // // public TvTimes(String wakeupTime, String sleepTime) { // this.wakeupTime = wakeupTime; // this.sleepTime = sleepTime; // } // // public String getWakeupTime() { // return wakeupTime; // } // // public void setWakeupTime(String wakeupTime) { // this.wakeupTime = wakeupTime; // } // // public String getSleepTime() { // return sleepTime; // } // // public void setSleepTime(String sleepTime) { // this.sleepTime = sleepTime; // } // // } // Path: src/main/java/org/chorem/ecd/service/PowerManagementService.java import org.chorem.ecd.dao.SettingsDao; import org.chorem.ecd.dao.TransactionRequired; import org.chorem.ecd.exception.InvalidArgumentException; import org.chorem.ecd.model.settings.TvTimes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import java.time.LocalTime; import java.time.format.DateTimeParseException; package org.chorem.ecd.service; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class PowerManagementService { private static final Logger logger = LoggerFactory.getLogger(PowerManagementService.class); @Inject protected SettingsDao settingsDao; public TvTimes getTvTimes() { return settingsDao.getTvTimes(); } @TransactionRequired public void setTvTimes(TvTimes tvTimes) { validateTvTimes(tvTimes); settingsDao.setTvTimes(tvTimes); }
private void validateTvTimes(TvTimes tvTimes) throws InvalidArgumentException {
juga999/easy-com-display
src/main/java/org/chorem/ecd/dao/SignageStreamDao.java
// Path: src/main/java/org/chorem/ecd/model/stream/SignageStream.java // public class SignageStream { // // private UUID id; // // private String name; // // private Integer timing; // // private LocalDateTime creationDateTime; // // private LocalDateTime lastUpdateDateTime; // // private List<SignageStreamFrame> frames; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getTiming() { // return timing; // } // // public void setTiming(Integer timing) { // this.timing = timing; // } // // public LocalDateTime getCreationDateTime() { // return creationDateTime; // } // // public void setCreationDateTime(LocalDateTime creationDateTime) { // this.creationDateTime = creationDateTime; // } // // public LocalDateTime getLastUpdateDateTime() { // return lastUpdateDateTime; // } // // public void setLastUpdateDateTime(LocalDateTime lastUpdateDateTime) { // this.lastUpdateDateTime = lastUpdateDateTime; // } // // public List<SignageStreamFrame> getFrames() { // return frames; // } // // public void setFrames(List<SignageStreamFrame> frames) { // this.frames = frames; // } // } // // Path: src/main/java/org/chorem/ecd/model/stream/SignageStreamFrame.java // public class SignageStreamFrame { // // private String src; // // private String thumbnail; // // public SignageStreamFrame(Path src, Path thumbnail) { // this(src.toString(), thumbnail.toString()); // } // // public SignageStreamFrame(String src, String thumbnail) { // this.src = src; // this.thumbnail = thumbnail; // } // // public String getSrc() { // return src; // } // // public void setSrc(String src) { // this.src = src; // } // // public String getThumbnail() { // return thumbnail; // } // // public void setThumbnail(String thumbnail) { // this.thumbnail = thumbnail; // } // }
import com.google.gson.reflect.TypeToken; import org.chorem.ecd.model.stream.SignageStream; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.RecordMapper; import org.chorem.ecd.model.stream.SignageStreamFrame; import org.jooq.impl.DSL; import org.jooq.util.postgres.PostgresDataType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.ApplicationScoped; import java.lang.reflect.Type; import java.sql.Timestamp; import java.time.Instant; import java.util.List; import java.util.UUID; import static org.chorem.ecd.mapping.tables.SignageStream.SIGNAGE_STREAM;
package org.chorem.ecd.dao; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class SignageStreamDao extends AbstractDao<SignageStream, UUID> { private static final Logger logger = LoggerFactory.getLogger(SignageStreamDao.class);
// Path: src/main/java/org/chorem/ecd/model/stream/SignageStream.java // public class SignageStream { // // private UUID id; // // private String name; // // private Integer timing; // // private LocalDateTime creationDateTime; // // private LocalDateTime lastUpdateDateTime; // // private List<SignageStreamFrame> frames; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getTiming() { // return timing; // } // // public void setTiming(Integer timing) { // this.timing = timing; // } // // public LocalDateTime getCreationDateTime() { // return creationDateTime; // } // // public void setCreationDateTime(LocalDateTime creationDateTime) { // this.creationDateTime = creationDateTime; // } // // public LocalDateTime getLastUpdateDateTime() { // return lastUpdateDateTime; // } // // public void setLastUpdateDateTime(LocalDateTime lastUpdateDateTime) { // this.lastUpdateDateTime = lastUpdateDateTime; // } // // public List<SignageStreamFrame> getFrames() { // return frames; // } // // public void setFrames(List<SignageStreamFrame> frames) { // this.frames = frames; // } // } // // Path: src/main/java/org/chorem/ecd/model/stream/SignageStreamFrame.java // public class SignageStreamFrame { // // private String src; // // private String thumbnail; // // public SignageStreamFrame(Path src, Path thumbnail) { // this(src.toString(), thumbnail.toString()); // } // // public SignageStreamFrame(String src, String thumbnail) { // this.src = src; // this.thumbnail = thumbnail; // } // // public String getSrc() { // return src; // } // // public void setSrc(String src) { // this.src = src; // } // // public String getThumbnail() { // return thumbnail; // } // // public void setThumbnail(String thumbnail) { // this.thumbnail = thumbnail; // } // } // Path: src/main/java/org/chorem/ecd/dao/SignageStreamDao.java import com.google.gson.reflect.TypeToken; import org.chorem.ecd.model.stream.SignageStream; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.RecordMapper; import org.chorem.ecd.model.stream.SignageStreamFrame; import org.jooq.impl.DSL; import org.jooq.util.postgres.PostgresDataType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.ApplicationScoped; import java.lang.reflect.Type; import java.sql.Timestamp; import java.time.Instant; import java.util.List; import java.util.UUID; import static org.chorem.ecd.mapping.tables.SignageStream.SIGNAGE_STREAM; package org.chorem.ecd.dao; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class SignageStreamDao extends AbstractDao<SignageStream, UUID> { private static final Logger logger = LoggerFactory.getLogger(SignageStreamDao.class);
private final Type framesListType = new TypeToken<List<SignageStreamFrame>>(){}.getType();
juga999/easy-com-display
src/main/java/org/chorem/ecd/service/PeriodicTasksExecutorService.java
// Path: src/main/java/org/chorem/ecd/task/EcdPeriodicTask.java // public abstract class EcdPeriodicTask implements Runnable { // // protected EcdConfig config; // // protected JsonService jsonService; // // public abstract String getName(); // // public abstract Integer getPeriodicity(); // // public abstract TimeUnit getPeriodicityUnit(); // // public void setConfig(EcdConfig config) { // this.config = config; // } // // public void setJsonService(JsonService jsonService) { // this.jsonService = jsonService; // } // // }
import com.google.common.collect.Maps; import org.chorem.ecd.task.EcdPeriodicTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.inject.Singleton; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture;
package org.chorem.ecd.service; /** * @author Julien Gaston (gaston@codelutin.com) */ @Singleton public class PeriodicTasksExecutorService { private static final Logger logger = LoggerFactory.getLogger(PeriodicTasksExecutorService.class); private ScheduledExecutorService executor = Executors.newScheduledThreadPool(4); private Map<String, ScheduledFuture<?>> taskFuturesMap = Maps.newConcurrentMap(); @PostConstruct public void init() { } @PreDestroy public void shutdown() { taskFuturesMap.forEach((name, future) -> { future.cancel(false); logger.info("Cancelled " + name); }); taskFuturesMap.clear(); }
// Path: src/main/java/org/chorem/ecd/task/EcdPeriodicTask.java // public abstract class EcdPeriodicTask implements Runnable { // // protected EcdConfig config; // // protected JsonService jsonService; // // public abstract String getName(); // // public abstract Integer getPeriodicity(); // // public abstract TimeUnit getPeriodicityUnit(); // // public void setConfig(EcdConfig config) { // this.config = config; // } // // public void setJsonService(JsonService jsonService) { // this.jsonService = jsonService; // } // // } // Path: src/main/java/org/chorem/ecd/service/PeriodicTasksExecutorService.java import com.google.common.collect.Maps; import org.chorem.ecd.task.EcdPeriodicTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.inject.Singleton; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; package org.chorem.ecd.service; /** * @author Julien Gaston (gaston@codelutin.com) */ @Singleton public class PeriodicTasksExecutorService { private static final Logger logger = LoggerFactory.getLogger(PeriodicTasksExecutorService.class); private ScheduledExecutorService executor = Executors.newScheduledThreadPool(4); private Map<String, ScheduledFuture<?>> taskFuturesMap = Maps.newConcurrentMap(); @PostConstruct public void init() { } @PreDestroy public void shutdown() { taskFuturesMap.forEach((name, future) -> { future.cancel(false); logger.info("Cancelled " + name); }); taskFuturesMap.clear(); }
public void schedule(EcdPeriodicTask task) {
juga999/easy-com-display
src/main/java/org/chorem/ecd/model/Playlist.java
// Path: src/main/java/org/chorem/ecd/model/news/NewsFeed.java // public class NewsFeed { // // private UUID id; // // private String name; // // private String url; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getUrl() { // return url; // } // // public URL getParsedUrl() { // URL parsedUrl = null; // try { // parsedUrl = new URL(getUrl()); // } catch (MalformedURLException e) { // } // return parsedUrl; // } // // public void setUrl(String url) { // this.url = url; // } // } // // Path: src/main/java/org/chorem/ecd/model/stream/SignageStream.java // public class SignageStream { // // private UUID id; // // private String name; // // private Integer timing; // // private LocalDateTime creationDateTime; // // private LocalDateTime lastUpdateDateTime; // // private List<SignageStreamFrame> frames; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getTiming() { // return timing; // } // // public void setTiming(Integer timing) { // this.timing = timing; // } // // public LocalDateTime getCreationDateTime() { // return creationDateTime; // } // // public void setCreationDateTime(LocalDateTime creationDateTime) { // this.creationDateTime = creationDateTime; // } // // public LocalDateTime getLastUpdateDateTime() { // return lastUpdateDateTime; // } // // public void setLastUpdateDateTime(LocalDateTime lastUpdateDateTime) { // this.lastUpdateDateTime = lastUpdateDateTime; // } // // public List<SignageStreamFrame> getFrames() { // return frames; // } // // public void setFrames(List<SignageStreamFrame> frames) { // this.frames = frames; // } // }
import com.google.common.collect.Lists; import org.chorem.ecd.model.news.NewsFeed; import org.chorem.ecd.model.stream.SignageStream; import java.util.List; import java.util.UUID;
package org.chorem.ecd.model; /** * @author Julien Gaston (gaston@codelutin.com) */ public class Playlist { private UUID id;
// Path: src/main/java/org/chorem/ecd/model/news/NewsFeed.java // public class NewsFeed { // // private UUID id; // // private String name; // // private String url; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getUrl() { // return url; // } // // public URL getParsedUrl() { // URL parsedUrl = null; // try { // parsedUrl = new URL(getUrl()); // } catch (MalformedURLException e) { // } // return parsedUrl; // } // // public void setUrl(String url) { // this.url = url; // } // } // // Path: src/main/java/org/chorem/ecd/model/stream/SignageStream.java // public class SignageStream { // // private UUID id; // // private String name; // // private Integer timing; // // private LocalDateTime creationDateTime; // // private LocalDateTime lastUpdateDateTime; // // private List<SignageStreamFrame> frames; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getTiming() { // return timing; // } // // public void setTiming(Integer timing) { // this.timing = timing; // } // // public LocalDateTime getCreationDateTime() { // return creationDateTime; // } // // public void setCreationDateTime(LocalDateTime creationDateTime) { // this.creationDateTime = creationDateTime; // } // // public LocalDateTime getLastUpdateDateTime() { // return lastUpdateDateTime; // } // // public void setLastUpdateDateTime(LocalDateTime lastUpdateDateTime) { // this.lastUpdateDateTime = lastUpdateDateTime; // } // // public List<SignageStreamFrame> getFrames() { // return frames; // } // // public void setFrames(List<SignageStreamFrame> frames) { // this.frames = frames; // } // } // Path: src/main/java/org/chorem/ecd/model/Playlist.java import com.google.common.collect.Lists; import org.chorem.ecd.model.news.NewsFeed; import org.chorem.ecd.model.stream.SignageStream; import java.util.List; import java.util.UUID; package org.chorem.ecd.model; /** * @author Julien Gaston (gaston@codelutin.com) */ public class Playlist { private UUID id;
private List<SignageStream> streams = Lists.newArrayList();
juga999/easy-com-display
src/main/java/org/chorem/ecd/model/Playlist.java
// Path: src/main/java/org/chorem/ecd/model/news/NewsFeed.java // public class NewsFeed { // // private UUID id; // // private String name; // // private String url; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getUrl() { // return url; // } // // public URL getParsedUrl() { // URL parsedUrl = null; // try { // parsedUrl = new URL(getUrl()); // } catch (MalformedURLException e) { // } // return parsedUrl; // } // // public void setUrl(String url) { // this.url = url; // } // } // // Path: src/main/java/org/chorem/ecd/model/stream/SignageStream.java // public class SignageStream { // // private UUID id; // // private String name; // // private Integer timing; // // private LocalDateTime creationDateTime; // // private LocalDateTime lastUpdateDateTime; // // private List<SignageStreamFrame> frames; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getTiming() { // return timing; // } // // public void setTiming(Integer timing) { // this.timing = timing; // } // // public LocalDateTime getCreationDateTime() { // return creationDateTime; // } // // public void setCreationDateTime(LocalDateTime creationDateTime) { // this.creationDateTime = creationDateTime; // } // // public LocalDateTime getLastUpdateDateTime() { // return lastUpdateDateTime; // } // // public void setLastUpdateDateTime(LocalDateTime lastUpdateDateTime) { // this.lastUpdateDateTime = lastUpdateDateTime; // } // // public List<SignageStreamFrame> getFrames() { // return frames; // } // // public void setFrames(List<SignageStreamFrame> frames) { // this.frames = frames; // } // }
import com.google.common.collect.Lists; import org.chorem.ecd.model.news.NewsFeed; import org.chorem.ecd.model.stream.SignageStream; import java.util.List; import java.util.UUID;
package org.chorem.ecd.model; /** * @author Julien Gaston (gaston@codelutin.com) */ public class Playlist { private UUID id; private List<SignageStream> streams = Lists.newArrayList();
// Path: src/main/java/org/chorem/ecd/model/news/NewsFeed.java // public class NewsFeed { // // private UUID id; // // private String name; // // private String url; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getUrl() { // return url; // } // // public URL getParsedUrl() { // URL parsedUrl = null; // try { // parsedUrl = new URL(getUrl()); // } catch (MalformedURLException e) { // } // return parsedUrl; // } // // public void setUrl(String url) { // this.url = url; // } // } // // Path: src/main/java/org/chorem/ecd/model/stream/SignageStream.java // public class SignageStream { // // private UUID id; // // private String name; // // private Integer timing; // // private LocalDateTime creationDateTime; // // private LocalDateTime lastUpdateDateTime; // // private List<SignageStreamFrame> frames; // // public UUID getId() { // return id; // } // // public void setId(UUID id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Integer getTiming() { // return timing; // } // // public void setTiming(Integer timing) { // this.timing = timing; // } // // public LocalDateTime getCreationDateTime() { // return creationDateTime; // } // // public void setCreationDateTime(LocalDateTime creationDateTime) { // this.creationDateTime = creationDateTime; // } // // public LocalDateTime getLastUpdateDateTime() { // return lastUpdateDateTime; // } // // public void setLastUpdateDateTime(LocalDateTime lastUpdateDateTime) { // this.lastUpdateDateTime = lastUpdateDateTime; // } // // public List<SignageStreamFrame> getFrames() { // return frames; // } // // public void setFrames(List<SignageStreamFrame> frames) { // this.frames = frames; // } // } // Path: src/main/java/org/chorem/ecd/model/Playlist.java import com.google.common.collect.Lists; import org.chorem.ecd.model.news.NewsFeed; import org.chorem.ecd.model.stream.SignageStream; import java.util.List; import java.util.UUID; package org.chorem.ecd.model; /** * @author Julien Gaston (gaston@codelutin.com) */ public class Playlist { private UUID id; private List<SignageStream> streams = Lists.newArrayList();
private List<NewsFeed> newsFeeds = Lists.newArrayList();
juga999/easy-com-display
src/main/java/org/chorem/ecd/task/AggregatedNewsBuilderPeriodicTask.java
// Path: src/main/java/org/chorem/ecd/model/news/AggregatedNews.java // public class AggregatedNews { // // private Map<String, List<String>> newsPerFeed = Maps.newHashMap(); // // public void addNews(String newsFeedTitle, List<String> newsFeedNews) { // newsPerFeed.put(newsFeedTitle, newsFeedNews); // } // // }
import org.chorem.ecd.model.news.AggregatedNews; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URL; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors;
package org.chorem.ecd.task; /** * @author Julien Gaston (gaston@codelutin.com) */ public class AggregatedNewsBuilderPeriodicTask extends EcdPeriodicTask { private static final Logger logger = LoggerFactory.getLogger(AggregatedNewsBuilderPeriodicTask.class); private final List<URL> newsFeedUrls; public static final String NAME = "AggregatedNewsBuilder"; public AggregatedNewsBuilderPeriodicTask(List<URL> newsFeedUrls) { this.newsFeedUrls = newsFeedUrls; } @Override public void run() {
// Path: src/main/java/org/chorem/ecd/model/news/AggregatedNews.java // public class AggregatedNews { // // private Map<String, List<String>> newsPerFeed = Maps.newHashMap(); // // public void addNews(String newsFeedTitle, List<String> newsFeedNews) { // newsPerFeed.put(newsFeedTitle, newsFeedNews); // } // // } // Path: src/main/java/org/chorem/ecd/task/AggregatedNewsBuilderPeriodicTask.java import org.chorem.ecd.model.news.AggregatedNews; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URL; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; package org.chorem.ecd.task; /** * @author Julien Gaston (gaston@codelutin.com) */ public class AggregatedNewsBuilderPeriodicTask extends EcdPeriodicTask { private static final Logger logger = LoggerFactory.getLogger(AggregatedNewsBuilderPeriodicTask.class); private final List<URL> newsFeedUrls; public static final String NAME = "AggregatedNewsBuilder"; public AggregatedNewsBuilderPeriodicTask(List<URL> newsFeedUrls) { this.newsFeedUrls = newsFeedUrls; } @Override public void run() {
AggregatedNews aggregatedNews = new AggregatedNews();
juga999/easy-com-display
src/main/java/org/chorem/ecd/service/AuthService.java
// Path: src/main/java/org/chorem/ecd/dao/PersonDao.java // @ApplicationScoped // public class PersonDao extends AbstractDao<org.chorem.ecd.model.Person, Integer> { // // public PersonDao() { // super(Person.class, PERSON, PERSON.ID::eq); // } // // public void addPerson(org.chorem.ecd.model.Person person) { // DSLContext create = dataSource.getSqlContext(); // PersonRecord personRecord = create.newRecord(PERSON); // personRecord.setName(person.getName()); // personRecord.store(); // } // } // // Path: src/main/java/org/chorem/ecd/model/Person.java // public class Person { // // private int id; // // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // }
import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTVerificationException; import com.auth0.jwt.interfaces.Payload; import com.google.common.base.Strings; import org.chorem.ecd.dao.PersonDao; import org.chorem.ecd.dao.TransactionRequired; import org.chorem.ecd.model.Person; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import java.io.UnsupportedEncodingException; import java.time.Duration; import java.time.Instant; import java.util.Date;
package org.chorem.ecd.service; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class AuthService { private static final Logger logger = LoggerFactory.getLogger(AuthService.class); @Inject
// Path: src/main/java/org/chorem/ecd/dao/PersonDao.java // @ApplicationScoped // public class PersonDao extends AbstractDao<org.chorem.ecd.model.Person, Integer> { // // public PersonDao() { // super(Person.class, PERSON, PERSON.ID::eq); // } // // public void addPerson(org.chorem.ecd.model.Person person) { // DSLContext create = dataSource.getSqlContext(); // PersonRecord personRecord = create.newRecord(PERSON); // personRecord.setName(person.getName()); // personRecord.store(); // } // } // // Path: src/main/java/org/chorem/ecd/model/Person.java // public class Person { // // private int id; // // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // Path: src/main/java/org/chorem/ecd/service/AuthService.java import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTVerificationException; import com.auth0.jwt.interfaces.Payload; import com.google.common.base.Strings; import org.chorem.ecd.dao.PersonDao; import org.chorem.ecd.dao.TransactionRequired; import org.chorem.ecd.model.Person; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import java.io.UnsupportedEncodingException; import java.time.Duration; import java.time.Instant; import java.util.Date; package org.chorem.ecd.service; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class AuthService { private static final Logger logger = LoggerFactory.getLogger(AuthService.class); @Inject
private PersonDao personDao;
juga999/easy-com-display
src/main/java/org/chorem/ecd/service/AuthService.java
// Path: src/main/java/org/chorem/ecd/dao/PersonDao.java // @ApplicationScoped // public class PersonDao extends AbstractDao<org.chorem.ecd.model.Person, Integer> { // // public PersonDao() { // super(Person.class, PERSON, PERSON.ID::eq); // } // // public void addPerson(org.chorem.ecd.model.Person person) { // DSLContext create = dataSource.getSqlContext(); // PersonRecord personRecord = create.newRecord(PERSON); // personRecord.setName(person.getName()); // personRecord.store(); // } // } // // Path: src/main/java/org/chorem/ecd/model/Person.java // public class Person { // // private int id; // // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // }
import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTVerificationException; import com.auth0.jwt.interfaces.Payload; import com.google.common.base.Strings; import org.chorem.ecd.dao.PersonDao; import org.chorem.ecd.dao.TransactionRequired; import org.chorem.ecd.model.Person; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import java.io.UnsupportedEncodingException; import java.time.Duration; import java.time.Instant; import java.util.Date;
package org.chorem.ecd.service; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class AuthService { private static final Logger logger = LoggerFactory.getLogger(AuthService.class); @Inject private PersonDao personDao; private final Algorithm algorithm; private final JWTVerifier verifier; public AuthService() throws UnsupportedEncodingException { algorithm = Algorithm.HMAC512("secretpassphrase"); verifier = JWT.require(algorithm).withIssuer("auth0").build(); } @TransactionRequired public String getSignedToken(String subject, String password) { if (Strings.isNullOrEmpty(subject) || Strings.isNullOrEmpty(password)) { return null; }
// Path: src/main/java/org/chorem/ecd/dao/PersonDao.java // @ApplicationScoped // public class PersonDao extends AbstractDao<org.chorem.ecd.model.Person, Integer> { // // public PersonDao() { // super(Person.class, PERSON, PERSON.ID::eq); // } // // public void addPerson(org.chorem.ecd.model.Person person) { // DSLContext create = dataSource.getSqlContext(); // PersonRecord personRecord = create.newRecord(PERSON); // personRecord.setName(person.getName()); // personRecord.store(); // } // } // // Path: src/main/java/org/chorem/ecd/model/Person.java // public class Person { // // private int id; // // private String name; // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // Path: src/main/java/org/chorem/ecd/service/AuthService.java import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTVerificationException; import com.auth0.jwt.interfaces.Payload; import com.google.common.base.Strings; import org.chorem.ecd.dao.PersonDao; import org.chorem.ecd.dao.TransactionRequired; import org.chorem.ecd.model.Person; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import java.io.UnsupportedEncodingException; import java.time.Duration; import java.time.Instant; import java.util.Date; package org.chorem.ecd.service; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class AuthService { private static final Logger logger = LoggerFactory.getLogger(AuthService.class); @Inject private PersonDao personDao; private final Algorithm algorithm; private final JWTVerifier verifier; public AuthService() throws UnsupportedEncodingException { algorithm = Algorithm.HMAC512("secretpassphrase"); verifier = JWT.require(algorithm).withIssuer("auth0").build(); } @TransactionRequired public String getSignedToken(String subject, String password) { if (Strings.isNullOrEmpty(subject) || Strings.isNullOrEmpty(password)) { return null; }
Person person = new Person();
juga999/easy-com-display
src/main/java/org/chorem/ecd/service/MediaConverterService.java
// Path: src/main/java/org/chorem/ecd/EcdConfig.java // @ApplicationScoped // public class EcdConfig { // // private static final Logger logger = LoggerFactory.getLogger(EcdConfig.class); // // private final Properties props; // // public static final String STREAMS_DIR = "streams"; // public static final String NEWS_DIR = "news"; // public static final String WEATHER_DIR = "weather"; // // public EcdConfig() { // props = new Properties(); // try { // props.load(getClass().getClassLoader().getResourceAsStream("ecd.properties")); // } catch (IOException e) { // logger.error(e.getMessage(), e); // } // } // // public String getDataSourceUrl() { // return props.getProperty("ecd.datasource.url"); // } // // public String getDataSourceLogin() { // return props.getProperty("ecd.datasource.login"); // } // // public String getDataSourcePwd() { // return props.getProperty("ecd.datasource.pwd"); // } // // public String getApiPathPrefix() { // return "/api/ecd"; // } // // public String getMediaPathPrefix() { // return "/media/ecd"; // } // // public String getDataDir() { // return props.getProperty("ecd.data.dir"); // } // // public String getUploadDir() { return props.getProperty("ecd.upload.dir"); } // // public String getUnoconvCmd() { // return props.getProperty("ecd.cmd.unoconv"); // } // // public String getResizeCmd() { // return props.getProperty("ecd.cmd.resize"); // } // // public String getLocationSearchUrlFormat() { // return props.getProperty("ecd.location.searchUrlFormat"); // } // // public Integer getDefaultStreamTiming() { // return Integer.valueOf(props.getProperty("ecd.default.streamTiming")); // } // // public Path getStreamsPath() { // return Paths.get(getDataDir(), STREAMS_DIR); // } // // public Path getAggregatedNewsPath() { // return Paths.get(getDataDir(), NEWS_DIR, "aggregated.json"); // } // // public Path getWeatherForecastPath() { // return Paths.get(getDataDir(), WEATHER_DIR, "forecast.json"); // } // // } // // Path: src/main/java/org/chorem/ecd/model/stream/SignageStreamFrame.java // public class SignageStreamFrame { // // private String src; // // private String thumbnail; // // public SignageStreamFrame(Path src, Path thumbnail) { // this(src.toString(), thumbnail.toString()); // } // // public SignageStreamFrame(String src, String thumbnail) { // this.src = src; // this.thumbnail = thumbnail; // } // // public String getSrc() { // return src; // } // // public void setSrc(String src) { // this.src = src; // } // // public String getThumbnail() { // return thumbnail; // } // // public void setThumbnail(String thumbnail) { // this.thumbnail = thumbnail; // } // }
import com.google.common.base.CharMatcher; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Lists; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecutor; import org.apache.commons.exec.PumpStreamHandler; import org.chorem.ecd.EcdConfig; import org.chorem.ecd.model.stream.SignageStreamFrame; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.stream.Collectors;
package org.chorem.ecd.service; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class MediaConverterService { private static final Logger logger = LoggerFactory.getLogger(MediaConverterService.class); @Inject
// Path: src/main/java/org/chorem/ecd/EcdConfig.java // @ApplicationScoped // public class EcdConfig { // // private static final Logger logger = LoggerFactory.getLogger(EcdConfig.class); // // private final Properties props; // // public static final String STREAMS_DIR = "streams"; // public static final String NEWS_DIR = "news"; // public static final String WEATHER_DIR = "weather"; // // public EcdConfig() { // props = new Properties(); // try { // props.load(getClass().getClassLoader().getResourceAsStream("ecd.properties")); // } catch (IOException e) { // logger.error(e.getMessage(), e); // } // } // // public String getDataSourceUrl() { // return props.getProperty("ecd.datasource.url"); // } // // public String getDataSourceLogin() { // return props.getProperty("ecd.datasource.login"); // } // // public String getDataSourcePwd() { // return props.getProperty("ecd.datasource.pwd"); // } // // public String getApiPathPrefix() { // return "/api/ecd"; // } // // public String getMediaPathPrefix() { // return "/media/ecd"; // } // // public String getDataDir() { // return props.getProperty("ecd.data.dir"); // } // // public String getUploadDir() { return props.getProperty("ecd.upload.dir"); } // // public String getUnoconvCmd() { // return props.getProperty("ecd.cmd.unoconv"); // } // // public String getResizeCmd() { // return props.getProperty("ecd.cmd.resize"); // } // // public String getLocationSearchUrlFormat() { // return props.getProperty("ecd.location.searchUrlFormat"); // } // // public Integer getDefaultStreamTiming() { // return Integer.valueOf(props.getProperty("ecd.default.streamTiming")); // } // // public Path getStreamsPath() { // return Paths.get(getDataDir(), STREAMS_DIR); // } // // public Path getAggregatedNewsPath() { // return Paths.get(getDataDir(), NEWS_DIR, "aggregated.json"); // } // // public Path getWeatherForecastPath() { // return Paths.get(getDataDir(), WEATHER_DIR, "forecast.json"); // } // // } // // Path: src/main/java/org/chorem/ecd/model/stream/SignageStreamFrame.java // public class SignageStreamFrame { // // private String src; // // private String thumbnail; // // public SignageStreamFrame(Path src, Path thumbnail) { // this(src.toString(), thumbnail.toString()); // } // // public SignageStreamFrame(String src, String thumbnail) { // this.src = src; // this.thumbnail = thumbnail; // } // // public String getSrc() { // return src; // } // // public void setSrc(String src) { // this.src = src; // } // // public String getThumbnail() { // return thumbnail; // } // // public void setThumbnail(String thumbnail) { // this.thumbnail = thumbnail; // } // } // Path: src/main/java/org/chorem/ecd/service/MediaConverterService.java import com.google.common.base.CharMatcher; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Lists; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecutor; import org.apache.commons.exec.PumpStreamHandler; import org.chorem.ecd.EcdConfig; import org.chorem.ecd.model.stream.SignageStreamFrame; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.stream.Collectors; package org.chorem.ecd.service; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class MediaConverterService { private static final Logger logger = LoggerFactory.getLogger(MediaConverterService.class); @Inject
private EcdConfig config;
juga999/easy-com-display
src/main/java/org/chorem/ecd/service/MediaConverterService.java
// Path: src/main/java/org/chorem/ecd/EcdConfig.java // @ApplicationScoped // public class EcdConfig { // // private static final Logger logger = LoggerFactory.getLogger(EcdConfig.class); // // private final Properties props; // // public static final String STREAMS_DIR = "streams"; // public static final String NEWS_DIR = "news"; // public static final String WEATHER_DIR = "weather"; // // public EcdConfig() { // props = new Properties(); // try { // props.load(getClass().getClassLoader().getResourceAsStream("ecd.properties")); // } catch (IOException e) { // logger.error(e.getMessage(), e); // } // } // // public String getDataSourceUrl() { // return props.getProperty("ecd.datasource.url"); // } // // public String getDataSourceLogin() { // return props.getProperty("ecd.datasource.login"); // } // // public String getDataSourcePwd() { // return props.getProperty("ecd.datasource.pwd"); // } // // public String getApiPathPrefix() { // return "/api/ecd"; // } // // public String getMediaPathPrefix() { // return "/media/ecd"; // } // // public String getDataDir() { // return props.getProperty("ecd.data.dir"); // } // // public String getUploadDir() { return props.getProperty("ecd.upload.dir"); } // // public String getUnoconvCmd() { // return props.getProperty("ecd.cmd.unoconv"); // } // // public String getResizeCmd() { // return props.getProperty("ecd.cmd.resize"); // } // // public String getLocationSearchUrlFormat() { // return props.getProperty("ecd.location.searchUrlFormat"); // } // // public Integer getDefaultStreamTiming() { // return Integer.valueOf(props.getProperty("ecd.default.streamTiming")); // } // // public Path getStreamsPath() { // return Paths.get(getDataDir(), STREAMS_DIR); // } // // public Path getAggregatedNewsPath() { // return Paths.get(getDataDir(), NEWS_DIR, "aggregated.json"); // } // // public Path getWeatherForecastPath() { // return Paths.get(getDataDir(), WEATHER_DIR, "forecast.json"); // } // // } // // Path: src/main/java/org/chorem/ecd/model/stream/SignageStreamFrame.java // public class SignageStreamFrame { // // private String src; // // private String thumbnail; // // public SignageStreamFrame(Path src, Path thumbnail) { // this(src.toString(), thumbnail.toString()); // } // // public SignageStreamFrame(String src, String thumbnail) { // this.src = src; // this.thumbnail = thumbnail; // } // // public String getSrc() { // return src; // } // // public void setSrc(String src) { // this.src = src; // } // // public String getThumbnail() { // return thumbnail; // } // // public void setThumbnail(String thumbnail) { // this.thumbnail = thumbnail; // } // }
import com.google.common.base.CharMatcher; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Lists; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecutor; import org.apache.commons.exec.PumpStreamHandler; import org.chorem.ecd.EcdConfig; import org.chorem.ecd.model.stream.SignageStreamFrame; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.stream.Collectors;
package org.chorem.ecd.service; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class MediaConverterService { private static final Logger logger = LoggerFactory.getLogger(MediaConverterService.class); @Inject private EcdConfig config; public String getUnoconvVersion() { return getVersion(config.getUnoconvCmd()); } public String getConvertVersion() { return getVersion(config.getResizeCmd()); }
// Path: src/main/java/org/chorem/ecd/EcdConfig.java // @ApplicationScoped // public class EcdConfig { // // private static final Logger logger = LoggerFactory.getLogger(EcdConfig.class); // // private final Properties props; // // public static final String STREAMS_DIR = "streams"; // public static final String NEWS_DIR = "news"; // public static final String WEATHER_DIR = "weather"; // // public EcdConfig() { // props = new Properties(); // try { // props.load(getClass().getClassLoader().getResourceAsStream("ecd.properties")); // } catch (IOException e) { // logger.error(e.getMessage(), e); // } // } // // public String getDataSourceUrl() { // return props.getProperty("ecd.datasource.url"); // } // // public String getDataSourceLogin() { // return props.getProperty("ecd.datasource.login"); // } // // public String getDataSourcePwd() { // return props.getProperty("ecd.datasource.pwd"); // } // // public String getApiPathPrefix() { // return "/api/ecd"; // } // // public String getMediaPathPrefix() { // return "/media/ecd"; // } // // public String getDataDir() { // return props.getProperty("ecd.data.dir"); // } // // public String getUploadDir() { return props.getProperty("ecd.upload.dir"); } // // public String getUnoconvCmd() { // return props.getProperty("ecd.cmd.unoconv"); // } // // public String getResizeCmd() { // return props.getProperty("ecd.cmd.resize"); // } // // public String getLocationSearchUrlFormat() { // return props.getProperty("ecd.location.searchUrlFormat"); // } // // public Integer getDefaultStreamTiming() { // return Integer.valueOf(props.getProperty("ecd.default.streamTiming")); // } // // public Path getStreamsPath() { // return Paths.get(getDataDir(), STREAMS_DIR); // } // // public Path getAggregatedNewsPath() { // return Paths.get(getDataDir(), NEWS_DIR, "aggregated.json"); // } // // public Path getWeatherForecastPath() { // return Paths.get(getDataDir(), WEATHER_DIR, "forecast.json"); // } // // } // // Path: src/main/java/org/chorem/ecd/model/stream/SignageStreamFrame.java // public class SignageStreamFrame { // // private String src; // // private String thumbnail; // // public SignageStreamFrame(Path src, Path thumbnail) { // this(src.toString(), thumbnail.toString()); // } // // public SignageStreamFrame(String src, String thumbnail) { // this.src = src; // this.thumbnail = thumbnail; // } // // public String getSrc() { // return src; // } // // public void setSrc(String src) { // this.src = src; // } // // public String getThumbnail() { // return thumbnail; // } // // public void setThumbnail(String thumbnail) { // this.thumbnail = thumbnail; // } // } // Path: src/main/java/org/chorem/ecd/service/MediaConverterService.java import com.google.common.base.CharMatcher; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Lists; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecutor; import org.apache.commons.exec.PumpStreamHandler; import org.chorem.ecd.EcdConfig; import org.chorem.ecd.model.stream.SignageStreamFrame; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.stream.Collectors; package org.chorem.ecd.service; /** * @author Julien Gaston (gaston@codelutin.com) */ @ApplicationScoped public class MediaConverterService { private static final Logger logger = LoggerFactory.getLogger(MediaConverterService.class); @Inject private EcdConfig config; public String getUnoconvVersion() { return getVersion(config.getUnoconvCmd()); } public String getConvertVersion() { return getVersion(config.getResizeCmd()); }
public List<SignageStreamFrame> extractFrames(Path source, Path destDir) throws IOException {
CROW-NDOV/displaydirect
distribution/src/main/java/nl/crowndov/displaydirect/distribution/input/LineProvider.java
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/domain/travelinfo/Line.java // public class Line implements Serializable { // // private static final long serialVersionUID = -7614598114730697681L; // // private String code; // private String publicNumber; // private TransportType type; // // public Line(String code, String publicNumber, TransportType type) { // this.code = code; // this.publicNumber = publicNumber; // this.type = type; // } // // public String getCode() { // return code; // } // // public String getPublicNumber() { // return publicNumber; // } // // public TransportType getType() { // return type; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Line line = (Line) o; // // if (code != null ? !code.equals(line.code) : line.code != null) return false; // if (publicNumber != null ? !publicNumber.equals(line.publicNumber) : line.publicNumber != null) return false; // return type == line.type; // } // // @Override // public int hashCode() { // int result = code != null ? code.hashCode() : 0; // result = 31 * result + (publicNumber != null ? publicNumber.hashCode() : 0); // result = 31 * result + (type != null ? type.hashCode() : 0); // return result; // } // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/util/AbstractService.java // public abstract class AbstractService { // // private static final Logger LOGGER = LoggerFactory.getLogger(AbstractService.class); // private static final Gson GSON = JsonFile.gson(); // // protected static void backup(Runnable func) { // func.run(); // } // // protected static <T> Optional<T> readFile(String key, Class<T> clazz) { // return JsonFile.read(key).map(s1 -> (T) GSON.fromJson(s1, clazz)); // } // // protected static <T> Optional<T> readSerializedFile(String key) { // Path input = getPathSerialized(key); // LOGGER.info("Reading from {}", input.toString()); // if (!input.toFile().exists()) { // return Optional.empty(); // } // try ( FileInputStream fis = new FileInputStream(input.toString()); // ObjectInputStream ois = new ObjectInputStream(fis)) { // T result = (T) ois.readObject(); // return Optional.of(result); // } catch (ClassNotFoundException e) { // LOGGER.error("Error deserializing {}", key, e); // } catch (Exception e) { // LOGGER.error("Error reading {}", key, e); // } // return Optional.empty(); // } // // protected static <T> void writeFile(String key, T data) { // String dataStr = GSON.toJson(data); // LOGGER.info("Got serialized data {} (len {})", key, dataStr.length()); // JsonFile.write(key, dataStr); // } // // protected static <T> void writeFileSerialize(String key, T data) { // String out = getPathSerialized(key+"-temp").toString(); // LOGGER.info("Writing to {}", out); // try (FileOutputStream fos = new FileOutputStream(out, false); // ObjectOutputStream oos = new ObjectOutputStream(fos)) { // oos.writeObject(data); // // Once done, move to the location we read, so that in case the (long) export is interupted, we don't lose a backup // Files.move(getPathSerialized(key+"-temp"), getPathSerialized(key), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); // } catch (IOException e) { // LOGGER.error("Error writing {}", key, e); // } // } // // private static Path getPathSerialized(String key) { // return Paths.get(Configuration.getFileBasePath(), key+".out"); // } // // protected static void schedule(ScheduledExecutorService executor, String label, Runnable run, String firstTime, int hoursRepeated) { // long minutes = DateTimeUtil.getMinutesTill(firstTime); // LOGGER.info("Scheduling task {} to first run in {} minutes, every {} hours thereafter", label, minutes, hoursRepeated); // executor.scheduleAtFixedRate(run, minutes, hoursRepeated*60, TimeUnit.MINUTES); // } // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/util/Store.java // public class Store { // // public static class StringList extends ArrayList<String> {} // // public static class ValidationTokenStore extends ConcurrentHashMap<String, ValidationToken> {} // // public static class PlanningStore extends ConcurrentHashMap<String, QuayStore> {} // // public static class LineStore extends ConcurrentHashMap<String, Line> {} // // public static class DestinationStore extends ConcurrentHashMap<String, Destination> {} // // public static class SubscriptionQuayStore extends ConcurrentHashMap<String, List<Subscription>> {} // // public static class SubscriptionStore extends ConcurrentHashMap<String, Subscription> {} // // public static class TimingPointStore extends ConcurrentHashMap<String, String> {} // }
import nl.crowndov.displaydirect.distribution.domain.travelinfo.Line; import nl.crowndov.displaydirect.distribution.util.AbstractService; import nl.crowndov.displaydirect.distribution.util.Store; import java.util.List; import java.util.Map;
package nl.crowndov.displaydirect.distribution.input; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class LineProvider extends AbstractService { private static final Store.LineStore lines = new Store.LineStore(); public static void start() { readFile("lines", Store.LineStore.class).ifPresent(lines::putAll); } public static void stop() { backup(); } public static void backup() { writeFile("lines", lines); }
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/domain/travelinfo/Line.java // public class Line implements Serializable { // // private static final long serialVersionUID = -7614598114730697681L; // // private String code; // private String publicNumber; // private TransportType type; // // public Line(String code, String publicNumber, TransportType type) { // this.code = code; // this.publicNumber = publicNumber; // this.type = type; // } // // public String getCode() { // return code; // } // // public String getPublicNumber() { // return publicNumber; // } // // public TransportType getType() { // return type; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // Line line = (Line) o; // // if (code != null ? !code.equals(line.code) : line.code != null) return false; // if (publicNumber != null ? !publicNumber.equals(line.publicNumber) : line.publicNumber != null) return false; // return type == line.type; // } // // @Override // public int hashCode() { // int result = code != null ? code.hashCode() : 0; // result = 31 * result + (publicNumber != null ? publicNumber.hashCode() : 0); // result = 31 * result + (type != null ? type.hashCode() : 0); // return result; // } // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/util/AbstractService.java // public abstract class AbstractService { // // private static final Logger LOGGER = LoggerFactory.getLogger(AbstractService.class); // private static final Gson GSON = JsonFile.gson(); // // protected static void backup(Runnable func) { // func.run(); // } // // protected static <T> Optional<T> readFile(String key, Class<T> clazz) { // return JsonFile.read(key).map(s1 -> (T) GSON.fromJson(s1, clazz)); // } // // protected static <T> Optional<T> readSerializedFile(String key) { // Path input = getPathSerialized(key); // LOGGER.info("Reading from {}", input.toString()); // if (!input.toFile().exists()) { // return Optional.empty(); // } // try ( FileInputStream fis = new FileInputStream(input.toString()); // ObjectInputStream ois = new ObjectInputStream(fis)) { // T result = (T) ois.readObject(); // return Optional.of(result); // } catch (ClassNotFoundException e) { // LOGGER.error("Error deserializing {}", key, e); // } catch (Exception e) { // LOGGER.error("Error reading {}", key, e); // } // return Optional.empty(); // } // // protected static <T> void writeFile(String key, T data) { // String dataStr = GSON.toJson(data); // LOGGER.info("Got serialized data {} (len {})", key, dataStr.length()); // JsonFile.write(key, dataStr); // } // // protected static <T> void writeFileSerialize(String key, T data) { // String out = getPathSerialized(key+"-temp").toString(); // LOGGER.info("Writing to {}", out); // try (FileOutputStream fos = new FileOutputStream(out, false); // ObjectOutputStream oos = new ObjectOutputStream(fos)) { // oos.writeObject(data); // // Once done, move to the location we read, so that in case the (long) export is interupted, we don't lose a backup // Files.move(getPathSerialized(key+"-temp"), getPathSerialized(key), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); // } catch (IOException e) { // LOGGER.error("Error writing {}", key, e); // } // } // // private static Path getPathSerialized(String key) { // return Paths.get(Configuration.getFileBasePath(), key+".out"); // } // // protected static void schedule(ScheduledExecutorService executor, String label, Runnable run, String firstTime, int hoursRepeated) { // long minutes = DateTimeUtil.getMinutesTill(firstTime); // LOGGER.info("Scheduling task {} to first run in {} minutes, every {} hours thereafter", label, minutes, hoursRepeated); // executor.scheduleAtFixedRate(run, minutes, hoursRepeated*60, TimeUnit.MINUTES); // } // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/util/Store.java // public class Store { // // public static class StringList extends ArrayList<String> {} // // public static class ValidationTokenStore extends ConcurrentHashMap<String, ValidationToken> {} // // public static class PlanningStore extends ConcurrentHashMap<String, QuayStore> {} // // public static class LineStore extends ConcurrentHashMap<String, Line> {} // // public static class DestinationStore extends ConcurrentHashMap<String, Destination> {} // // public static class SubscriptionQuayStore extends ConcurrentHashMap<String, List<Subscription>> {} // // public static class SubscriptionStore extends ConcurrentHashMap<String, Subscription> {} // // public static class TimingPointStore extends ConcurrentHashMap<String, String> {} // } // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/input/LineProvider.java import nl.crowndov.displaydirect.distribution.domain.travelinfo.Line; import nl.crowndov.displaydirect.distribution.util.AbstractService; import nl.crowndov.displaydirect.distribution.util.Store; import java.util.List; import java.util.Map; package nl.crowndov.displaydirect.distribution.input; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class LineProvider extends AbstractService { private static final Store.LineStore lines = new Store.LineStore(); public static void start() { readFile("lines", Store.LineStore.class).ifPresent(lines::putAll); } public static void stop() { backup(); } public static void backup() { writeFile("lines", lines); }
public static void updateLines(List<Line> input) {
CROW-NDOV/displaydirect
distribution/src/main/java/nl/crowndov/displaydirect/distribution/input/Kv78ReceiveTask.java
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/Configuration.java // public class Configuration { // // private static final Logger LOGGER = LoggerFactory.getLogger(Configuration.class); // // private static AbstractConfiguration config = ConfigurationManager.getConfigInstance(); // // public static List<String> getKvEndpoints() { // return Arrays.asList(config.getStringArray("distribution.kv78turbo.endpoints")); // } // // public static String[] getKvPublishers() { // return config.getStringArray("distribution.kv78turbo.publishers"); // } // // public static ZoneId getZoneId() { // return ZoneId.of(config.getString("distribution.timezone.default")); // } // // public static String getOutputTransport() { // return config.getString("distribution.transport", "mqtt"); // } // // public static String getMqttBrokerHost() { // return config.getString("distribution.mqtt.host", "localhost:1883"); // } // // public static int getZmqInternalPort() { // return 9800; // } // // public static String getMqttClientId() { // return config.getString("distribution.mqtt.client_id", "distribution"); // } // // public static int getAuthorizationTokenMaxAge() { // return config.getInt("distribution.authorization.max_age_hours"); // } // // public static List<String> getAuthorizationWhitelist() { // return Arrays.asList(config.getStringArray("distribution.authorization.whitelist_prefix")); // } // // public static String getBaseUrl() { // return config.getString("distribution.install.base_url", "http://localhost:8080"); // } // // public static String getSmtpUsername() { // return config.getString("distribution.smtp.username", null); // } // // public static String getSmtpPassword() { // return config.getString("distribution.smtp.password", null); // } // // public static String getSmtpFrom() { // return config.getString("distribution.smtp.from"); // } // // public static String getSmtpHostname() { // return config.getString("distribution.smtp.hostname"); // } // // public static String getSmtpReplyTo() { // return config.getString("distribution.smtp.reply_to"); // } // // public static boolean getSmtpSsl() { return config.getBoolean("distribution.smtp.ssl", false); } // // public static int getSmtpPort() { // return config.getInt("distribution.smtp.port", 25); // } // // public static int getSmtpConnectTimeout() { // return config.getInt("distribution.smtp.connect_timeout", 10*1000); // } // // public static String getFileBasePath() { // return config.getString("distribution.backup.path", System.getProperty("java.io.tmpdir")); // } // // public static String getKv7PlanningPath() { // return config.getString("distribution.kv78turbo.path.planning"); // } // // public static String getKv7CalendarPath() { // return config.getString("distribution.kv78turbo.path.calendar"); // } // // public static String getChbPath() { // return config.getString("distribution.chb.path"); // } // // // public static String getPlanningLoaderTime() { // return config.getString("distribution.planning.loadTime", "03:30"); // } // // public static String getPlanningCleanupTime() { // return config.getString("distribution.planning.cleanupTime", "04:00"); // } // // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/util/ZeroMQUtils.java // public class ZeroMQUtils { // // public static String[] gunzipMultifameZMsg(ZMsg msg) throws IOException { // Iterator<ZFrame> frames = msg.iterator(); // // pop off first frame, which contains "/GOVI/KV8" (the feed name) // // (isn't there a method for this?) // String header = frames.next().toString(); // ByteArrayOutputStream buffer = new ByteArrayOutputStream(); // while (frames.hasNext()) { // ZFrame frame = frames.next(); // byte[] frameData = frame.getData(); // buffer.write(frameData); // } // if (buffer.size() == 0) { // return null; // } // // chain input streams to gunzip contents of byte buffer // InputStream gzippedMessageStream = new ByteArrayInputStream( // buffer.toByteArray()); // InputStream messageStream = new GZIPInputStream(gzippedMessageStream); // // copy input stream back to transport stream // buffer.reset(); // byte[] b = new byte[4096]; // for (int n; (n = messageStream.read(b)) != -1;) { // buffer.write(b, 0, n); // } // return new String[] { header, buffer.toString() }; // } // }
import nl.crowndov.displaydirect.distribution.Configuration; import nl.crowndov.displaydirect.distribution.util.ZeroMQUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zeromq.ZMQ; import org.zeromq.ZMsg; import java.util.List; import java.util.concurrent.TimeUnit;
package nl.crowndov.displaydirect.distribution.input; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class Kv78ReceiveTask implements Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(Kv78ReceiveTask.class);
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/Configuration.java // public class Configuration { // // private static final Logger LOGGER = LoggerFactory.getLogger(Configuration.class); // // private static AbstractConfiguration config = ConfigurationManager.getConfigInstance(); // // public static List<String> getKvEndpoints() { // return Arrays.asList(config.getStringArray("distribution.kv78turbo.endpoints")); // } // // public static String[] getKvPublishers() { // return config.getStringArray("distribution.kv78turbo.publishers"); // } // // public static ZoneId getZoneId() { // return ZoneId.of(config.getString("distribution.timezone.default")); // } // // public static String getOutputTransport() { // return config.getString("distribution.transport", "mqtt"); // } // // public static String getMqttBrokerHost() { // return config.getString("distribution.mqtt.host", "localhost:1883"); // } // // public static int getZmqInternalPort() { // return 9800; // } // // public static String getMqttClientId() { // return config.getString("distribution.mqtt.client_id", "distribution"); // } // // public static int getAuthorizationTokenMaxAge() { // return config.getInt("distribution.authorization.max_age_hours"); // } // // public static List<String> getAuthorizationWhitelist() { // return Arrays.asList(config.getStringArray("distribution.authorization.whitelist_prefix")); // } // // public static String getBaseUrl() { // return config.getString("distribution.install.base_url", "http://localhost:8080"); // } // // public static String getSmtpUsername() { // return config.getString("distribution.smtp.username", null); // } // // public static String getSmtpPassword() { // return config.getString("distribution.smtp.password", null); // } // // public static String getSmtpFrom() { // return config.getString("distribution.smtp.from"); // } // // public static String getSmtpHostname() { // return config.getString("distribution.smtp.hostname"); // } // // public static String getSmtpReplyTo() { // return config.getString("distribution.smtp.reply_to"); // } // // public static boolean getSmtpSsl() { return config.getBoolean("distribution.smtp.ssl", false); } // // public static int getSmtpPort() { // return config.getInt("distribution.smtp.port", 25); // } // // public static int getSmtpConnectTimeout() { // return config.getInt("distribution.smtp.connect_timeout", 10*1000); // } // // public static String getFileBasePath() { // return config.getString("distribution.backup.path", System.getProperty("java.io.tmpdir")); // } // // public static String getKv7PlanningPath() { // return config.getString("distribution.kv78turbo.path.planning"); // } // // public static String getKv7CalendarPath() { // return config.getString("distribution.kv78turbo.path.calendar"); // } // // public static String getChbPath() { // return config.getString("distribution.chb.path"); // } // // // public static String getPlanningLoaderTime() { // return config.getString("distribution.planning.loadTime", "03:30"); // } // // public static String getPlanningCleanupTime() { // return config.getString("distribution.planning.cleanupTime", "04:00"); // } // // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/util/ZeroMQUtils.java // public class ZeroMQUtils { // // public static String[] gunzipMultifameZMsg(ZMsg msg) throws IOException { // Iterator<ZFrame> frames = msg.iterator(); // // pop off first frame, which contains "/GOVI/KV8" (the feed name) // // (isn't there a method for this?) // String header = frames.next().toString(); // ByteArrayOutputStream buffer = new ByteArrayOutputStream(); // while (frames.hasNext()) { // ZFrame frame = frames.next(); // byte[] frameData = frame.getData(); // buffer.write(frameData); // } // if (buffer.size() == 0) { // return null; // } // // chain input streams to gunzip contents of byte buffer // InputStream gzippedMessageStream = new ByteArrayInputStream( // buffer.toByteArray()); // InputStream messageStream = new GZIPInputStream(gzippedMessageStream); // // copy input stream back to transport stream // buffer.reset(); // byte[] b = new byte[4096]; // for (int n; (n = messageStream.read(b)) != -1;) { // buffer.write(b, 0, n); // } // return new String[] { header, buffer.toString() }; // } // } // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/input/Kv78ReceiveTask.java import nl.crowndov.displaydirect.distribution.Configuration; import nl.crowndov.displaydirect.distribution.util.ZeroMQUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zeromq.ZMQ; import org.zeromq.ZMsg; import java.util.List; import java.util.concurrent.TimeUnit; package nl.crowndov.displaydirect.distribution.input; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class Kv78ReceiveTask implements Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(Kv78ReceiveTask.class);
private final String[] kvPublishers = Configuration.getKvPublishers();
CROW-NDOV/displaydirect
distribution/src/main/java/nl/crowndov/displaydirect/distribution/messages/processing/StopCodeProcessor.java
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/chb/StopStore.java // public class StopStore { // // private static final Logger LOGGER = LoggerFactory.getLogger(StopStore.class); // // private static Map<String, String> store = new HashMap<>(); // private static Set<String> missing = new HashSet<>(); // // public static Optional<String> getQuayFromCode(String dataOwner, String stopCode) { // String key = dataOwner+"|"+stopCode; // if (store.containsKey(key)) { // return Optional.of(store.get(key)); // } // missing.add(key); // return Optional.empty(); // } // // public static boolean stopExists(String quayOrStopCode) { // return store.values().contains(quayOrStopCode); // } // // public static Map<String, String> getStore() { // return store; // } // // public static Set<String> getMissing() { // return missing; // } // // public static void setStore(Map<String, String> storeData) { // store = storeData; // } // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/domain/travelinfo/RealtimeMessage.java // public class RealtimeMessage implements Serializable { // // private static final long serialVersionUID = -8692508260190453615L; // // private Type type; // private LocalDate date; // private String dataOwnerCode; // private String stopCode; // // private String quayCode; // // public RealtimeMessage() { // } // // public RealtimeMessage(Type type, LocalDate date, String dataOwnerCode, String stopCode) { // this.type = type; // this.date = date; // this.dataOwnerCode = dataOwnerCode; // this.stopCode = stopCode; // } // // public String getDataOwnerCode() { // return dataOwnerCode; // } // // public LocalDate getDate() { // return date; // } // // public Type getType() { // return type; // } // // public String getStopCode() { // return stopCode; // } // // public String getQuayCode() { // return quayCode; // } // // public void setQuayCode(String quayCode) { // this.quayCode = quayCode; // } // // public enum Type { // PASSTIME, // MESSAGE_UPDATE, // MESSAGE_DELETE, // } // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/stats/MetricStore.java // public class MetricStore { // // private static List<Metric> metrics = new ArrayList<>(); // private static ConcurrentMap<String, ConcurrentMap<LocalDateTime, Metric>> buckets = new ConcurrentHashMap<>(); // private static MetricStore instance; // // public static synchronized MetricStore getInstance() { // if (instance == null) { // instance = new MetricStore(); // } // return instance; // } // // public void storeMetric(String name, long value) { // Metric m = new Metric(name, value); // metrics.add(m); // } // // public void setBucketValue(String name, TemporalUnit bucket, long value) { // ensureMetricInBucket(name); // LocalDateTime bucketSlot = LocalDateTime.now().truncatedTo(bucket); // buckets.get(name).put(bucketSlot, new Metric(name, value, bucketSlot)); // } // // public void increaseBucketValue(String name, TemporalUnit bucket) { // ensureMetricInBucket(name); // LocalDateTime key = LocalDateTime.now().truncatedTo(bucket); // if (!buckets.get(name).containsKey(key)) { // buckets.get(name).put(key, new Metric(name, 1)); // } else { // Metric previous = buckets.get(name).get(key); // buckets.get(name).put(key, new Metric(name, previous.getValue() + 1, key)); // } // } // // private void ensureMetricInBucket(String name) { // if (!buckets.containsKey(name)) { // buckets.put(name, new ConcurrentSkipListMap<>()); // } // } // // public Map<String, List<Metric>> getMetrics() { // return Stream.concat(buckets.values().stream().flatMap(m -> m.values().stream()), metrics.stream()) // .collect(Collectors.groupingBy(Metric::getName)); // } // // public List<Metric> getMetric(String name) { // if (buckets.containsKey(name)) { // return new ArrayList<>(buckets.get(name).values()); // } // return metrics.parallelStream() // .filter(m -> m.getName().equalsIgnoreCase(name)) // .collect(Collectors.toList()); // } // }
import nl.crowndov.displaydirect.distribution.chb.StopStore; import nl.crowndov.displaydirect.distribution.domain.travelinfo.RealtimeMessage; import nl.crowndov.displaydirect.distribution.stats.MetricStore; import java.time.temporal.ChronoUnit; import java.util.Optional;
package nl.crowndov.displaydirect.distribution.messages.processing; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class StopCodeProcessor implements Processor<RealtimeMessage> { private static MetricStore metrics = MetricStore.getInstance(); @Override public RealtimeMessage process(RealtimeMessage input) {
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/chb/StopStore.java // public class StopStore { // // private static final Logger LOGGER = LoggerFactory.getLogger(StopStore.class); // // private static Map<String, String> store = new HashMap<>(); // private static Set<String> missing = new HashSet<>(); // // public static Optional<String> getQuayFromCode(String dataOwner, String stopCode) { // String key = dataOwner+"|"+stopCode; // if (store.containsKey(key)) { // return Optional.of(store.get(key)); // } // missing.add(key); // return Optional.empty(); // } // // public static boolean stopExists(String quayOrStopCode) { // return store.values().contains(quayOrStopCode); // } // // public static Map<String, String> getStore() { // return store; // } // // public static Set<String> getMissing() { // return missing; // } // // public static void setStore(Map<String, String> storeData) { // store = storeData; // } // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/domain/travelinfo/RealtimeMessage.java // public class RealtimeMessage implements Serializable { // // private static final long serialVersionUID = -8692508260190453615L; // // private Type type; // private LocalDate date; // private String dataOwnerCode; // private String stopCode; // // private String quayCode; // // public RealtimeMessage() { // } // // public RealtimeMessage(Type type, LocalDate date, String dataOwnerCode, String stopCode) { // this.type = type; // this.date = date; // this.dataOwnerCode = dataOwnerCode; // this.stopCode = stopCode; // } // // public String getDataOwnerCode() { // return dataOwnerCode; // } // // public LocalDate getDate() { // return date; // } // // public Type getType() { // return type; // } // // public String getStopCode() { // return stopCode; // } // // public String getQuayCode() { // return quayCode; // } // // public void setQuayCode(String quayCode) { // this.quayCode = quayCode; // } // // public enum Type { // PASSTIME, // MESSAGE_UPDATE, // MESSAGE_DELETE, // } // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/stats/MetricStore.java // public class MetricStore { // // private static List<Metric> metrics = new ArrayList<>(); // private static ConcurrentMap<String, ConcurrentMap<LocalDateTime, Metric>> buckets = new ConcurrentHashMap<>(); // private static MetricStore instance; // // public static synchronized MetricStore getInstance() { // if (instance == null) { // instance = new MetricStore(); // } // return instance; // } // // public void storeMetric(String name, long value) { // Metric m = new Metric(name, value); // metrics.add(m); // } // // public void setBucketValue(String name, TemporalUnit bucket, long value) { // ensureMetricInBucket(name); // LocalDateTime bucketSlot = LocalDateTime.now().truncatedTo(bucket); // buckets.get(name).put(bucketSlot, new Metric(name, value, bucketSlot)); // } // // public void increaseBucketValue(String name, TemporalUnit bucket) { // ensureMetricInBucket(name); // LocalDateTime key = LocalDateTime.now().truncatedTo(bucket); // if (!buckets.get(name).containsKey(key)) { // buckets.get(name).put(key, new Metric(name, 1)); // } else { // Metric previous = buckets.get(name).get(key); // buckets.get(name).put(key, new Metric(name, previous.getValue() + 1, key)); // } // } // // private void ensureMetricInBucket(String name) { // if (!buckets.containsKey(name)) { // buckets.put(name, new ConcurrentSkipListMap<>()); // } // } // // public Map<String, List<Metric>> getMetrics() { // return Stream.concat(buckets.values().stream().flatMap(m -> m.values().stream()), metrics.stream()) // .collect(Collectors.groupingBy(Metric::getName)); // } // // public List<Metric> getMetric(String name) { // if (buckets.containsKey(name)) { // return new ArrayList<>(buckets.get(name).values()); // } // return metrics.parallelStream() // .filter(m -> m.getName().equalsIgnoreCase(name)) // .collect(Collectors.toList()); // } // } // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/messages/processing/StopCodeProcessor.java import nl.crowndov.displaydirect.distribution.chb.StopStore; import nl.crowndov.displaydirect.distribution.domain.travelinfo.RealtimeMessage; import nl.crowndov.displaydirect.distribution.stats.MetricStore; import java.time.temporal.ChronoUnit; import java.util.Optional; package nl.crowndov.displaydirect.distribution.messages.processing; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class StopCodeProcessor implements Processor<RealtimeMessage> { private static MetricStore metrics = MetricStore.getInstance(); @Override public RealtimeMessage process(RealtimeMessage input) {
Optional<String> quay = StopStore.getQuayFromCode(input.getDataOwnerCode(), input.getStopCode());
CROW-NDOV/displaydirect
distribution/src/main/java/nl/crowndov/displaydirect/distribution/resources/AuthorizationResource.java
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/authorization/AuthorizationWhitelist.java // public class AuthorizationWhitelist extends AbstractService { // // private static final Logger LOGGER = LoggerFactory.getLogger(AuthorizationWhitelist.class); // // private static List<String> validKeys = new ArrayList<>(); // private static Store.ValidationTokenStore validationTokens = new Store.ValidationTokenStore(); // // private static Transport transport = TransportFactory.get(); // // private static MessageDigest DIGEST = null; // // static { // try { // DIGEST = MessageDigest.getInstance("SHA-256"); // } catch (NoSuchAlgorithmException e) { // LOGGER.error("Failed to initialize hash algorithm", e); // } // } // // public static void start() { // backup(() -> { // readFile("authorization_keys", Store.StringList.class).ifPresent(k -> validKeys = k); // readFile("authorization_tokens", Store.ValidationTokenStore.class).ifPresent(vt -> validationTokens = vt); // }); // } // // public static void stop() { // writeFile("authorization_keys", validKeys); // writeFile("authorization_tokens", validationTokens); // } // // // public static boolean isValid(Subscription sub) { // return validKeys.contains(getKey(sub.getId(), sub.getEmail())) || Configuration.getAuthorizationWhitelist().contains(sub.getPrefix()); // } // // private static String getKey(String systemId, String email) { // return systemId + "_" + email.toLowerCase(); // } // // public static Optional<ValidationToken> addValidation(String systemId, Subscription subscribe) { // ZonedDateTime now = ZonedDateTime.now(Configuration.getZoneId()); // // Check a validation token hasn't already been handed out for this system and it's still valid // if (validationTokens.values().stream().anyMatch(vt -> vt.getSystemId().contentEquals(systemId) && vt.getGenerated().plusHours(48).isAfter(now))) { // return Optional.empty(); // } // ValidationToken v = new ValidationToken(newToken(), systemId, subscribe.getEmail(), ZonedDateTime.now(ZoneId.of("UTC")), subscribe); // validationTokens.put(v.getToken(), v); // // Map<String, Object> variables = new HashMap<>(); // variables.put("id", systemId); // variables.put("description", subscribe.getDescription()); // variables.put("url", Configuration.getBaseUrl() + "/admin/authorize?token=" + v.getToken()); // EmailUtil.sendHtmlEmail(subscribe.getEmail(), "Rond aanmelding DisplayDirect af", "authenticate", variables); // // return Optional.ofNullable(v); // } // // private static String newToken() { // return getHash(UUID.randomUUID().toString()); // } // // private static String getHash(String s) { // return DatatypeConverter.printHexBinary(DIGEST.digest(s.getBytes())); // } // // public static boolean validate(String token) { // if (validationTokens.containsKey(token) && validationTokens.get(token).isValid()) { // ValidationToken vt = validationTokens.get(token); // validKeys.add(getKey(vt.getSystemId(), vt.getEmail())); // validationTokens.remove(token); // // TODO: Might need to do this in a different thread, this will trigger 48 hours of messages // // Get the planning we need // TODO: Duplicated // List<RealtimeMessage> times = QuayDataProvider.getDataForQuay(vt.getSubscription().getSubscribedQuayCodes(), true); // sendStatus(vt.getSystemId(), true, DisplayDirectMessage.SubscriptionResponse.Status.AUTHORISATION_VALIDATED); // if (times.size() > 0) { // LOGGER.debug("Got {} times to send", times.size()); // transport.sendMessage(TopicFactory.travelInformation(vt.getSystemId()), DisplayDirectMessageFactory.fromRealTime(times, vt.getSubscription()), QoS.AT_LEAST_ONCE); // sendStatus(vt.getSystemId(), true, DisplayDirectMessage.SubscriptionResponse.Status.PLANNING_SENT); // } else { // sendStatus(vt.getSystemId(), true, DisplayDirectMessage.SubscriptionResponse.Status.NO_PLANNING); // } // // SubscriptionStore.add(vt.getSubscription()); // Log.send(LogCode.AUTHORISATION_VALIDATED, vt.getSystemId(), "Authorization processed"); // Log.send(LogCode.SUBSCRIPTION_ADDED, vt.getSystemId(), "System subscribed succesfully, authorization processed"); // return true; // } // return false; // } // // public static void remove(Subscription sub) { // // aah // validKeys.remove(getKey(sub.getId(), sub.getEmail())); // } // // public static List<ValidationToken> getTokens() { // return new ArrayList<>(validationTokens.values()); // } // // public static List<String> getValid() { // return validKeys; // } // // // TODO: Duplicate method // private static boolean sendStatus(String id, boolean success, DisplayDirectMessage.SubscriptionResponse.Status s) { // return transport.sendMessage(TopicFactory.subscriptionResponse(id), DisplayDirectMessageFactory.toSubscriptionStatus(success, s), QoS.EXACTLY_ONCE); // } // }
import nl.crowndov.displaydirect.distribution.authorization.AuthorizationWhitelist; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response;
package nl.crowndov.displaydirect.distribution.resources; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ @Path("/v1/authorization") public class AuthorizationResource { @GET public Response get() {
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/authorization/AuthorizationWhitelist.java // public class AuthorizationWhitelist extends AbstractService { // // private static final Logger LOGGER = LoggerFactory.getLogger(AuthorizationWhitelist.class); // // private static List<String> validKeys = new ArrayList<>(); // private static Store.ValidationTokenStore validationTokens = new Store.ValidationTokenStore(); // // private static Transport transport = TransportFactory.get(); // // private static MessageDigest DIGEST = null; // // static { // try { // DIGEST = MessageDigest.getInstance("SHA-256"); // } catch (NoSuchAlgorithmException e) { // LOGGER.error("Failed to initialize hash algorithm", e); // } // } // // public static void start() { // backup(() -> { // readFile("authorization_keys", Store.StringList.class).ifPresent(k -> validKeys = k); // readFile("authorization_tokens", Store.ValidationTokenStore.class).ifPresent(vt -> validationTokens = vt); // }); // } // // public static void stop() { // writeFile("authorization_keys", validKeys); // writeFile("authorization_tokens", validationTokens); // } // // // public static boolean isValid(Subscription sub) { // return validKeys.contains(getKey(sub.getId(), sub.getEmail())) || Configuration.getAuthorizationWhitelist().contains(sub.getPrefix()); // } // // private static String getKey(String systemId, String email) { // return systemId + "_" + email.toLowerCase(); // } // // public static Optional<ValidationToken> addValidation(String systemId, Subscription subscribe) { // ZonedDateTime now = ZonedDateTime.now(Configuration.getZoneId()); // // Check a validation token hasn't already been handed out for this system and it's still valid // if (validationTokens.values().stream().anyMatch(vt -> vt.getSystemId().contentEquals(systemId) && vt.getGenerated().plusHours(48).isAfter(now))) { // return Optional.empty(); // } // ValidationToken v = new ValidationToken(newToken(), systemId, subscribe.getEmail(), ZonedDateTime.now(ZoneId.of("UTC")), subscribe); // validationTokens.put(v.getToken(), v); // // Map<String, Object> variables = new HashMap<>(); // variables.put("id", systemId); // variables.put("description", subscribe.getDescription()); // variables.put("url", Configuration.getBaseUrl() + "/admin/authorize?token=" + v.getToken()); // EmailUtil.sendHtmlEmail(subscribe.getEmail(), "Rond aanmelding DisplayDirect af", "authenticate", variables); // // return Optional.ofNullable(v); // } // // private static String newToken() { // return getHash(UUID.randomUUID().toString()); // } // // private static String getHash(String s) { // return DatatypeConverter.printHexBinary(DIGEST.digest(s.getBytes())); // } // // public static boolean validate(String token) { // if (validationTokens.containsKey(token) && validationTokens.get(token).isValid()) { // ValidationToken vt = validationTokens.get(token); // validKeys.add(getKey(vt.getSystemId(), vt.getEmail())); // validationTokens.remove(token); // // TODO: Might need to do this in a different thread, this will trigger 48 hours of messages // // Get the planning we need // TODO: Duplicated // List<RealtimeMessage> times = QuayDataProvider.getDataForQuay(vt.getSubscription().getSubscribedQuayCodes(), true); // sendStatus(vt.getSystemId(), true, DisplayDirectMessage.SubscriptionResponse.Status.AUTHORISATION_VALIDATED); // if (times.size() > 0) { // LOGGER.debug("Got {} times to send", times.size()); // transport.sendMessage(TopicFactory.travelInformation(vt.getSystemId()), DisplayDirectMessageFactory.fromRealTime(times, vt.getSubscription()), QoS.AT_LEAST_ONCE); // sendStatus(vt.getSystemId(), true, DisplayDirectMessage.SubscriptionResponse.Status.PLANNING_SENT); // } else { // sendStatus(vt.getSystemId(), true, DisplayDirectMessage.SubscriptionResponse.Status.NO_PLANNING); // } // // SubscriptionStore.add(vt.getSubscription()); // Log.send(LogCode.AUTHORISATION_VALIDATED, vt.getSystemId(), "Authorization processed"); // Log.send(LogCode.SUBSCRIPTION_ADDED, vt.getSystemId(), "System subscribed succesfully, authorization processed"); // return true; // } // return false; // } // // public static void remove(Subscription sub) { // // aah // validKeys.remove(getKey(sub.getId(), sub.getEmail())); // } // // public static List<ValidationToken> getTokens() { // return new ArrayList<>(validationTokens.values()); // } // // public static List<String> getValid() { // return validKeys; // } // // // TODO: Duplicate method // private static boolean sendStatus(String id, boolean success, DisplayDirectMessage.SubscriptionResponse.Status s) { // return transport.sendMessage(TopicFactory.subscriptionResponse(id), DisplayDirectMessageFactory.toSubscriptionStatus(success, s), QoS.EXACTLY_ONCE); // } // } // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/resources/AuthorizationResource.java import nl.crowndov.displaydirect.distribution.authorization.AuthorizationWhitelist; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response; package nl.crowndov.displaydirect.distribution.resources; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ @Path("/v1/authorization") public class AuthorizationResource { @GET public Response get() {
return Response.ok(AuthorizationWhitelist.getValid()).build();
CROW-NDOV/displaydirect
distribution/src/main/java/nl/crowndov/displaydirect/distribution/resources/StopResource.java
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/chb/StopStore.java // public class StopStore { // // private static final Logger LOGGER = LoggerFactory.getLogger(StopStore.class); // // private static Map<String, String> store = new HashMap<>(); // private static Set<String> missing = new HashSet<>(); // // public static Optional<String> getQuayFromCode(String dataOwner, String stopCode) { // String key = dataOwner+"|"+stopCode; // if (store.containsKey(key)) { // return Optional.of(store.get(key)); // } // missing.add(key); // return Optional.empty(); // } // // public static boolean stopExists(String quayOrStopCode) { // return store.values().contains(quayOrStopCode); // } // // public static Map<String, String> getStore() { // return store; // } // // public static Set<String> getMissing() { // return missing; // } // // public static void setStore(Map<String, String> storeData) { // store = storeData; // } // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/input/TimingPointProvider.java // public class TimingPointProvider extends AbstractService { // // private static final Store.TimingPointStore points = new Store.TimingPointStore(); // // public static void start() { // readFile("timing_points", Store.TimingPointStore.class).ifPresent(points::putAll); // } // // public static void stop() { // backup(); // } // // public static void backup() { // writeFile("timing_points", points); // } // // public static void updateTimingPoints(Map<String, String> input) { // points.putAll(input); // } // // public static Optional<String> getStopFromTimingPoint(String dataOwnerCode, String timingPointCode) { // return Optional.ofNullable(points.getOrDefault(dataOwnerCode+"|"+timingPointCode, null)); // } // // public static Store.TimingPointStore getAll() { // return points; // } // }
import nl.crowndov.displaydirect.distribution.chb.StopStore; import nl.crowndov.displaydirect.distribution.input.TimingPointProvider; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response;
package nl.crowndov.displaydirect.distribution.resources; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ @Path("/v1/stop") public class StopResource { @GET public Response get() {
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/chb/StopStore.java // public class StopStore { // // private static final Logger LOGGER = LoggerFactory.getLogger(StopStore.class); // // private static Map<String, String> store = new HashMap<>(); // private static Set<String> missing = new HashSet<>(); // // public static Optional<String> getQuayFromCode(String dataOwner, String stopCode) { // String key = dataOwner+"|"+stopCode; // if (store.containsKey(key)) { // return Optional.of(store.get(key)); // } // missing.add(key); // return Optional.empty(); // } // // public static boolean stopExists(String quayOrStopCode) { // return store.values().contains(quayOrStopCode); // } // // public static Map<String, String> getStore() { // return store; // } // // public static Set<String> getMissing() { // return missing; // } // // public static void setStore(Map<String, String> storeData) { // store = storeData; // } // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/input/TimingPointProvider.java // public class TimingPointProvider extends AbstractService { // // private static final Store.TimingPointStore points = new Store.TimingPointStore(); // // public static void start() { // readFile("timing_points", Store.TimingPointStore.class).ifPresent(points::putAll); // } // // public static void stop() { // backup(); // } // // public static void backup() { // writeFile("timing_points", points); // } // // public static void updateTimingPoints(Map<String, String> input) { // points.putAll(input); // } // // public static Optional<String> getStopFromTimingPoint(String dataOwnerCode, String timingPointCode) { // return Optional.ofNullable(points.getOrDefault(dataOwnerCode+"|"+timingPointCode, null)); // } // // public static Store.TimingPointStore getAll() { // return points; // } // } // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/resources/StopResource.java import nl.crowndov.displaydirect.distribution.chb.StopStore; import nl.crowndov.displaydirect.distribution.input.TimingPointProvider; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response; package nl.crowndov.displaydirect.distribution.resources; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ @Path("/v1/stop") public class StopResource { @GET public Response get() {
return Response.ok(StopStore.getStore()).build();
CROW-NDOV/displaydirect
distribution/src/main/java/nl/crowndov/displaydirect/distribution/resources/StopResource.java
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/chb/StopStore.java // public class StopStore { // // private static final Logger LOGGER = LoggerFactory.getLogger(StopStore.class); // // private static Map<String, String> store = new HashMap<>(); // private static Set<String> missing = new HashSet<>(); // // public static Optional<String> getQuayFromCode(String dataOwner, String stopCode) { // String key = dataOwner+"|"+stopCode; // if (store.containsKey(key)) { // return Optional.of(store.get(key)); // } // missing.add(key); // return Optional.empty(); // } // // public static boolean stopExists(String quayOrStopCode) { // return store.values().contains(quayOrStopCode); // } // // public static Map<String, String> getStore() { // return store; // } // // public static Set<String> getMissing() { // return missing; // } // // public static void setStore(Map<String, String> storeData) { // store = storeData; // } // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/input/TimingPointProvider.java // public class TimingPointProvider extends AbstractService { // // private static final Store.TimingPointStore points = new Store.TimingPointStore(); // // public static void start() { // readFile("timing_points", Store.TimingPointStore.class).ifPresent(points::putAll); // } // // public static void stop() { // backup(); // } // // public static void backup() { // writeFile("timing_points", points); // } // // public static void updateTimingPoints(Map<String, String> input) { // points.putAll(input); // } // // public static Optional<String> getStopFromTimingPoint(String dataOwnerCode, String timingPointCode) { // return Optional.ofNullable(points.getOrDefault(dataOwnerCode+"|"+timingPointCode, null)); // } // // public static Store.TimingPointStore getAll() { // return points; // } // }
import nl.crowndov.displaydirect.distribution.chb.StopStore; import nl.crowndov.displaydirect.distribution.input.TimingPointProvider; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response;
package nl.crowndov.displaydirect.distribution.resources; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ @Path("/v1/stop") public class StopResource { @GET public Response get() { return Response.ok(StopStore.getStore()).build(); } @GET @Path("/missing") public Response getMissing() { return Response.ok(StopStore.getMissing()).build(); } @GET @Path("/timingpoint") public Response getTimingPoints() {
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/chb/StopStore.java // public class StopStore { // // private static final Logger LOGGER = LoggerFactory.getLogger(StopStore.class); // // private static Map<String, String> store = new HashMap<>(); // private static Set<String> missing = new HashSet<>(); // // public static Optional<String> getQuayFromCode(String dataOwner, String stopCode) { // String key = dataOwner+"|"+stopCode; // if (store.containsKey(key)) { // return Optional.of(store.get(key)); // } // missing.add(key); // return Optional.empty(); // } // // public static boolean stopExists(String quayOrStopCode) { // return store.values().contains(quayOrStopCode); // } // // public static Map<String, String> getStore() { // return store; // } // // public static Set<String> getMissing() { // return missing; // } // // public static void setStore(Map<String, String> storeData) { // store = storeData; // } // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/input/TimingPointProvider.java // public class TimingPointProvider extends AbstractService { // // private static final Store.TimingPointStore points = new Store.TimingPointStore(); // // public static void start() { // readFile("timing_points", Store.TimingPointStore.class).ifPresent(points::putAll); // } // // public static void stop() { // backup(); // } // // public static void backup() { // writeFile("timing_points", points); // } // // public static void updateTimingPoints(Map<String, String> input) { // points.putAll(input); // } // // public static Optional<String> getStopFromTimingPoint(String dataOwnerCode, String timingPointCode) { // return Optional.ofNullable(points.getOrDefault(dataOwnerCode+"|"+timingPointCode, null)); // } // // public static Store.TimingPointStore getAll() { // return points; // } // } // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/resources/StopResource.java import nl.crowndov.displaydirect.distribution.chb.StopStore; import nl.crowndov.displaydirect.distribution.input.TimingPointProvider; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response; package nl.crowndov.displaydirect.distribution.resources; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ @Path("/v1/stop") public class StopResource { @GET public Response get() { return Response.ok(StopStore.getStore()).build(); } @GET @Path("/missing") public Response getMissing() { return Response.ok(StopStore.getMissing()).build(); } @GET @Path("/timingpoint") public Response getTimingPoints() {
return Response.ok(TimingPointProvider.getAll()).build();
CROW-NDOV/displaydirect
distribution/src/main/java/nl/crowndov/displaydirect/distribution/transport/TransportFactory.java
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/Configuration.java // public class Configuration { // // private static final Logger LOGGER = LoggerFactory.getLogger(Configuration.class); // // private static AbstractConfiguration config = ConfigurationManager.getConfigInstance(); // // public static List<String> getKvEndpoints() { // return Arrays.asList(config.getStringArray("distribution.kv78turbo.endpoints")); // } // // public static String[] getKvPublishers() { // return config.getStringArray("distribution.kv78turbo.publishers"); // } // // public static ZoneId getZoneId() { // return ZoneId.of(config.getString("distribution.timezone.default")); // } // // public static String getOutputTransport() { // return config.getString("distribution.transport", "mqtt"); // } // // public static String getMqttBrokerHost() { // return config.getString("distribution.mqtt.host", "localhost:1883"); // } // // public static int getZmqInternalPort() { // return 9800; // } // // public static String getMqttClientId() { // return config.getString("distribution.mqtt.client_id", "distribution"); // } // // public static int getAuthorizationTokenMaxAge() { // return config.getInt("distribution.authorization.max_age_hours"); // } // // public static List<String> getAuthorizationWhitelist() { // return Arrays.asList(config.getStringArray("distribution.authorization.whitelist_prefix")); // } // // public static String getBaseUrl() { // return config.getString("distribution.install.base_url", "http://localhost:8080"); // } // // public static String getSmtpUsername() { // return config.getString("distribution.smtp.username", null); // } // // public static String getSmtpPassword() { // return config.getString("distribution.smtp.password", null); // } // // public static String getSmtpFrom() { // return config.getString("distribution.smtp.from"); // } // // public static String getSmtpHostname() { // return config.getString("distribution.smtp.hostname"); // } // // public static String getSmtpReplyTo() { // return config.getString("distribution.smtp.reply_to"); // } // // public static boolean getSmtpSsl() { return config.getBoolean("distribution.smtp.ssl", false); } // // public static int getSmtpPort() { // return config.getInt("distribution.smtp.port", 25); // } // // public static int getSmtpConnectTimeout() { // return config.getInt("distribution.smtp.connect_timeout", 10*1000); // } // // public static String getFileBasePath() { // return config.getString("distribution.backup.path", System.getProperty("java.io.tmpdir")); // } // // public static String getKv7PlanningPath() { // return config.getString("distribution.kv78turbo.path.planning"); // } // // public static String getKv7CalendarPath() { // return config.getString("distribution.kv78turbo.path.calendar"); // } // // public static String getChbPath() { // return config.getString("distribution.chb.path"); // } // // // public static String getPlanningLoaderTime() { // return config.getString("distribution.planning.loadTime", "03:30"); // } // // public static String getPlanningCleanupTime() { // return config.getString("distribution.planning.cleanupTime", "04:00"); // } // // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/transport/mqtt/MqttTransport.java // public class MqttTransport implements Transport { // // private static final Logger LOGGER = LoggerFactory.getLogger(MqttTransport.class); // // private OnMessageReceivedListener listener = null; // // private final MqttClient.OnMessageListener PUBLISH_LISTENER = (topic, data, ack) -> { // LOGGER.trace("Got incoming message on topic {}", topic); // boolean result = false; // if (listener != null) { // result = listener.onMessageReceived(topic, data); // } // if (result) { // If not we'll retry this message // ack.run(); // } // }; // // private MqttClient c = new MqttClient(PUBLISH_LISTENER); // // @Override // public boolean sendMessage(String topic, byte[] data) { // return sendMessage(topic, data, QoS.AT_LEAST_ONCE); // } // // @Override // public boolean sendMessage(String topic, byte[] data, QoS quality) { // return data != null && c.send(topic, data, quality); // } // // @Override // public void registerListener(OnMessageReceivedListener listener) { // this.listener = listener; // } // // @Override // public void stop() { // c.stop(); // } // // }
import nl.crowndov.displaydirect.distribution.Configuration; import nl.crowndov.displaydirect.distribution.transport.mqtt.MqttTransport;
package nl.crowndov.displaydirect.distribution.transport; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class TransportFactory { public static Transport instance = null; public static synchronized Transport get() {
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/Configuration.java // public class Configuration { // // private static final Logger LOGGER = LoggerFactory.getLogger(Configuration.class); // // private static AbstractConfiguration config = ConfigurationManager.getConfigInstance(); // // public static List<String> getKvEndpoints() { // return Arrays.asList(config.getStringArray("distribution.kv78turbo.endpoints")); // } // // public static String[] getKvPublishers() { // return config.getStringArray("distribution.kv78turbo.publishers"); // } // // public static ZoneId getZoneId() { // return ZoneId.of(config.getString("distribution.timezone.default")); // } // // public static String getOutputTransport() { // return config.getString("distribution.transport", "mqtt"); // } // // public static String getMqttBrokerHost() { // return config.getString("distribution.mqtt.host", "localhost:1883"); // } // // public static int getZmqInternalPort() { // return 9800; // } // // public static String getMqttClientId() { // return config.getString("distribution.mqtt.client_id", "distribution"); // } // // public static int getAuthorizationTokenMaxAge() { // return config.getInt("distribution.authorization.max_age_hours"); // } // // public static List<String> getAuthorizationWhitelist() { // return Arrays.asList(config.getStringArray("distribution.authorization.whitelist_prefix")); // } // // public static String getBaseUrl() { // return config.getString("distribution.install.base_url", "http://localhost:8080"); // } // // public static String getSmtpUsername() { // return config.getString("distribution.smtp.username", null); // } // // public static String getSmtpPassword() { // return config.getString("distribution.smtp.password", null); // } // // public static String getSmtpFrom() { // return config.getString("distribution.smtp.from"); // } // // public static String getSmtpHostname() { // return config.getString("distribution.smtp.hostname"); // } // // public static String getSmtpReplyTo() { // return config.getString("distribution.smtp.reply_to"); // } // // public static boolean getSmtpSsl() { return config.getBoolean("distribution.smtp.ssl", false); } // // public static int getSmtpPort() { // return config.getInt("distribution.smtp.port", 25); // } // // public static int getSmtpConnectTimeout() { // return config.getInt("distribution.smtp.connect_timeout", 10*1000); // } // // public static String getFileBasePath() { // return config.getString("distribution.backup.path", System.getProperty("java.io.tmpdir")); // } // // public static String getKv7PlanningPath() { // return config.getString("distribution.kv78turbo.path.planning"); // } // // public static String getKv7CalendarPath() { // return config.getString("distribution.kv78turbo.path.calendar"); // } // // public static String getChbPath() { // return config.getString("distribution.chb.path"); // } // // // public static String getPlanningLoaderTime() { // return config.getString("distribution.planning.loadTime", "03:30"); // } // // public static String getPlanningCleanupTime() { // return config.getString("distribution.planning.cleanupTime", "04:00"); // } // // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/transport/mqtt/MqttTransport.java // public class MqttTransport implements Transport { // // private static final Logger LOGGER = LoggerFactory.getLogger(MqttTransport.class); // // private OnMessageReceivedListener listener = null; // // private final MqttClient.OnMessageListener PUBLISH_LISTENER = (topic, data, ack) -> { // LOGGER.trace("Got incoming message on topic {}", topic); // boolean result = false; // if (listener != null) { // result = listener.onMessageReceived(topic, data); // } // if (result) { // If not we'll retry this message // ack.run(); // } // }; // // private MqttClient c = new MqttClient(PUBLISH_LISTENER); // // @Override // public boolean sendMessage(String topic, byte[] data) { // return sendMessage(topic, data, QoS.AT_LEAST_ONCE); // } // // @Override // public boolean sendMessage(String topic, byte[] data, QoS quality) { // return data != null && c.send(topic, data, quality); // } // // @Override // public void registerListener(OnMessageReceivedListener listener) { // this.listener = listener; // } // // @Override // public void stop() { // c.stop(); // } // // } // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/transport/TransportFactory.java import nl.crowndov.displaydirect.distribution.Configuration; import nl.crowndov.displaydirect.distribution.transport.mqtt.MqttTransport; package nl.crowndov.displaydirect.distribution.transport; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class TransportFactory { public static Transport instance = null; public static synchronized Transport get() {
if (Configuration.getOutputTransport().equalsIgnoreCase("mqtt")) {
CROW-NDOV/displaydirect
distribution/src/main/java/nl/crowndov/displaydirect/distribution/transport/TransportFactory.java
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/Configuration.java // public class Configuration { // // private static final Logger LOGGER = LoggerFactory.getLogger(Configuration.class); // // private static AbstractConfiguration config = ConfigurationManager.getConfigInstance(); // // public static List<String> getKvEndpoints() { // return Arrays.asList(config.getStringArray("distribution.kv78turbo.endpoints")); // } // // public static String[] getKvPublishers() { // return config.getStringArray("distribution.kv78turbo.publishers"); // } // // public static ZoneId getZoneId() { // return ZoneId.of(config.getString("distribution.timezone.default")); // } // // public static String getOutputTransport() { // return config.getString("distribution.transport", "mqtt"); // } // // public static String getMqttBrokerHost() { // return config.getString("distribution.mqtt.host", "localhost:1883"); // } // // public static int getZmqInternalPort() { // return 9800; // } // // public static String getMqttClientId() { // return config.getString("distribution.mqtt.client_id", "distribution"); // } // // public static int getAuthorizationTokenMaxAge() { // return config.getInt("distribution.authorization.max_age_hours"); // } // // public static List<String> getAuthorizationWhitelist() { // return Arrays.asList(config.getStringArray("distribution.authorization.whitelist_prefix")); // } // // public static String getBaseUrl() { // return config.getString("distribution.install.base_url", "http://localhost:8080"); // } // // public static String getSmtpUsername() { // return config.getString("distribution.smtp.username", null); // } // // public static String getSmtpPassword() { // return config.getString("distribution.smtp.password", null); // } // // public static String getSmtpFrom() { // return config.getString("distribution.smtp.from"); // } // // public static String getSmtpHostname() { // return config.getString("distribution.smtp.hostname"); // } // // public static String getSmtpReplyTo() { // return config.getString("distribution.smtp.reply_to"); // } // // public static boolean getSmtpSsl() { return config.getBoolean("distribution.smtp.ssl", false); } // // public static int getSmtpPort() { // return config.getInt("distribution.smtp.port", 25); // } // // public static int getSmtpConnectTimeout() { // return config.getInt("distribution.smtp.connect_timeout", 10*1000); // } // // public static String getFileBasePath() { // return config.getString("distribution.backup.path", System.getProperty("java.io.tmpdir")); // } // // public static String getKv7PlanningPath() { // return config.getString("distribution.kv78turbo.path.planning"); // } // // public static String getKv7CalendarPath() { // return config.getString("distribution.kv78turbo.path.calendar"); // } // // public static String getChbPath() { // return config.getString("distribution.chb.path"); // } // // // public static String getPlanningLoaderTime() { // return config.getString("distribution.planning.loadTime", "03:30"); // } // // public static String getPlanningCleanupTime() { // return config.getString("distribution.planning.cleanupTime", "04:00"); // } // // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/transport/mqtt/MqttTransport.java // public class MqttTransport implements Transport { // // private static final Logger LOGGER = LoggerFactory.getLogger(MqttTransport.class); // // private OnMessageReceivedListener listener = null; // // private final MqttClient.OnMessageListener PUBLISH_LISTENER = (topic, data, ack) -> { // LOGGER.trace("Got incoming message on topic {}", topic); // boolean result = false; // if (listener != null) { // result = listener.onMessageReceived(topic, data); // } // if (result) { // If not we'll retry this message // ack.run(); // } // }; // // private MqttClient c = new MqttClient(PUBLISH_LISTENER); // // @Override // public boolean sendMessage(String topic, byte[] data) { // return sendMessage(topic, data, QoS.AT_LEAST_ONCE); // } // // @Override // public boolean sendMessage(String topic, byte[] data, QoS quality) { // return data != null && c.send(topic, data, quality); // } // // @Override // public void registerListener(OnMessageReceivedListener listener) { // this.listener = listener; // } // // @Override // public void stop() { // c.stop(); // } // // }
import nl.crowndov.displaydirect.distribution.Configuration; import nl.crowndov.displaydirect.distribution.transport.mqtt.MqttTransport;
package nl.crowndov.displaydirect.distribution.transport; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class TransportFactory { public static Transport instance = null; public static synchronized Transport get() { if (Configuration.getOutputTransport().equalsIgnoreCase("mqtt")) {
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/Configuration.java // public class Configuration { // // private static final Logger LOGGER = LoggerFactory.getLogger(Configuration.class); // // private static AbstractConfiguration config = ConfigurationManager.getConfigInstance(); // // public static List<String> getKvEndpoints() { // return Arrays.asList(config.getStringArray("distribution.kv78turbo.endpoints")); // } // // public static String[] getKvPublishers() { // return config.getStringArray("distribution.kv78turbo.publishers"); // } // // public static ZoneId getZoneId() { // return ZoneId.of(config.getString("distribution.timezone.default")); // } // // public static String getOutputTransport() { // return config.getString("distribution.transport", "mqtt"); // } // // public static String getMqttBrokerHost() { // return config.getString("distribution.mqtt.host", "localhost:1883"); // } // // public static int getZmqInternalPort() { // return 9800; // } // // public static String getMqttClientId() { // return config.getString("distribution.mqtt.client_id", "distribution"); // } // // public static int getAuthorizationTokenMaxAge() { // return config.getInt("distribution.authorization.max_age_hours"); // } // // public static List<String> getAuthorizationWhitelist() { // return Arrays.asList(config.getStringArray("distribution.authorization.whitelist_prefix")); // } // // public static String getBaseUrl() { // return config.getString("distribution.install.base_url", "http://localhost:8080"); // } // // public static String getSmtpUsername() { // return config.getString("distribution.smtp.username", null); // } // // public static String getSmtpPassword() { // return config.getString("distribution.smtp.password", null); // } // // public static String getSmtpFrom() { // return config.getString("distribution.smtp.from"); // } // // public static String getSmtpHostname() { // return config.getString("distribution.smtp.hostname"); // } // // public static String getSmtpReplyTo() { // return config.getString("distribution.smtp.reply_to"); // } // // public static boolean getSmtpSsl() { return config.getBoolean("distribution.smtp.ssl", false); } // // public static int getSmtpPort() { // return config.getInt("distribution.smtp.port", 25); // } // // public static int getSmtpConnectTimeout() { // return config.getInt("distribution.smtp.connect_timeout", 10*1000); // } // // public static String getFileBasePath() { // return config.getString("distribution.backup.path", System.getProperty("java.io.tmpdir")); // } // // public static String getKv7PlanningPath() { // return config.getString("distribution.kv78turbo.path.planning"); // } // // public static String getKv7CalendarPath() { // return config.getString("distribution.kv78turbo.path.calendar"); // } // // public static String getChbPath() { // return config.getString("distribution.chb.path"); // } // // // public static String getPlanningLoaderTime() { // return config.getString("distribution.planning.loadTime", "03:30"); // } // // public static String getPlanningCleanupTime() { // return config.getString("distribution.planning.cleanupTime", "04:00"); // } // // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/transport/mqtt/MqttTransport.java // public class MqttTransport implements Transport { // // private static final Logger LOGGER = LoggerFactory.getLogger(MqttTransport.class); // // private OnMessageReceivedListener listener = null; // // private final MqttClient.OnMessageListener PUBLISH_LISTENER = (topic, data, ack) -> { // LOGGER.trace("Got incoming message on topic {}", topic); // boolean result = false; // if (listener != null) { // result = listener.onMessageReceived(topic, data); // } // if (result) { // If not we'll retry this message // ack.run(); // } // }; // // private MqttClient c = new MqttClient(PUBLISH_LISTENER); // // @Override // public boolean sendMessage(String topic, byte[] data) { // return sendMessage(topic, data, QoS.AT_LEAST_ONCE); // } // // @Override // public boolean sendMessage(String topic, byte[] data, QoS quality) { // return data != null && c.send(topic, data, quality); // } // // @Override // public void registerListener(OnMessageReceivedListener listener) { // this.listener = listener; // } // // @Override // public void stop() { // c.stop(); // } // // } // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/transport/TransportFactory.java import nl.crowndov.displaydirect.distribution.Configuration; import nl.crowndov.displaydirect.distribution.transport.mqtt.MqttTransport; package nl.crowndov.displaydirect.distribution.transport; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class TransportFactory { public static Transport instance = null; public static synchronized Transport get() { if (Configuration.getOutputTransport().equalsIgnoreCase("mqtt")) {
if (instance == null || !(instance instanceof MqttTransport)) {
CROW-NDOV/displaydirect
virtual_screen/src/main/java/nl/crowndov/displaydirect/virtual_screen/test/TestMain.java
// Path: virtual_screen/src/main/java/nl/crowndov/displaydirect/virtual_screen/Main.java // public class Main { // // private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); // // public static void main(String[] args) { // run(new Configuration()); // } // // public static void run(Configuration configuration) { // DisplayDirectClient c = new DisplayDirectClient(configuration); // c.setListener(new Listener()); // c.start(); // // while (!Thread.interrupted()) { // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // c.stop(); // break; // } // } // } // // private static class Listener implements OnDisplayDirectListener { // // @Override // public void onScreenContentsChange(List<PassTime> times) { // String display = times.stream() // .map(PassTime::toString) // .collect(Collectors.joining("\r\n")); // System.out.println(display+"\r\n============="); // } // // @Override // public void onSubscriptionResponse(DisplayDirectMessage.SubscriptionResponse response) { // LOGGER.info("Got subscription status response of '{}' with status '{}'", response.getSuccess(), response.getStatus()); // } // // @Override // public void onMessage(DisplayDirectMessage.Container value) { // // } // } // }
import nl.crowndov.displaydirect.virtual_screen.Main; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.stream.IntStream;
package nl.crowndov.displaydirect.virtual_screen.test; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class TestMain { private static final Logger LOGGER = LoggerFactory.getLogger(TestMain.class); private static final int NUMBER = 500 ; public static void main(String[] args) throws InterruptedException { Executor exec = Executors.newFixedThreadPool(NUMBER); IntStream.range(0, NUMBER).forEach(i -> {
// Path: virtual_screen/src/main/java/nl/crowndov/displaydirect/virtual_screen/Main.java // public class Main { // // private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); // // public static void main(String[] args) { // run(new Configuration()); // } // // public static void run(Configuration configuration) { // DisplayDirectClient c = new DisplayDirectClient(configuration); // c.setListener(new Listener()); // c.start(); // // while (!Thread.interrupted()) { // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // c.stop(); // break; // } // } // } // // private static class Listener implements OnDisplayDirectListener { // // @Override // public void onScreenContentsChange(List<PassTime> times) { // String display = times.stream() // .map(PassTime::toString) // .collect(Collectors.joining("\r\n")); // System.out.println(display+"\r\n============="); // } // // @Override // public void onSubscriptionResponse(DisplayDirectMessage.SubscriptionResponse response) { // LOGGER.info("Got subscription status response of '{}' with status '{}'", response.getSuccess(), response.getStatus()); // } // // @Override // public void onMessage(DisplayDirectMessage.Container value) { // // } // } // } // Path: virtual_screen/src/main/java/nl/crowndov/displaydirect/virtual_screen/test/TestMain.java import nl.crowndov.displaydirect.virtual_screen.Main; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.stream.IntStream; package nl.crowndov.displaydirect.virtual_screen.test; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class TestMain { private static final Logger LOGGER = LoggerFactory.getLogger(TestMain.class); private static final int NUMBER = 500 ; public static void main(String[] args) throws InterruptedException { Executor exec = Executors.newFixedThreadPool(NUMBER); IntStream.range(0, NUMBER).forEach(i -> {
exec.execute(() -> Main.run(new TestConfiguration()));
CROW-NDOV/displaydirect
distribution/src/main/java/nl/crowndov/displaydirect/distribution/input/Kv78ProcessTask.java
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/stats/MetricStore.java // public class MetricStore { // // private static List<Metric> metrics = new ArrayList<>(); // private static ConcurrentMap<String, ConcurrentMap<LocalDateTime, Metric>> buckets = new ConcurrentHashMap<>(); // private static MetricStore instance; // // public static synchronized MetricStore getInstance() { // if (instance == null) { // instance = new MetricStore(); // } // return instance; // } // // public void storeMetric(String name, long value) { // Metric m = new Metric(name, value); // metrics.add(m); // } // // public void setBucketValue(String name, TemporalUnit bucket, long value) { // ensureMetricInBucket(name); // LocalDateTime bucketSlot = LocalDateTime.now().truncatedTo(bucket); // buckets.get(name).put(bucketSlot, new Metric(name, value, bucketSlot)); // } // // public void increaseBucketValue(String name, TemporalUnit bucket) { // ensureMetricInBucket(name); // LocalDateTime key = LocalDateTime.now().truncatedTo(bucket); // if (!buckets.get(name).containsKey(key)) { // buckets.get(name).put(key, new Metric(name, 1)); // } else { // Metric previous = buckets.get(name).get(key); // buckets.get(name).put(key, new Metric(name, previous.getValue() + 1, key)); // } // } // // private void ensureMetricInBucket(String name) { // if (!buckets.containsKey(name)) { // buckets.put(name, new ConcurrentSkipListMap<>()); // } // } // // public Map<String, List<Metric>> getMetrics() { // return Stream.concat(buckets.values().stream().flatMap(m -> m.values().stream()), metrics.stream()) // .collect(Collectors.groupingBy(Metric::getName)); // } // // public List<Metric> getMetric(String name) { // if (buckets.containsKey(name)) { // return new ArrayList<>(buckets.get(name).values()); // } // return metrics.parallelStream() // .filter(m -> m.getName().equalsIgnoreCase(name)) // .collect(Collectors.toList()); // } // }
import nl.crowndov.displaydirect.distribution.stats.MetricStore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zeromq.ZMQ; import org.zeromq.ZMQException; import java.time.temporal.ChronoUnit; import java.util.concurrent.atomic.AtomicBoolean;
package nl.crowndov.displaydirect.distribution.input; public class Kv78ProcessTask implements Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(Kv78ProcessTask.class); private final int port; private ZMQ.Context processContext = ZMQ.context(1); private ZMQ.Socket pull = processContext.socket(ZMQ.PULL);
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/stats/MetricStore.java // public class MetricStore { // // private static List<Metric> metrics = new ArrayList<>(); // private static ConcurrentMap<String, ConcurrentMap<LocalDateTime, Metric>> buckets = new ConcurrentHashMap<>(); // private static MetricStore instance; // // public static synchronized MetricStore getInstance() { // if (instance == null) { // instance = new MetricStore(); // } // return instance; // } // // public void storeMetric(String name, long value) { // Metric m = new Metric(name, value); // metrics.add(m); // } // // public void setBucketValue(String name, TemporalUnit bucket, long value) { // ensureMetricInBucket(name); // LocalDateTime bucketSlot = LocalDateTime.now().truncatedTo(bucket); // buckets.get(name).put(bucketSlot, new Metric(name, value, bucketSlot)); // } // // public void increaseBucketValue(String name, TemporalUnit bucket) { // ensureMetricInBucket(name); // LocalDateTime key = LocalDateTime.now().truncatedTo(bucket); // if (!buckets.get(name).containsKey(key)) { // buckets.get(name).put(key, new Metric(name, 1)); // } else { // Metric previous = buckets.get(name).get(key); // buckets.get(name).put(key, new Metric(name, previous.getValue() + 1, key)); // } // } // // private void ensureMetricInBucket(String name) { // if (!buckets.containsKey(name)) { // buckets.put(name, new ConcurrentSkipListMap<>()); // } // } // // public Map<String, List<Metric>> getMetrics() { // return Stream.concat(buckets.values().stream().flatMap(m -> m.values().stream()), metrics.stream()) // .collect(Collectors.groupingBy(Metric::getName)); // } // // public List<Metric> getMetric(String name) { // if (buckets.containsKey(name)) { // return new ArrayList<>(buckets.get(name).values()); // } // return metrics.parallelStream() // .filter(m -> m.getName().equalsIgnoreCase(name)) // .collect(Collectors.toList()); // } // } // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/input/Kv78ProcessTask.java import nl.crowndov.displaydirect.distribution.stats.MetricStore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zeromq.ZMQ; import org.zeromq.ZMQException; import java.time.temporal.ChronoUnit; import java.util.concurrent.atomic.AtomicBoolean; package nl.crowndov.displaydirect.distribution.input; public class Kv78ProcessTask implements Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(Kv78ProcessTask.class); private final int port; private ZMQ.Context processContext = ZMQ.context(1); private ZMQ.Socket pull = processContext.socket(ZMQ.PULL);
private MetricStore metrics = MetricStore.getInstance();
CROW-NDOV/displaydirect
distribution/src/main/java/nl/crowndov/displaydirect/distribution/util/EmailUtil.java
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/Configuration.java // public class Configuration { // // private static final Logger LOGGER = LoggerFactory.getLogger(Configuration.class); // // private static AbstractConfiguration config = ConfigurationManager.getConfigInstance(); // // public static List<String> getKvEndpoints() { // return Arrays.asList(config.getStringArray("distribution.kv78turbo.endpoints")); // } // // public static String[] getKvPublishers() { // return config.getStringArray("distribution.kv78turbo.publishers"); // } // // public static ZoneId getZoneId() { // return ZoneId.of(config.getString("distribution.timezone.default")); // } // // public static String getOutputTransport() { // return config.getString("distribution.transport", "mqtt"); // } // // public static String getMqttBrokerHost() { // return config.getString("distribution.mqtt.host", "localhost:1883"); // } // // public static int getZmqInternalPort() { // return 9800; // } // // public static String getMqttClientId() { // return config.getString("distribution.mqtt.client_id", "distribution"); // } // // public static int getAuthorizationTokenMaxAge() { // return config.getInt("distribution.authorization.max_age_hours"); // } // // public static List<String> getAuthorizationWhitelist() { // return Arrays.asList(config.getStringArray("distribution.authorization.whitelist_prefix")); // } // // public static String getBaseUrl() { // return config.getString("distribution.install.base_url", "http://localhost:8080"); // } // // public static String getSmtpUsername() { // return config.getString("distribution.smtp.username", null); // } // // public static String getSmtpPassword() { // return config.getString("distribution.smtp.password", null); // } // // public static String getSmtpFrom() { // return config.getString("distribution.smtp.from"); // } // // public static String getSmtpHostname() { // return config.getString("distribution.smtp.hostname"); // } // // public static String getSmtpReplyTo() { // return config.getString("distribution.smtp.reply_to"); // } // // public static boolean getSmtpSsl() { return config.getBoolean("distribution.smtp.ssl", false); } // // public static int getSmtpPort() { // return config.getInt("distribution.smtp.port", 25); // } // // public static int getSmtpConnectTimeout() { // return config.getInt("distribution.smtp.connect_timeout", 10*1000); // } // // public static String getFileBasePath() { // return config.getString("distribution.backup.path", System.getProperty("java.io.tmpdir")); // } // // public static String getKv7PlanningPath() { // return config.getString("distribution.kv78turbo.path.planning"); // } // // public static String getKv7CalendarPath() { // return config.getString("distribution.kv78turbo.path.calendar"); // } // // public static String getChbPath() { // return config.getString("distribution.chb.path"); // } // // // public static String getPlanningLoaderTime() { // return config.getString("distribution.planning.loadTime", "03:30"); // } // // public static String getPlanningCleanupTime() { // return config.getString("distribution.planning.cleanupTime", "04:00"); // } // // }
import nl.crowndov.displaydirect.distribution.Configuration; import org.apache.commons.mail.DefaultAuthenticator; import org.apache.commons.mail.Email; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.HtmlEmail; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map;
package nl.crowndov.displaydirect.distribution.util; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class EmailUtil { private static final Logger LOGGER = LoggerFactory.getLogger(EmailUtil.class); public static String getHtmlBody(String template, Map<String, Object> variables) { String html = TemplateUtil.renderTemplate("templates/"+template+".html.mustache", variables); if (html == null || html.isEmpty()) { // TODO: Null check or optional if template doesn't exist html = getTextBody(template, variables).replace("\n", "<br />"); } return html; } public static String getTextBody(String template, Map<String, Object> body) { return TemplateUtil.renderTemplate("templates/"+template+".txt.mustache", body); } public static void sendHtmlEmail(String to, String subject, String template, Map<String, Object> variables) { try { final HtmlEmail email = new HtmlEmail(); setupEmail(email, to, subject, template, variables); email.setHtmlMsg(EmailUtil.getHtmlBody(template, variables)); email.setTextMsg(EmailUtil.getTextBody(template, variables));
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/Configuration.java // public class Configuration { // // private static final Logger LOGGER = LoggerFactory.getLogger(Configuration.class); // // private static AbstractConfiguration config = ConfigurationManager.getConfigInstance(); // // public static List<String> getKvEndpoints() { // return Arrays.asList(config.getStringArray("distribution.kv78turbo.endpoints")); // } // // public static String[] getKvPublishers() { // return config.getStringArray("distribution.kv78turbo.publishers"); // } // // public static ZoneId getZoneId() { // return ZoneId.of(config.getString("distribution.timezone.default")); // } // // public static String getOutputTransport() { // return config.getString("distribution.transport", "mqtt"); // } // // public static String getMqttBrokerHost() { // return config.getString("distribution.mqtt.host", "localhost:1883"); // } // // public static int getZmqInternalPort() { // return 9800; // } // // public static String getMqttClientId() { // return config.getString("distribution.mqtt.client_id", "distribution"); // } // // public static int getAuthorizationTokenMaxAge() { // return config.getInt("distribution.authorization.max_age_hours"); // } // // public static List<String> getAuthorizationWhitelist() { // return Arrays.asList(config.getStringArray("distribution.authorization.whitelist_prefix")); // } // // public static String getBaseUrl() { // return config.getString("distribution.install.base_url", "http://localhost:8080"); // } // // public static String getSmtpUsername() { // return config.getString("distribution.smtp.username", null); // } // // public static String getSmtpPassword() { // return config.getString("distribution.smtp.password", null); // } // // public static String getSmtpFrom() { // return config.getString("distribution.smtp.from"); // } // // public static String getSmtpHostname() { // return config.getString("distribution.smtp.hostname"); // } // // public static String getSmtpReplyTo() { // return config.getString("distribution.smtp.reply_to"); // } // // public static boolean getSmtpSsl() { return config.getBoolean("distribution.smtp.ssl", false); } // // public static int getSmtpPort() { // return config.getInt("distribution.smtp.port", 25); // } // // public static int getSmtpConnectTimeout() { // return config.getInt("distribution.smtp.connect_timeout", 10*1000); // } // // public static String getFileBasePath() { // return config.getString("distribution.backup.path", System.getProperty("java.io.tmpdir")); // } // // public static String getKv7PlanningPath() { // return config.getString("distribution.kv78turbo.path.planning"); // } // // public static String getKv7CalendarPath() { // return config.getString("distribution.kv78turbo.path.calendar"); // } // // public static String getChbPath() { // return config.getString("distribution.chb.path"); // } // // // public static String getPlanningLoaderTime() { // return config.getString("distribution.planning.loadTime", "03:30"); // } // // public static String getPlanningCleanupTime() { // return config.getString("distribution.planning.cleanupTime", "04:00"); // } // // } // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/util/EmailUtil.java import nl.crowndov.displaydirect.distribution.Configuration; import org.apache.commons.mail.DefaultAuthenticator; import org.apache.commons.mail.Email; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.HtmlEmail; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; package nl.crowndov.displaydirect.distribution.util; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class EmailUtil { private static final Logger LOGGER = LoggerFactory.getLogger(EmailUtil.class); public static String getHtmlBody(String template, Map<String, Object> variables) { String html = TemplateUtil.renderTemplate("templates/"+template+".html.mustache", variables); if (html == null || html.isEmpty()) { // TODO: Null check or optional if template doesn't exist html = getTextBody(template, variables).replace("\n", "<br />"); } return html; } public static String getTextBody(String template, Map<String, Object> body) { return TemplateUtil.renderTemplate("templates/"+template+".txt.mustache", body); } public static void sendHtmlEmail(String to, String subject, String template, Map<String, Object> variables) { try { final HtmlEmail email = new HtmlEmail(); setupEmail(email, to, subject, template, variables); email.setHtmlMsg(EmailUtil.getHtmlBody(template, variables)); email.setTextMsg(EmailUtil.getTextBody(template, variables));
email.setSocketConnectionTimeout(Configuration.getSmtpConnectTimeout());
CROW-NDOV/displaydirect
distribution/src/main/java/nl/crowndov/displaydirect/distribution/resources/DestinationResource.java
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/input/DestinationProvider.java // public class DestinationProvider extends AbstractService { // // private static final Store.DestinationStore destinations = new Store.DestinationStore(); // // public static void start() { // readFile("destinations", Store.DestinationStore.class).ifPresent(destinations::putAll); // } // // public static void stop() { // backup(); // } // // public static void backup() { // writeFile("destinations", destinations); // } // // public static void updateDestinations(List<Destination> dests) { // dests.forEach(d -> destinations.putIfAbsent(d.getCode(), d)); // } // // public static Destination get(String code) { // return destinations.get(code); // } // // public static Destination get(String dataowner, String destinationCode) { // return get(dataowner+":"+destinationCode); // } // // public static Map<String, Destination> getAll() { // return destinations; // } // // // // }
import nl.crowndov.displaydirect.distribution.input.DestinationProvider; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response;
package nl.crowndov.displaydirect.distribution.resources; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ @Path("/v1/destination") public class DestinationResource { @GET public Response get() {
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/input/DestinationProvider.java // public class DestinationProvider extends AbstractService { // // private static final Store.DestinationStore destinations = new Store.DestinationStore(); // // public static void start() { // readFile("destinations", Store.DestinationStore.class).ifPresent(destinations::putAll); // } // // public static void stop() { // backup(); // } // // public static void backup() { // writeFile("destinations", destinations); // } // // public static void updateDestinations(List<Destination> dests) { // dests.forEach(d -> destinations.putIfAbsent(d.getCode(), d)); // } // // public static Destination get(String code) { // return destinations.get(code); // } // // public static Destination get(String dataowner, String destinationCode) { // return get(dataowner+":"+destinationCode); // } // // public static Map<String, Destination> getAll() { // return destinations; // } // // // // } // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/resources/DestinationResource.java import nl.crowndov.displaydirect.distribution.input.DestinationProvider; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response; package nl.crowndov.displaydirect.distribution.resources; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ @Path("/v1/destination") public class DestinationResource { @GET public Response get() {
return Response.ok(DestinationProvider.getAll()).build();
CROW-NDOV/displaydirect
distribution/src/main/java/nl/crowndov/displaydirect/distribution/util/DateTimeUtil.java
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/Configuration.java // public class Configuration { // // private static final Logger LOGGER = LoggerFactory.getLogger(Configuration.class); // // private static AbstractConfiguration config = ConfigurationManager.getConfigInstance(); // // public static List<String> getKvEndpoints() { // return Arrays.asList(config.getStringArray("distribution.kv78turbo.endpoints")); // } // // public static String[] getKvPublishers() { // return config.getStringArray("distribution.kv78turbo.publishers"); // } // // public static ZoneId getZoneId() { // return ZoneId.of(config.getString("distribution.timezone.default")); // } // // public static String getOutputTransport() { // return config.getString("distribution.transport", "mqtt"); // } // // public static String getMqttBrokerHost() { // return config.getString("distribution.mqtt.host", "localhost:1883"); // } // // public static int getZmqInternalPort() { // return 9800; // } // // public static String getMqttClientId() { // return config.getString("distribution.mqtt.client_id", "distribution"); // } // // public static int getAuthorizationTokenMaxAge() { // return config.getInt("distribution.authorization.max_age_hours"); // } // // public static List<String> getAuthorizationWhitelist() { // return Arrays.asList(config.getStringArray("distribution.authorization.whitelist_prefix")); // } // // public static String getBaseUrl() { // return config.getString("distribution.install.base_url", "http://localhost:8080"); // } // // public static String getSmtpUsername() { // return config.getString("distribution.smtp.username", null); // } // // public static String getSmtpPassword() { // return config.getString("distribution.smtp.password", null); // } // // public static String getSmtpFrom() { // return config.getString("distribution.smtp.from"); // } // // public static String getSmtpHostname() { // return config.getString("distribution.smtp.hostname"); // } // // public static String getSmtpReplyTo() { // return config.getString("distribution.smtp.reply_to"); // } // // public static boolean getSmtpSsl() { return config.getBoolean("distribution.smtp.ssl", false); } // // public static int getSmtpPort() { // return config.getInt("distribution.smtp.port", 25); // } // // public static int getSmtpConnectTimeout() { // return config.getInt("distribution.smtp.connect_timeout", 10*1000); // } // // public static String getFileBasePath() { // return config.getString("distribution.backup.path", System.getProperty("java.io.tmpdir")); // } // // public static String getKv7PlanningPath() { // return config.getString("distribution.kv78turbo.path.planning"); // } // // public static String getKv7CalendarPath() { // return config.getString("distribution.kv78turbo.path.calendar"); // } // // public static String getChbPath() { // return config.getString("distribution.chb.path"); // } // // // public static String getPlanningLoaderTime() { // return config.getString("distribution.planning.loadTime", "03:30"); // } // // public static String getPlanningCleanupTime() { // return config.getString("distribution.planning.cleanupTime", "04:00"); // } // // }
import nl.crowndov.displaydirect.distribution.Configuration; import java.time.LocalDate; import java.time.LocalTime; import java.time.ZonedDateTime; import java.time.temporal.ChronoUnit;
package nl.crowndov.displaydirect.distribution.util; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class DateTimeUtil { public static ZonedDateTime getTime(LocalDate date, String time) { String[] split = time.split(":"); int hour = Integer.valueOf(split[0]); boolean addDay = false; if (hour > 23) { hour = hour - 24; addDay = true; }
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/Configuration.java // public class Configuration { // // private static final Logger LOGGER = LoggerFactory.getLogger(Configuration.class); // // private static AbstractConfiguration config = ConfigurationManager.getConfigInstance(); // // public static List<String> getKvEndpoints() { // return Arrays.asList(config.getStringArray("distribution.kv78turbo.endpoints")); // } // // public static String[] getKvPublishers() { // return config.getStringArray("distribution.kv78turbo.publishers"); // } // // public static ZoneId getZoneId() { // return ZoneId.of(config.getString("distribution.timezone.default")); // } // // public static String getOutputTransport() { // return config.getString("distribution.transport", "mqtt"); // } // // public static String getMqttBrokerHost() { // return config.getString("distribution.mqtt.host", "localhost:1883"); // } // // public static int getZmqInternalPort() { // return 9800; // } // // public static String getMqttClientId() { // return config.getString("distribution.mqtt.client_id", "distribution"); // } // // public static int getAuthorizationTokenMaxAge() { // return config.getInt("distribution.authorization.max_age_hours"); // } // // public static List<String> getAuthorizationWhitelist() { // return Arrays.asList(config.getStringArray("distribution.authorization.whitelist_prefix")); // } // // public static String getBaseUrl() { // return config.getString("distribution.install.base_url", "http://localhost:8080"); // } // // public static String getSmtpUsername() { // return config.getString("distribution.smtp.username", null); // } // // public static String getSmtpPassword() { // return config.getString("distribution.smtp.password", null); // } // // public static String getSmtpFrom() { // return config.getString("distribution.smtp.from"); // } // // public static String getSmtpHostname() { // return config.getString("distribution.smtp.hostname"); // } // // public static String getSmtpReplyTo() { // return config.getString("distribution.smtp.reply_to"); // } // // public static boolean getSmtpSsl() { return config.getBoolean("distribution.smtp.ssl", false); } // // public static int getSmtpPort() { // return config.getInt("distribution.smtp.port", 25); // } // // public static int getSmtpConnectTimeout() { // return config.getInt("distribution.smtp.connect_timeout", 10*1000); // } // // public static String getFileBasePath() { // return config.getString("distribution.backup.path", System.getProperty("java.io.tmpdir")); // } // // public static String getKv7PlanningPath() { // return config.getString("distribution.kv78turbo.path.planning"); // } // // public static String getKv7CalendarPath() { // return config.getString("distribution.kv78turbo.path.calendar"); // } // // public static String getChbPath() { // return config.getString("distribution.chb.path"); // } // // // public static String getPlanningLoaderTime() { // return config.getString("distribution.planning.loadTime", "03:30"); // } // // public static String getPlanningCleanupTime() { // return config.getString("distribution.planning.cleanupTime", "04:00"); // } // // } // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/util/DateTimeUtil.java import nl.crowndov.displaydirect.distribution.Configuration; import java.time.LocalDate; import java.time.LocalTime; import java.time.ZonedDateTime; import java.time.temporal.ChronoUnit; package nl.crowndov.displaydirect.distribution.util; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class DateTimeUtil { public static ZonedDateTime getTime(LocalDate date, String time) { String[] split = time.split(":"); int hour = Integer.valueOf(split[0]); boolean addDay = false; if (hour > 23) { hour = hour - 24; addDay = true; }
ZonedDateTime dateTime = ZonedDateTime.of(date, LocalTime.of(hour, Integer.valueOf(split[1]), Integer.valueOf(split[2])), Configuration.getZoneId());
CROW-NDOV/displaydirect
distribution/src/main/java/nl/crowndov/displaydirect/distribution/resources/LineResource.java
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/input/LineProvider.java // public class LineProvider extends AbstractService { // // private static final Store.LineStore lines = new Store.LineStore(); // // public static void start() { // readFile("lines", Store.LineStore.class).ifPresent(lines::putAll); // } // // public static void stop() { // backup(); // } // // public static void backup() { // writeFile("lines", lines); // } // // public static void updateLines(List<Line> input) { // input.forEach(d -> lines.putIfAbsent(d.getCode(), d)); // } // // public static Line get(String code) { // return lines.get(code); // } // // public static Line get(String dataowner, String linePlanningNumber) { // return get(dataowner+":"+linePlanningNumber); // } // // public static Map<String, Line> getAll() { // return lines; // } // }
import nl.crowndov.displaydirect.distribution.input.LineProvider; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response;
package nl.crowndov.displaydirect.distribution.resources; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ @Path("/v1/line") public class LineResource { @GET public Response get() {
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/input/LineProvider.java // public class LineProvider extends AbstractService { // // private static final Store.LineStore lines = new Store.LineStore(); // // public static void start() { // readFile("lines", Store.LineStore.class).ifPresent(lines::putAll); // } // // public static void stop() { // backup(); // } // // public static void backup() { // writeFile("lines", lines); // } // // public static void updateLines(List<Line> input) { // input.forEach(d -> lines.putIfAbsent(d.getCode(), d)); // } // // public static Line get(String code) { // return lines.get(code); // } // // public static Line get(String dataowner, String linePlanningNumber) { // return get(dataowner+":"+linePlanningNumber); // } // // public static Map<String, Line> getAll() { // return lines; // } // } // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/resources/LineResource.java import nl.crowndov.displaydirect.distribution.input.LineProvider; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response; package nl.crowndov.displaydirect.distribution.resources; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ @Path("/v1/line") public class LineResource { @GET public Response get() {
return Response.ok(LineProvider.getAll()).build();
CROW-NDOV/displaydirect
distribution/src/main/java/nl/crowndov/displaydirect/distribution/util/JsonFile.java
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/Configuration.java // public class Configuration { // // private static final Logger LOGGER = LoggerFactory.getLogger(Configuration.class); // // private static AbstractConfiguration config = ConfigurationManager.getConfigInstance(); // // public static List<String> getKvEndpoints() { // return Arrays.asList(config.getStringArray("distribution.kv78turbo.endpoints")); // } // // public static String[] getKvPublishers() { // return config.getStringArray("distribution.kv78turbo.publishers"); // } // // public static ZoneId getZoneId() { // return ZoneId.of(config.getString("distribution.timezone.default")); // } // // public static String getOutputTransport() { // return config.getString("distribution.transport", "mqtt"); // } // // public static String getMqttBrokerHost() { // return config.getString("distribution.mqtt.host", "localhost:1883"); // } // // public static int getZmqInternalPort() { // return 9800; // } // // public static String getMqttClientId() { // return config.getString("distribution.mqtt.client_id", "distribution"); // } // // public static int getAuthorizationTokenMaxAge() { // return config.getInt("distribution.authorization.max_age_hours"); // } // // public static List<String> getAuthorizationWhitelist() { // return Arrays.asList(config.getStringArray("distribution.authorization.whitelist_prefix")); // } // // public static String getBaseUrl() { // return config.getString("distribution.install.base_url", "http://localhost:8080"); // } // // public static String getSmtpUsername() { // return config.getString("distribution.smtp.username", null); // } // // public static String getSmtpPassword() { // return config.getString("distribution.smtp.password", null); // } // // public static String getSmtpFrom() { // return config.getString("distribution.smtp.from"); // } // // public static String getSmtpHostname() { // return config.getString("distribution.smtp.hostname"); // } // // public static String getSmtpReplyTo() { // return config.getString("distribution.smtp.reply_to"); // } // // public static boolean getSmtpSsl() { return config.getBoolean("distribution.smtp.ssl", false); } // // public static int getSmtpPort() { // return config.getInt("distribution.smtp.port", 25); // } // // public static int getSmtpConnectTimeout() { // return config.getInt("distribution.smtp.connect_timeout", 10*1000); // } // // public static String getFileBasePath() { // return config.getString("distribution.backup.path", System.getProperty("java.io.tmpdir")); // } // // public static String getKv7PlanningPath() { // return config.getString("distribution.kv78turbo.path.planning"); // } // // public static String getKv7CalendarPath() { // return config.getString("distribution.kv78turbo.path.calendar"); // } // // public static String getChbPath() { // return config.getString("distribution.chb.path"); // } // // // public static String getPlanningLoaderTime() { // return config.getString("distribution.planning.loadTime", "03:30"); // } // // public static String getPlanningCleanupTime() { // return config.getString("distribution.planning.cleanupTime", "04:00"); // } // // }
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import nl.crowndov.displaydirect.distribution.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.time.ZonedDateTime; import java.util.Optional; import java.util.stream.Collectors;
package nl.crowndov.displaydirect.distribution.util; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class JsonFile { private static final Logger LOGGER = LoggerFactory.getLogger(JsonFile.class); private static Gson GSON = new GsonBuilder() .registerTypeAdapter(ZonedDateTime.class, new TypeAdapter<ZonedDateTime>() { @Override public void write(JsonWriter out, ZonedDateTime value) throws IOException { out.nullValue(); } @Override public ZonedDateTime read(JsonReader in) throws IOException { return null; } }) .create(); public static Gson gson() { return GSON; } public static void write(String key, String json) { Path output = getPath(key); try { Files.write(output, json.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); } catch (IOException e) { LOGGER.error("Failed to write data to file {}", output.toString(), e); } } private static Path getPath(String key) {
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/Configuration.java // public class Configuration { // // private static final Logger LOGGER = LoggerFactory.getLogger(Configuration.class); // // private static AbstractConfiguration config = ConfigurationManager.getConfigInstance(); // // public static List<String> getKvEndpoints() { // return Arrays.asList(config.getStringArray("distribution.kv78turbo.endpoints")); // } // // public static String[] getKvPublishers() { // return config.getStringArray("distribution.kv78turbo.publishers"); // } // // public static ZoneId getZoneId() { // return ZoneId.of(config.getString("distribution.timezone.default")); // } // // public static String getOutputTransport() { // return config.getString("distribution.transport", "mqtt"); // } // // public static String getMqttBrokerHost() { // return config.getString("distribution.mqtt.host", "localhost:1883"); // } // // public static int getZmqInternalPort() { // return 9800; // } // // public static String getMqttClientId() { // return config.getString("distribution.mqtt.client_id", "distribution"); // } // // public static int getAuthorizationTokenMaxAge() { // return config.getInt("distribution.authorization.max_age_hours"); // } // // public static List<String> getAuthorizationWhitelist() { // return Arrays.asList(config.getStringArray("distribution.authorization.whitelist_prefix")); // } // // public static String getBaseUrl() { // return config.getString("distribution.install.base_url", "http://localhost:8080"); // } // // public static String getSmtpUsername() { // return config.getString("distribution.smtp.username", null); // } // // public static String getSmtpPassword() { // return config.getString("distribution.smtp.password", null); // } // // public static String getSmtpFrom() { // return config.getString("distribution.smtp.from"); // } // // public static String getSmtpHostname() { // return config.getString("distribution.smtp.hostname"); // } // // public static String getSmtpReplyTo() { // return config.getString("distribution.smtp.reply_to"); // } // // public static boolean getSmtpSsl() { return config.getBoolean("distribution.smtp.ssl", false); } // // public static int getSmtpPort() { // return config.getInt("distribution.smtp.port", 25); // } // // public static int getSmtpConnectTimeout() { // return config.getInt("distribution.smtp.connect_timeout", 10*1000); // } // // public static String getFileBasePath() { // return config.getString("distribution.backup.path", System.getProperty("java.io.tmpdir")); // } // // public static String getKv7PlanningPath() { // return config.getString("distribution.kv78turbo.path.planning"); // } // // public static String getKv7CalendarPath() { // return config.getString("distribution.kv78turbo.path.calendar"); // } // // public static String getChbPath() { // return config.getString("distribution.chb.path"); // } // // // public static String getPlanningLoaderTime() { // return config.getString("distribution.planning.loadTime", "03:30"); // } // // public static String getPlanningCleanupTime() { // return config.getString("distribution.planning.cleanupTime", "04:00"); // } // // } // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/util/JsonFile.java import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import nl.crowndov.displaydirect.distribution.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.time.ZonedDateTime; import java.util.Optional; import java.util.stream.Collectors; package nl.crowndov.displaydirect.distribution.util; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class JsonFile { private static final Logger LOGGER = LoggerFactory.getLogger(JsonFile.class); private static Gson GSON = new GsonBuilder() .registerTypeAdapter(ZonedDateTime.class, new TypeAdapter<ZonedDateTime>() { @Override public void write(JsonWriter out, ZonedDateTime value) throws IOException { out.nullValue(); } @Override public ZonedDateTime read(JsonReader in) throws IOException { return null; } }) .create(); public static Gson gson() { return GSON; } public static void write(String key, String json) { Path output = getPath(key); try { Files.write(output, json.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); } catch (IOException e) { LOGGER.error("Failed to write data to file {}", output.toString(), e); } } private static Path getPath(String key) {
return Paths.get(Configuration.getFileBasePath(), key+".json");
CROW-NDOV/displaydirect
common_client/src/main/java/nl/crowndov/displaydirect/commonclient/mqtt/MqttClient.java
// Path: common/src/main/java/nl/crowndov/displaydirect/common/transport/mqtt/TopicFactory.java // public class TopicFactory { // // /** // * Generate a topic for subscribe messages // * @param stopSytemId An id for the originating stopsystem. If null, will be filled with a wildcard for that level // * @return A valid topic name for subscribe messages // */ // public static String subscribe(String stopSytemId) { // return stopSystemOrigin(stopSytemId, "subscribe"); // } // // /** // * Generate a topic for unsubscribe messages // * @param stopSytemId An id for the originating stopsystem. If null, will be filled with a wildcard for that level // * @return A valid topic name for unsubscribe messages // */ // public static String unsubscribe(String stopSytemId) { // return stopSystemOrigin(stopSytemId, "unsubscribe"); // } // // /** // * Generate a topic for travel information messages // * @param stopSytemId An id for the destination stopsystem. If null, will be filled with a wildcard for that level // * @return A valid topic name for travel information messages // */ // public static String travelInformation(String stopSytemId) { // return stopSystemDestination(stopSytemId, "travel_information"); // } // // /** // * Generate a topic for subscription response messages // * @param stopSytemId An id for the destination stopsystem. If null, will be filled with a wildcard for that level // * @return A valid topic name for subscription response messages // */ // public static String subscriptionResponse(String stopSytemId) { // return stopSystemDestination(stopSytemId, "subscription_response"); // } // // /** // * Generate a topic for monitoring messages about stops // * @param stopSytemId An id for the object stopsystem. If null, will be filled with a wildcard for that level // * @return A valid topic name for monitoring messages // */ // public static String monitoring(String stopSytemId) { // return stopSystemDestination(stopSytemId, "monitoring"); // } // // /** // * Generate a topic for monitoring messages about the distribution function // * @return A valid topic name for monitoring messages // */ // public static String monitoring() { // return "distribution/monitoring"; // } // // private static String stopSystemDestination(String stopSytemId, String category) { // return "stopsystem/"+ idOrWildcard(stopSytemId) + "/" + category; // } // // private static String stopSystemOrigin(String stopSytemId, String command) { // return command + "/stopsystem/"+ idOrWildcard(stopSytemId); // } // // private static String idOrWildcard(String id) { // return id != null ? id : "+"; // } // // } // // Path: common_client/src/main/java/nl/crowndov/displaydirect/commonclient/domain/SubscriptionBuilder.java // public class SubscriptionBuilder { // // public static DisplayDirectMessage.Subscribe subscribe(DisplayParameters display, SystemParameters system) { // DisplayDirectMessage.Subscribe.Builder build = DisplayDirectMessage.Subscribe.newBuilder() // .addAllStopCode(system.getStopCodes()) // .setDisplayProperties(DisplayDirectMessage.Subscribe.DisplayProperties.newBuilder().setTextCharacters(0)) // .setFieldFilter(DisplayDirectMessage.Subscribe.FieldFilter.newBuilder() // .setTripStopStatus(DisplayDirectMessage.Subscribe.FieldFilter.Delivery.ALWAYS) // .setTargetDepartureTime(DisplayDirectMessage.Subscribe.FieldFilter.Delivery.ALWAYS) // .setDestination(DisplayDirectMessage.Subscribe.FieldFilter.Delivery.ALWAYS) // .setLinePublicNumber(DisplayDirectMessage.Subscribe.FieldFilter.Delivery.ALWAYS) // .setTransportType(DisplayDirectMessage.Subscribe.FieldFilter.Delivery.ALWAYS)) // .setEmail(system.getEmail()) // .setDescription(system.getDescription()); // // return build.build(); // } // // public static DisplayDirectMessage.Unsubscribe unsubscribe() { // return DisplayDirectMessage.Unsubscribe.newBuilder().setIsPermanent(false).build(); // } // }
import nl.crowndov.displaydirect.common.transport.mqtt.TopicFactory; import nl.crowndov.displaydirect.commonclient.domain.SubscriptionBuilder; import org.fusesource.hawtbuf.Buffer; import org.fusesource.hawtbuf.UTF8Buffer; import org.fusesource.mqtt.client.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URISyntaxException;
package nl.crowndov.displaydirect.commonclient.mqtt; /** * Copyright 2017 CROW-NDOV * <p> * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class MqttClient { private static final Logger LOGGER = LoggerFactory.getLogger(MqttClient.class); private MQTT mqtt; private final CallbackConnection connection;
// Path: common/src/main/java/nl/crowndov/displaydirect/common/transport/mqtt/TopicFactory.java // public class TopicFactory { // // /** // * Generate a topic for subscribe messages // * @param stopSytemId An id for the originating stopsystem. If null, will be filled with a wildcard for that level // * @return A valid topic name for subscribe messages // */ // public static String subscribe(String stopSytemId) { // return stopSystemOrigin(stopSytemId, "subscribe"); // } // // /** // * Generate a topic for unsubscribe messages // * @param stopSytemId An id for the originating stopsystem. If null, will be filled with a wildcard for that level // * @return A valid topic name for unsubscribe messages // */ // public static String unsubscribe(String stopSytemId) { // return stopSystemOrigin(stopSytemId, "unsubscribe"); // } // // /** // * Generate a topic for travel information messages // * @param stopSytemId An id for the destination stopsystem. If null, will be filled with a wildcard for that level // * @return A valid topic name for travel information messages // */ // public static String travelInformation(String stopSytemId) { // return stopSystemDestination(stopSytemId, "travel_information"); // } // // /** // * Generate a topic for subscription response messages // * @param stopSytemId An id for the destination stopsystem. If null, will be filled with a wildcard for that level // * @return A valid topic name for subscription response messages // */ // public static String subscriptionResponse(String stopSytemId) { // return stopSystemDestination(stopSytemId, "subscription_response"); // } // // /** // * Generate a topic for monitoring messages about stops // * @param stopSytemId An id for the object stopsystem. If null, will be filled with a wildcard for that level // * @return A valid topic name for monitoring messages // */ // public static String monitoring(String stopSytemId) { // return stopSystemDestination(stopSytemId, "monitoring"); // } // // /** // * Generate a topic for monitoring messages about the distribution function // * @return A valid topic name for monitoring messages // */ // public static String monitoring() { // return "distribution/monitoring"; // } // // private static String stopSystemDestination(String stopSytemId, String category) { // return "stopsystem/"+ idOrWildcard(stopSytemId) + "/" + category; // } // // private static String stopSystemOrigin(String stopSytemId, String command) { // return command + "/stopsystem/"+ idOrWildcard(stopSytemId); // } // // private static String idOrWildcard(String id) { // return id != null ? id : "+"; // } // // } // // Path: common_client/src/main/java/nl/crowndov/displaydirect/commonclient/domain/SubscriptionBuilder.java // public class SubscriptionBuilder { // // public static DisplayDirectMessage.Subscribe subscribe(DisplayParameters display, SystemParameters system) { // DisplayDirectMessage.Subscribe.Builder build = DisplayDirectMessage.Subscribe.newBuilder() // .addAllStopCode(system.getStopCodes()) // .setDisplayProperties(DisplayDirectMessage.Subscribe.DisplayProperties.newBuilder().setTextCharacters(0)) // .setFieldFilter(DisplayDirectMessage.Subscribe.FieldFilter.newBuilder() // .setTripStopStatus(DisplayDirectMessage.Subscribe.FieldFilter.Delivery.ALWAYS) // .setTargetDepartureTime(DisplayDirectMessage.Subscribe.FieldFilter.Delivery.ALWAYS) // .setDestination(DisplayDirectMessage.Subscribe.FieldFilter.Delivery.ALWAYS) // .setLinePublicNumber(DisplayDirectMessage.Subscribe.FieldFilter.Delivery.ALWAYS) // .setTransportType(DisplayDirectMessage.Subscribe.FieldFilter.Delivery.ALWAYS)) // .setEmail(system.getEmail()) // .setDescription(system.getDescription()); // // return build.build(); // } // // public static DisplayDirectMessage.Unsubscribe unsubscribe() { // return DisplayDirectMessage.Unsubscribe.newBuilder().setIsPermanent(false).build(); // } // } // Path: common_client/src/main/java/nl/crowndov/displaydirect/commonclient/mqtt/MqttClient.java import nl.crowndov.displaydirect.common.transport.mqtt.TopicFactory; import nl.crowndov.displaydirect.commonclient.domain.SubscriptionBuilder; import org.fusesource.hawtbuf.Buffer; import org.fusesource.hawtbuf.UTF8Buffer; import org.fusesource.mqtt.client.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URISyntaxException; package nl.crowndov.displaydirect.commonclient.mqtt; /** * Copyright 2017 CROW-NDOV * <p> * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class MqttClient { private static final Logger LOGGER = LoggerFactory.getLogger(MqttClient.class); private MQTT mqtt; private final CallbackConnection connection;
private final byte[] disconnect = SubscriptionBuilder.unsubscribe().toByteArray();
CROW-NDOV/displaydirect
common_client/src/main/java/nl/crowndov/displaydirect/commonclient/mqtt/MqttClient.java
// Path: common/src/main/java/nl/crowndov/displaydirect/common/transport/mqtt/TopicFactory.java // public class TopicFactory { // // /** // * Generate a topic for subscribe messages // * @param stopSytemId An id for the originating stopsystem. If null, will be filled with a wildcard for that level // * @return A valid topic name for subscribe messages // */ // public static String subscribe(String stopSytemId) { // return stopSystemOrigin(stopSytemId, "subscribe"); // } // // /** // * Generate a topic for unsubscribe messages // * @param stopSytemId An id for the originating stopsystem. If null, will be filled with a wildcard for that level // * @return A valid topic name for unsubscribe messages // */ // public static String unsubscribe(String stopSytemId) { // return stopSystemOrigin(stopSytemId, "unsubscribe"); // } // // /** // * Generate a topic for travel information messages // * @param stopSytemId An id for the destination stopsystem. If null, will be filled with a wildcard for that level // * @return A valid topic name for travel information messages // */ // public static String travelInformation(String stopSytemId) { // return stopSystemDestination(stopSytemId, "travel_information"); // } // // /** // * Generate a topic for subscription response messages // * @param stopSytemId An id for the destination stopsystem. If null, will be filled with a wildcard for that level // * @return A valid topic name for subscription response messages // */ // public static String subscriptionResponse(String stopSytemId) { // return stopSystemDestination(stopSytemId, "subscription_response"); // } // // /** // * Generate a topic for monitoring messages about stops // * @param stopSytemId An id for the object stopsystem. If null, will be filled with a wildcard for that level // * @return A valid topic name for monitoring messages // */ // public static String monitoring(String stopSytemId) { // return stopSystemDestination(stopSytemId, "monitoring"); // } // // /** // * Generate a topic for monitoring messages about the distribution function // * @return A valid topic name for monitoring messages // */ // public static String monitoring() { // return "distribution/monitoring"; // } // // private static String stopSystemDestination(String stopSytemId, String category) { // return "stopsystem/"+ idOrWildcard(stopSytemId) + "/" + category; // } // // private static String stopSystemOrigin(String stopSytemId, String command) { // return command + "/stopsystem/"+ idOrWildcard(stopSytemId); // } // // private static String idOrWildcard(String id) { // return id != null ? id : "+"; // } // // } // // Path: common_client/src/main/java/nl/crowndov/displaydirect/commonclient/domain/SubscriptionBuilder.java // public class SubscriptionBuilder { // // public static DisplayDirectMessage.Subscribe subscribe(DisplayParameters display, SystemParameters system) { // DisplayDirectMessage.Subscribe.Builder build = DisplayDirectMessage.Subscribe.newBuilder() // .addAllStopCode(system.getStopCodes()) // .setDisplayProperties(DisplayDirectMessage.Subscribe.DisplayProperties.newBuilder().setTextCharacters(0)) // .setFieldFilter(DisplayDirectMessage.Subscribe.FieldFilter.newBuilder() // .setTripStopStatus(DisplayDirectMessage.Subscribe.FieldFilter.Delivery.ALWAYS) // .setTargetDepartureTime(DisplayDirectMessage.Subscribe.FieldFilter.Delivery.ALWAYS) // .setDestination(DisplayDirectMessage.Subscribe.FieldFilter.Delivery.ALWAYS) // .setLinePublicNumber(DisplayDirectMessage.Subscribe.FieldFilter.Delivery.ALWAYS) // .setTransportType(DisplayDirectMessage.Subscribe.FieldFilter.Delivery.ALWAYS)) // .setEmail(system.getEmail()) // .setDescription(system.getDescription()); // // return build.build(); // } // // public static DisplayDirectMessage.Unsubscribe unsubscribe() { // return DisplayDirectMessage.Unsubscribe.newBuilder().setIsPermanent(false).build(); // } // }
import nl.crowndov.displaydirect.common.transport.mqtt.TopicFactory; import nl.crowndov.displaydirect.commonclient.domain.SubscriptionBuilder; import org.fusesource.hawtbuf.Buffer; import org.fusesource.hawtbuf.UTF8Buffer; import org.fusesource.mqtt.client.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URISyntaxException;
package nl.crowndov.displaydirect.commonclient.mqtt; /** * Copyright 2017 CROW-NDOV * <p> * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class MqttClient { private static final Logger LOGGER = LoggerFactory.getLogger(MqttClient.class); private MQTT mqtt; private final CallbackConnection connection; private final byte[] disconnect = SubscriptionBuilder.unsubscribe().toByteArray(); private final String disconnectTopic; public MqttClient(String hostname, String clientId, onClientAction msg) { mqtt = new MQTT(); try { mqtt.setHost(hostname); } catch (URISyntaxException e) { LOGGER.error("Error setting host"); } mqtt.setClientId(clientId); mqtt.setCleanSession(true); mqtt.setWillMessage(new UTF8Buffer(disconnect));
// Path: common/src/main/java/nl/crowndov/displaydirect/common/transport/mqtt/TopicFactory.java // public class TopicFactory { // // /** // * Generate a topic for subscribe messages // * @param stopSytemId An id for the originating stopsystem. If null, will be filled with a wildcard for that level // * @return A valid topic name for subscribe messages // */ // public static String subscribe(String stopSytemId) { // return stopSystemOrigin(stopSytemId, "subscribe"); // } // // /** // * Generate a topic for unsubscribe messages // * @param stopSytemId An id for the originating stopsystem. If null, will be filled with a wildcard for that level // * @return A valid topic name for unsubscribe messages // */ // public static String unsubscribe(String stopSytemId) { // return stopSystemOrigin(stopSytemId, "unsubscribe"); // } // // /** // * Generate a topic for travel information messages // * @param stopSytemId An id for the destination stopsystem. If null, will be filled with a wildcard for that level // * @return A valid topic name for travel information messages // */ // public static String travelInformation(String stopSytemId) { // return stopSystemDestination(stopSytemId, "travel_information"); // } // // /** // * Generate a topic for subscription response messages // * @param stopSytemId An id for the destination stopsystem. If null, will be filled with a wildcard for that level // * @return A valid topic name for subscription response messages // */ // public static String subscriptionResponse(String stopSytemId) { // return stopSystemDestination(stopSytemId, "subscription_response"); // } // // /** // * Generate a topic for monitoring messages about stops // * @param stopSytemId An id for the object stopsystem. If null, will be filled with a wildcard for that level // * @return A valid topic name for monitoring messages // */ // public static String monitoring(String stopSytemId) { // return stopSystemDestination(stopSytemId, "monitoring"); // } // // /** // * Generate a topic for monitoring messages about the distribution function // * @return A valid topic name for monitoring messages // */ // public static String monitoring() { // return "distribution/monitoring"; // } // // private static String stopSystemDestination(String stopSytemId, String category) { // return "stopsystem/"+ idOrWildcard(stopSytemId) + "/" + category; // } // // private static String stopSystemOrigin(String stopSytemId, String command) { // return command + "/stopsystem/"+ idOrWildcard(stopSytemId); // } // // private static String idOrWildcard(String id) { // return id != null ? id : "+"; // } // // } // // Path: common_client/src/main/java/nl/crowndov/displaydirect/commonclient/domain/SubscriptionBuilder.java // public class SubscriptionBuilder { // // public static DisplayDirectMessage.Subscribe subscribe(DisplayParameters display, SystemParameters system) { // DisplayDirectMessage.Subscribe.Builder build = DisplayDirectMessage.Subscribe.newBuilder() // .addAllStopCode(system.getStopCodes()) // .setDisplayProperties(DisplayDirectMessage.Subscribe.DisplayProperties.newBuilder().setTextCharacters(0)) // .setFieldFilter(DisplayDirectMessage.Subscribe.FieldFilter.newBuilder() // .setTripStopStatus(DisplayDirectMessage.Subscribe.FieldFilter.Delivery.ALWAYS) // .setTargetDepartureTime(DisplayDirectMessage.Subscribe.FieldFilter.Delivery.ALWAYS) // .setDestination(DisplayDirectMessage.Subscribe.FieldFilter.Delivery.ALWAYS) // .setLinePublicNumber(DisplayDirectMessage.Subscribe.FieldFilter.Delivery.ALWAYS) // .setTransportType(DisplayDirectMessage.Subscribe.FieldFilter.Delivery.ALWAYS)) // .setEmail(system.getEmail()) // .setDescription(system.getDescription()); // // return build.build(); // } // // public static DisplayDirectMessage.Unsubscribe unsubscribe() { // return DisplayDirectMessage.Unsubscribe.newBuilder().setIsPermanent(false).build(); // } // } // Path: common_client/src/main/java/nl/crowndov/displaydirect/commonclient/mqtt/MqttClient.java import nl.crowndov.displaydirect.common.transport.mqtt.TopicFactory; import nl.crowndov.displaydirect.commonclient.domain.SubscriptionBuilder; import org.fusesource.hawtbuf.Buffer; import org.fusesource.hawtbuf.UTF8Buffer; import org.fusesource.mqtt.client.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URISyntaxException; package nl.crowndov.displaydirect.commonclient.mqtt; /** * Copyright 2017 CROW-NDOV * <p> * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class MqttClient { private static final Logger LOGGER = LoggerFactory.getLogger(MqttClient.class); private MQTT mqtt; private final CallbackConnection connection; private final byte[] disconnect = SubscriptionBuilder.unsubscribe().toByteArray(); private final String disconnectTopic; public MqttClient(String hostname, String clientId, onClientAction msg) { mqtt = new MQTT(); try { mqtt.setHost(hostname); } catch (URISyntaxException e) { LOGGER.error("Error setting host"); } mqtt.setClientId(clientId); mqtt.setCleanSession(true); mqtt.setWillMessage(new UTF8Buffer(disconnect));
disconnectTopic = TopicFactory.unsubscribe(clientId);
CROW-NDOV/displaydirect
distribution/src/main/java/nl/crowndov/displaydirect/distribution/util/AbstractService.java
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/Configuration.java // public class Configuration { // // private static final Logger LOGGER = LoggerFactory.getLogger(Configuration.class); // // private static AbstractConfiguration config = ConfigurationManager.getConfigInstance(); // // public static List<String> getKvEndpoints() { // return Arrays.asList(config.getStringArray("distribution.kv78turbo.endpoints")); // } // // public static String[] getKvPublishers() { // return config.getStringArray("distribution.kv78turbo.publishers"); // } // // public static ZoneId getZoneId() { // return ZoneId.of(config.getString("distribution.timezone.default")); // } // // public static String getOutputTransport() { // return config.getString("distribution.transport", "mqtt"); // } // // public static String getMqttBrokerHost() { // return config.getString("distribution.mqtt.host", "localhost:1883"); // } // // public static int getZmqInternalPort() { // return 9800; // } // // public static String getMqttClientId() { // return config.getString("distribution.mqtt.client_id", "distribution"); // } // // public static int getAuthorizationTokenMaxAge() { // return config.getInt("distribution.authorization.max_age_hours"); // } // // public static List<String> getAuthorizationWhitelist() { // return Arrays.asList(config.getStringArray("distribution.authorization.whitelist_prefix")); // } // // public static String getBaseUrl() { // return config.getString("distribution.install.base_url", "http://localhost:8080"); // } // // public static String getSmtpUsername() { // return config.getString("distribution.smtp.username", null); // } // // public static String getSmtpPassword() { // return config.getString("distribution.smtp.password", null); // } // // public static String getSmtpFrom() { // return config.getString("distribution.smtp.from"); // } // // public static String getSmtpHostname() { // return config.getString("distribution.smtp.hostname"); // } // // public static String getSmtpReplyTo() { // return config.getString("distribution.smtp.reply_to"); // } // // public static boolean getSmtpSsl() { return config.getBoolean("distribution.smtp.ssl", false); } // // public static int getSmtpPort() { // return config.getInt("distribution.smtp.port", 25); // } // // public static int getSmtpConnectTimeout() { // return config.getInt("distribution.smtp.connect_timeout", 10*1000); // } // // public static String getFileBasePath() { // return config.getString("distribution.backup.path", System.getProperty("java.io.tmpdir")); // } // // public static String getKv7PlanningPath() { // return config.getString("distribution.kv78turbo.path.planning"); // } // // public static String getKv7CalendarPath() { // return config.getString("distribution.kv78turbo.path.calendar"); // } // // public static String getChbPath() { // return config.getString("distribution.chb.path"); // } // // // public static String getPlanningLoaderTime() { // return config.getString("distribution.planning.loadTime", "03:30"); // } // // public static String getPlanningCleanupTime() { // return config.getString("distribution.planning.cleanupTime", "04:00"); // } // // }
import com.google.gson.Gson; import nl.crowndov.displaydirect.distribution.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.nio.file.*; import java.util.Optional; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit;
T result = (T) ois.readObject(); return Optional.of(result); } catch (ClassNotFoundException e) { LOGGER.error("Error deserializing {}", key, e); } catch (Exception e) { LOGGER.error("Error reading {}", key, e); } return Optional.empty(); } protected static <T> void writeFile(String key, T data) { String dataStr = GSON.toJson(data); LOGGER.info("Got serialized data {} (len {})", key, dataStr.length()); JsonFile.write(key, dataStr); } protected static <T> void writeFileSerialize(String key, T data) { String out = getPathSerialized(key+"-temp").toString(); LOGGER.info("Writing to {}", out); try (FileOutputStream fos = new FileOutputStream(out, false); ObjectOutputStream oos = new ObjectOutputStream(fos)) { oos.writeObject(data); // Once done, move to the location we read, so that in case the (long) export is interupted, we don't lose a backup Files.move(getPathSerialized(key+"-temp"), getPathSerialized(key), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); } catch (IOException e) { LOGGER.error("Error writing {}", key, e); } } private static Path getPathSerialized(String key) {
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/Configuration.java // public class Configuration { // // private static final Logger LOGGER = LoggerFactory.getLogger(Configuration.class); // // private static AbstractConfiguration config = ConfigurationManager.getConfigInstance(); // // public static List<String> getKvEndpoints() { // return Arrays.asList(config.getStringArray("distribution.kv78turbo.endpoints")); // } // // public static String[] getKvPublishers() { // return config.getStringArray("distribution.kv78turbo.publishers"); // } // // public static ZoneId getZoneId() { // return ZoneId.of(config.getString("distribution.timezone.default")); // } // // public static String getOutputTransport() { // return config.getString("distribution.transport", "mqtt"); // } // // public static String getMqttBrokerHost() { // return config.getString("distribution.mqtt.host", "localhost:1883"); // } // // public static int getZmqInternalPort() { // return 9800; // } // // public static String getMqttClientId() { // return config.getString("distribution.mqtt.client_id", "distribution"); // } // // public static int getAuthorizationTokenMaxAge() { // return config.getInt("distribution.authorization.max_age_hours"); // } // // public static List<String> getAuthorizationWhitelist() { // return Arrays.asList(config.getStringArray("distribution.authorization.whitelist_prefix")); // } // // public static String getBaseUrl() { // return config.getString("distribution.install.base_url", "http://localhost:8080"); // } // // public static String getSmtpUsername() { // return config.getString("distribution.smtp.username", null); // } // // public static String getSmtpPassword() { // return config.getString("distribution.smtp.password", null); // } // // public static String getSmtpFrom() { // return config.getString("distribution.smtp.from"); // } // // public static String getSmtpHostname() { // return config.getString("distribution.smtp.hostname"); // } // // public static String getSmtpReplyTo() { // return config.getString("distribution.smtp.reply_to"); // } // // public static boolean getSmtpSsl() { return config.getBoolean("distribution.smtp.ssl", false); } // // public static int getSmtpPort() { // return config.getInt("distribution.smtp.port", 25); // } // // public static int getSmtpConnectTimeout() { // return config.getInt("distribution.smtp.connect_timeout", 10*1000); // } // // public static String getFileBasePath() { // return config.getString("distribution.backup.path", System.getProperty("java.io.tmpdir")); // } // // public static String getKv7PlanningPath() { // return config.getString("distribution.kv78turbo.path.planning"); // } // // public static String getKv7CalendarPath() { // return config.getString("distribution.kv78turbo.path.calendar"); // } // // public static String getChbPath() { // return config.getString("distribution.chb.path"); // } // // // public static String getPlanningLoaderTime() { // return config.getString("distribution.planning.loadTime", "03:30"); // } // // public static String getPlanningCleanupTime() { // return config.getString("distribution.planning.cleanupTime", "04:00"); // } // // } // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/util/AbstractService.java import com.google.gson.Gson; import nl.crowndov.displaydirect.distribution.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.nio.file.*; import java.util.Optional; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; T result = (T) ois.readObject(); return Optional.of(result); } catch (ClassNotFoundException e) { LOGGER.error("Error deserializing {}", key, e); } catch (Exception e) { LOGGER.error("Error reading {}", key, e); } return Optional.empty(); } protected static <T> void writeFile(String key, T data) { String dataStr = GSON.toJson(data); LOGGER.info("Got serialized data {} (len {})", key, dataStr.length()); JsonFile.write(key, dataStr); } protected static <T> void writeFileSerialize(String key, T data) { String out = getPathSerialized(key+"-temp").toString(); LOGGER.info("Writing to {}", out); try (FileOutputStream fos = new FileOutputStream(out, false); ObjectOutputStream oos = new ObjectOutputStream(fos)) { oos.writeObject(data); // Once done, move to the location we read, so that in case the (long) export is interupted, we don't lose a backup Files.move(getPathSerialized(key+"-temp"), getPathSerialized(key), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); } catch (IOException e) { LOGGER.error("Error writing {}", key, e); } } private static Path getPathSerialized(String key) {
return Paths.get(Configuration.getFileBasePath(), key+".out");
CROW-NDOV/displaydirect
dashboard/src/main/java/nl/crowndov/displaydirect/dashboard/GsonMessageBodyHandler.java
// Path: dashboard/src/main/java/nl/crowndov/displaydirect/dashboard/util/GsonFactory.java // public class GsonFactory { // // public static Gson get() { // final GsonBuilder gsonBuilder = new GsonBuilder(); // return gsonBuilder // .registerTypeAdapter(LocalDate.class, new DateAdapter()) // .registerTypeAdapter(LocalDateTime.class, new DateTimeAdapter()) // .create(); // } // }
import com.google.gson.Gson; import nl.crowndov.displaydirect.dashboard.util.GsonFactory; import javax.ws.rs.Consumes; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import java.io.*; import java.lang.annotation.Annotation; import java.lang.reflect.Type;
package nl.crowndov.displaydirect.dashboard; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ @Provider @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public final class GsonMessageBodyHandler implements MessageBodyWriter<Object>, MessageBodyReader<Object> { private static final String UTF_8 = "UTF-8"; private Gson gson; private Gson getGson() { if (gson == null) {
// Path: dashboard/src/main/java/nl/crowndov/displaydirect/dashboard/util/GsonFactory.java // public class GsonFactory { // // public static Gson get() { // final GsonBuilder gsonBuilder = new GsonBuilder(); // return gsonBuilder // .registerTypeAdapter(LocalDate.class, new DateAdapter()) // .registerTypeAdapter(LocalDateTime.class, new DateTimeAdapter()) // .create(); // } // } // Path: dashboard/src/main/java/nl/crowndov/displaydirect/dashboard/GsonMessageBodyHandler.java import com.google.gson.Gson; import nl.crowndov.displaydirect.dashboard.util.GsonFactory; import javax.ws.rs.Consumes; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import java.io.*; import java.lang.annotation.Annotation; import java.lang.reflect.Type; package nl.crowndov.displaydirect.dashboard; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ @Provider @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public final class GsonMessageBodyHandler implements MessageBodyWriter<Object>, MessageBodyReader<Object> { private static final String UTF_8 = "UTF-8"; private Gson gson; private Gson getGson() { if (gson == null) {
gson = GsonFactory.get();
CROW-NDOV/displaydirect
distribution/src/main/java/nl/crowndov/displaydirect/distribution/resources/SubscriptionResource.java
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/messages/SubscriptionStore.java // public class SubscriptionStore extends AbstractService { // // private static final MetricStore metrics = MetricStore.getInstance(); // // // TODO: Guava table thing // private static Store.SubscriptionQuayStore quayIndex = new Store.SubscriptionQuayStore(); // private static Store.SubscriptionStore systemIndex = new Store.SubscriptionStore(); // // public static void start() { // readFile("subscriptions", Store.SubscriptionStore.class).ifPresent(subs -> { // systemIndex = subs; // subs.values().forEach(SubscriptionStore::populateQuayIndexFromSub); // Rebuild the list of quays // // TODO: Do something with planning here to ensure the stopsystems have latest & greatest? // }); // } // // public static void stop() { // writeFile("subscriptions", systemIndex); // } // // public static boolean hasSubscription(String quay) { // return quayIndex.containsKey(quay); // } // // public static boolean isSystemSubscribed(String stopSystemId) { // // TODO: Also check authorization system for waiting subscriptions // return systemIndex.containsKey(stopSystemId); // } // // public static int getSubscribedStopCount() { // return quayIndex.keySet().size(); // } // // public static List<Subscription> getForQuay(String quay) { // if (quayIndex.containsKey(quay)) { // return quayIndex.get(quay); // } // return new ArrayList<>(); // } // // public static Optional<Subscription> getForSystem(String id) { // if (systemIndex.containsKey(id)) { // return Optional.of(systemIndex.get(id)); // } // return Optional.empty(); // } // // // TODO: Think about multithreading // public static synchronized void add(Subscription sub) { // populateQuayIndexFromSub(sub); // systemIndex.put(sub.getId(), sub); // This overwrites existing entries // updateStats(); // } // // private static void populateQuayIndexFromSub(Subscription sub) { // sub.getSubscribedQuayCodes().forEach(quay -> { // if (!quayIndex.containsKey(quay)) { // quayIndex.put(quay, new ArrayList<>()); // } // quayIndex.get(quay).add(sub); // }); // } // // public static synchronized void remove(String id) { // if (systemIndex.containsKey(id)) { // Subscription s = systemIndex.get(id); // s.getSubscribedQuayCodes().forEach(quay -> { // List<Subscription> quays = quayIndex.get(quay); // if (quays != null) { // quays.remove(s); // // Cleanup // if (quays.size() == 0) { // quayIndex.remove(quay); // } // } // }); // systemIndex.remove(id); // updateStats(); // } // } // // // private static void updateStats() { // metrics.storeMetric("subscriptions.active", systemIndex.size()); // metrics.storeMetric("subscriptions.stops", quayIndex.size()); // } // // public static Map<String, Subscription> getAllSystems() { // return systemIndex; // } // // public static Map<String, List<Subscription>> getAllQuays() { // return quayIndex; // } // }
import nl.crowndov.displaydirect.distribution.messages.SubscriptionStore; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response;
package nl.crowndov.displaydirect.distribution.resources; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ @Path("/v1/subscription") public class SubscriptionResource { @GET public Response get() {
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/messages/SubscriptionStore.java // public class SubscriptionStore extends AbstractService { // // private static final MetricStore metrics = MetricStore.getInstance(); // // // TODO: Guava table thing // private static Store.SubscriptionQuayStore quayIndex = new Store.SubscriptionQuayStore(); // private static Store.SubscriptionStore systemIndex = new Store.SubscriptionStore(); // // public static void start() { // readFile("subscriptions", Store.SubscriptionStore.class).ifPresent(subs -> { // systemIndex = subs; // subs.values().forEach(SubscriptionStore::populateQuayIndexFromSub); // Rebuild the list of quays // // TODO: Do something with planning here to ensure the stopsystems have latest & greatest? // }); // } // // public static void stop() { // writeFile("subscriptions", systemIndex); // } // // public static boolean hasSubscription(String quay) { // return quayIndex.containsKey(quay); // } // // public static boolean isSystemSubscribed(String stopSystemId) { // // TODO: Also check authorization system for waiting subscriptions // return systemIndex.containsKey(stopSystemId); // } // // public static int getSubscribedStopCount() { // return quayIndex.keySet().size(); // } // // public static List<Subscription> getForQuay(String quay) { // if (quayIndex.containsKey(quay)) { // return quayIndex.get(quay); // } // return new ArrayList<>(); // } // // public static Optional<Subscription> getForSystem(String id) { // if (systemIndex.containsKey(id)) { // return Optional.of(systemIndex.get(id)); // } // return Optional.empty(); // } // // // TODO: Think about multithreading // public static synchronized void add(Subscription sub) { // populateQuayIndexFromSub(sub); // systemIndex.put(sub.getId(), sub); // This overwrites existing entries // updateStats(); // } // // private static void populateQuayIndexFromSub(Subscription sub) { // sub.getSubscribedQuayCodes().forEach(quay -> { // if (!quayIndex.containsKey(quay)) { // quayIndex.put(quay, new ArrayList<>()); // } // quayIndex.get(quay).add(sub); // }); // } // // public static synchronized void remove(String id) { // if (systemIndex.containsKey(id)) { // Subscription s = systemIndex.get(id); // s.getSubscribedQuayCodes().forEach(quay -> { // List<Subscription> quays = quayIndex.get(quay); // if (quays != null) { // quays.remove(s); // // Cleanup // if (quays.size() == 0) { // quayIndex.remove(quay); // } // } // }); // systemIndex.remove(id); // updateStats(); // } // } // // // private static void updateStats() { // metrics.storeMetric("subscriptions.active", systemIndex.size()); // metrics.storeMetric("subscriptions.stops", quayIndex.size()); // } // // public static Map<String, Subscription> getAllSystems() { // return systemIndex; // } // // public static Map<String, List<Subscription>> getAllQuays() { // return quayIndex; // } // } // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/resources/SubscriptionResource.java import nl.crowndov.displaydirect.distribution.messages.SubscriptionStore; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response; package nl.crowndov.displaydirect.distribution.resources; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ @Path("/v1/subscription") public class SubscriptionResource { @GET public Response get() {
return Response.ok(SubscriptionStore.getAllSystems()).build();
CROW-NDOV/displaydirect
dashboard/src/main/java/nl/crowndov/displaydirect/dashboard/BootListener.java
// Path: dashboard/src/main/java/nl/crowndov/displaydirect/dashboard/mqtt/MonitoringHandler.java // public class MonitoringHandler implements Callback<DisplayDirectMessage.Monitoring> { // // private static final Logger LOGGER = LoggerFactory.getLogger(MonitoringHandler.class); // // @Override // public void onSuccess(DisplayDirectMessage.Monitoring value) { // if (value.getLogsList().size() > 0) { // value.getLogsList().forEach(m -> LogStore.add(DisplayDirectMessageParser.toLogMessage(m))); // } else if (value.getMetricsList().size() > 0) { // value.getMetricsList().forEach(m -> MetricStore.update(DisplayDirectMessageParser.toMetric(m))); // } else { // LOGGER.error("Got empty log message"); // } // } // // @Override // public void onFailure(Throwable value) { // LOGGER.info("Failed with error", value); // } // } // // Path: dashboard/src/main/java/nl/crowndov/displaydirect/dashboard/mqtt/MqttClient.java // public class MqttClient { // // private static final Logger LOGGER = LoggerFactory.getLogger(MqttClient.class); // // private MQTT mqtt; // private final CallbackConnection connection; // // private Callback<byte[]> subscriptionCompleteCallback = new Callback<byte[]>() { // @Override // public void onSuccess(byte[] value) { // LOGGER.info("Subscribed succesfully"); // } // // @Override // public void onFailure(Throwable value) { // LOGGER.info("Error during subscribing", value); // } // }; // // public MqttClient(Callback<DisplayDirectMessage.Monitoring> msg) { // mqtt = new MQTT(); // try { // mqtt.setHost(Configuration.getHostname()); // } catch (URISyntaxException e) { // LOGGER.error("Error setting host"); // } // mqtt.setClientId(Configuration.getClientId()); // mqtt.setCleanSession(false); // // mqtt.setKeepAlive((short) 60); // // mqtt.setReconnectBackOffMultiplier(3); // // mqtt.setConnectAttemptsMax(10000); // // mqtt.setReconnectDelay(20); // // mqtt.setReconnectDelayMax(10000); // mqtt.setVersion("3.1.1"); // // connection = mqtt.callbackConnection(); // LOGGER.info("Setting up connection"); // connection.listener(new Listener() { // @Override // public void onConnected() { // LOGGER.info("Connected"); // } // // @Override // public void onDisconnected() { // LOGGER.info("Disconnected"); // } // // @Override // public void onPublish(UTF8Buffer topic, Buffer body, Runnable ack) { // try { // DisplayDirectMessage.Monitoring mon = DisplayDirectMessage.Monitoring.parseFrom(body.toByteArray()); // msg.onSuccess(mon); // } catch (InvalidProtocolBufferException e) { // LOGGER.error("Failed to parse message", e); // msg.onFailure(e); // } // ack.run(); // } // // @Override // public void onFailure(Throwable value) { // LOGGER.info("MQTT Client failed", value); // } // }); // connection.connect(new Callback<Void>() { // @Override // public void onSuccess(Void value) { // LOGGER.info("Subscribing to topics"); // Topic[] topics = { new Topic (TopicFactory.monitoring(), QoS.AT_LEAST_ONCE) }; // connection.subscribe(topics, subscriptionCompleteCallback); // // TODO: Figure this out // Topic[] topics2 = { new Topic (TopicFactory.monitoring("+"), QoS.AT_LEAST_ONCE) }; // connection.subscribe(topics2, subscriptionCompleteCallback); // } // // @Override // public void onFailure(Throwable value) { // LOGGER.info("Connection failure", value); // } // }); // // } // // public void stop() { // connection.disconnect(new Callback<Void>() { // @Override // public void onSuccess(Void value) { // LOGGER.info("Disconnect success"); // } // // @Override // public void onFailure(Throwable value) { // LOGGER.info("Disconnect failure"); // } // }); // } // // public void publish(String queue, byte[] msg, QoS qos, Callback<Void> callback) { // if (qos == null) { // qos = QoS.AT_LEAST_ONCE; // } // if (callback == null) { // callback = new Callback<Void>() { // @Override // public void onSuccess(Void value) { // // } // // @Override // public void onFailure(Throwable value) { // LOGGER.info("Error sending message"); // } // }; // } // connection.publish(queue, msg, qos, false, callback); // } // }
import com.netflix.config.ConfigurationManager; import nl.crowndov.displaydirect.dashboard.mqtt.MonitoringHandler; import nl.crowndov.displaydirect.dashboard.mqtt.MqttClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import java.io.IOException;
package nl.crowndov.displaydirect.dashboard; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ @WebListener public class BootListener implements ServletContextListener { private static final Logger LOGGER = LoggerFactory.getLogger(BootListener.class);
// Path: dashboard/src/main/java/nl/crowndov/displaydirect/dashboard/mqtt/MonitoringHandler.java // public class MonitoringHandler implements Callback<DisplayDirectMessage.Monitoring> { // // private static final Logger LOGGER = LoggerFactory.getLogger(MonitoringHandler.class); // // @Override // public void onSuccess(DisplayDirectMessage.Monitoring value) { // if (value.getLogsList().size() > 0) { // value.getLogsList().forEach(m -> LogStore.add(DisplayDirectMessageParser.toLogMessage(m))); // } else if (value.getMetricsList().size() > 0) { // value.getMetricsList().forEach(m -> MetricStore.update(DisplayDirectMessageParser.toMetric(m))); // } else { // LOGGER.error("Got empty log message"); // } // } // // @Override // public void onFailure(Throwable value) { // LOGGER.info("Failed with error", value); // } // } // // Path: dashboard/src/main/java/nl/crowndov/displaydirect/dashboard/mqtt/MqttClient.java // public class MqttClient { // // private static final Logger LOGGER = LoggerFactory.getLogger(MqttClient.class); // // private MQTT mqtt; // private final CallbackConnection connection; // // private Callback<byte[]> subscriptionCompleteCallback = new Callback<byte[]>() { // @Override // public void onSuccess(byte[] value) { // LOGGER.info("Subscribed succesfully"); // } // // @Override // public void onFailure(Throwable value) { // LOGGER.info("Error during subscribing", value); // } // }; // // public MqttClient(Callback<DisplayDirectMessage.Monitoring> msg) { // mqtt = new MQTT(); // try { // mqtt.setHost(Configuration.getHostname()); // } catch (URISyntaxException e) { // LOGGER.error("Error setting host"); // } // mqtt.setClientId(Configuration.getClientId()); // mqtt.setCleanSession(false); // // mqtt.setKeepAlive((short) 60); // // mqtt.setReconnectBackOffMultiplier(3); // // mqtt.setConnectAttemptsMax(10000); // // mqtt.setReconnectDelay(20); // // mqtt.setReconnectDelayMax(10000); // mqtt.setVersion("3.1.1"); // // connection = mqtt.callbackConnection(); // LOGGER.info("Setting up connection"); // connection.listener(new Listener() { // @Override // public void onConnected() { // LOGGER.info("Connected"); // } // // @Override // public void onDisconnected() { // LOGGER.info("Disconnected"); // } // // @Override // public void onPublish(UTF8Buffer topic, Buffer body, Runnable ack) { // try { // DisplayDirectMessage.Monitoring mon = DisplayDirectMessage.Monitoring.parseFrom(body.toByteArray()); // msg.onSuccess(mon); // } catch (InvalidProtocolBufferException e) { // LOGGER.error("Failed to parse message", e); // msg.onFailure(e); // } // ack.run(); // } // // @Override // public void onFailure(Throwable value) { // LOGGER.info("MQTT Client failed", value); // } // }); // connection.connect(new Callback<Void>() { // @Override // public void onSuccess(Void value) { // LOGGER.info("Subscribing to topics"); // Topic[] topics = { new Topic (TopicFactory.monitoring(), QoS.AT_LEAST_ONCE) }; // connection.subscribe(topics, subscriptionCompleteCallback); // // TODO: Figure this out // Topic[] topics2 = { new Topic (TopicFactory.monitoring("+"), QoS.AT_LEAST_ONCE) }; // connection.subscribe(topics2, subscriptionCompleteCallback); // } // // @Override // public void onFailure(Throwable value) { // LOGGER.info("Connection failure", value); // } // }); // // } // // public void stop() { // connection.disconnect(new Callback<Void>() { // @Override // public void onSuccess(Void value) { // LOGGER.info("Disconnect success"); // } // // @Override // public void onFailure(Throwable value) { // LOGGER.info("Disconnect failure"); // } // }); // } // // public void publish(String queue, byte[] msg, QoS qos, Callback<Void> callback) { // if (qos == null) { // qos = QoS.AT_LEAST_ONCE; // } // if (callback == null) { // callback = new Callback<Void>() { // @Override // public void onSuccess(Void value) { // // } // // @Override // public void onFailure(Throwable value) { // LOGGER.info("Error sending message"); // } // }; // } // connection.publish(queue, msg, qos, false, callback); // } // } // Path: dashboard/src/main/java/nl/crowndov/displaydirect/dashboard/BootListener.java import com.netflix.config.ConfigurationManager; import nl.crowndov.displaydirect.dashboard.mqtt.MonitoringHandler; import nl.crowndov.displaydirect.dashboard.mqtt.MqttClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import java.io.IOException; package nl.crowndov.displaydirect.dashboard; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ @WebListener public class BootListener implements ServletContextListener { private static final Logger LOGGER = LoggerFactory.getLogger(BootListener.class);
private MqttClient mqtt;
CROW-NDOV/displaydirect
dashboard/src/main/java/nl/crowndov/displaydirect/dashboard/BootListener.java
// Path: dashboard/src/main/java/nl/crowndov/displaydirect/dashboard/mqtt/MonitoringHandler.java // public class MonitoringHandler implements Callback<DisplayDirectMessage.Monitoring> { // // private static final Logger LOGGER = LoggerFactory.getLogger(MonitoringHandler.class); // // @Override // public void onSuccess(DisplayDirectMessage.Monitoring value) { // if (value.getLogsList().size() > 0) { // value.getLogsList().forEach(m -> LogStore.add(DisplayDirectMessageParser.toLogMessage(m))); // } else if (value.getMetricsList().size() > 0) { // value.getMetricsList().forEach(m -> MetricStore.update(DisplayDirectMessageParser.toMetric(m))); // } else { // LOGGER.error("Got empty log message"); // } // } // // @Override // public void onFailure(Throwable value) { // LOGGER.info("Failed with error", value); // } // } // // Path: dashboard/src/main/java/nl/crowndov/displaydirect/dashboard/mqtt/MqttClient.java // public class MqttClient { // // private static final Logger LOGGER = LoggerFactory.getLogger(MqttClient.class); // // private MQTT mqtt; // private final CallbackConnection connection; // // private Callback<byte[]> subscriptionCompleteCallback = new Callback<byte[]>() { // @Override // public void onSuccess(byte[] value) { // LOGGER.info("Subscribed succesfully"); // } // // @Override // public void onFailure(Throwable value) { // LOGGER.info("Error during subscribing", value); // } // }; // // public MqttClient(Callback<DisplayDirectMessage.Monitoring> msg) { // mqtt = new MQTT(); // try { // mqtt.setHost(Configuration.getHostname()); // } catch (URISyntaxException e) { // LOGGER.error("Error setting host"); // } // mqtt.setClientId(Configuration.getClientId()); // mqtt.setCleanSession(false); // // mqtt.setKeepAlive((short) 60); // // mqtt.setReconnectBackOffMultiplier(3); // // mqtt.setConnectAttemptsMax(10000); // // mqtt.setReconnectDelay(20); // // mqtt.setReconnectDelayMax(10000); // mqtt.setVersion("3.1.1"); // // connection = mqtt.callbackConnection(); // LOGGER.info("Setting up connection"); // connection.listener(new Listener() { // @Override // public void onConnected() { // LOGGER.info("Connected"); // } // // @Override // public void onDisconnected() { // LOGGER.info("Disconnected"); // } // // @Override // public void onPublish(UTF8Buffer topic, Buffer body, Runnable ack) { // try { // DisplayDirectMessage.Monitoring mon = DisplayDirectMessage.Monitoring.parseFrom(body.toByteArray()); // msg.onSuccess(mon); // } catch (InvalidProtocolBufferException e) { // LOGGER.error("Failed to parse message", e); // msg.onFailure(e); // } // ack.run(); // } // // @Override // public void onFailure(Throwable value) { // LOGGER.info("MQTT Client failed", value); // } // }); // connection.connect(new Callback<Void>() { // @Override // public void onSuccess(Void value) { // LOGGER.info("Subscribing to topics"); // Topic[] topics = { new Topic (TopicFactory.monitoring(), QoS.AT_LEAST_ONCE) }; // connection.subscribe(topics, subscriptionCompleteCallback); // // TODO: Figure this out // Topic[] topics2 = { new Topic (TopicFactory.monitoring("+"), QoS.AT_LEAST_ONCE) }; // connection.subscribe(topics2, subscriptionCompleteCallback); // } // // @Override // public void onFailure(Throwable value) { // LOGGER.info("Connection failure", value); // } // }); // // } // // public void stop() { // connection.disconnect(new Callback<Void>() { // @Override // public void onSuccess(Void value) { // LOGGER.info("Disconnect success"); // } // // @Override // public void onFailure(Throwable value) { // LOGGER.info("Disconnect failure"); // } // }); // } // // public void publish(String queue, byte[] msg, QoS qos, Callback<Void> callback) { // if (qos == null) { // qos = QoS.AT_LEAST_ONCE; // } // if (callback == null) { // callback = new Callback<Void>() { // @Override // public void onSuccess(Void value) { // // } // // @Override // public void onFailure(Throwable value) { // LOGGER.info("Error sending message"); // } // }; // } // connection.publish(queue, msg, qos, false, callback); // } // }
import com.netflix.config.ConfigurationManager; import nl.crowndov.displaydirect.dashboard.mqtt.MonitoringHandler; import nl.crowndov.displaydirect.dashboard.mqtt.MqttClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import java.io.IOException;
package nl.crowndov.displaydirect.dashboard; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ @WebListener public class BootListener implements ServletContextListener { private static final Logger LOGGER = LoggerFactory.getLogger(BootListener.class); private MqttClient mqtt; @Override public void contextInitialized(ServletContextEvent sce) { try { ConfigurationManager.loadCascadedPropertiesFromResources("configuration"); } catch (IOException e) { LOGGER.error("Failed to load properties", e); }
// Path: dashboard/src/main/java/nl/crowndov/displaydirect/dashboard/mqtt/MonitoringHandler.java // public class MonitoringHandler implements Callback<DisplayDirectMessage.Monitoring> { // // private static final Logger LOGGER = LoggerFactory.getLogger(MonitoringHandler.class); // // @Override // public void onSuccess(DisplayDirectMessage.Monitoring value) { // if (value.getLogsList().size() > 0) { // value.getLogsList().forEach(m -> LogStore.add(DisplayDirectMessageParser.toLogMessage(m))); // } else if (value.getMetricsList().size() > 0) { // value.getMetricsList().forEach(m -> MetricStore.update(DisplayDirectMessageParser.toMetric(m))); // } else { // LOGGER.error("Got empty log message"); // } // } // // @Override // public void onFailure(Throwable value) { // LOGGER.info("Failed with error", value); // } // } // // Path: dashboard/src/main/java/nl/crowndov/displaydirect/dashboard/mqtt/MqttClient.java // public class MqttClient { // // private static final Logger LOGGER = LoggerFactory.getLogger(MqttClient.class); // // private MQTT mqtt; // private final CallbackConnection connection; // // private Callback<byte[]> subscriptionCompleteCallback = new Callback<byte[]>() { // @Override // public void onSuccess(byte[] value) { // LOGGER.info("Subscribed succesfully"); // } // // @Override // public void onFailure(Throwable value) { // LOGGER.info("Error during subscribing", value); // } // }; // // public MqttClient(Callback<DisplayDirectMessage.Monitoring> msg) { // mqtt = new MQTT(); // try { // mqtt.setHost(Configuration.getHostname()); // } catch (URISyntaxException e) { // LOGGER.error("Error setting host"); // } // mqtt.setClientId(Configuration.getClientId()); // mqtt.setCleanSession(false); // // mqtt.setKeepAlive((short) 60); // // mqtt.setReconnectBackOffMultiplier(3); // // mqtt.setConnectAttemptsMax(10000); // // mqtt.setReconnectDelay(20); // // mqtt.setReconnectDelayMax(10000); // mqtt.setVersion("3.1.1"); // // connection = mqtt.callbackConnection(); // LOGGER.info("Setting up connection"); // connection.listener(new Listener() { // @Override // public void onConnected() { // LOGGER.info("Connected"); // } // // @Override // public void onDisconnected() { // LOGGER.info("Disconnected"); // } // // @Override // public void onPublish(UTF8Buffer topic, Buffer body, Runnable ack) { // try { // DisplayDirectMessage.Monitoring mon = DisplayDirectMessage.Monitoring.parseFrom(body.toByteArray()); // msg.onSuccess(mon); // } catch (InvalidProtocolBufferException e) { // LOGGER.error("Failed to parse message", e); // msg.onFailure(e); // } // ack.run(); // } // // @Override // public void onFailure(Throwable value) { // LOGGER.info("MQTT Client failed", value); // } // }); // connection.connect(new Callback<Void>() { // @Override // public void onSuccess(Void value) { // LOGGER.info("Subscribing to topics"); // Topic[] topics = { new Topic (TopicFactory.monitoring(), QoS.AT_LEAST_ONCE) }; // connection.subscribe(topics, subscriptionCompleteCallback); // // TODO: Figure this out // Topic[] topics2 = { new Topic (TopicFactory.monitoring("+"), QoS.AT_LEAST_ONCE) }; // connection.subscribe(topics2, subscriptionCompleteCallback); // } // // @Override // public void onFailure(Throwable value) { // LOGGER.info("Connection failure", value); // } // }); // // } // // public void stop() { // connection.disconnect(new Callback<Void>() { // @Override // public void onSuccess(Void value) { // LOGGER.info("Disconnect success"); // } // // @Override // public void onFailure(Throwable value) { // LOGGER.info("Disconnect failure"); // } // }); // } // // public void publish(String queue, byte[] msg, QoS qos, Callback<Void> callback) { // if (qos == null) { // qos = QoS.AT_LEAST_ONCE; // } // if (callback == null) { // callback = new Callback<Void>() { // @Override // public void onSuccess(Void value) { // // } // // @Override // public void onFailure(Throwable value) { // LOGGER.info("Error sending message"); // } // }; // } // connection.publish(queue, msg, qos, false, callback); // } // } // Path: dashboard/src/main/java/nl/crowndov/displaydirect/dashboard/BootListener.java import com.netflix.config.ConfigurationManager; import nl.crowndov.displaydirect.dashboard.mqtt.MonitoringHandler; import nl.crowndov.displaydirect.dashboard.mqtt.MqttClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import java.io.IOException; package nl.crowndov.displaydirect.dashboard; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ @WebListener public class BootListener implements ServletContextListener { private static final Logger LOGGER = LoggerFactory.getLogger(BootListener.class); private MqttClient mqtt; @Override public void contextInitialized(ServletContextEvent sce) { try { ConfigurationManager.loadCascadedPropertiesFromResources("configuration"); } catch (IOException e) { LOGGER.error("Failed to load properties", e); }
mqtt = new MqttClient(new MonitoringHandler());
CROW-NDOV/displaydirect
distribution/src/test/java/nl/crowndov/displaydirect/distribution/kv78/PlanningLoaderTest.java
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/chb/PassengerStopAssignmentLoader.java // public class PassengerStopAssignmentLoader { // // private static final Logger LOGGER = LoggerFactory.getLogger(PassengerStopAssignmentLoader.class); // // public static Map<String, String> load() { // Map<String, String> mapping = new HashMap<>(); // File chbFile = getFile(); // if (chbFile == null) { // return null; // } // // try (FileInputStream fis = new FileInputStream(chbFile); // GZIPInputStream input = new GZIPInputStream(fis)) { // Export export = (Export) JAXBContext.newInstance(Export.class).createUnmarshaller().unmarshal(input); // if (export != null) { // int count = handleExport(mapping, export); // MetricStore.getInstance().storeMetric("chb.mappings", count); // LOGGER.info("Got export, with {} entries", count); // } // } catch (JAXBException | IOException e) { // LOGGER.info("Got exception reading CHB file", e); // } // return mapping; // } // // private static File getFile() { // File path = new File(Configuration.getChbPath()); // File[] fs = path.listFiles(); // if (fs == null || fs.length == 0) { // return null; // } // File chbFile = null; // for (File f : fs) { // if (chbFile == null && f.getName().startsWith("PassengerStopAssignmentExportCHB") && f.getName().endsWith("xml.gz")) { // chbFile = f; // } // } // if (chbFile != null) { // LOGGER.info("File to match {}", chbFile.getName()); // } else { // return null; // } // return chbFile; // } // // private static int handleExport(Map<String, String> mapping, Export export) { // int i[] = {0}; // export.getQuays().getQuay().forEach(q -> { // q.getUserstopcodes().getUserstopcodedata().forEach(usc -> { // mapping.put(usc.getDataownercode()+"|"+usc.getUserstopcode(), q.getQuaycode()); // // i[0] += 1; // }); // }); // return i[0]; // } // // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/chb/StopStore.java // public class StopStore { // // private static final Logger LOGGER = LoggerFactory.getLogger(StopStore.class); // // private static Map<String, String> store = new HashMap<>(); // private static Set<String> missing = new HashSet<>(); // // public static Optional<String> getQuayFromCode(String dataOwner, String stopCode) { // String key = dataOwner+"|"+stopCode; // if (store.containsKey(key)) { // return Optional.of(store.get(key)); // } // missing.add(key); // return Optional.empty(); // } // // public static boolean stopExists(String quayOrStopCode) { // return store.values().contains(quayOrStopCode); // } // // public static Map<String, String> getStore() { // return store; // } // // public static Set<String> getMissing() { // return missing; // } // // public static void setStore(Map<String, String> storeData) { // store = storeData; // } // }
import nl.crowndov.displaydirect.distribution.chb.PassengerStopAssignmentLoader; import nl.crowndov.displaydirect.distribution.chb.StopStore; import com.netflix.config.ConfigurationManager; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.io.IOException; import java.util.Map;
package nl.crowndov.displaydirect.distribution.kv78; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class PlanningLoaderTest { @Before public void setup() { try { ConfigurationManager.loadCascadedPropertiesFromResources("configuration"); } catch (IOException ignored) {} } @Test @Ignore public void testPlanningLoader() {
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/chb/PassengerStopAssignmentLoader.java // public class PassengerStopAssignmentLoader { // // private static final Logger LOGGER = LoggerFactory.getLogger(PassengerStopAssignmentLoader.class); // // public static Map<String, String> load() { // Map<String, String> mapping = new HashMap<>(); // File chbFile = getFile(); // if (chbFile == null) { // return null; // } // // try (FileInputStream fis = new FileInputStream(chbFile); // GZIPInputStream input = new GZIPInputStream(fis)) { // Export export = (Export) JAXBContext.newInstance(Export.class).createUnmarshaller().unmarshal(input); // if (export != null) { // int count = handleExport(mapping, export); // MetricStore.getInstance().storeMetric("chb.mappings", count); // LOGGER.info("Got export, with {} entries", count); // } // } catch (JAXBException | IOException e) { // LOGGER.info("Got exception reading CHB file", e); // } // return mapping; // } // // private static File getFile() { // File path = new File(Configuration.getChbPath()); // File[] fs = path.listFiles(); // if (fs == null || fs.length == 0) { // return null; // } // File chbFile = null; // for (File f : fs) { // if (chbFile == null && f.getName().startsWith("PassengerStopAssignmentExportCHB") && f.getName().endsWith("xml.gz")) { // chbFile = f; // } // } // if (chbFile != null) { // LOGGER.info("File to match {}", chbFile.getName()); // } else { // return null; // } // return chbFile; // } // // private static int handleExport(Map<String, String> mapping, Export export) { // int i[] = {0}; // export.getQuays().getQuay().forEach(q -> { // q.getUserstopcodes().getUserstopcodedata().forEach(usc -> { // mapping.put(usc.getDataownercode()+"|"+usc.getUserstopcode(), q.getQuaycode()); // // i[0] += 1; // }); // }); // return i[0]; // } // // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/chb/StopStore.java // public class StopStore { // // private static final Logger LOGGER = LoggerFactory.getLogger(StopStore.class); // // private static Map<String, String> store = new HashMap<>(); // private static Set<String> missing = new HashSet<>(); // // public static Optional<String> getQuayFromCode(String dataOwner, String stopCode) { // String key = dataOwner+"|"+stopCode; // if (store.containsKey(key)) { // return Optional.of(store.get(key)); // } // missing.add(key); // return Optional.empty(); // } // // public static boolean stopExists(String quayOrStopCode) { // return store.values().contains(quayOrStopCode); // } // // public static Map<String, String> getStore() { // return store; // } // // public static Set<String> getMissing() { // return missing; // } // // public static void setStore(Map<String, String> storeData) { // store = storeData; // } // } // Path: distribution/src/test/java/nl/crowndov/displaydirect/distribution/kv78/PlanningLoaderTest.java import nl.crowndov.displaydirect.distribution.chb.PassengerStopAssignmentLoader; import nl.crowndov.displaydirect.distribution.chb.StopStore; import com.netflix.config.ConfigurationManager; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.io.IOException; import java.util.Map; package nl.crowndov.displaydirect.distribution.kv78; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class PlanningLoaderTest { @Before public void setup() { try { ConfigurationManager.loadCascadedPropertiesFromResources("configuration"); } catch (IOException ignored) {} } @Test @Ignore public void testPlanningLoader() {
Map<String,String> result = PassengerStopAssignmentLoader.load();
CROW-NDOV/displaydirect
distribution/src/test/java/nl/crowndov/displaydirect/distribution/kv78/PlanningLoaderTest.java
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/chb/PassengerStopAssignmentLoader.java // public class PassengerStopAssignmentLoader { // // private static final Logger LOGGER = LoggerFactory.getLogger(PassengerStopAssignmentLoader.class); // // public static Map<String, String> load() { // Map<String, String> mapping = new HashMap<>(); // File chbFile = getFile(); // if (chbFile == null) { // return null; // } // // try (FileInputStream fis = new FileInputStream(chbFile); // GZIPInputStream input = new GZIPInputStream(fis)) { // Export export = (Export) JAXBContext.newInstance(Export.class).createUnmarshaller().unmarshal(input); // if (export != null) { // int count = handleExport(mapping, export); // MetricStore.getInstance().storeMetric("chb.mappings", count); // LOGGER.info("Got export, with {} entries", count); // } // } catch (JAXBException | IOException e) { // LOGGER.info("Got exception reading CHB file", e); // } // return mapping; // } // // private static File getFile() { // File path = new File(Configuration.getChbPath()); // File[] fs = path.listFiles(); // if (fs == null || fs.length == 0) { // return null; // } // File chbFile = null; // for (File f : fs) { // if (chbFile == null && f.getName().startsWith("PassengerStopAssignmentExportCHB") && f.getName().endsWith("xml.gz")) { // chbFile = f; // } // } // if (chbFile != null) { // LOGGER.info("File to match {}", chbFile.getName()); // } else { // return null; // } // return chbFile; // } // // private static int handleExport(Map<String, String> mapping, Export export) { // int i[] = {0}; // export.getQuays().getQuay().forEach(q -> { // q.getUserstopcodes().getUserstopcodedata().forEach(usc -> { // mapping.put(usc.getDataownercode()+"|"+usc.getUserstopcode(), q.getQuaycode()); // // i[0] += 1; // }); // }); // return i[0]; // } // // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/chb/StopStore.java // public class StopStore { // // private static final Logger LOGGER = LoggerFactory.getLogger(StopStore.class); // // private static Map<String, String> store = new HashMap<>(); // private static Set<String> missing = new HashSet<>(); // // public static Optional<String> getQuayFromCode(String dataOwner, String stopCode) { // String key = dataOwner+"|"+stopCode; // if (store.containsKey(key)) { // return Optional.of(store.get(key)); // } // missing.add(key); // return Optional.empty(); // } // // public static boolean stopExists(String quayOrStopCode) { // return store.values().contains(quayOrStopCode); // } // // public static Map<String, String> getStore() { // return store; // } // // public static Set<String> getMissing() { // return missing; // } // // public static void setStore(Map<String, String> storeData) { // store = storeData; // } // }
import nl.crowndov.displaydirect.distribution.chb.PassengerStopAssignmentLoader; import nl.crowndov.displaydirect.distribution.chb.StopStore; import com.netflix.config.ConfigurationManager; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.io.IOException; import java.util.Map;
package nl.crowndov.displaydirect.distribution.kv78; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class PlanningLoaderTest { @Before public void setup() { try { ConfigurationManager.loadCascadedPropertiesFromResources("configuration"); } catch (IOException ignored) {} } @Test @Ignore public void testPlanningLoader() { Map<String,String> result = PassengerStopAssignmentLoader.load(); if (result.size() > 0) {
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/chb/PassengerStopAssignmentLoader.java // public class PassengerStopAssignmentLoader { // // private static final Logger LOGGER = LoggerFactory.getLogger(PassengerStopAssignmentLoader.class); // // public static Map<String, String> load() { // Map<String, String> mapping = new HashMap<>(); // File chbFile = getFile(); // if (chbFile == null) { // return null; // } // // try (FileInputStream fis = new FileInputStream(chbFile); // GZIPInputStream input = new GZIPInputStream(fis)) { // Export export = (Export) JAXBContext.newInstance(Export.class).createUnmarshaller().unmarshal(input); // if (export != null) { // int count = handleExport(mapping, export); // MetricStore.getInstance().storeMetric("chb.mappings", count); // LOGGER.info("Got export, with {} entries", count); // } // } catch (JAXBException | IOException e) { // LOGGER.info("Got exception reading CHB file", e); // } // return mapping; // } // // private static File getFile() { // File path = new File(Configuration.getChbPath()); // File[] fs = path.listFiles(); // if (fs == null || fs.length == 0) { // return null; // } // File chbFile = null; // for (File f : fs) { // if (chbFile == null && f.getName().startsWith("PassengerStopAssignmentExportCHB") && f.getName().endsWith("xml.gz")) { // chbFile = f; // } // } // if (chbFile != null) { // LOGGER.info("File to match {}", chbFile.getName()); // } else { // return null; // } // return chbFile; // } // // private static int handleExport(Map<String, String> mapping, Export export) { // int i[] = {0}; // export.getQuays().getQuay().forEach(q -> { // q.getUserstopcodes().getUserstopcodedata().forEach(usc -> { // mapping.put(usc.getDataownercode()+"|"+usc.getUserstopcode(), q.getQuaycode()); // // i[0] += 1; // }); // }); // return i[0]; // } // // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/chb/StopStore.java // public class StopStore { // // private static final Logger LOGGER = LoggerFactory.getLogger(StopStore.class); // // private static Map<String, String> store = new HashMap<>(); // private static Set<String> missing = new HashSet<>(); // // public static Optional<String> getQuayFromCode(String dataOwner, String stopCode) { // String key = dataOwner+"|"+stopCode; // if (store.containsKey(key)) { // return Optional.of(store.get(key)); // } // missing.add(key); // return Optional.empty(); // } // // public static boolean stopExists(String quayOrStopCode) { // return store.values().contains(quayOrStopCode); // } // // public static Map<String, String> getStore() { // return store; // } // // public static Set<String> getMissing() { // return missing; // } // // public static void setStore(Map<String, String> storeData) { // store = storeData; // } // } // Path: distribution/src/test/java/nl/crowndov/displaydirect/distribution/kv78/PlanningLoaderTest.java import nl.crowndov.displaydirect.distribution.chb.PassengerStopAssignmentLoader; import nl.crowndov.displaydirect.distribution.chb.StopStore; import com.netflix.config.ConfigurationManager; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.io.IOException; import java.util.Map; package nl.crowndov.displaydirect.distribution.kv78; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class PlanningLoaderTest { @Before public void setup() { try { ConfigurationManager.loadCascadedPropertiesFromResources("configuration"); } catch (IOException ignored) {} } @Test @Ignore public void testPlanningLoader() { Map<String,String> result = PassengerStopAssignmentLoader.load(); if (result.size() > 0) {
StopStore.setStore(result);
CROW-NDOV/displaydirect
distribution/src/main/java/nl/crowndov/displaydirect/distribution/kv78/PlanningMapper.java
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/chb/StopStore.java // public class StopStore { // // private static final Logger LOGGER = LoggerFactory.getLogger(StopStore.class); // // private static Map<String, String> store = new HashMap<>(); // private static Set<String> missing = new HashSet<>(); // // public static Optional<String> getQuayFromCode(String dataOwner, String stopCode) { // String key = dataOwner+"|"+stopCode; // if (store.containsKey(key)) { // return Optional.of(store.get(key)); // } // missing.add(key); // return Optional.empty(); // } // // public static boolean stopExists(String quayOrStopCode) { // return store.values().contains(quayOrStopCode); // } // // public static Map<String, String> getStore() { // return store; // } // // public static Set<String> getMissing() { // return missing; // } // // public static void setStore(Map<String, String> storeData) { // store = storeData; // } // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/util/DateTimeUtil.java // public class DateTimeUtil { // // public static ZonedDateTime getTime(LocalDate date, String time) { // String[] split = time.split(":"); // int hour = Integer.valueOf(split[0]); // boolean addDay = false; // if (hour > 23) { // hour = hour - 24; // addDay = true; // } // ZonedDateTime dateTime = ZonedDateTime.of(date, LocalTime.of(hour, Integer.valueOf(split[1]), Integer.valueOf(split[2])), Configuration.getZoneId()); // if (addDay) { // dateTime = dateTime.plusDays(1); // } // return dateTime; // } // // public static long getMinutesTill(String time) { // String[] split = time.split(":"); // return getMinutesTill(Integer.valueOf(split[0]), Integer.valueOf(split[1])); // } // // public static long getMinutesTill(int hour) { // return getMinutesTill(hour, 0); // } // // public static long getMinutesTill(int hour, int min) { // ZonedDateTime tomorrow = ZonedDateTime.now(Configuration.getZoneId()).plusDays(1).withHour(hour).withMinute(min); // return ChronoUnit.MINUTES.between(ZonedDateTime.now(Configuration.getZoneId()), tomorrow); // } // }
import nl.crowndov.displaydirect.distribution.chb.StopStore; import nl.crowndov.displaydirect.distribution.domain.travelinfo.*; import nl.crowndov.displaydirect.distribution.util.DateTimeUtil; import java.time.LocalDate; import java.time.ZonedDateTime; import java.util.Map; import java.util.Optional;
package nl.crowndov.displaydirect.distribution.kv78; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class PlanningMapper { public static PassTime passTime(LocalDate date, Map<String, String> r, ZonedDateTime generated) { PassTime pt = new PassTime(r.get("DataOwnerCode"), date, r.get("LinePlanningNumber"), Integer.valueOf(r.get("JourneyNumber")), r.get("UserStopCode"));
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/chb/StopStore.java // public class StopStore { // // private static final Logger LOGGER = LoggerFactory.getLogger(StopStore.class); // // private static Map<String, String> store = new HashMap<>(); // private static Set<String> missing = new HashSet<>(); // // public static Optional<String> getQuayFromCode(String dataOwner, String stopCode) { // String key = dataOwner+"|"+stopCode; // if (store.containsKey(key)) { // return Optional.of(store.get(key)); // } // missing.add(key); // return Optional.empty(); // } // // public static boolean stopExists(String quayOrStopCode) { // return store.values().contains(quayOrStopCode); // } // // public static Map<String, String> getStore() { // return store; // } // // public static Set<String> getMissing() { // return missing; // } // // public static void setStore(Map<String, String> storeData) { // store = storeData; // } // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/util/DateTimeUtil.java // public class DateTimeUtil { // // public static ZonedDateTime getTime(LocalDate date, String time) { // String[] split = time.split(":"); // int hour = Integer.valueOf(split[0]); // boolean addDay = false; // if (hour > 23) { // hour = hour - 24; // addDay = true; // } // ZonedDateTime dateTime = ZonedDateTime.of(date, LocalTime.of(hour, Integer.valueOf(split[1]), Integer.valueOf(split[2])), Configuration.getZoneId()); // if (addDay) { // dateTime = dateTime.plusDays(1); // } // return dateTime; // } // // public static long getMinutesTill(String time) { // String[] split = time.split(":"); // return getMinutesTill(Integer.valueOf(split[0]), Integer.valueOf(split[1])); // } // // public static long getMinutesTill(int hour) { // return getMinutesTill(hour, 0); // } // // public static long getMinutesTill(int hour, int min) { // ZonedDateTime tomorrow = ZonedDateTime.now(Configuration.getZoneId()).plusDays(1).withHour(hour).withMinute(min); // return ChronoUnit.MINUTES.between(ZonedDateTime.now(Configuration.getZoneId()), tomorrow); // } // } // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/kv78/PlanningMapper.java import nl.crowndov.displaydirect.distribution.chb.StopStore; import nl.crowndov.displaydirect.distribution.domain.travelinfo.*; import nl.crowndov.displaydirect.distribution.util.DateTimeUtil; import java.time.LocalDate; import java.time.ZonedDateTime; import java.util.Map; import java.util.Optional; package nl.crowndov.displaydirect.distribution.kv78; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class PlanningMapper { public static PassTime passTime(LocalDate date, Map<String, String> r, ZonedDateTime generated) { PassTime pt = new PassTime(r.get("DataOwnerCode"), date, r.get("LinePlanningNumber"), Integer.valueOf(r.get("JourneyNumber")), r.get("UserStopCode"));
pt.setTargetArrivalTime((int) DateTimeUtil.getTime(date, r.get("TargetArrivalTime")).toEpochSecond());
CROW-NDOV/displaydirect
distribution/src/main/java/nl/crowndov/displaydirect/distribution/kv78/PlanningMapper.java
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/chb/StopStore.java // public class StopStore { // // private static final Logger LOGGER = LoggerFactory.getLogger(StopStore.class); // // private static Map<String, String> store = new HashMap<>(); // private static Set<String> missing = new HashSet<>(); // // public static Optional<String> getQuayFromCode(String dataOwner, String stopCode) { // String key = dataOwner+"|"+stopCode; // if (store.containsKey(key)) { // return Optional.of(store.get(key)); // } // missing.add(key); // return Optional.empty(); // } // // public static boolean stopExists(String quayOrStopCode) { // return store.values().contains(quayOrStopCode); // } // // public static Map<String, String> getStore() { // return store; // } // // public static Set<String> getMissing() { // return missing; // } // // public static void setStore(Map<String, String> storeData) { // store = storeData; // } // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/util/DateTimeUtil.java // public class DateTimeUtil { // // public static ZonedDateTime getTime(LocalDate date, String time) { // String[] split = time.split(":"); // int hour = Integer.valueOf(split[0]); // boolean addDay = false; // if (hour > 23) { // hour = hour - 24; // addDay = true; // } // ZonedDateTime dateTime = ZonedDateTime.of(date, LocalTime.of(hour, Integer.valueOf(split[1]), Integer.valueOf(split[2])), Configuration.getZoneId()); // if (addDay) { // dateTime = dateTime.plusDays(1); // } // return dateTime; // } // // public static long getMinutesTill(String time) { // String[] split = time.split(":"); // return getMinutesTill(Integer.valueOf(split[0]), Integer.valueOf(split[1])); // } // // public static long getMinutesTill(int hour) { // return getMinutesTill(hour, 0); // } // // public static long getMinutesTill(int hour, int min) { // ZonedDateTime tomorrow = ZonedDateTime.now(Configuration.getZoneId()).plusDays(1).withHour(hour).withMinute(min); // return ChronoUnit.MINUTES.between(ZonedDateTime.now(Configuration.getZoneId()), tomorrow); // } // }
import nl.crowndov.displaydirect.distribution.chb.StopStore; import nl.crowndov.displaydirect.distribution.domain.travelinfo.*; import nl.crowndov.displaydirect.distribution.util.DateTimeUtil; import java.time.LocalDate; import java.time.ZonedDateTime; import java.util.Map; import java.util.Optional;
package nl.crowndov.displaydirect.distribution.kv78; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class PlanningMapper { public static PassTime passTime(LocalDate date, Map<String, String> r, ZonedDateTime generated) { PassTime pt = new PassTime(r.get("DataOwnerCode"), date, r.get("LinePlanningNumber"), Integer.valueOf(r.get("JourneyNumber")), r.get("UserStopCode")); pt.setTargetArrivalTime((int) DateTimeUtil.getTime(date, r.get("TargetArrivalTime")).toEpochSecond()); pt.setTargetDepartureTime((int) DateTimeUtil.getTime(date, r.get("TargetDepartureTime")).toEpochSecond()); if ("ACCESSIBLE".contentEquals(r.get("WheelChairAccessible"))) { pt.setWheelchairAccessible(true); } else if ("NOTACCESSIBLE".contentEquals(r.get("WheelChairAccessible"))) { pt.setWheelchairAccessible(false); } // Else null = unknown if (r.get("NumberOfCoaches") != null) { pt.setNumberOfCoaches(Integer.valueOf(r.get("NumberOfCoaches"))); }
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/chb/StopStore.java // public class StopStore { // // private static final Logger LOGGER = LoggerFactory.getLogger(StopStore.class); // // private static Map<String, String> store = new HashMap<>(); // private static Set<String> missing = new HashSet<>(); // // public static Optional<String> getQuayFromCode(String dataOwner, String stopCode) { // String key = dataOwner+"|"+stopCode; // if (store.containsKey(key)) { // return Optional.of(store.get(key)); // } // missing.add(key); // return Optional.empty(); // } // // public static boolean stopExists(String quayOrStopCode) { // return store.values().contains(quayOrStopCode); // } // // public static Map<String, String> getStore() { // return store; // } // // public static Set<String> getMissing() { // return missing; // } // // public static void setStore(Map<String, String> storeData) { // store = storeData; // } // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/util/DateTimeUtil.java // public class DateTimeUtil { // // public static ZonedDateTime getTime(LocalDate date, String time) { // String[] split = time.split(":"); // int hour = Integer.valueOf(split[0]); // boolean addDay = false; // if (hour > 23) { // hour = hour - 24; // addDay = true; // } // ZonedDateTime dateTime = ZonedDateTime.of(date, LocalTime.of(hour, Integer.valueOf(split[1]), Integer.valueOf(split[2])), Configuration.getZoneId()); // if (addDay) { // dateTime = dateTime.plusDays(1); // } // return dateTime; // } // // public static long getMinutesTill(String time) { // String[] split = time.split(":"); // return getMinutesTill(Integer.valueOf(split[0]), Integer.valueOf(split[1])); // } // // public static long getMinutesTill(int hour) { // return getMinutesTill(hour, 0); // } // // public static long getMinutesTill(int hour, int min) { // ZonedDateTime tomorrow = ZonedDateTime.now(Configuration.getZoneId()).plusDays(1).withHour(hour).withMinute(min); // return ChronoUnit.MINUTES.between(ZonedDateTime.now(Configuration.getZoneId()), tomorrow); // } // } // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/kv78/PlanningMapper.java import nl.crowndov.displaydirect.distribution.chb.StopStore; import nl.crowndov.displaydirect.distribution.domain.travelinfo.*; import nl.crowndov.displaydirect.distribution.util.DateTimeUtil; import java.time.LocalDate; import java.time.ZonedDateTime; import java.util.Map; import java.util.Optional; package nl.crowndov.displaydirect.distribution.kv78; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class PlanningMapper { public static PassTime passTime(LocalDate date, Map<String, String> r, ZonedDateTime generated) { PassTime pt = new PassTime(r.get("DataOwnerCode"), date, r.get("LinePlanningNumber"), Integer.valueOf(r.get("JourneyNumber")), r.get("UserStopCode")); pt.setTargetArrivalTime((int) DateTimeUtil.getTime(date, r.get("TargetArrivalTime")).toEpochSecond()); pt.setTargetDepartureTime((int) DateTimeUtil.getTime(date, r.get("TargetDepartureTime")).toEpochSecond()); if ("ACCESSIBLE".contentEquals(r.get("WheelChairAccessible"))) { pt.setWheelchairAccessible(true); } else if ("NOTACCESSIBLE".contentEquals(r.get("WheelChairAccessible"))) { pt.setWheelchairAccessible(false); } // Else null = unknown if (r.get("NumberOfCoaches") != null) { pt.setNumberOfCoaches(Integer.valueOf(r.get("NumberOfCoaches"))); }
Optional<String> quay = StopStore.getQuayFromCode(r.get("DataOwnerCode"), r.get("UserStopCode"));
CROW-NDOV/displaydirect
distribution/src/main/java/nl/crowndov/displaydirect/distribution/domain/client/Subscription.java
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/chb/StopStore.java // public class StopStore { // // private static final Logger LOGGER = LoggerFactory.getLogger(StopStore.class); // // private static Map<String, String> store = new HashMap<>(); // private static Set<String> missing = new HashSet<>(); // // public static Optional<String> getQuayFromCode(String dataOwner, String stopCode) { // String key = dataOwner+"|"+stopCode; // if (store.containsKey(key)) { // return Optional.of(store.get(key)); // } // missing.add(key); // return Optional.empty(); // } // // public static boolean stopExists(String quayOrStopCode) { // return store.values().contains(quayOrStopCode); // } // // public static Map<String, String> getStore() { // return store; // } // // public static Set<String> getMissing() { // return missing; // } // // public static void setStore(Map<String, String> storeData) { // store = storeData; // } // }
import nl.crowndov.displaydirect.distribution.chb.StopStore; import java.util.ArrayList; import java.util.List;
public FieldDelivery getGeneratedTimestamp() { return generatedTimestamp; } public void setGeneratedTimestamp(FieldDelivery generatedTimestamp) { this.generatedTimestamp = generatedTimestamp; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean isValid() { return email != null && subscribedQuayCodes != null && subscribedQuayCodes.size() >= 1; } public boolean hasValidStop() {
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/chb/StopStore.java // public class StopStore { // // private static final Logger LOGGER = LoggerFactory.getLogger(StopStore.class); // // private static Map<String, String> store = new HashMap<>(); // private static Set<String> missing = new HashSet<>(); // // public static Optional<String> getQuayFromCode(String dataOwner, String stopCode) { // String key = dataOwner+"|"+stopCode; // if (store.containsKey(key)) { // return Optional.of(store.get(key)); // } // missing.add(key); // return Optional.empty(); // } // // public static boolean stopExists(String quayOrStopCode) { // return store.values().contains(quayOrStopCode); // } // // public static Map<String, String> getStore() { // return store; // } // // public static Set<String> getMissing() { // return missing; // } // // public static void setStore(Map<String, String> storeData) { // store = storeData; // } // } // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/domain/client/Subscription.java import nl.crowndov.displaydirect.distribution.chb.StopStore; import java.util.ArrayList; import java.util.List; public FieldDelivery getGeneratedTimestamp() { return generatedTimestamp; } public void setGeneratedTimestamp(FieldDelivery generatedTimestamp) { this.generatedTimestamp = generatedTimestamp; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean isValid() { return email != null && subscribedQuayCodes != null && subscribedQuayCodes.size() >= 1; } public boolean hasValidStop() {
return subscribedQuayCodes.stream().allMatch(StopStore::stopExists);
CROW-NDOV/displaydirect
distribution/src/main/java/nl/crowndov/displaydirect/distribution/input/RealTimeProvider.java
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/util/CatchableRunnable.java // public class CatchableRunnable implements Runnable { // private final Runnable runnable; // private final Logger logger; // // public CatchableRunnable(Runnable runnable, Class c) { // this.runnable = runnable; // // Allow to customize the class used to log any error messages // this.logger = LoggerFactory.getLogger(c); // } // // public CatchableRunnable(Runnable runnable) { // this(runnable, CatchableRunnable.class); // } // // @Override // public void run() { // try { // runnable.run(); // } catch (Exception e) { // if (logger != null) { // logger.error("Failed to run task {}, got exception", runnable.toString(), e); // } // } // } // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/Configuration.java // public class Configuration { // // private static final Logger LOGGER = LoggerFactory.getLogger(Configuration.class); // // private static AbstractConfiguration config = ConfigurationManager.getConfigInstance(); // // public static List<String> getKvEndpoints() { // return Arrays.asList(config.getStringArray("distribution.kv78turbo.endpoints")); // } // // public static String[] getKvPublishers() { // return config.getStringArray("distribution.kv78turbo.publishers"); // } // // public static ZoneId getZoneId() { // return ZoneId.of(config.getString("distribution.timezone.default")); // } // // public static String getOutputTransport() { // return config.getString("distribution.transport", "mqtt"); // } // // public static String getMqttBrokerHost() { // return config.getString("distribution.mqtt.host", "localhost:1883"); // } // // public static int getZmqInternalPort() { // return 9800; // } // // public static String getMqttClientId() { // return config.getString("distribution.mqtt.client_id", "distribution"); // } // // public static int getAuthorizationTokenMaxAge() { // return config.getInt("distribution.authorization.max_age_hours"); // } // // public static List<String> getAuthorizationWhitelist() { // return Arrays.asList(config.getStringArray("distribution.authorization.whitelist_prefix")); // } // // public static String getBaseUrl() { // return config.getString("distribution.install.base_url", "http://localhost:8080"); // } // // public static String getSmtpUsername() { // return config.getString("distribution.smtp.username", null); // } // // public static String getSmtpPassword() { // return config.getString("distribution.smtp.password", null); // } // // public static String getSmtpFrom() { // return config.getString("distribution.smtp.from"); // } // // public static String getSmtpHostname() { // return config.getString("distribution.smtp.hostname"); // } // // public static String getSmtpReplyTo() { // return config.getString("distribution.smtp.reply_to"); // } // // public static boolean getSmtpSsl() { return config.getBoolean("distribution.smtp.ssl", false); } // // public static int getSmtpPort() { // return config.getInt("distribution.smtp.port", 25); // } // // public static int getSmtpConnectTimeout() { // return config.getInt("distribution.smtp.connect_timeout", 10*1000); // } // // public static String getFileBasePath() { // return config.getString("distribution.backup.path", System.getProperty("java.io.tmpdir")); // } // // public static String getKv7PlanningPath() { // return config.getString("distribution.kv78turbo.path.planning"); // } // // public static String getKv7CalendarPath() { // return config.getString("distribution.kv78turbo.path.calendar"); // } // // public static String getChbPath() { // return config.getString("distribution.chb.path"); // } // // // public static String getPlanningLoaderTime() { // return config.getString("distribution.planning.loadTime", "03:30"); // } // // public static String getPlanningCleanupTime() { // return config.getString("distribution.planning.cleanupTime", "04:00"); // } // // }
import nl.crowndov.displaydirect.distribution.util.CatchableRunnable; import nl.crowndov.displaydirect.distribution.Configuration; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
package nl.crowndov.displaydirect.distribution.input; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class RealTimeProvider { private static ExecutorService executor = Executors.newFixedThreadPool(2); private static Kv78ReceiveTask receive; private static Kv78ProcessTask process; public static void start() {
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/util/CatchableRunnable.java // public class CatchableRunnable implements Runnable { // private final Runnable runnable; // private final Logger logger; // // public CatchableRunnable(Runnable runnable, Class c) { // this.runnable = runnable; // // Allow to customize the class used to log any error messages // this.logger = LoggerFactory.getLogger(c); // } // // public CatchableRunnable(Runnable runnable) { // this(runnable, CatchableRunnable.class); // } // // @Override // public void run() { // try { // runnable.run(); // } catch (Exception e) { // if (logger != null) { // logger.error("Failed to run task {}, got exception", runnable.toString(), e); // } // } // } // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/Configuration.java // public class Configuration { // // private static final Logger LOGGER = LoggerFactory.getLogger(Configuration.class); // // private static AbstractConfiguration config = ConfigurationManager.getConfigInstance(); // // public static List<String> getKvEndpoints() { // return Arrays.asList(config.getStringArray("distribution.kv78turbo.endpoints")); // } // // public static String[] getKvPublishers() { // return config.getStringArray("distribution.kv78turbo.publishers"); // } // // public static ZoneId getZoneId() { // return ZoneId.of(config.getString("distribution.timezone.default")); // } // // public static String getOutputTransport() { // return config.getString("distribution.transport", "mqtt"); // } // // public static String getMqttBrokerHost() { // return config.getString("distribution.mqtt.host", "localhost:1883"); // } // // public static int getZmqInternalPort() { // return 9800; // } // // public static String getMqttClientId() { // return config.getString("distribution.mqtt.client_id", "distribution"); // } // // public static int getAuthorizationTokenMaxAge() { // return config.getInt("distribution.authorization.max_age_hours"); // } // // public static List<String> getAuthorizationWhitelist() { // return Arrays.asList(config.getStringArray("distribution.authorization.whitelist_prefix")); // } // // public static String getBaseUrl() { // return config.getString("distribution.install.base_url", "http://localhost:8080"); // } // // public static String getSmtpUsername() { // return config.getString("distribution.smtp.username", null); // } // // public static String getSmtpPassword() { // return config.getString("distribution.smtp.password", null); // } // // public static String getSmtpFrom() { // return config.getString("distribution.smtp.from"); // } // // public static String getSmtpHostname() { // return config.getString("distribution.smtp.hostname"); // } // // public static String getSmtpReplyTo() { // return config.getString("distribution.smtp.reply_to"); // } // // public static boolean getSmtpSsl() { return config.getBoolean("distribution.smtp.ssl", false); } // // public static int getSmtpPort() { // return config.getInt("distribution.smtp.port", 25); // } // // public static int getSmtpConnectTimeout() { // return config.getInt("distribution.smtp.connect_timeout", 10*1000); // } // // public static String getFileBasePath() { // return config.getString("distribution.backup.path", System.getProperty("java.io.tmpdir")); // } // // public static String getKv7PlanningPath() { // return config.getString("distribution.kv78turbo.path.planning"); // } // // public static String getKv7CalendarPath() { // return config.getString("distribution.kv78turbo.path.calendar"); // } // // public static String getChbPath() { // return config.getString("distribution.chb.path"); // } // // // public static String getPlanningLoaderTime() { // return config.getString("distribution.planning.loadTime", "03:30"); // } // // public static String getPlanningCleanupTime() { // return config.getString("distribution.planning.cleanupTime", "04:00"); // } // // } // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/input/RealTimeProvider.java import nl.crowndov.displaydirect.distribution.util.CatchableRunnable; import nl.crowndov.displaydirect.distribution.Configuration; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; package nl.crowndov.displaydirect.distribution.input; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class RealTimeProvider { private static ExecutorService executor = Executors.newFixedThreadPool(2); private static Kv78ReceiveTask receive; private static Kv78ProcessTask process; public static void start() {
receive = new Kv78ReceiveTask(Configuration.getZmqInternalPort());
CROW-NDOV/displaydirect
distribution/src/main/java/nl/crowndov/displaydirect/distribution/input/RealTimeProvider.java
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/util/CatchableRunnable.java // public class CatchableRunnable implements Runnable { // private final Runnable runnable; // private final Logger logger; // // public CatchableRunnable(Runnable runnable, Class c) { // this.runnable = runnable; // // Allow to customize the class used to log any error messages // this.logger = LoggerFactory.getLogger(c); // } // // public CatchableRunnable(Runnable runnable) { // this(runnable, CatchableRunnable.class); // } // // @Override // public void run() { // try { // runnable.run(); // } catch (Exception e) { // if (logger != null) { // logger.error("Failed to run task {}, got exception", runnable.toString(), e); // } // } // } // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/Configuration.java // public class Configuration { // // private static final Logger LOGGER = LoggerFactory.getLogger(Configuration.class); // // private static AbstractConfiguration config = ConfigurationManager.getConfigInstance(); // // public static List<String> getKvEndpoints() { // return Arrays.asList(config.getStringArray("distribution.kv78turbo.endpoints")); // } // // public static String[] getKvPublishers() { // return config.getStringArray("distribution.kv78turbo.publishers"); // } // // public static ZoneId getZoneId() { // return ZoneId.of(config.getString("distribution.timezone.default")); // } // // public static String getOutputTransport() { // return config.getString("distribution.transport", "mqtt"); // } // // public static String getMqttBrokerHost() { // return config.getString("distribution.mqtt.host", "localhost:1883"); // } // // public static int getZmqInternalPort() { // return 9800; // } // // public static String getMqttClientId() { // return config.getString("distribution.mqtt.client_id", "distribution"); // } // // public static int getAuthorizationTokenMaxAge() { // return config.getInt("distribution.authorization.max_age_hours"); // } // // public static List<String> getAuthorizationWhitelist() { // return Arrays.asList(config.getStringArray("distribution.authorization.whitelist_prefix")); // } // // public static String getBaseUrl() { // return config.getString("distribution.install.base_url", "http://localhost:8080"); // } // // public static String getSmtpUsername() { // return config.getString("distribution.smtp.username", null); // } // // public static String getSmtpPassword() { // return config.getString("distribution.smtp.password", null); // } // // public static String getSmtpFrom() { // return config.getString("distribution.smtp.from"); // } // // public static String getSmtpHostname() { // return config.getString("distribution.smtp.hostname"); // } // // public static String getSmtpReplyTo() { // return config.getString("distribution.smtp.reply_to"); // } // // public static boolean getSmtpSsl() { return config.getBoolean("distribution.smtp.ssl", false); } // // public static int getSmtpPort() { // return config.getInt("distribution.smtp.port", 25); // } // // public static int getSmtpConnectTimeout() { // return config.getInt("distribution.smtp.connect_timeout", 10*1000); // } // // public static String getFileBasePath() { // return config.getString("distribution.backup.path", System.getProperty("java.io.tmpdir")); // } // // public static String getKv7PlanningPath() { // return config.getString("distribution.kv78turbo.path.planning"); // } // // public static String getKv7CalendarPath() { // return config.getString("distribution.kv78turbo.path.calendar"); // } // // public static String getChbPath() { // return config.getString("distribution.chb.path"); // } // // // public static String getPlanningLoaderTime() { // return config.getString("distribution.planning.loadTime", "03:30"); // } // // public static String getPlanningCleanupTime() { // return config.getString("distribution.planning.cleanupTime", "04:00"); // } // // }
import nl.crowndov.displaydirect.distribution.util.CatchableRunnable; import nl.crowndov.displaydirect.distribution.Configuration; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
package nl.crowndov.displaydirect.distribution.input; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class RealTimeProvider { private static ExecutorService executor = Executors.newFixedThreadPool(2); private static Kv78ReceiveTask receive; private static Kv78ProcessTask process; public static void start() { receive = new Kv78ReceiveTask(Configuration.getZmqInternalPort()); process = new Kv78ProcessTask(Configuration.getZmqInternalPort());
// Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/util/CatchableRunnable.java // public class CatchableRunnable implements Runnable { // private final Runnable runnable; // private final Logger logger; // // public CatchableRunnable(Runnable runnable, Class c) { // this.runnable = runnable; // // Allow to customize the class used to log any error messages // this.logger = LoggerFactory.getLogger(c); // } // // public CatchableRunnable(Runnable runnable) { // this(runnable, CatchableRunnable.class); // } // // @Override // public void run() { // try { // runnable.run(); // } catch (Exception e) { // if (logger != null) { // logger.error("Failed to run task {}, got exception", runnable.toString(), e); // } // } // } // } // // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/Configuration.java // public class Configuration { // // private static final Logger LOGGER = LoggerFactory.getLogger(Configuration.class); // // private static AbstractConfiguration config = ConfigurationManager.getConfigInstance(); // // public static List<String> getKvEndpoints() { // return Arrays.asList(config.getStringArray("distribution.kv78turbo.endpoints")); // } // // public static String[] getKvPublishers() { // return config.getStringArray("distribution.kv78turbo.publishers"); // } // // public static ZoneId getZoneId() { // return ZoneId.of(config.getString("distribution.timezone.default")); // } // // public static String getOutputTransport() { // return config.getString("distribution.transport", "mqtt"); // } // // public static String getMqttBrokerHost() { // return config.getString("distribution.mqtt.host", "localhost:1883"); // } // // public static int getZmqInternalPort() { // return 9800; // } // // public static String getMqttClientId() { // return config.getString("distribution.mqtt.client_id", "distribution"); // } // // public static int getAuthorizationTokenMaxAge() { // return config.getInt("distribution.authorization.max_age_hours"); // } // // public static List<String> getAuthorizationWhitelist() { // return Arrays.asList(config.getStringArray("distribution.authorization.whitelist_prefix")); // } // // public static String getBaseUrl() { // return config.getString("distribution.install.base_url", "http://localhost:8080"); // } // // public static String getSmtpUsername() { // return config.getString("distribution.smtp.username", null); // } // // public static String getSmtpPassword() { // return config.getString("distribution.smtp.password", null); // } // // public static String getSmtpFrom() { // return config.getString("distribution.smtp.from"); // } // // public static String getSmtpHostname() { // return config.getString("distribution.smtp.hostname"); // } // // public static String getSmtpReplyTo() { // return config.getString("distribution.smtp.reply_to"); // } // // public static boolean getSmtpSsl() { return config.getBoolean("distribution.smtp.ssl", false); } // // public static int getSmtpPort() { // return config.getInt("distribution.smtp.port", 25); // } // // public static int getSmtpConnectTimeout() { // return config.getInt("distribution.smtp.connect_timeout", 10*1000); // } // // public static String getFileBasePath() { // return config.getString("distribution.backup.path", System.getProperty("java.io.tmpdir")); // } // // public static String getKv7PlanningPath() { // return config.getString("distribution.kv78turbo.path.planning"); // } // // public static String getKv7CalendarPath() { // return config.getString("distribution.kv78turbo.path.calendar"); // } // // public static String getChbPath() { // return config.getString("distribution.chb.path"); // } // // // public static String getPlanningLoaderTime() { // return config.getString("distribution.planning.loadTime", "03:30"); // } // // public static String getPlanningCleanupTime() { // return config.getString("distribution.planning.cleanupTime", "04:00"); // } // // } // Path: distribution/src/main/java/nl/crowndov/displaydirect/distribution/input/RealTimeProvider.java import nl.crowndov.displaydirect.distribution.util.CatchableRunnable; import nl.crowndov.displaydirect.distribution.Configuration; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; package nl.crowndov.displaydirect.distribution.input; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class RealTimeProvider { private static ExecutorService executor = Executors.newFixedThreadPool(2); private static Kv78ReceiveTask receive; private static Kv78ProcessTask process; public static void start() { receive = new Kv78ReceiveTask(Configuration.getZmqInternalPort()); process = new Kv78ProcessTask(Configuration.getZmqInternalPort());
executor.submit(new CatchableRunnable(receive, RealTimeProvider.class));
CROW-NDOV/displaydirect
common_client/src/main/java/nl/crowndov/displaydirect/commonclient/client/DisplayConfiguration.java
// Path: common_client/src/main/java/nl/crowndov/displaydirect/commonclient/configuration/DisplayParameters.java // public interface DisplayParameters { // // /* ALTERBEST */ long getDestinationAlternatingSeconds(); // // /* TOONTIJD */ long getJourneyMinimumDepartureMinutes(); // // /* TOONMAX */ long getMaxCombinedDirections(); // // /* SNELWIS */ boolean hideJourneyOnArrival(); // // /* VERTREKTIMEOUT */ long getDepartureTimeoutSeconds(); // // /* RITRESET */ long getJourneyTimeoutSeconds(); // // /* INDICATORVANAF */ long getUnplannedJourneyTimeoutSeconds(); // // /* VERVALTWEERGAVE */ boolean showCancelledTrip(); // // /* WITREGEL */ boolean showBlankLine(); // // /* VRIJETEKSTTIMEOUT */ int getGeneralMessageTimeoutMinutes(); // // /* KEEPALIVETIME */ int getMqttKeepaliveTime(); // } // // Path: common_client/src/main/java/nl/crowndov/displaydirect/commonclient/configuration/SystemParameters.java // public interface SystemParameters { // // // String getConnectionString(); // In the form of hostname, hostname:port or tls://hostname:port // // List<String> getStopCodes(); // // String getEmail(); // // String getDescription(); // // String getSessionId(); // This should consist of group_id, eg. OPENGEO_123 // // String getClientGroup(); // // String getClientId(); // // int getSubscriptionRetryMinutes(); // }
import nl.crowndov.displaydirect.commonclient.configuration.DisplayParameters; import nl.crowndov.displaydirect.commonclient.configuration.SystemParameters; import java.time.ZoneId;
package nl.crowndov.displaydirect.commonclient.client; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class DisplayConfiguration { private static DisplayParameters display;
// Path: common_client/src/main/java/nl/crowndov/displaydirect/commonclient/configuration/DisplayParameters.java // public interface DisplayParameters { // // /* ALTERBEST */ long getDestinationAlternatingSeconds(); // // /* TOONTIJD */ long getJourneyMinimumDepartureMinutes(); // // /* TOONMAX */ long getMaxCombinedDirections(); // // /* SNELWIS */ boolean hideJourneyOnArrival(); // // /* VERTREKTIMEOUT */ long getDepartureTimeoutSeconds(); // // /* RITRESET */ long getJourneyTimeoutSeconds(); // // /* INDICATORVANAF */ long getUnplannedJourneyTimeoutSeconds(); // // /* VERVALTWEERGAVE */ boolean showCancelledTrip(); // // /* WITREGEL */ boolean showBlankLine(); // // /* VRIJETEKSTTIMEOUT */ int getGeneralMessageTimeoutMinutes(); // // /* KEEPALIVETIME */ int getMqttKeepaliveTime(); // } // // Path: common_client/src/main/java/nl/crowndov/displaydirect/commonclient/configuration/SystemParameters.java // public interface SystemParameters { // // // String getConnectionString(); // In the form of hostname, hostname:port or tls://hostname:port // // List<String> getStopCodes(); // // String getEmail(); // // String getDescription(); // // String getSessionId(); // This should consist of group_id, eg. OPENGEO_123 // // String getClientGroup(); // // String getClientId(); // // int getSubscriptionRetryMinutes(); // } // Path: common_client/src/main/java/nl/crowndov/displaydirect/commonclient/client/DisplayConfiguration.java import nl.crowndov.displaydirect.commonclient.configuration.DisplayParameters; import nl.crowndov.displaydirect.commonclient.configuration.SystemParameters; import java.time.ZoneId; package nl.crowndov.displaydirect.commonclient.client; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ public class DisplayConfiguration { private static DisplayParameters display;
private static SystemParameters system;
CROW-NDOV/displaydirect
virtual_screen/src/main/java/nl/crowndov/displaydirect/virtual_screen/resources/DepartureResource.java
// Path: common_client/src/main/java/nl/crowndov/displaydirect/commonclient/store/DataStore.java // public class DataStore { // // private static Map<Integer, PassTime> departures = new HashMap<>(); // // public static void apply(PassTime p) { // if (p.getStatus() == DisplayDirectMessage.PassingTimes.TripStopStatus.DELETED) { // departures.remove(p.getPassTimeHash()); // } else { // departures.put(p.getPassTimeHash(), p); // } // } // // public static void apply(List<PassTime> p) { // p.forEach(DataStore::apply); // } // // public static List<PassTime> getDepartures() { // return departures.values().stream() // .filter(PassTime::isCurrent) // .sorted(Comparator.comparingInt(PassTime::getExpectedDepartureTime)) // .limit(11) // .collect(Collectors.toList()); // } // // // public static Collection<PassTime> getAll() { // return departures.values(); // } // }
import nl.crowndov.displaydirect.commonclient.store.DataStore; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response;
package nl.crowndov.displaydirect.virtual_screen.resources; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ @Path("/v1/departures") @Produces(MediaType.APPLICATION_JSON) public class DepartureResource { @GET public Response getDepartures() {
// Path: common_client/src/main/java/nl/crowndov/displaydirect/commonclient/store/DataStore.java // public class DataStore { // // private static Map<Integer, PassTime> departures = new HashMap<>(); // // public static void apply(PassTime p) { // if (p.getStatus() == DisplayDirectMessage.PassingTimes.TripStopStatus.DELETED) { // departures.remove(p.getPassTimeHash()); // } else { // departures.put(p.getPassTimeHash(), p); // } // } // // public static void apply(List<PassTime> p) { // p.forEach(DataStore::apply); // } // // public static List<PassTime> getDepartures() { // return departures.values().stream() // .filter(PassTime::isCurrent) // .sorted(Comparator.comparingInt(PassTime::getExpectedDepartureTime)) // .limit(11) // .collect(Collectors.toList()); // } // // // public static Collection<PassTime> getAll() { // return departures.values(); // } // } // Path: virtual_screen/src/main/java/nl/crowndov/displaydirect/virtual_screen/resources/DepartureResource.java import nl.crowndov.displaydirect.commonclient.store.DataStore; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; package nl.crowndov.displaydirect.virtual_screen.resources; /** * Copyright 2017 CROW-NDOV * * This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package. */ @Path("/v1/departures") @Produces(MediaType.APPLICATION_JSON) public class DepartureResource { @GET public Response getDepartures() {
return Response.ok(DataStore.getDepartures()).build();
VisualizeMobile/AKANAndroid
src/br/com/visualize/akan/domain/model/Statistic.java
// Path: src/br/com/visualize/akan/domain/enumeration/Month.java // public enum Month { // WITHOUT_MONTH( 0 ), // // JANUARY( 1 ), // FEBRUARY( 2 ), // MARCH( 3 ), // // APRIL( 4 ), // MAY( 5 ), // JUNE( 6 ), // // JULY( 7 ), // AUGUST( 8 ), // SEPTEMBER( 9 ), // // OCTOBER( 10 ), // NOVEMBER( 11 ), // DECEMBER( 12 ); // // private int valueMonth; // // Month( int value ) { // valueMonth = value; // } // // /** // * Return the numerical value of the month. // * // * @return The numerical value of the month. // */ // public int getvalueMonth() { // return valueMonth; // } // } // // Path: src/br/com/visualize/akan/domain/enumeration/SubQuota.java // public enum SubQuota { // WITHOUT_TYPE( 0 ), // OFFICE( 1, "office" ), // FUEL( 3, "fuel" ), // // TECHNICAL_WORK_AND_CONSULTING( 4, "technical_work_and_consulting" ), // DISCLOSURE_PARLIAMENTARY_ACTIVITY( 5, "disclosure_parliamentary_activity" ), // SAFETY( 8, "safety" ), // // AIR_FREIGHT( 119, "air_freight" ), // TELEPHONY( 10, "telephony" ), // POSTAL_SERVICES( 11, "postal_services" ), // // SIGNATURE_OF_PUBLICATION( 12, "signature_of_publication" ), // ALIMENTATION( 13, "alimentation" ), // ACCOMMODATION( 14, "accommodation" ), // // LEASE_OF_VEHICLES( 15, "lease_of_vehicles" ), // ISSUANCE_OF_AIR_TICKETS( 9, "issuance_of_air_tickets" ); // // private int valueSubQuota; // private String representativeName; // // SubQuota( int value ) { // valueSubQuota = value; // } // // SubQuota( int value, String name ) { // this.valueSubQuota = value; // this.representativeName = name; // } // // /** // * Return the numerical value of the sub-quota that represent it in database. // * // * @return The numerical value of the sub-quota that represent it in database. // */ // public int getValueSubQuota() { // return valueSubQuota; // } // // /** // * Return a name that represent the sub-quota. // * // * @return The name that represent this sub-quota. // */ // public String getRepresentativeNameQuota() { // return representativeName; // } // }
import br.com.visualize.akan.domain.enumeration.Month; import br.com.visualize.akan.domain.enumeration.SubQuota;
package br.com.visualize.akan.domain.model; public class Statistic { private SubQuota subquota; private int idStatistic; private int year;
// Path: src/br/com/visualize/akan/domain/enumeration/Month.java // public enum Month { // WITHOUT_MONTH( 0 ), // // JANUARY( 1 ), // FEBRUARY( 2 ), // MARCH( 3 ), // // APRIL( 4 ), // MAY( 5 ), // JUNE( 6 ), // // JULY( 7 ), // AUGUST( 8 ), // SEPTEMBER( 9 ), // // OCTOBER( 10 ), // NOVEMBER( 11 ), // DECEMBER( 12 ); // // private int valueMonth; // // Month( int value ) { // valueMonth = value; // } // // /** // * Return the numerical value of the month. // * // * @return The numerical value of the month. // */ // public int getvalueMonth() { // return valueMonth; // } // } // // Path: src/br/com/visualize/akan/domain/enumeration/SubQuota.java // public enum SubQuota { // WITHOUT_TYPE( 0 ), // OFFICE( 1, "office" ), // FUEL( 3, "fuel" ), // // TECHNICAL_WORK_AND_CONSULTING( 4, "technical_work_and_consulting" ), // DISCLOSURE_PARLIAMENTARY_ACTIVITY( 5, "disclosure_parliamentary_activity" ), // SAFETY( 8, "safety" ), // // AIR_FREIGHT( 119, "air_freight" ), // TELEPHONY( 10, "telephony" ), // POSTAL_SERVICES( 11, "postal_services" ), // // SIGNATURE_OF_PUBLICATION( 12, "signature_of_publication" ), // ALIMENTATION( 13, "alimentation" ), // ACCOMMODATION( 14, "accommodation" ), // // LEASE_OF_VEHICLES( 15, "lease_of_vehicles" ), // ISSUANCE_OF_AIR_TICKETS( 9, "issuance_of_air_tickets" ); // // private int valueSubQuota; // private String representativeName; // // SubQuota( int value ) { // valueSubQuota = value; // } // // SubQuota( int value, String name ) { // this.valueSubQuota = value; // this.representativeName = name; // } // // /** // * Return the numerical value of the sub-quota that represent it in database. // * // * @return The numerical value of the sub-quota that represent it in database. // */ // public int getValueSubQuota() { // return valueSubQuota; // } // // /** // * Return a name that represent the sub-quota. // * // * @return The name that represent this sub-quota. // */ // public String getRepresentativeNameQuota() { // return representativeName; // } // } // Path: src/br/com/visualize/akan/domain/model/Statistic.java import br.com.visualize.akan.domain.enumeration.Month; import br.com.visualize.akan.domain.enumeration.SubQuota; package br.com.visualize.akan.domain.model; public class Statistic { private SubQuota subquota; private int idStatistic; private int year;
private Month month;
VisualizeMobile/AKANAndroid
src/br/com/visualize/akan/domain/model/Quota.java
// Path: src/br/com/visualize/akan/domain/enumeration/Month.java // public enum Month { // WITHOUT_MONTH( 0 ), // // JANUARY( 1 ), // FEBRUARY( 2 ), // MARCH( 3 ), // // APRIL( 4 ), // MAY( 5 ), // JUNE( 6 ), // // JULY( 7 ), // AUGUST( 8 ), // SEPTEMBER( 9 ), // // OCTOBER( 10 ), // NOVEMBER( 11 ), // DECEMBER( 12 ); // // private int valueMonth; // // Month( int value ) { // valueMonth = value; // } // // /** // * Return the numerical value of the month. // * // * @return The numerical value of the month. // */ // public int getvalueMonth() { // return valueMonth; // } // } // // Path: src/br/com/visualize/akan/domain/enumeration/SubQuota.java // public enum SubQuota { // WITHOUT_TYPE( 0 ), // OFFICE( 1, "office" ), // FUEL( 3, "fuel" ), // // TECHNICAL_WORK_AND_CONSULTING( 4, "technical_work_and_consulting" ), // DISCLOSURE_PARLIAMENTARY_ACTIVITY( 5, "disclosure_parliamentary_activity" ), // SAFETY( 8, "safety" ), // // AIR_FREIGHT( 119, "air_freight" ), // TELEPHONY( 10, "telephony" ), // POSTAL_SERVICES( 11, "postal_services" ), // // SIGNATURE_OF_PUBLICATION( 12, "signature_of_publication" ), // ALIMENTATION( 13, "alimentation" ), // ACCOMMODATION( 14, "accommodation" ), // // LEASE_OF_VEHICLES( 15, "lease_of_vehicles" ), // ISSUANCE_OF_AIR_TICKETS( 9, "issuance_of_air_tickets" ); // // private int valueSubQuota; // private String representativeName; // // SubQuota( int value ) { // valueSubQuota = value; // } // // SubQuota( int value, String name ) { // this.valueSubQuota = value; // this.representativeName = name; // } // // /** // * Return the numerical value of the sub-quota that represent it in database. // * // * @return The numerical value of the sub-quota that represent it in database. // */ // public int getValueSubQuota() { // return valueSubQuota; // } // // /** // * Return a name that represent the sub-quota. // * // * @return The name that represent this sub-quota. // */ // public String getRepresentativeNameQuota() { // return representativeName; // } // }
import br.com.visualize.akan.domain.enumeration.Month; import br.com.visualize.akan.domain.enumeration.SubQuota;
/* * File: Quota.java * Purpose: Bringing the implementation of model Quota, a class that directly * references the business domain. */ package br.com.visualize.akan.domain.model; /** * This class represents the model of quota for application. It contains the * essential data to represent and maintain a quota. */ public class Quota { private int idQuota = 0; private int idCongressman = 0; private int idUpdateQuota = 0;
// Path: src/br/com/visualize/akan/domain/enumeration/Month.java // public enum Month { // WITHOUT_MONTH( 0 ), // // JANUARY( 1 ), // FEBRUARY( 2 ), // MARCH( 3 ), // // APRIL( 4 ), // MAY( 5 ), // JUNE( 6 ), // // JULY( 7 ), // AUGUST( 8 ), // SEPTEMBER( 9 ), // // OCTOBER( 10 ), // NOVEMBER( 11 ), // DECEMBER( 12 ); // // private int valueMonth; // // Month( int value ) { // valueMonth = value; // } // // /** // * Return the numerical value of the month. // * // * @return The numerical value of the month. // */ // public int getvalueMonth() { // return valueMonth; // } // } // // Path: src/br/com/visualize/akan/domain/enumeration/SubQuota.java // public enum SubQuota { // WITHOUT_TYPE( 0 ), // OFFICE( 1, "office" ), // FUEL( 3, "fuel" ), // // TECHNICAL_WORK_AND_CONSULTING( 4, "technical_work_and_consulting" ), // DISCLOSURE_PARLIAMENTARY_ACTIVITY( 5, "disclosure_parliamentary_activity" ), // SAFETY( 8, "safety" ), // // AIR_FREIGHT( 119, "air_freight" ), // TELEPHONY( 10, "telephony" ), // POSTAL_SERVICES( 11, "postal_services" ), // // SIGNATURE_OF_PUBLICATION( 12, "signature_of_publication" ), // ALIMENTATION( 13, "alimentation" ), // ACCOMMODATION( 14, "accommodation" ), // // LEASE_OF_VEHICLES( 15, "lease_of_vehicles" ), // ISSUANCE_OF_AIR_TICKETS( 9, "issuance_of_air_tickets" ); // // private int valueSubQuota; // private String representativeName; // // SubQuota( int value ) { // valueSubQuota = value; // } // // SubQuota( int value, String name ) { // this.valueSubQuota = value; // this.representativeName = name; // } // // /** // * Return the numerical value of the sub-quota that represent it in database. // * // * @return The numerical value of the sub-quota that represent it in database. // */ // public int getValueSubQuota() { // return valueSubQuota; // } // // /** // * Return a name that represent the sub-quota. // * // * @return The name that represent this sub-quota. // */ // public String getRepresentativeNameQuota() { // return representativeName; // } // } // Path: src/br/com/visualize/akan/domain/model/Quota.java import br.com.visualize.akan.domain.enumeration.Month; import br.com.visualize.akan.domain.enumeration.SubQuota; /* * File: Quota.java * Purpose: Bringing the implementation of model Quota, a class that directly * references the business domain. */ package br.com.visualize.akan.domain.model; /** * This class represents the model of quota for application. It contains the * essential data to represent and maintain a quota. */ public class Quota { private int idQuota = 0; private int idCongressman = 0; private int idUpdateQuota = 0;
private SubQuota typeQuota = SubQuota.WITHOUT_TYPE;
VisualizeMobile/AKANAndroid
src/br/com/visualize/akan/domain/model/Quota.java
// Path: src/br/com/visualize/akan/domain/enumeration/Month.java // public enum Month { // WITHOUT_MONTH( 0 ), // // JANUARY( 1 ), // FEBRUARY( 2 ), // MARCH( 3 ), // // APRIL( 4 ), // MAY( 5 ), // JUNE( 6 ), // // JULY( 7 ), // AUGUST( 8 ), // SEPTEMBER( 9 ), // // OCTOBER( 10 ), // NOVEMBER( 11 ), // DECEMBER( 12 ); // // private int valueMonth; // // Month( int value ) { // valueMonth = value; // } // // /** // * Return the numerical value of the month. // * // * @return The numerical value of the month. // */ // public int getvalueMonth() { // return valueMonth; // } // } // // Path: src/br/com/visualize/akan/domain/enumeration/SubQuota.java // public enum SubQuota { // WITHOUT_TYPE( 0 ), // OFFICE( 1, "office" ), // FUEL( 3, "fuel" ), // // TECHNICAL_WORK_AND_CONSULTING( 4, "technical_work_and_consulting" ), // DISCLOSURE_PARLIAMENTARY_ACTIVITY( 5, "disclosure_parliamentary_activity" ), // SAFETY( 8, "safety" ), // // AIR_FREIGHT( 119, "air_freight" ), // TELEPHONY( 10, "telephony" ), // POSTAL_SERVICES( 11, "postal_services" ), // // SIGNATURE_OF_PUBLICATION( 12, "signature_of_publication" ), // ALIMENTATION( 13, "alimentation" ), // ACCOMMODATION( 14, "accommodation" ), // // LEASE_OF_VEHICLES( 15, "lease_of_vehicles" ), // ISSUANCE_OF_AIR_TICKETS( 9, "issuance_of_air_tickets" ); // // private int valueSubQuota; // private String representativeName; // // SubQuota( int value ) { // valueSubQuota = value; // } // // SubQuota( int value, String name ) { // this.valueSubQuota = value; // this.representativeName = name; // } // // /** // * Return the numerical value of the sub-quota that represent it in database. // * // * @return The numerical value of the sub-quota that represent it in database. // */ // public int getValueSubQuota() { // return valueSubQuota; // } // // /** // * Return a name that represent the sub-quota. // * // * @return The name that represent this sub-quota. // */ // public String getRepresentativeNameQuota() { // return representativeName; // } // }
import br.com.visualize.akan.domain.enumeration.Month; import br.com.visualize.akan.domain.enumeration.SubQuota;
/* * File: Quota.java * Purpose: Bringing the implementation of model Quota, a class that directly * references the business domain. */ package br.com.visualize.akan.domain.model; /** * This class represents the model of quota for application. It contains the * essential data to represent and maintain a quota. */ public class Quota { private int idQuota = 0; private int idCongressman = 0; private int idUpdateQuota = 0; private SubQuota typeQuota = SubQuota.WITHOUT_TYPE;
// Path: src/br/com/visualize/akan/domain/enumeration/Month.java // public enum Month { // WITHOUT_MONTH( 0 ), // // JANUARY( 1 ), // FEBRUARY( 2 ), // MARCH( 3 ), // // APRIL( 4 ), // MAY( 5 ), // JUNE( 6 ), // // JULY( 7 ), // AUGUST( 8 ), // SEPTEMBER( 9 ), // // OCTOBER( 10 ), // NOVEMBER( 11 ), // DECEMBER( 12 ); // // private int valueMonth; // // Month( int value ) { // valueMonth = value; // } // // /** // * Return the numerical value of the month. // * // * @return The numerical value of the month. // */ // public int getvalueMonth() { // return valueMonth; // } // } // // Path: src/br/com/visualize/akan/domain/enumeration/SubQuota.java // public enum SubQuota { // WITHOUT_TYPE( 0 ), // OFFICE( 1, "office" ), // FUEL( 3, "fuel" ), // // TECHNICAL_WORK_AND_CONSULTING( 4, "technical_work_and_consulting" ), // DISCLOSURE_PARLIAMENTARY_ACTIVITY( 5, "disclosure_parliamentary_activity" ), // SAFETY( 8, "safety" ), // // AIR_FREIGHT( 119, "air_freight" ), // TELEPHONY( 10, "telephony" ), // POSTAL_SERVICES( 11, "postal_services" ), // // SIGNATURE_OF_PUBLICATION( 12, "signature_of_publication" ), // ALIMENTATION( 13, "alimentation" ), // ACCOMMODATION( 14, "accommodation" ), // // LEASE_OF_VEHICLES( 15, "lease_of_vehicles" ), // ISSUANCE_OF_AIR_TICKETS( 9, "issuance_of_air_tickets" ); // // private int valueSubQuota; // private String representativeName; // // SubQuota( int value ) { // valueSubQuota = value; // } // // SubQuota( int value, String name ) { // this.valueSubQuota = value; // this.representativeName = name; // } // // /** // * Return the numerical value of the sub-quota that represent it in database. // * // * @return The numerical value of the sub-quota that represent it in database. // */ // public int getValueSubQuota() { // return valueSubQuota; // } // // /** // * Return a name that represent the sub-quota. // * // * @return The name that represent this sub-quota. // */ // public String getRepresentativeNameQuota() { // return representativeName; // } // } // Path: src/br/com/visualize/akan/domain/model/Quota.java import br.com.visualize.akan.domain.enumeration.Month; import br.com.visualize.akan.domain.enumeration.SubQuota; /* * File: Quota.java * Purpose: Bringing the implementation of model Quota, a class that directly * references the business domain. */ package br.com.visualize.akan.domain.model; /** * This class represents the model of quota for application. It contains the * essential data to represent and maintain a quota. */ public class Quota { private int idQuota = 0; private int idCongressman = 0; private int idUpdateQuota = 0; private SubQuota typeQuota = SubQuota.WITHOUT_TYPE;
private Month monthReferenceQuota = Month.WITHOUT_MONTH;
VisualizeMobile/AKANAndroid
src/br/com/visualize/akan/api/dao/Dao.java
// Path: src/br/com/visualize/akan/api/helper/DatabaseHelper.java // public class DatabaseHelper extends SQLiteOpenHelper { // // private static final String dbName = "AKAN.db"; // // private static final String congressmanTable = "CREATE TABLE [CONGRESSMAN] " // + "([ID_CONGRESSMAN] VARCHAR(10) unique, [ID_UPDATE] INT, " // + "[NAME_CONGRESSMAN] VARCHAR(40), [PARTY] VARCHAR(10), " // + "[UF_CONGRESSMAN] VARCHAR (2), [TOTAL_SPENT_CONGRESSMAN] DOUBLE, " // + "[STATUS_CONGRESSMAN] BOOLEAN, [PHOTO_CONGRESSMAN] VARCHAR(255), " // + "[RANKING_CONGRESSMAN] INT);"; // // private static final String quotaTable = "CREATE TABLE [QUOTA] " // + "([ID_QUOTA] VARCHAR(10) unique, [ID_CONGRESSMAN] VARCHAR(10), " // + "[ID_UPDATE] INT, [TYPE_QUOTA] INT(10), [DESCRIPTION_QUOTA] " // + "VARCHAR (40), [MONTH_QUOTA] INT, [YEAR_QUOTA] INT, " // + "[VALUE_QUOTA] DOUBLE);"; // // private static final String urlTable = "CREATE TABLE [URL] " // + "([UPDATE_VERIFIER_URL] VARCHAR(10), " // + "[ID_UPDATE_URL] VARCHAR(255), [DEFAULT_URL] VARCHAR (255), " // + "[FIRST_URL] VARCHAR (255), [SECOND_URL] VARCHAR (255));"; // // private static final String statisticTable = "CREATE TABLE [STATISTIC] " // + "([ID_STATISTIC] VARCHAR(10) unique, [MONTH_STATISTIC] INT, " // + "[STD_DEVIATION] DOUBLE, [AVERAGE_STATISTIC] DOUBLE, " // + "[MAX_VALUE_STATISTIC] DOUBLE, [YEAR_STATISTIC] INT," // + "ID_SUBQUOTA INT(10));"; // // private static final String versionTable = "CREATE TABLE [VERSION] " // + "([ID_VERSION] VARCHAR(10) unique, [NUM_VERSION] INT);"; // // public DatabaseHelper( Context context ) { // super( context, dbName, null, 1 ); // } // // public DatabaseHelper( Context context, String name, CursorFactory factory, // int version ) { // // super( context, name, factory, version ); // } // // /** // * Describes the actions that will be made when creating the database. // * Creates the tables. // */ // @Override // public void onCreate( SQLiteDatabase db ) { // db.execSQL( congressmanTable ); // db.execSQL( quotaTable ); // db.execSQL( urlTable ); // db.execSQL( statisticTable ); // db.execSQL( versionTable ); // } // // /** // * Describes the actions that will be made if there is a update in the // * database. // */ // @Override // public void onUpgrade( SQLiteDatabase db, int oldVersion, int newVersion ) { // /* ! Empty Method. */ // } // }
import android.content.Context; import android.database.sqlite.SQLiteDatabase; import br.com.visualize.akan.api.helper.DatabaseHelper; import android.content.ContentValues;
/* * File: Dao.java * Purpose: Brings the implementation of class DAO. */ package br.com.visualize.akan.api.dao; /** * Serves to keep details shared between classes Data Access Object. */ public abstract class Dao { protected static final boolean EMPTY = true; protected static final boolean NOT_EMPTY = false;
// Path: src/br/com/visualize/akan/api/helper/DatabaseHelper.java // public class DatabaseHelper extends SQLiteOpenHelper { // // private static final String dbName = "AKAN.db"; // // private static final String congressmanTable = "CREATE TABLE [CONGRESSMAN] " // + "([ID_CONGRESSMAN] VARCHAR(10) unique, [ID_UPDATE] INT, " // + "[NAME_CONGRESSMAN] VARCHAR(40), [PARTY] VARCHAR(10), " // + "[UF_CONGRESSMAN] VARCHAR (2), [TOTAL_SPENT_CONGRESSMAN] DOUBLE, " // + "[STATUS_CONGRESSMAN] BOOLEAN, [PHOTO_CONGRESSMAN] VARCHAR(255), " // + "[RANKING_CONGRESSMAN] INT);"; // // private static final String quotaTable = "CREATE TABLE [QUOTA] " // + "([ID_QUOTA] VARCHAR(10) unique, [ID_CONGRESSMAN] VARCHAR(10), " // + "[ID_UPDATE] INT, [TYPE_QUOTA] INT(10), [DESCRIPTION_QUOTA] " // + "VARCHAR (40), [MONTH_QUOTA] INT, [YEAR_QUOTA] INT, " // + "[VALUE_QUOTA] DOUBLE);"; // // private static final String urlTable = "CREATE TABLE [URL] " // + "([UPDATE_VERIFIER_URL] VARCHAR(10), " // + "[ID_UPDATE_URL] VARCHAR(255), [DEFAULT_URL] VARCHAR (255), " // + "[FIRST_URL] VARCHAR (255), [SECOND_URL] VARCHAR (255));"; // // private static final String statisticTable = "CREATE TABLE [STATISTIC] " // + "([ID_STATISTIC] VARCHAR(10) unique, [MONTH_STATISTIC] INT, " // + "[STD_DEVIATION] DOUBLE, [AVERAGE_STATISTIC] DOUBLE, " // + "[MAX_VALUE_STATISTIC] DOUBLE, [YEAR_STATISTIC] INT," // + "ID_SUBQUOTA INT(10));"; // // private static final String versionTable = "CREATE TABLE [VERSION] " // + "([ID_VERSION] VARCHAR(10) unique, [NUM_VERSION] INT);"; // // public DatabaseHelper( Context context ) { // super( context, dbName, null, 1 ); // } // // public DatabaseHelper( Context context, String name, CursorFactory factory, // int version ) { // // super( context, name, factory, version ); // } // // /** // * Describes the actions that will be made when creating the database. // * Creates the tables. // */ // @Override // public void onCreate( SQLiteDatabase db ) { // db.execSQL( congressmanTable ); // db.execSQL( quotaTable ); // db.execSQL( urlTable ); // db.execSQL( statisticTable ); // db.execSQL( versionTable ); // } // // /** // * Describes the actions that will be made if there is a update in the // * database. // */ // @Override // public void onUpgrade( SQLiteDatabase db, int oldVersion, int newVersion ) { // /* ! Empty Method. */ // } // } // Path: src/br/com/visualize/akan/api/dao/Dao.java import android.content.Context; import android.database.sqlite.SQLiteDatabase; import br.com.visualize.akan.api.helper.DatabaseHelper; import android.content.ContentValues; /* * File: Dao.java * Purpose: Brings the implementation of class DAO. */ package br.com.visualize.akan.api.dao; /** * Serves to keep details shared between classes Data Access Object. */ public abstract class Dao { protected static final boolean EMPTY = true; protected static final boolean NOT_EMPTY = false;
protected static DatabaseHelper database;
VisualizeMobile/AKANAndroid
src/br/com/visualize/akan/api/request/HttpConnection.java
// Path: src/br/com/visualize/akan/domain/exception/ConnectionFailedException.java // public class ConnectionFailedException extends Exception { // private static final long serialVersionUID = 834455534735333354L; // // public ConnectionFailedException() { // /*! Empty Constructor. */ // } // // public ConnectionFailedException( String message ) { // super( message ); // } // }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import br.com.visualize.akan.domain.exception.ConnectionFailedException;
/* * File: HttpConnection.java * Purpose: Brings the implementation of class HttpConnection. */ package br.com.visualize.akan.api.request; /** * Responsible for supporting the connection via Client-Server for the * application. */ public class HttpConnection { /** * Creates an object handler that encapsulates the process of generating a * response object from a HttpResponse. */ public final static ResponseHandler<String> responseHandler = new ResponseHandler<String>() { /** * Processes an HttpResponse and returns some value corresponding to that * response. * * @param response * The response to process. * * @return The response sent by the server. * * @throws IOException */ public String handleResponse( HttpResponse response ) throws IOException { HttpEntity entity = response.getEntity(); String result = null; BufferedReader buffer = new BufferedReader( new InputStreamReader( entity.getContent() ) ); StringBuilder builder = new StringBuilder(); String line = null; while( ( line = buffer.readLine() ) != null ) { builder.append( line + "\n" ); } buffer.close(); result = builder.toString(); return result; } }; /** * Returns the ResponseHandler generated by HttpConnection to handle server * responses. * * @return The ResponseHandler created. */ public synchronized static ResponseHandler<String> getResponseHandler() { return responseHandler; } /** * Use responseHandler created to request the requested through a URL. * * @param response * The response to process. * * @param url * requested URL. * * @return JSON is that the server response. * * @throws ConnectionFailedException */ public static String request( ResponseHandler<String> response, String url )
// Path: src/br/com/visualize/akan/domain/exception/ConnectionFailedException.java // public class ConnectionFailedException extends Exception { // private static final long serialVersionUID = 834455534735333354L; // // public ConnectionFailedException() { // /*! Empty Constructor. */ // } // // public ConnectionFailedException( String message ) { // super( message ); // } // } // Path: src/br/com/visualize/akan/api/request/HttpConnection.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import br.com.visualize.akan.domain.exception.ConnectionFailedException; /* * File: HttpConnection.java * Purpose: Brings the implementation of class HttpConnection. */ package br.com.visualize.akan.api.request; /** * Responsible for supporting the connection via Client-Server for the * application. */ public class HttpConnection { /** * Creates an object handler that encapsulates the process of generating a * response object from a HttpResponse. */ public final static ResponseHandler<String> responseHandler = new ResponseHandler<String>() { /** * Processes an HttpResponse and returns some value corresponding to that * response. * * @param response * The response to process. * * @return The response sent by the server. * * @throws IOException */ public String handleResponse( HttpResponse response ) throws IOException { HttpEntity entity = response.getEntity(); String result = null; BufferedReader buffer = new BufferedReader( new InputStreamReader( entity.getContent() ) ); StringBuilder builder = new StringBuilder(); String line = null; while( ( line = buffer.readLine() ) != null ) { builder.append( line + "\n" ); } buffer.close(); result = builder.toString(); return result; } }; /** * Returns the ResponseHandler generated by HttpConnection to handle server * responses. * * @return The ResponseHandler created. */ public synchronized static ResponseHandler<String> getResponseHandler() { return responseHandler; } /** * Use responseHandler created to request the requested through a URL. * * @param response * The response to process. * * @param url * requested URL. * * @return JSON is that the server response. * * @throws ConnectionFailedException */ public static String request( ResponseHandler<String> response, String url )
throws ConnectionFailedException {
VisualizeMobile/AKANAndroid
src/br/com/visualize/akan/api/dao/UrlDao.java
// Path: src/br/com/visualize/akan/api/helper/DatabaseHelper.java // public class DatabaseHelper extends SQLiteOpenHelper { // // private static final String dbName = "AKAN.db"; // // private static final String congressmanTable = "CREATE TABLE [CONGRESSMAN] " // + "([ID_CONGRESSMAN] VARCHAR(10) unique, [ID_UPDATE] INT, " // + "[NAME_CONGRESSMAN] VARCHAR(40), [PARTY] VARCHAR(10), " // + "[UF_CONGRESSMAN] VARCHAR (2), [TOTAL_SPENT_CONGRESSMAN] DOUBLE, " // + "[STATUS_CONGRESSMAN] BOOLEAN, [PHOTO_CONGRESSMAN] VARCHAR(255), " // + "[RANKING_CONGRESSMAN] INT);"; // // private static final String quotaTable = "CREATE TABLE [QUOTA] " // + "([ID_QUOTA] VARCHAR(10) unique, [ID_CONGRESSMAN] VARCHAR(10), " // + "[ID_UPDATE] INT, [TYPE_QUOTA] INT(10), [DESCRIPTION_QUOTA] " // + "VARCHAR (40), [MONTH_QUOTA] INT, [YEAR_QUOTA] INT, " // + "[VALUE_QUOTA] DOUBLE);"; // // private static final String urlTable = "CREATE TABLE [URL] " // + "([UPDATE_VERIFIER_URL] VARCHAR(10), " // + "[ID_UPDATE_URL] VARCHAR(255), [DEFAULT_URL] VARCHAR (255), " // + "[FIRST_URL] VARCHAR (255), [SECOND_URL] VARCHAR (255));"; // // private static final String statisticTable = "CREATE TABLE [STATISTIC] " // + "([ID_STATISTIC] VARCHAR(10) unique, [MONTH_STATISTIC] INT, " // + "[STD_DEVIATION] DOUBLE, [AVERAGE_STATISTIC] DOUBLE, " // + "[MAX_VALUE_STATISTIC] DOUBLE, [YEAR_STATISTIC] INT," // + "ID_SUBQUOTA INT(10));"; // // private static final String versionTable = "CREATE TABLE [VERSION] " // + "([ID_VERSION] VARCHAR(10) unique, [NUM_VERSION] INT);"; // // public DatabaseHelper( Context context ) { // super( context, dbName, null, 1 ); // } // // public DatabaseHelper( Context context, String name, CursorFactory factory, // int version ) { // // super( context, name, factory, version ); // } // // /** // * Describes the actions that will be made when creating the database. // * Creates the tables. // */ // @Override // public void onCreate( SQLiteDatabase db ) { // db.execSQL( congressmanTable ); // db.execSQL( quotaTable ); // db.execSQL( urlTable ); // db.execSQL( statisticTable ); // db.execSQL( versionTable ); // } // // /** // * Describes the actions that will be made if there is a update in the // * database. // */ // @Override // public void onUpgrade( SQLiteDatabase db, int oldVersion, int newVersion ) { // /* ! Empty Method. */ // } // } // // Path: src/br/com/visualize/akan/domain/model/Url.java // public class Url { // private int idUpdateUrl = 0; // private int updateVerifierUrl = 0; // // private String defaultUrl = ""; // private String firstAlternativeUrl = ""; // private String secondAlternativeUrl = ""; // // public Url() { // /*! Empty Constructor */ // } // // public Url( int idUpdateUrl, String defaultUrl ) { // this.idUpdateUrl = idUpdateUrl; // this.defaultUrl = defaultUrl; // } // // public int getIdUpdateUrl() { // return idUpdateUrl; // } // // public void setIdUpdateUrl( int idUpdateUrl ) { // this.idUpdateUrl = idUpdateUrl; // } // // public int getUpdateVerifierUrl() { // return updateVerifierUrl; // } // // public void setUpdateVerifierUrl( int updateVerifierUrl ) { // this.updateVerifierUrl = updateVerifierUrl; // } // // public String getDefaultUrl() { // return defaultUrl; // } // // public void setDefaultUrl( String defaultUrl ) { // this.defaultUrl = defaultUrl; // } // // public String getFirstAlternativeUrl() { // return firstAlternativeUrl; // } // // public void setFirstAlternativeUrl( String firstAlternativeUrl ) { // this.firstAlternativeUrl = firstAlternativeUrl; // } // // public String getSecondAlternativeUrl() { // return secondAlternativeUrl; // } // // public void setSecondAlternativeUrl( String secondAlternativeUrl ) { // this.secondAlternativeUrl = secondAlternativeUrl; // } // }
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import br.com.visualize.akan.api.helper.DatabaseHelper; import br.com.visualize.akan.domain.model.Url;
/* * File: UrlDao.java Purpose: Bringing the implementation of model URL, a class * that directly references the business domain. */ package br.com.visualize.akan.api.dao; /** * This class represents the Data Access Object for the URL, responsible for all * data base operations like selections, insertions and updates. */ public class UrlDao extends Dao { private static final boolean EMPTY = true; private static final boolean NOT_EMPTY = false; private String defaultUrl = "http://192.168.1.4:3000"; private String tableName = "URL"; private static UrlDao instanceUrlDao = null; private static String tableColumns[ ] = { "UPDATE_VERIFIER_URL", "ID_UPDATE_URL", "DEFAULT_URL", "FIRST_URL", "SECOND_URL" }; protected UrlDao( Context context ) {
// Path: src/br/com/visualize/akan/api/helper/DatabaseHelper.java // public class DatabaseHelper extends SQLiteOpenHelper { // // private static final String dbName = "AKAN.db"; // // private static final String congressmanTable = "CREATE TABLE [CONGRESSMAN] " // + "([ID_CONGRESSMAN] VARCHAR(10) unique, [ID_UPDATE] INT, " // + "[NAME_CONGRESSMAN] VARCHAR(40), [PARTY] VARCHAR(10), " // + "[UF_CONGRESSMAN] VARCHAR (2), [TOTAL_SPENT_CONGRESSMAN] DOUBLE, " // + "[STATUS_CONGRESSMAN] BOOLEAN, [PHOTO_CONGRESSMAN] VARCHAR(255), " // + "[RANKING_CONGRESSMAN] INT);"; // // private static final String quotaTable = "CREATE TABLE [QUOTA] " // + "([ID_QUOTA] VARCHAR(10) unique, [ID_CONGRESSMAN] VARCHAR(10), " // + "[ID_UPDATE] INT, [TYPE_QUOTA] INT(10), [DESCRIPTION_QUOTA] " // + "VARCHAR (40), [MONTH_QUOTA] INT, [YEAR_QUOTA] INT, " // + "[VALUE_QUOTA] DOUBLE);"; // // private static final String urlTable = "CREATE TABLE [URL] " // + "([UPDATE_VERIFIER_URL] VARCHAR(10), " // + "[ID_UPDATE_URL] VARCHAR(255), [DEFAULT_URL] VARCHAR (255), " // + "[FIRST_URL] VARCHAR (255), [SECOND_URL] VARCHAR (255));"; // // private static final String statisticTable = "CREATE TABLE [STATISTIC] " // + "([ID_STATISTIC] VARCHAR(10) unique, [MONTH_STATISTIC] INT, " // + "[STD_DEVIATION] DOUBLE, [AVERAGE_STATISTIC] DOUBLE, " // + "[MAX_VALUE_STATISTIC] DOUBLE, [YEAR_STATISTIC] INT," // + "ID_SUBQUOTA INT(10));"; // // private static final String versionTable = "CREATE TABLE [VERSION] " // + "([ID_VERSION] VARCHAR(10) unique, [NUM_VERSION] INT);"; // // public DatabaseHelper( Context context ) { // super( context, dbName, null, 1 ); // } // // public DatabaseHelper( Context context, String name, CursorFactory factory, // int version ) { // // super( context, name, factory, version ); // } // // /** // * Describes the actions that will be made when creating the database. // * Creates the tables. // */ // @Override // public void onCreate( SQLiteDatabase db ) { // db.execSQL( congressmanTable ); // db.execSQL( quotaTable ); // db.execSQL( urlTable ); // db.execSQL( statisticTable ); // db.execSQL( versionTable ); // } // // /** // * Describes the actions that will be made if there is a update in the // * database. // */ // @Override // public void onUpgrade( SQLiteDatabase db, int oldVersion, int newVersion ) { // /* ! Empty Method. */ // } // } // // Path: src/br/com/visualize/akan/domain/model/Url.java // public class Url { // private int idUpdateUrl = 0; // private int updateVerifierUrl = 0; // // private String defaultUrl = ""; // private String firstAlternativeUrl = ""; // private String secondAlternativeUrl = ""; // // public Url() { // /*! Empty Constructor */ // } // // public Url( int idUpdateUrl, String defaultUrl ) { // this.idUpdateUrl = idUpdateUrl; // this.defaultUrl = defaultUrl; // } // // public int getIdUpdateUrl() { // return idUpdateUrl; // } // // public void setIdUpdateUrl( int idUpdateUrl ) { // this.idUpdateUrl = idUpdateUrl; // } // // public int getUpdateVerifierUrl() { // return updateVerifierUrl; // } // // public void setUpdateVerifierUrl( int updateVerifierUrl ) { // this.updateVerifierUrl = updateVerifierUrl; // } // // public String getDefaultUrl() { // return defaultUrl; // } // // public void setDefaultUrl( String defaultUrl ) { // this.defaultUrl = defaultUrl; // } // // public String getFirstAlternativeUrl() { // return firstAlternativeUrl; // } // // public void setFirstAlternativeUrl( String firstAlternativeUrl ) { // this.firstAlternativeUrl = firstAlternativeUrl; // } // // public String getSecondAlternativeUrl() { // return secondAlternativeUrl; // } // // public void setSecondAlternativeUrl( String secondAlternativeUrl ) { // this.secondAlternativeUrl = secondAlternativeUrl; // } // } // Path: src/br/com/visualize/akan/api/dao/UrlDao.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import br.com.visualize.akan.api.helper.DatabaseHelper; import br.com.visualize.akan.domain.model.Url; /* * File: UrlDao.java Purpose: Bringing the implementation of model URL, a class * that directly references the business domain. */ package br.com.visualize.akan.api.dao; /** * This class represents the Data Access Object for the URL, responsible for all * data base operations like selections, insertions and updates. */ public class UrlDao extends Dao { private static final boolean EMPTY = true; private static final boolean NOT_EMPTY = false; private String defaultUrl = "http://192.168.1.4:3000"; private String tableName = "URL"; private static UrlDao instanceUrlDao = null; private static String tableColumns[ ] = { "UPDATE_VERIFIER_URL", "ID_UPDATE_URL", "DEFAULT_URL", "FIRST_URL", "SECOND_URL" }; protected UrlDao( Context context ) {
UrlDao.database = new DatabaseHelper( context );
jsonld-java/jsonld-java
core/src/main/java/com/github/jsonldjava/core/JsonLdOptions.java
// Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public enum Embed { // ALWAYS, NEVER, LAST, LINK; // }
import com.github.jsonldjava.core.JsonLdConsts.Embed;
return copy; } // Base options : http://www.w3.org/TR/json-ld-api/#idl-def-JsonLdOptions /** * http://www.w3.org/TR/json-ld-api/#widl-JsonLdOptions-base */ private String base = null; /** * http://www.w3.org/TR/json-ld-api/#widl-JsonLdOptions-compactArrays */ private Boolean compactArrays = DEFAULT_COMPACT_ARRAYS; /** * http://www.w3.org/TR/json-ld-api/#widl-JsonLdOptions-expandContext */ private Object expandContext = null; /** * http://www.w3.org/TR/json-ld-api/#widl-JsonLdOptions-processingMode */ private String processingMode = JSON_LD_1_0; /** * http://www.w3.org/TR/json-ld-api/#widl-JsonLdOptions-documentLoader */ private DocumentLoader documentLoader = new DocumentLoader(); // Frame options : http://json-ld.org/spec/latest/json-ld-framing/
// Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public enum Embed { // ALWAYS, NEVER, LAST, LINK; // } // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdOptions.java import com.github.jsonldjava.core.JsonLdConsts.Embed; return copy; } // Base options : http://www.w3.org/TR/json-ld-api/#idl-def-JsonLdOptions /** * http://www.w3.org/TR/json-ld-api/#widl-JsonLdOptions-base */ private String base = null; /** * http://www.w3.org/TR/json-ld-api/#widl-JsonLdOptions-compactArrays */ private Boolean compactArrays = DEFAULT_COMPACT_ARRAYS; /** * http://www.w3.org/TR/json-ld-api/#widl-JsonLdOptions-expandContext */ private Object expandContext = null; /** * http://www.w3.org/TR/json-ld-api/#widl-JsonLdOptions-processingMode */ private String processingMode = JSON_LD_1_0; /** * http://www.w3.org/TR/json-ld-api/#widl-JsonLdOptions-documentLoader */ private DocumentLoader documentLoader = new DocumentLoader(); // Frame options : http://json-ld.org/spec/latest/json-ld-framing/
private Embed embed = Embed.LAST;
jsonld-java/jsonld-java
core/src/main/java/com/github/jsonldjava/core/JsonLdProcessor.java
// Path: core/src/main/java/com/github/jsonldjava/utils/Obj.java // public static Map<String, Object> newMap() { // return new LinkedHashMap<String, Object>(4, 0.75f); // } // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdError.java // public enum Error { // LOADING_DOCUMENT_FAILED("loading document failed"), // // LIST_OF_LISTS("list of lists"), // // INVALID_INDEX_VALUE("invalid @index value"), // // CONFLICTING_INDEXES("conflicting indexes"), // // INVALID_ID_VALUE("invalid @id value"), // // INVALID_LOCAL_CONTEXT("invalid local context"), // // MULTIPLE_CONTEXT_LINK_HEADERS("multiple context link headers"), // // LOADING_REMOTE_CONTEXT_FAILED("loading remote context failed"), // // LOADING_INJECTED_CONTEXT_FAILED("loading injected context failed"), // // INVALID_REMOTE_CONTEXT("invalid remote context"), // // RECURSIVE_CONTEXT_INCLUSION("recursive context inclusion"), // // INVALID_BASE_IRI("invalid base IRI"), // // INVALID_VOCAB_MAPPING("invalid vocab mapping"), // // INVALID_DEFAULT_LANGUAGE("invalid default language"), // // KEYWORD_REDEFINITION("keyword redefinition"), // // INVALID_TERM_DEFINITION("invalid term definition"), // // INVALID_REVERSE_PROPERTY("invalid reverse property"), // // INVALID_IRI_MAPPING("invalid IRI mapping"), // // CYCLIC_IRI_MAPPING("cyclic IRI mapping"), // // INVALID_KEYWORD_ALIAS("invalid keyword alias"), // // INVALID_TYPE_MAPPING("invalid type mapping"), // // INVALID_LANGUAGE_MAPPING("invalid language mapping"), // // COLLIDING_KEYWORDS("colliding keywords"), // // INVALID_CONTAINER_MAPPING("invalid container mapping"), // // INVALID_TYPE_VALUE("invalid type value"), // // INVALID_VALUE_OBJECT("invalid value object"), // // INVALID_VALUE_OBJECT_VALUE("invalid value object value"), // // INVALID_LANGUAGE_TAGGED_STRING("invalid language-tagged string"), // // INVALID_LANGUAGE_TAGGED_VALUE("invalid language-tagged value"), // // INVALID_TYPED_VALUE("invalid typed value"), // // INVALID_SET_OR_LIST_OBJECT("invalid set or list object"), // // INVALID_LANGUAGE_MAP_VALUE("invalid language map value"), // // COMPACTION_TO_LIST_OF_LISTS("compaction to list of lists"), // // INVALID_REVERSE_PROPERTY_MAP("invalid reverse property map"), // // INVALID_REVERSE_VALUE("invalid @reverse value"), // // INVALID_REVERSE_PROPERTY_VALUE("invalid reverse property value"), // // INVALID_EMBED_VALUE("invalid @embed value"), // // // non spec related errors // SYNTAX_ERROR("syntax error"), // // NOT_IMPLEMENTED("not implemnted"), // // UNKNOWN_FORMAT("unknown format"), // // INVALID_INPUT("invalid input"), // // PARSE_ERROR("parse error"), // // UNKNOWN_ERROR("unknown error"); // // private final String error; // // private Error(String error) { // this.error = error; // } // // @Override // public String toString() { // return error; // } // } // // Path: core/src/main/java/com/github/jsonldjava/impl/NQuadRDFParser.java // public class NQuadRDFParser implements RDFParser { // @Override // public RDFDataset parse(Object input) throws JsonLdError { // if (input instanceof String) { // return RDFDatasetUtils.parseNQuads((String) input); // } else { // throw new JsonLdError(JsonLdError.Error.INVALID_INPUT, // "NQuad Parser expected string input."); // } // } // // }
import static com.github.jsonldjava.utils.Obj.newMap; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import com.github.jsonldjava.core.JsonLdError.Error; import com.github.jsonldjava.impl.NQuadRDFParser; import com.github.jsonldjava.impl.NQuadTripleCallback;
// 9) return (Map<String, Object>) compacted; } /** * Expands the given input according to the steps in the * <a href="http://www.w3.org/TR/json-ld-api/#expansion-algorithm">Expansion * algorithm</a>. * * @param input * The input JSON-LD object. * @param opts * The {@link JsonLdOptions} that are to be sent to the expansion * algorithm. * @return The expanded JSON-LD document * @throws JsonLdError * If there is an error while expanding. */ public static List<Object> expand(Object input, JsonLdOptions opts) throws JsonLdError { // 1) // TODO: look into java futures/promises // 2) TODO: better verification of DOMString IRI if (input instanceof String && ((String) input).contains(":")) { try { final RemoteDocument tmp = opts.getDocumentLoader().loadDocument((String) input); input = tmp.getDocument(); // TODO: figure out how to deal with remote context } catch (final Exception e) {
// Path: core/src/main/java/com/github/jsonldjava/utils/Obj.java // public static Map<String, Object> newMap() { // return new LinkedHashMap<String, Object>(4, 0.75f); // } // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdError.java // public enum Error { // LOADING_DOCUMENT_FAILED("loading document failed"), // // LIST_OF_LISTS("list of lists"), // // INVALID_INDEX_VALUE("invalid @index value"), // // CONFLICTING_INDEXES("conflicting indexes"), // // INVALID_ID_VALUE("invalid @id value"), // // INVALID_LOCAL_CONTEXT("invalid local context"), // // MULTIPLE_CONTEXT_LINK_HEADERS("multiple context link headers"), // // LOADING_REMOTE_CONTEXT_FAILED("loading remote context failed"), // // LOADING_INJECTED_CONTEXT_FAILED("loading injected context failed"), // // INVALID_REMOTE_CONTEXT("invalid remote context"), // // RECURSIVE_CONTEXT_INCLUSION("recursive context inclusion"), // // INVALID_BASE_IRI("invalid base IRI"), // // INVALID_VOCAB_MAPPING("invalid vocab mapping"), // // INVALID_DEFAULT_LANGUAGE("invalid default language"), // // KEYWORD_REDEFINITION("keyword redefinition"), // // INVALID_TERM_DEFINITION("invalid term definition"), // // INVALID_REVERSE_PROPERTY("invalid reverse property"), // // INVALID_IRI_MAPPING("invalid IRI mapping"), // // CYCLIC_IRI_MAPPING("cyclic IRI mapping"), // // INVALID_KEYWORD_ALIAS("invalid keyword alias"), // // INVALID_TYPE_MAPPING("invalid type mapping"), // // INVALID_LANGUAGE_MAPPING("invalid language mapping"), // // COLLIDING_KEYWORDS("colliding keywords"), // // INVALID_CONTAINER_MAPPING("invalid container mapping"), // // INVALID_TYPE_VALUE("invalid type value"), // // INVALID_VALUE_OBJECT("invalid value object"), // // INVALID_VALUE_OBJECT_VALUE("invalid value object value"), // // INVALID_LANGUAGE_TAGGED_STRING("invalid language-tagged string"), // // INVALID_LANGUAGE_TAGGED_VALUE("invalid language-tagged value"), // // INVALID_TYPED_VALUE("invalid typed value"), // // INVALID_SET_OR_LIST_OBJECT("invalid set or list object"), // // INVALID_LANGUAGE_MAP_VALUE("invalid language map value"), // // COMPACTION_TO_LIST_OF_LISTS("compaction to list of lists"), // // INVALID_REVERSE_PROPERTY_MAP("invalid reverse property map"), // // INVALID_REVERSE_VALUE("invalid @reverse value"), // // INVALID_REVERSE_PROPERTY_VALUE("invalid reverse property value"), // // INVALID_EMBED_VALUE("invalid @embed value"), // // // non spec related errors // SYNTAX_ERROR("syntax error"), // // NOT_IMPLEMENTED("not implemnted"), // // UNKNOWN_FORMAT("unknown format"), // // INVALID_INPUT("invalid input"), // // PARSE_ERROR("parse error"), // // UNKNOWN_ERROR("unknown error"); // // private final String error; // // private Error(String error) { // this.error = error; // } // // @Override // public String toString() { // return error; // } // } // // Path: core/src/main/java/com/github/jsonldjava/impl/NQuadRDFParser.java // public class NQuadRDFParser implements RDFParser { // @Override // public RDFDataset parse(Object input) throws JsonLdError { // if (input instanceof String) { // return RDFDatasetUtils.parseNQuads((String) input); // } else { // throw new JsonLdError(JsonLdError.Error.INVALID_INPUT, // "NQuad Parser expected string input."); // } // } // // } // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdProcessor.java import static com.github.jsonldjava.utils.Obj.newMap; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import com.github.jsonldjava.core.JsonLdError.Error; import com.github.jsonldjava.impl.NQuadRDFParser; import com.github.jsonldjava.impl.NQuadTripleCallback; // 9) return (Map<String, Object>) compacted; } /** * Expands the given input according to the steps in the * <a href="http://www.w3.org/TR/json-ld-api/#expansion-algorithm">Expansion * algorithm</a>. * * @param input * The input JSON-LD object. * @param opts * The {@link JsonLdOptions} that are to be sent to the expansion * algorithm. * @return The expanded JSON-LD document * @throws JsonLdError * If there is an error while expanding. */ public static List<Object> expand(Object input, JsonLdOptions opts) throws JsonLdError { // 1) // TODO: look into java futures/promises // 2) TODO: better verification of DOMString IRI if (input instanceof String && ((String) input).contains(":")) { try { final RemoteDocument tmp = opts.getDocumentLoader().loadDocument((String) input); input = tmp.getDocument(); // TODO: figure out how to deal with remote context } catch (final Exception e) {
throw new JsonLdError(Error.LOADING_DOCUMENT_FAILED, e);
jsonld-java/jsonld-java
core/src/main/java/com/github/jsonldjava/core/JsonLdProcessor.java
// Path: core/src/main/java/com/github/jsonldjava/utils/Obj.java // public static Map<String, Object> newMap() { // return new LinkedHashMap<String, Object>(4, 0.75f); // } // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdError.java // public enum Error { // LOADING_DOCUMENT_FAILED("loading document failed"), // // LIST_OF_LISTS("list of lists"), // // INVALID_INDEX_VALUE("invalid @index value"), // // CONFLICTING_INDEXES("conflicting indexes"), // // INVALID_ID_VALUE("invalid @id value"), // // INVALID_LOCAL_CONTEXT("invalid local context"), // // MULTIPLE_CONTEXT_LINK_HEADERS("multiple context link headers"), // // LOADING_REMOTE_CONTEXT_FAILED("loading remote context failed"), // // LOADING_INJECTED_CONTEXT_FAILED("loading injected context failed"), // // INVALID_REMOTE_CONTEXT("invalid remote context"), // // RECURSIVE_CONTEXT_INCLUSION("recursive context inclusion"), // // INVALID_BASE_IRI("invalid base IRI"), // // INVALID_VOCAB_MAPPING("invalid vocab mapping"), // // INVALID_DEFAULT_LANGUAGE("invalid default language"), // // KEYWORD_REDEFINITION("keyword redefinition"), // // INVALID_TERM_DEFINITION("invalid term definition"), // // INVALID_REVERSE_PROPERTY("invalid reverse property"), // // INVALID_IRI_MAPPING("invalid IRI mapping"), // // CYCLIC_IRI_MAPPING("cyclic IRI mapping"), // // INVALID_KEYWORD_ALIAS("invalid keyword alias"), // // INVALID_TYPE_MAPPING("invalid type mapping"), // // INVALID_LANGUAGE_MAPPING("invalid language mapping"), // // COLLIDING_KEYWORDS("colliding keywords"), // // INVALID_CONTAINER_MAPPING("invalid container mapping"), // // INVALID_TYPE_VALUE("invalid type value"), // // INVALID_VALUE_OBJECT("invalid value object"), // // INVALID_VALUE_OBJECT_VALUE("invalid value object value"), // // INVALID_LANGUAGE_TAGGED_STRING("invalid language-tagged string"), // // INVALID_LANGUAGE_TAGGED_VALUE("invalid language-tagged value"), // // INVALID_TYPED_VALUE("invalid typed value"), // // INVALID_SET_OR_LIST_OBJECT("invalid set or list object"), // // INVALID_LANGUAGE_MAP_VALUE("invalid language map value"), // // COMPACTION_TO_LIST_OF_LISTS("compaction to list of lists"), // // INVALID_REVERSE_PROPERTY_MAP("invalid reverse property map"), // // INVALID_REVERSE_VALUE("invalid @reverse value"), // // INVALID_REVERSE_PROPERTY_VALUE("invalid reverse property value"), // // INVALID_EMBED_VALUE("invalid @embed value"), // // // non spec related errors // SYNTAX_ERROR("syntax error"), // // NOT_IMPLEMENTED("not implemnted"), // // UNKNOWN_FORMAT("unknown format"), // // INVALID_INPUT("invalid input"), // // PARSE_ERROR("parse error"), // // UNKNOWN_ERROR("unknown error"); // // private final String error; // // private Error(String error) { // this.error = error; // } // // @Override // public String toString() { // return error; // } // } // // Path: core/src/main/java/com/github/jsonldjava/impl/NQuadRDFParser.java // public class NQuadRDFParser implements RDFParser { // @Override // public RDFDataset parse(Object input) throws JsonLdError { // if (input instanceof String) { // return RDFDatasetUtils.parseNQuads((String) input); // } else { // throw new JsonLdError(JsonLdError.Error.INVALID_INPUT, // "NQuad Parser expected string input."); // } // } // // }
import static com.github.jsonldjava.utils.Obj.newMap; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import com.github.jsonldjava.core.JsonLdError.Error; import com.github.jsonldjava.impl.NQuadRDFParser; import com.github.jsonldjava.impl.NQuadTripleCallback;
* Builds the context to be returned in framing, flattening and compaction algorithms. * In cases where the context is empty or from an unexpected type, it returns null. * When JsonLdOptions compactArrays is set to true and the context contains a List with a single element, * the element is returned instead of the list */ private static Object returnedContext(Object context, JsonLdOptions opts) { if (context != null && ((context instanceof Map && !((Map<String, Object>) context).isEmpty()) || (context instanceof List && !((List<Object>) context).isEmpty()) || (context instanceof String && !((String) context).isEmpty()))) { if (context instanceof List && ((List<Object>) context).size() == 1 && opts.getCompactArrays()) { return ((List<Object>) context).get(0); } return context; } else { return null; } } /** * A registry for RDF Parsers (in this case, JSONLDSerializers) used by * fromRDF if no specific serializer is specified and options.format is set. * * TODO: this would fit better in the document loader class */ private static Map<String, RDFParser> rdfParsers = new LinkedHashMap<String, RDFParser>() { { // automatically register nquad serializer
// Path: core/src/main/java/com/github/jsonldjava/utils/Obj.java // public static Map<String, Object> newMap() { // return new LinkedHashMap<String, Object>(4, 0.75f); // } // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdError.java // public enum Error { // LOADING_DOCUMENT_FAILED("loading document failed"), // // LIST_OF_LISTS("list of lists"), // // INVALID_INDEX_VALUE("invalid @index value"), // // CONFLICTING_INDEXES("conflicting indexes"), // // INVALID_ID_VALUE("invalid @id value"), // // INVALID_LOCAL_CONTEXT("invalid local context"), // // MULTIPLE_CONTEXT_LINK_HEADERS("multiple context link headers"), // // LOADING_REMOTE_CONTEXT_FAILED("loading remote context failed"), // // LOADING_INJECTED_CONTEXT_FAILED("loading injected context failed"), // // INVALID_REMOTE_CONTEXT("invalid remote context"), // // RECURSIVE_CONTEXT_INCLUSION("recursive context inclusion"), // // INVALID_BASE_IRI("invalid base IRI"), // // INVALID_VOCAB_MAPPING("invalid vocab mapping"), // // INVALID_DEFAULT_LANGUAGE("invalid default language"), // // KEYWORD_REDEFINITION("keyword redefinition"), // // INVALID_TERM_DEFINITION("invalid term definition"), // // INVALID_REVERSE_PROPERTY("invalid reverse property"), // // INVALID_IRI_MAPPING("invalid IRI mapping"), // // CYCLIC_IRI_MAPPING("cyclic IRI mapping"), // // INVALID_KEYWORD_ALIAS("invalid keyword alias"), // // INVALID_TYPE_MAPPING("invalid type mapping"), // // INVALID_LANGUAGE_MAPPING("invalid language mapping"), // // COLLIDING_KEYWORDS("colliding keywords"), // // INVALID_CONTAINER_MAPPING("invalid container mapping"), // // INVALID_TYPE_VALUE("invalid type value"), // // INVALID_VALUE_OBJECT("invalid value object"), // // INVALID_VALUE_OBJECT_VALUE("invalid value object value"), // // INVALID_LANGUAGE_TAGGED_STRING("invalid language-tagged string"), // // INVALID_LANGUAGE_TAGGED_VALUE("invalid language-tagged value"), // // INVALID_TYPED_VALUE("invalid typed value"), // // INVALID_SET_OR_LIST_OBJECT("invalid set or list object"), // // INVALID_LANGUAGE_MAP_VALUE("invalid language map value"), // // COMPACTION_TO_LIST_OF_LISTS("compaction to list of lists"), // // INVALID_REVERSE_PROPERTY_MAP("invalid reverse property map"), // // INVALID_REVERSE_VALUE("invalid @reverse value"), // // INVALID_REVERSE_PROPERTY_VALUE("invalid reverse property value"), // // INVALID_EMBED_VALUE("invalid @embed value"), // // // non spec related errors // SYNTAX_ERROR("syntax error"), // // NOT_IMPLEMENTED("not implemnted"), // // UNKNOWN_FORMAT("unknown format"), // // INVALID_INPUT("invalid input"), // // PARSE_ERROR("parse error"), // // UNKNOWN_ERROR("unknown error"); // // private final String error; // // private Error(String error) { // this.error = error; // } // // @Override // public String toString() { // return error; // } // } // // Path: core/src/main/java/com/github/jsonldjava/impl/NQuadRDFParser.java // public class NQuadRDFParser implements RDFParser { // @Override // public RDFDataset parse(Object input) throws JsonLdError { // if (input instanceof String) { // return RDFDatasetUtils.parseNQuads((String) input); // } else { // throw new JsonLdError(JsonLdError.Error.INVALID_INPUT, // "NQuad Parser expected string input."); // } // } // // } // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdProcessor.java import static com.github.jsonldjava.utils.Obj.newMap; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import com.github.jsonldjava.core.JsonLdError.Error; import com.github.jsonldjava.impl.NQuadRDFParser; import com.github.jsonldjava.impl.NQuadTripleCallback; * Builds the context to be returned in framing, flattening and compaction algorithms. * In cases where the context is empty or from an unexpected type, it returns null. * When JsonLdOptions compactArrays is set to true and the context contains a List with a single element, * the element is returned instead of the list */ private static Object returnedContext(Object context, JsonLdOptions opts) { if (context != null && ((context instanceof Map && !((Map<String, Object>) context).isEmpty()) || (context instanceof List && !((List<Object>) context).isEmpty()) || (context instanceof String && !((String) context).isEmpty()))) { if (context instanceof List && ((List<Object>) context).size() == 1 && opts.getCompactArrays()) { return ((List<Object>) context).get(0); } return context; } else { return null; } } /** * A registry for RDF Parsers (in this case, JSONLDSerializers) used by * fromRDF if no specific serializer is specified and options.format is set. * * TODO: this would fit better in the document loader class */ private static Map<String, RDFParser> rdfParsers = new LinkedHashMap<String, RDFParser>() { { // automatically register nquad serializer
put(JsonLdConsts.APPLICATION_NQUADS, new NQuadRDFParser());
jsonld-java/jsonld-java
core/src/main/java/com/github/jsonldjava/core/RDFDatasetUtils.java
// Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_LANGSTRING = RDF_SYNTAX_NS + "langString"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_STRING = XSD_NS + "string"; // // Path: core/src/main/java/com/github/jsonldjava/core/Regex.java // final public static Pattern HEX = Pattern.compile("[0-9A-Fa-f]");
import static com.github.jsonldjava.core.JsonLdConsts.RDF_LANGSTRING; import static com.github.jsonldjava.core.JsonLdConsts.XSD_STRING; import static com.github.jsonldjava.core.Regex.HEX; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern;
output.append(" <"); escape(p.getValue(), output); output.append("> "); } // otherwise it must be a bnode (TODO: can we only allow this if the // flag is set in options?) else { output.append(" "); escape(p.getValue(), output); output.append(" "); } // object is IRI, bnode or literal if (o.isIRI()) { output.append("<"); escape(o.getValue(), output); output.append(">"); } else if (o.isBlankNode()) { // normalization mode if (bnode != null) { output.append(bnode.equals(o.getValue()) ? "_:a" : "_:z"); } // normal mode else { output.append(o.getValue()); } } else { output.append("\""); escape(o.getValue(), output); output.append("\"");
// Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_LANGSTRING = RDF_SYNTAX_NS + "langString"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_STRING = XSD_NS + "string"; // // Path: core/src/main/java/com/github/jsonldjava/core/Regex.java // final public static Pattern HEX = Pattern.compile("[0-9A-Fa-f]"); // Path: core/src/main/java/com/github/jsonldjava/core/RDFDatasetUtils.java import static com.github.jsonldjava.core.JsonLdConsts.RDF_LANGSTRING; import static com.github.jsonldjava.core.JsonLdConsts.XSD_STRING; import static com.github.jsonldjava.core.Regex.HEX; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; output.append(" <"); escape(p.getValue(), output); output.append("> "); } // otherwise it must be a bnode (TODO: can we only allow this if the // flag is set in options?) else { output.append(" "); escape(p.getValue(), output); output.append(" "); } // object is IRI, bnode or literal if (o.isIRI()) { output.append("<"); escape(o.getValue(), output); output.append(">"); } else if (o.isBlankNode()) { // normalization mode if (bnode != null) { output.append(bnode.equals(o.getValue()) ? "_:a" : "_:z"); } // normal mode else { output.append(o.getValue()); } } else { output.append("\""); escape(o.getValue(), output); output.append("\"");
if (RDF_LANGSTRING.equals(o.getDatatype())) {
jsonld-java/jsonld-java
core/src/main/java/com/github/jsonldjava/core/RDFDatasetUtils.java
// Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_LANGSTRING = RDF_SYNTAX_NS + "langString"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_STRING = XSD_NS + "string"; // // Path: core/src/main/java/com/github/jsonldjava/core/Regex.java // final public static Pattern HEX = Pattern.compile("[0-9A-Fa-f]");
import static com.github.jsonldjava.core.JsonLdConsts.RDF_LANGSTRING; import static com.github.jsonldjava.core.JsonLdConsts.XSD_STRING; import static com.github.jsonldjava.core.Regex.HEX; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern;
output.append("> "); } // otherwise it must be a bnode (TODO: can we only allow this if the // flag is set in options?) else { output.append(" "); escape(p.getValue(), output); output.append(" "); } // object is IRI, bnode or literal if (o.isIRI()) { output.append("<"); escape(o.getValue(), output); output.append(">"); } else if (o.isBlankNode()) { // normalization mode if (bnode != null) { output.append(bnode.equals(o.getValue()) ? "_:a" : "_:z"); } // normal mode else { output.append(o.getValue()); } } else { output.append("\""); escape(o.getValue(), output); output.append("\""); if (RDF_LANGSTRING.equals(o.getDatatype())) { output.append("@").append(o.getLanguage());
// Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_LANGSTRING = RDF_SYNTAX_NS + "langString"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_STRING = XSD_NS + "string"; // // Path: core/src/main/java/com/github/jsonldjava/core/Regex.java // final public static Pattern HEX = Pattern.compile("[0-9A-Fa-f]"); // Path: core/src/main/java/com/github/jsonldjava/core/RDFDatasetUtils.java import static com.github.jsonldjava.core.JsonLdConsts.RDF_LANGSTRING; import static com.github.jsonldjava.core.JsonLdConsts.XSD_STRING; import static com.github.jsonldjava.core.Regex.HEX; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; output.append("> "); } // otherwise it must be a bnode (TODO: can we only allow this if the // flag is set in options?) else { output.append(" "); escape(p.getValue(), output); output.append(" "); } // object is IRI, bnode or literal if (o.isIRI()) { output.append("<"); escape(o.getValue(), output); output.append(">"); } else if (o.isBlankNode()) { // normalization mode if (bnode != null) { output.append(bnode.equals(o.getValue()) ? "_:a" : "_:z"); } // normal mode else { output.append(o.getValue()); } } else { output.append("\""); escape(o.getValue(), output); output.append("\""); if (RDF_LANGSTRING.equals(o.getDatatype())) { output.append("@").append(o.getLanguage());
} else if (!XSD_STRING.equals(o.getDatatype())) {
jsonld-java/jsonld-java
core/src/main/java/com/github/jsonldjava/core/RDFDatasetUtils.java
// Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_LANGSTRING = RDF_SYNTAX_NS + "langString"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_STRING = XSD_NS + "string"; // // Path: core/src/main/java/com/github/jsonldjava/core/Regex.java // final public static Pattern HEX = Pattern.compile("[0-9A-Fa-f]");
import static com.github.jsonldjava.core.JsonLdConsts.RDF_LANGSTRING; import static com.github.jsonldjava.core.JsonLdConsts.XSD_STRING; import static com.github.jsonldjava.core.Regex.HEX; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern;
if (RDF_LANGSTRING.equals(o.getDatatype())) { output.append("@").append(o.getLanguage()); } else if (!XSD_STRING.equals(o.getDatatype())) { output.append("^^<"); escape(o.getDatatype(), output); output.append(">"); } } // graph if (graphName != null) { if (graphName.indexOf("_:") != 0) { output.append(" <"); escape(graphName, output); output.append(">"); } else if (bnode != null) { output.append(" _:g"); } else { output.append(" ").append(graphName); } } output.append(" .\n"); } static String toNQuad(RDFDataset.Quad triple, String graphName) { return toNQuad(triple, graphName, null); } final private static Pattern UCHAR_MATCHED = Pattern
// Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_LANGSTRING = RDF_SYNTAX_NS + "langString"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_STRING = XSD_NS + "string"; // // Path: core/src/main/java/com/github/jsonldjava/core/Regex.java // final public static Pattern HEX = Pattern.compile("[0-9A-Fa-f]"); // Path: core/src/main/java/com/github/jsonldjava/core/RDFDatasetUtils.java import static com.github.jsonldjava.core.JsonLdConsts.RDF_LANGSTRING; import static com.github.jsonldjava.core.JsonLdConsts.XSD_STRING; import static com.github.jsonldjava.core.Regex.HEX; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; if (RDF_LANGSTRING.equals(o.getDatatype())) { output.append("@").append(o.getLanguage()); } else if (!XSD_STRING.equals(o.getDatatype())) { output.append("^^<"); escape(o.getDatatype(), output); output.append(">"); } } // graph if (graphName != null) { if (graphName.indexOf("_:") != 0) { output.append(" <"); escape(graphName, output); output.append(">"); } else if (bnode != null) { output.append(" _:g"); } else { output.append(" ").append(graphName); } } output.append(" .\n"); } static String toNQuad(RDFDataset.Quad triple, String graphName) { return toNQuad(triple, graphName, null); } final private static Pattern UCHAR_MATCHED = Pattern
.compile("\\u005C(?:([tbnrf\\\"'])|(?:u(" + HEX + "{4}))|(?:U(" + HEX + "{8})))");
jsonld-java/jsonld-java
core/src/main/java/com/github/jsonldjava/core/RDFDataset.java
// Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_FIRST = RDF_SYNTAX_NS + "first"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_LANGSTRING = RDF_SYNTAX_NS + "langString"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_NIL = RDF_SYNTAX_NS + "nil"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_REST = RDF_SYNTAX_NS + "rest"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_TYPE = RDF_SYNTAX_NS + "type"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_BOOLEAN = XSD_NS + "boolean"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_DECIMAL = XSD_NS + "decimal"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_DOUBLE = XSD_NS + "double"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_INTEGER = XSD_NS + "integer"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_STRING = XSD_NS + "string"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static boolean isKeyword(Object key) { // if (!isString(key)) { // return false; // } // return "@base".equals(key) || "@context".equals(key) || "@container".equals(key) // || "@default".equals(key) || "@embed".equals(key) || "@explicit".equals(key) // || "@graph".equals(key) || "@id".equals(key) || "@index".equals(key) // || "@language".equals(key) || "@list".equals(key) || "@omitDefault".equals(key) // || "@reverse".equals(key) || "@preserve".equals(key) || "@set".equals(key) // || "@type".equals(key) || "@value".equals(key) || "@vocab".equals(key) // || "@requireAll".equals(key); // } // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static Boolean isList(Object v) { // return (v instanceof Map && ((Map<String, Object>) v).containsKey("@list")); // } // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static Boolean isObject(Object v) { // return (v instanceof Map); // } // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static Boolean isString(Object v) { // // TODO: should this return true for arrays of strings as well? // return (v instanceof String); // } // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static Boolean isValue(Object v) { // return (v instanceof Map && ((Map<String, Object>) v).containsKey("@value")); // } // // Path: core/src/main/java/com/github/jsonldjava/utils/Obj.java // public static Map<String, Object> newMap() { // return new LinkedHashMap<String, Object>(4, 0.75f); // }
import static com.github.jsonldjava.core.JsonLdConsts.RDF_FIRST; import static com.github.jsonldjava.core.JsonLdConsts.RDF_LANGSTRING; import static com.github.jsonldjava.core.JsonLdConsts.RDF_NIL; import static com.github.jsonldjava.core.JsonLdConsts.RDF_REST; import static com.github.jsonldjava.core.JsonLdConsts.RDF_TYPE; import static com.github.jsonldjava.core.JsonLdConsts.XSD_BOOLEAN; import static com.github.jsonldjava.core.JsonLdConsts.XSD_DECIMAL; import static com.github.jsonldjava.core.JsonLdConsts.XSD_DOUBLE; import static com.github.jsonldjava.core.JsonLdConsts.XSD_INTEGER; import static com.github.jsonldjava.core.JsonLdConsts.XSD_STRING; import static com.github.jsonldjava.core.JsonLdUtils.isKeyword; import static com.github.jsonldjava.core.JsonLdUtils.isList; import static com.github.jsonldjava.core.JsonLdUtils.isObject; import static com.github.jsonldjava.core.JsonLdUtils.isString; import static com.github.jsonldjava.core.JsonLdUtils.isValue; import static com.github.jsonldjava.utils.Obj.newMap; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.regex.Pattern;
public boolean isBlankNode() { return false; } } public static class BlankNode extends Node { private static final long serialVersionUID = -2842402820440697318L; public BlankNode(String attribute) { super(); put("type", "blank node"); put("value", attribute); } @Override public boolean isLiteral() { return false; } @Override public boolean isIRI() { return false; } @Override public boolean isBlankNode() { return true; } }
// Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_FIRST = RDF_SYNTAX_NS + "first"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_LANGSTRING = RDF_SYNTAX_NS + "langString"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_NIL = RDF_SYNTAX_NS + "nil"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_REST = RDF_SYNTAX_NS + "rest"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_TYPE = RDF_SYNTAX_NS + "type"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_BOOLEAN = XSD_NS + "boolean"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_DECIMAL = XSD_NS + "decimal"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_DOUBLE = XSD_NS + "double"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_INTEGER = XSD_NS + "integer"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_STRING = XSD_NS + "string"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static boolean isKeyword(Object key) { // if (!isString(key)) { // return false; // } // return "@base".equals(key) || "@context".equals(key) || "@container".equals(key) // || "@default".equals(key) || "@embed".equals(key) || "@explicit".equals(key) // || "@graph".equals(key) || "@id".equals(key) || "@index".equals(key) // || "@language".equals(key) || "@list".equals(key) || "@omitDefault".equals(key) // || "@reverse".equals(key) || "@preserve".equals(key) || "@set".equals(key) // || "@type".equals(key) || "@value".equals(key) || "@vocab".equals(key) // || "@requireAll".equals(key); // } // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static Boolean isList(Object v) { // return (v instanceof Map && ((Map<String, Object>) v).containsKey("@list")); // } // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static Boolean isObject(Object v) { // return (v instanceof Map); // } // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static Boolean isString(Object v) { // // TODO: should this return true for arrays of strings as well? // return (v instanceof String); // } // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static Boolean isValue(Object v) { // return (v instanceof Map && ((Map<String, Object>) v).containsKey("@value")); // } // // Path: core/src/main/java/com/github/jsonldjava/utils/Obj.java // public static Map<String, Object> newMap() { // return new LinkedHashMap<String, Object>(4, 0.75f); // } // Path: core/src/main/java/com/github/jsonldjava/core/RDFDataset.java import static com.github.jsonldjava.core.JsonLdConsts.RDF_FIRST; import static com.github.jsonldjava.core.JsonLdConsts.RDF_LANGSTRING; import static com.github.jsonldjava.core.JsonLdConsts.RDF_NIL; import static com.github.jsonldjava.core.JsonLdConsts.RDF_REST; import static com.github.jsonldjava.core.JsonLdConsts.RDF_TYPE; import static com.github.jsonldjava.core.JsonLdConsts.XSD_BOOLEAN; import static com.github.jsonldjava.core.JsonLdConsts.XSD_DECIMAL; import static com.github.jsonldjava.core.JsonLdConsts.XSD_DOUBLE; import static com.github.jsonldjava.core.JsonLdConsts.XSD_INTEGER; import static com.github.jsonldjava.core.JsonLdConsts.XSD_STRING; import static com.github.jsonldjava.core.JsonLdUtils.isKeyword; import static com.github.jsonldjava.core.JsonLdUtils.isList; import static com.github.jsonldjava.core.JsonLdUtils.isObject; import static com.github.jsonldjava.core.JsonLdUtils.isString; import static com.github.jsonldjava.core.JsonLdUtils.isValue; import static com.github.jsonldjava.utils.Obj.newMap; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; public boolean isBlankNode() { return false; } } public static class BlankNode extends Node { private static final long serialVersionUID = -2842402820440697318L; public BlankNode(String attribute) { super(); put("type", "blank node"); put("value", attribute); } @Override public boolean isLiteral() { return false; } @Override public boolean isIRI() { return false; } @Override public boolean isBlankNode() { return true; } }
private static final Node first = new IRI(RDF_FIRST);
jsonld-java/jsonld-java
core/src/main/java/com/github/jsonldjava/core/RDFDataset.java
// Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_FIRST = RDF_SYNTAX_NS + "first"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_LANGSTRING = RDF_SYNTAX_NS + "langString"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_NIL = RDF_SYNTAX_NS + "nil"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_REST = RDF_SYNTAX_NS + "rest"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_TYPE = RDF_SYNTAX_NS + "type"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_BOOLEAN = XSD_NS + "boolean"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_DECIMAL = XSD_NS + "decimal"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_DOUBLE = XSD_NS + "double"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_INTEGER = XSD_NS + "integer"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_STRING = XSD_NS + "string"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static boolean isKeyword(Object key) { // if (!isString(key)) { // return false; // } // return "@base".equals(key) || "@context".equals(key) || "@container".equals(key) // || "@default".equals(key) || "@embed".equals(key) || "@explicit".equals(key) // || "@graph".equals(key) || "@id".equals(key) || "@index".equals(key) // || "@language".equals(key) || "@list".equals(key) || "@omitDefault".equals(key) // || "@reverse".equals(key) || "@preserve".equals(key) || "@set".equals(key) // || "@type".equals(key) || "@value".equals(key) || "@vocab".equals(key) // || "@requireAll".equals(key); // } // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static Boolean isList(Object v) { // return (v instanceof Map && ((Map<String, Object>) v).containsKey("@list")); // } // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static Boolean isObject(Object v) { // return (v instanceof Map); // } // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static Boolean isString(Object v) { // // TODO: should this return true for arrays of strings as well? // return (v instanceof String); // } // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static Boolean isValue(Object v) { // return (v instanceof Map && ((Map<String, Object>) v).containsKey("@value")); // } // // Path: core/src/main/java/com/github/jsonldjava/utils/Obj.java // public static Map<String, Object> newMap() { // return new LinkedHashMap<String, Object>(4, 0.75f); // }
import static com.github.jsonldjava.core.JsonLdConsts.RDF_FIRST; import static com.github.jsonldjava.core.JsonLdConsts.RDF_LANGSTRING; import static com.github.jsonldjava.core.JsonLdConsts.RDF_NIL; import static com.github.jsonldjava.core.JsonLdConsts.RDF_REST; import static com.github.jsonldjava.core.JsonLdConsts.RDF_TYPE; import static com.github.jsonldjava.core.JsonLdConsts.XSD_BOOLEAN; import static com.github.jsonldjava.core.JsonLdConsts.XSD_DECIMAL; import static com.github.jsonldjava.core.JsonLdConsts.XSD_DOUBLE; import static com.github.jsonldjava.core.JsonLdConsts.XSD_INTEGER; import static com.github.jsonldjava.core.JsonLdConsts.XSD_STRING; import static com.github.jsonldjava.core.JsonLdUtils.isKeyword; import static com.github.jsonldjava.core.JsonLdUtils.isList; import static com.github.jsonldjava.core.JsonLdUtils.isObject; import static com.github.jsonldjava.core.JsonLdUtils.isString; import static com.github.jsonldjava.core.JsonLdUtils.isValue; import static com.github.jsonldjava.utils.Obj.newMap; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.regex.Pattern;
return false; } } public static class BlankNode extends Node { private static final long serialVersionUID = -2842402820440697318L; public BlankNode(String attribute) { super(); put("type", "blank node"); put("value", attribute); } @Override public boolean isLiteral() { return false; } @Override public boolean isIRI() { return false; } @Override public boolean isBlankNode() { return true; } } private static final Node first = new IRI(RDF_FIRST);
// Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_FIRST = RDF_SYNTAX_NS + "first"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_LANGSTRING = RDF_SYNTAX_NS + "langString"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_NIL = RDF_SYNTAX_NS + "nil"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_REST = RDF_SYNTAX_NS + "rest"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_TYPE = RDF_SYNTAX_NS + "type"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_BOOLEAN = XSD_NS + "boolean"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_DECIMAL = XSD_NS + "decimal"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_DOUBLE = XSD_NS + "double"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_INTEGER = XSD_NS + "integer"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_STRING = XSD_NS + "string"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static boolean isKeyword(Object key) { // if (!isString(key)) { // return false; // } // return "@base".equals(key) || "@context".equals(key) || "@container".equals(key) // || "@default".equals(key) || "@embed".equals(key) || "@explicit".equals(key) // || "@graph".equals(key) || "@id".equals(key) || "@index".equals(key) // || "@language".equals(key) || "@list".equals(key) || "@omitDefault".equals(key) // || "@reverse".equals(key) || "@preserve".equals(key) || "@set".equals(key) // || "@type".equals(key) || "@value".equals(key) || "@vocab".equals(key) // || "@requireAll".equals(key); // } // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static Boolean isList(Object v) { // return (v instanceof Map && ((Map<String, Object>) v).containsKey("@list")); // } // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static Boolean isObject(Object v) { // return (v instanceof Map); // } // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static Boolean isString(Object v) { // // TODO: should this return true for arrays of strings as well? // return (v instanceof String); // } // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static Boolean isValue(Object v) { // return (v instanceof Map && ((Map<String, Object>) v).containsKey("@value")); // } // // Path: core/src/main/java/com/github/jsonldjava/utils/Obj.java // public static Map<String, Object> newMap() { // return new LinkedHashMap<String, Object>(4, 0.75f); // } // Path: core/src/main/java/com/github/jsonldjava/core/RDFDataset.java import static com.github.jsonldjava.core.JsonLdConsts.RDF_FIRST; import static com.github.jsonldjava.core.JsonLdConsts.RDF_LANGSTRING; import static com.github.jsonldjava.core.JsonLdConsts.RDF_NIL; import static com.github.jsonldjava.core.JsonLdConsts.RDF_REST; import static com.github.jsonldjava.core.JsonLdConsts.RDF_TYPE; import static com.github.jsonldjava.core.JsonLdConsts.XSD_BOOLEAN; import static com.github.jsonldjava.core.JsonLdConsts.XSD_DECIMAL; import static com.github.jsonldjava.core.JsonLdConsts.XSD_DOUBLE; import static com.github.jsonldjava.core.JsonLdConsts.XSD_INTEGER; import static com.github.jsonldjava.core.JsonLdConsts.XSD_STRING; import static com.github.jsonldjava.core.JsonLdUtils.isKeyword; import static com.github.jsonldjava.core.JsonLdUtils.isList; import static com.github.jsonldjava.core.JsonLdUtils.isObject; import static com.github.jsonldjava.core.JsonLdUtils.isString; import static com.github.jsonldjava.core.JsonLdUtils.isValue; import static com.github.jsonldjava.utils.Obj.newMap; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; return false; } } public static class BlankNode extends Node { private static final long serialVersionUID = -2842402820440697318L; public BlankNode(String attribute) { super(); put("type", "blank node"); put("value", attribute); } @Override public boolean isLiteral() { return false; } @Override public boolean isIRI() { return false; } @Override public boolean isBlankNode() { return true; } } private static final Node first = new IRI(RDF_FIRST);
private static final Node rest = new IRI(RDF_REST);
jsonld-java/jsonld-java
core/src/main/java/com/github/jsonldjava/core/RDFDataset.java
// Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_FIRST = RDF_SYNTAX_NS + "first"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_LANGSTRING = RDF_SYNTAX_NS + "langString"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_NIL = RDF_SYNTAX_NS + "nil"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_REST = RDF_SYNTAX_NS + "rest"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_TYPE = RDF_SYNTAX_NS + "type"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_BOOLEAN = XSD_NS + "boolean"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_DECIMAL = XSD_NS + "decimal"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_DOUBLE = XSD_NS + "double"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_INTEGER = XSD_NS + "integer"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_STRING = XSD_NS + "string"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static boolean isKeyword(Object key) { // if (!isString(key)) { // return false; // } // return "@base".equals(key) || "@context".equals(key) || "@container".equals(key) // || "@default".equals(key) || "@embed".equals(key) || "@explicit".equals(key) // || "@graph".equals(key) || "@id".equals(key) || "@index".equals(key) // || "@language".equals(key) || "@list".equals(key) || "@omitDefault".equals(key) // || "@reverse".equals(key) || "@preserve".equals(key) || "@set".equals(key) // || "@type".equals(key) || "@value".equals(key) || "@vocab".equals(key) // || "@requireAll".equals(key); // } // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static Boolean isList(Object v) { // return (v instanceof Map && ((Map<String, Object>) v).containsKey("@list")); // } // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static Boolean isObject(Object v) { // return (v instanceof Map); // } // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static Boolean isString(Object v) { // // TODO: should this return true for arrays of strings as well? // return (v instanceof String); // } // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static Boolean isValue(Object v) { // return (v instanceof Map && ((Map<String, Object>) v).containsKey("@value")); // } // // Path: core/src/main/java/com/github/jsonldjava/utils/Obj.java // public static Map<String, Object> newMap() { // return new LinkedHashMap<String, Object>(4, 0.75f); // }
import static com.github.jsonldjava.core.JsonLdConsts.RDF_FIRST; import static com.github.jsonldjava.core.JsonLdConsts.RDF_LANGSTRING; import static com.github.jsonldjava.core.JsonLdConsts.RDF_NIL; import static com.github.jsonldjava.core.JsonLdConsts.RDF_REST; import static com.github.jsonldjava.core.JsonLdConsts.RDF_TYPE; import static com.github.jsonldjava.core.JsonLdConsts.XSD_BOOLEAN; import static com.github.jsonldjava.core.JsonLdConsts.XSD_DECIMAL; import static com.github.jsonldjava.core.JsonLdConsts.XSD_DOUBLE; import static com.github.jsonldjava.core.JsonLdConsts.XSD_INTEGER; import static com.github.jsonldjava.core.JsonLdConsts.XSD_STRING; import static com.github.jsonldjava.core.JsonLdUtils.isKeyword; import static com.github.jsonldjava.core.JsonLdUtils.isList; import static com.github.jsonldjava.core.JsonLdUtils.isObject; import static com.github.jsonldjava.core.JsonLdUtils.isString; import static com.github.jsonldjava.core.JsonLdUtils.isValue; import static com.github.jsonldjava.utils.Obj.newMap; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.regex.Pattern;
} } public static class BlankNode extends Node { private static final long serialVersionUID = -2842402820440697318L; public BlankNode(String attribute) { super(); put("type", "blank node"); put("value", attribute); } @Override public boolean isLiteral() { return false; } @Override public boolean isIRI() { return false; } @Override public boolean isBlankNode() { return true; } } private static final Node first = new IRI(RDF_FIRST); private static final Node rest = new IRI(RDF_REST);
// Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_FIRST = RDF_SYNTAX_NS + "first"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_LANGSTRING = RDF_SYNTAX_NS + "langString"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_NIL = RDF_SYNTAX_NS + "nil"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_REST = RDF_SYNTAX_NS + "rest"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String RDF_TYPE = RDF_SYNTAX_NS + "type"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_BOOLEAN = XSD_NS + "boolean"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_DECIMAL = XSD_NS + "decimal"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_DOUBLE = XSD_NS + "double"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_INTEGER = XSD_NS + "integer"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdConsts.java // public static final String XSD_STRING = XSD_NS + "string"; // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static boolean isKeyword(Object key) { // if (!isString(key)) { // return false; // } // return "@base".equals(key) || "@context".equals(key) || "@container".equals(key) // || "@default".equals(key) || "@embed".equals(key) || "@explicit".equals(key) // || "@graph".equals(key) || "@id".equals(key) || "@index".equals(key) // || "@language".equals(key) || "@list".equals(key) || "@omitDefault".equals(key) // || "@reverse".equals(key) || "@preserve".equals(key) || "@set".equals(key) // || "@type".equals(key) || "@value".equals(key) || "@vocab".equals(key) // || "@requireAll".equals(key); // } // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static Boolean isList(Object v) { // return (v instanceof Map && ((Map<String, Object>) v).containsKey("@list")); // } // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static Boolean isObject(Object v) { // return (v instanceof Map); // } // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static Boolean isString(Object v) { // // TODO: should this return true for arrays of strings as well? // return (v instanceof String); // } // // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java // static Boolean isValue(Object v) { // return (v instanceof Map && ((Map<String, Object>) v).containsKey("@value")); // } // // Path: core/src/main/java/com/github/jsonldjava/utils/Obj.java // public static Map<String, Object> newMap() { // return new LinkedHashMap<String, Object>(4, 0.75f); // } // Path: core/src/main/java/com/github/jsonldjava/core/RDFDataset.java import static com.github.jsonldjava.core.JsonLdConsts.RDF_FIRST; import static com.github.jsonldjava.core.JsonLdConsts.RDF_LANGSTRING; import static com.github.jsonldjava.core.JsonLdConsts.RDF_NIL; import static com.github.jsonldjava.core.JsonLdConsts.RDF_REST; import static com.github.jsonldjava.core.JsonLdConsts.RDF_TYPE; import static com.github.jsonldjava.core.JsonLdConsts.XSD_BOOLEAN; import static com.github.jsonldjava.core.JsonLdConsts.XSD_DECIMAL; import static com.github.jsonldjava.core.JsonLdConsts.XSD_DOUBLE; import static com.github.jsonldjava.core.JsonLdConsts.XSD_INTEGER; import static com.github.jsonldjava.core.JsonLdConsts.XSD_STRING; import static com.github.jsonldjava.core.JsonLdUtils.isKeyword; import static com.github.jsonldjava.core.JsonLdUtils.isList; import static com.github.jsonldjava.core.JsonLdUtils.isObject; import static com.github.jsonldjava.core.JsonLdUtils.isString; import static com.github.jsonldjava.core.JsonLdUtils.isValue; import static com.github.jsonldjava.utils.Obj.newMap; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; } } public static class BlankNode extends Node { private static final long serialVersionUID = -2842402820440697318L; public BlankNode(String attribute) { super(); put("type", "blank node"); put("value", attribute); } @Override public boolean isLiteral() { return false; } @Override public boolean isIRI() { return false; } @Override public boolean isBlankNode() { return true; } } private static final Node first = new IRI(RDF_FIRST); private static final Node rest = new IRI(RDF_REST);
private static final Node nil = new IRI(RDF_NIL);
jsonld-java/jsonld-java
core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java
// Path: core/src/main/java/com/github/jsonldjava/utils/Obj.java // public class Obj { // // /** // * Helper function for creating maps and tuning them as necessary. // * // * @return A new {@link Map} instance. // */ // public static Map<String, Object> newMap() { // return new LinkedHashMap<String, Object>(4, 0.75f); // } // // /** // * Helper function for creating maps and tuning them as necessary. // * // * @param key // * A key to add to the map on creation. // * @param value // * A value to attach to the key in the new map. // * @return A new {@link Map} instance. // */ // public static Map<String, Object> newMap(String key, Object value) { // final Map<String, Object> result = newMap(); // result.put(key, value); // return result; // } // // /** // * Used to make getting values from maps embedded in maps embedded in maps // * easier TODO: roll out the loops for efficiency // * // * @param map // * The map to get a key from // * @param keys // * The list of keys to attempt to get from the map. The first key // * found with a non-null value is returned, or if none are found, // * the original map is returned. // * @return The key from the map, or the original map if none of the keys are // * found. // */ // public static Object get(Map<String, Object> map, String... keys) { // Map<String, Object> result = map; // for (final String key : keys) { // result = (Map<String, Object>) map.get(key); // // make sure we don't crash if we get a null somewhere down the line // if (result == null) { // return result; // } // } // return result; // } // // public static Object put(Object map, String key1, Object value) { // ((Map<String, Object>) map).put(key1, value); // return map; // } // // public static Object put(Object map, String key1, String key2, Object value) { // ((Map<String, Object>) ((Map<String, Object>) map).get(key1)).put(key2, value); // return map; // } // // public static Object put(Object map, String key1, String key2, String key3, Object value) { // ((Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) map).get(key1)) // .get(key2)).put(key3, value); // return map; // } // // public static Object put(Object map, String key1, String key2, String key3, String key4, // Object value) { // ((Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) map) // .get(key1)).get(key2)).get(key3)).put(key4, value); // return map; // } // // public static boolean contains(Object map, String... keys) { // for (final String key : keys) { // map = ((Map<String, Object>) map).get(key); // if (map == null) { // return false; // } // } // return true; // } // // public static Object remove(Object map, String k1, String k2) { // return ((Map<String, Object>) ((Map<String, Object>) map).get(k1)).remove(k2); // } // // /** // * A null-safe equals check using v1.equals(v2) if they are both not null. // * // * @param v1 // * The source object for the equals check. // * @param v2 // * The object to be checked for equality using the first objects // * equals method. // * @return True if the objects were both null. True if both objects were not // * null and v1.equals(v2). False otherwise. // */ // public static boolean equals(Object v1, Object v2) { // return v1 == null ? v2 == null : v1.equals(v2); // } // }
import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import com.github.jsonldjava.utils.Obj;
static int compareShortestLeast(String a, String b) { if (a.length() < b.length()) { return -1; } else if (b.length() < a.length()) { return 1; } return Integer.signum(a.compareTo(b)); } /** * Compares two JSON-LD values for equality. Two JSON-LD values will be * considered equal if: * * 1. They are both primitives of the same type and value. 2. They are * both @values with the same @value, @type, and @language, OR 3. They both * have @ids they are the same. * * @param v1 * the first value. * @param v2 * the second value. * * @return true if v1 and v2 are considered equal, false if not. */ static boolean compareValues(Object v1, Object v2) { if (v1.equals(v2)) { return true; } if (isValue(v1) && isValue(v2)
// Path: core/src/main/java/com/github/jsonldjava/utils/Obj.java // public class Obj { // // /** // * Helper function for creating maps and tuning them as necessary. // * // * @return A new {@link Map} instance. // */ // public static Map<String, Object> newMap() { // return new LinkedHashMap<String, Object>(4, 0.75f); // } // // /** // * Helper function for creating maps and tuning them as necessary. // * // * @param key // * A key to add to the map on creation. // * @param value // * A value to attach to the key in the new map. // * @return A new {@link Map} instance. // */ // public static Map<String, Object> newMap(String key, Object value) { // final Map<String, Object> result = newMap(); // result.put(key, value); // return result; // } // // /** // * Used to make getting values from maps embedded in maps embedded in maps // * easier TODO: roll out the loops for efficiency // * // * @param map // * The map to get a key from // * @param keys // * The list of keys to attempt to get from the map. The first key // * found with a non-null value is returned, or if none are found, // * the original map is returned. // * @return The key from the map, or the original map if none of the keys are // * found. // */ // public static Object get(Map<String, Object> map, String... keys) { // Map<String, Object> result = map; // for (final String key : keys) { // result = (Map<String, Object>) map.get(key); // // make sure we don't crash if we get a null somewhere down the line // if (result == null) { // return result; // } // } // return result; // } // // public static Object put(Object map, String key1, Object value) { // ((Map<String, Object>) map).put(key1, value); // return map; // } // // public static Object put(Object map, String key1, String key2, Object value) { // ((Map<String, Object>) ((Map<String, Object>) map).get(key1)).put(key2, value); // return map; // } // // public static Object put(Object map, String key1, String key2, String key3, Object value) { // ((Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) map).get(key1)) // .get(key2)).put(key3, value); // return map; // } // // public static Object put(Object map, String key1, String key2, String key3, String key4, // Object value) { // ((Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) map) // .get(key1)).get(key2)).get(key3)).put(key4, value); // return map; // } // // public static boolean contains(Object map, String... keys) { // for (final String key : keys) { // map = ((Map<String, Object>) map).get(key); // if (map == null) { // return false; // } // } // return true; // } // // public static Object remove(Object map, String k1, String k2) { // return ((Map<String, Object>) ((Map<String, Object>) map).get(k1)).remove(k2); // } // // /** // * A null-safe equals check using v1.equals(v2) if they are both not null. // * // * @param v1 // * The source object for the equals check. // * @param v2 // * The object to be checked for equality using the first objects // * equals method. // * @return True if the objects were both null. True if both objects were not // * null and v1.equals(v2). False otherwise. // */ // public static boolean equals(Object v1, Object v2) { // return v1 == null ? v2 == null : v1.equals(v2); // } // } // Path: core/src/main/java/com/github/jsonldjava/core/JsonLdUtils.java import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import com.github.jsonldjava.utils.Obj; static int compareShortestLeast(String a, String b) { if (a.length() < b.length()) { return -1; } else if (b.length() < a.length()) { return 1; } return Integer.signum(a.compareTo(b)); } /** * Compares two JSON-LD values for equality. Two JSON-LD values will be * considered equal if: * * 1. They are both primitives of the same type and value. 2. They are * both @values with the same @value, @type, and @language, OR 3. They both * have @ids they are the same. * * @param v1 * the first value. * @param v2 * the second value. * * @return true if v1 and v2 are considered equal, false if not. */ static boolean compareValues(Object v1, Object v2) { if (v1.equals(v2)) { return true; } if (isValue(v1) && isValue(v2)
&& Obj.equals(((Map<String, Object>) v1).get("@value"),
uncodecn/uncode-dal-all
uncode-dal/src/main/java/cn/uncode/dal/descriptor/Content.java
// Path: uncode-dal/src/main/java/cn/uncode/dal/utils/ColumnWrapperUtils.java // public class ColumnWrapperUtils { // // private static final String KEY_WORDS = "index,key,value,table,option,fields,version,user,name,status,desc,group,signal,"; // // public static String wrap(String column) { // if (KEY_WORDS.indexOf(column) != -1) { // return "`" + column + "`"; // } else { // return column; // } // } // // }
import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import cn.uncode.dal.utils.ColumnWrapperUtils;
package cn.uncode.dal.descriptor; /** * 表内容 * @author ywj * */ public class Content implements Serializable { /** * */ private static final long serialVersionUID = -4742799207318016984L; /** * 所有字段-字符串 */ private String columns; private String database; /** * 表名 */ private String tableName; /** * 字段列表 */ private Map<String, Column> fields; /** * 索索列表 */ private Map<String, List<String>> indexs; /** * 索索字段-名称对应 */ private Map<String, String> indexFields; /** * 主键 */ private PrimaryKey primaryKey; /** * 版本字段 */ private Column versionField; public Content(){ super(); fields = new HashMap<String, Column>(); indexs = new HashMap<String, List<String>>(); indexFields = new HashMap<String, String>(); primaryKey = new PrimaryKey(); } /** * 处理后的表字段 {@code String} 格式的字符串 * <ul> * <li>对字段时行排序处理,sql也会进行排序;</li> * <li>最高级别隐藏不需要显示的字段;</li> * <li>生成主键相关信息;</li> * <li>生成外键相关信息;</li> * <li>生成自定义显示信息;</li> * </ul> * @return 处理后的表字段 {@code String} 格式的字符串。 * @since 1.0 */ public String caculationAllColumn(){ if(StringUtils.isNotEmpty(columns)){ return columns; }else{ StringBuffer sb = new StringBuffer(); List<Column> fds = new ArrayList<Column>(); if(fds == null || fds.size() == 0){ fds.addAll(this.fields.values()); } for(Column f:fds){
// Path: uncode-dal/src/main/java/cn/uncode/dal/utils/ColumnWrapperUtils.java // public class ColumnWrapperUtils { // // private static final String KEY_WORDS = "index,key,value,table,option,fields,version,user,name,status,desc,group,signal,"; // // public static String wrap(String column) { // if (KEY_WORDS.indexOf(column) != -1) { // return "`" + column + "`"; // } else { // return column; // } // } // // } // Path: uncode-dal/src/main/java/cn/uncode/dal/descriptor/Content.java import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import cn.uncode.dal.utils.ColumnWrapperUtils; package cn.uncode.dal.descriptor; /** * 表内容 * @author ywj * */ public class Content implements Serializable { /** * */ private static final long serialVersionUID = -4742799207318016984L; /** * 所有字段-字符串 */ private String columns; private String database; /** * 表名 */ private String tableName; /** * 字段列表 */ private Map<String, Column> fields; /** * 索索列表 */ private Map<String, List<String>> indexs; /** * 索索字段-名称对应 */ private Map<String, String> indexFields; /** * 主键 */ private PrimaryKey primaryKey; /** * 版本字段 */ private Column versionField; public Content(){ super(); fields = new HashMap<String, Column>(); indexs = new HashMap<String, List<String>>(); indexFields = new HashMap<String, String>(); primaryKey = new PrimaryKey(); } /** * 处理后的表字段 {@code String} 格式的字符串 * <ul> * <li>对字段时行排序处理,sql也会进行排序;</li> * <li>最高级别隐藏不需要显示的字段;</li> * <li>生成主键相关信息;</li> * <li>生成外键相关信息;</li> * <li>生成自定义显示信息;</li> * </ul> * @return 处理后的表字段 {@code String} 格式的字符串。 * @since 1.0 */ public String caculationAllColumn(){ if(StringUtils.isNotEmpty(columns)){ return columns; }else{ StringBuffer sb = new StringBuffer(); List<Column> fds = new ArrayList<Column>(); if(fds == null || fds.size() == 0){ fds.addAll(this.fields.values()); } for(Column f:fds){
sb.append(ColumnWrapperUtils.wrap(f.getFieldName())).append(",");
uncodecn/uncode-dal-all
uncode-dal/src/main/java/cn/uncode/dal/asyn/AsynMongoTask.java
// Path: uncode-dal/src/main/java/cn/uncode/dal/core/MongoDAL.java // public interface MongoDAL { // // int NO_CACHE = -2; // // int PERSISTENT_CACHE = 0; // // String PAGE_INDEX_KEY = "pageIndex"; // String PAGE_SIZE_KEY = "pageSize"; // String PAGE_COUNT_KEY = "pageCount"; // String RECORD_TOTAL_KEY = "recordTotal"; // // //------------------------- // // selectByCriteria // //------------------------- // QueryResult selectByCriteria(List<String> fields, QueryCriteria queryCriteria); // // QueryResult selectByCriteria(String[] fields, QueryCriteria queryCriteria); // // QueryResult selectByCriteria(List<String> fields, QueryCriteria queryCriteria, int seconds); // // QueryResult selectByCriteria(String[] fields, QueryCriteria queryCriteria, int seconds); // // QueryResult selectByCriteria(QueryCriteria queryCriteria); // // QueryResult selectByCriteria(QueryCriteria queryCriteria, int seconds); // // QueryResult selectPageByCriteria(List<String> fields, QueryCriteria queryCriteria); // // QueryResult selectPageByCriteria(String[] fields, QueryCriteria queryCriteria); // // QueryResult selectPageByCriteria(List<String> fields, QueryCriteria queryCriteria, int seconds); // // QueryResult selectPageByCriteria(String[] fields, QueryCriteria queryCriteria, int seconds); // // QueryResult selectPageByCriteria(QueryCriteria queryCriteria); // // QueryResult selectPageByCriteria(QueryCriteria queryCriteria, int seconds); // // //------------------------- // // countByCriteria // //------------------------- // int countByCriteria(QueryCriteria queryCriteria); // // int countByCriteria(QueryCriteria queryCriteria, int seconds); // // //------------------------- // // selectByPrimaryKey // //------------------------- // QueryResult selectByPrimaryKey(Object obj); // // QueryResult selectByPrimaryKey(Object obj, int seconds); // // QueryResult selectByPrimaryKey(List<String> fields, Object obj); // // QueryResult selectByPrimaryKey(String[] fields, Object obj); // // QueryResult selectByPrimaryKey(List<String> fields, Object obj, int seconds); // // QueryResult selectByPrimaryKey(String[] fields, Object obj, int seconds); // // QueryResult selectByPrimaryKey(String[] fields, String database, Object obj, int seconds); // // QueryResult selectByPrimaryKey(Class<?> clazz, Object id); // // QueryResult selectByPrimaryKey(String table, Object id); // // QueryResult selectByPrimaryKey(Class<?> clazz, Object id, int seconds); // // QueryResult selectByPrimaryKey(String table, Object id, int seconds); // // QueryResult selectByPrimaryKey(List<String> fields, Class<?> clazz, Object id); // // QueryResult selectByPrimaryKey(List<String> fields, String table, Object id); // // QueryResult selectByPrimaryKey(List<String> fields, Class<?> clazz, Object id, int seconds); // // QueryResult selectByPrimaryKey(List<String> fields, String table, Object id, int seconds); // // //------------------------- // // insert // //------------------------- // Object insert(Object obj); // // Object insert(String table, Map<String, Object> obj); // // Object insert(String database, String table, Map<String, Object> obj); // // void asynInsert(Object obj); // // void asynInsert(String table, Map<String, Object> obj); // // void asynInsert(String database, String table, Map<String, Object> obj); // // //------------------------- // // update // //------------------------- // int updateByCriteria(Object obj, QueryCriteria queryCriteria); // // int updateByPrimaryKey(Object obj); // // int updateByPrimaryKey(String table, Map<String, Object> obj); // // int updateByPrimaryKey(String database, String table, Map<String, Object> obj); // // //------------------------- // // delete // //------------------------- // int deleteByPrimaryKey(Object obj); // // int deleteByPrimaryKey(String table, Map<String, Object> obj); // // int deleteByPrimaryKey(Class<?> clazz, Object id); // // int deleteByPrimaryKey(String table, Object id); // // int deleteByPrimaryKey(String database, String table, Object id); // // int deleteByCriteria(QueryCriteria queryCriteria); // // //------------------------- // // other // //------------------------- // void reloadTable(String tableName); // // void clearCache(String tableName); // // void reloadTable(String database, String tableName); // // void clearCache(String database, String tableName); // // public Object getTemplate(); // // public void runScript(String script); // // // }
import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cn.uncode.dal.core.MongoDAL;
package cn.uncode.dal.asyn; /** * 日志写任务 * * @author juny.ye */ public class AsynMongoTask implements Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(AsynMongoTask.class); /** * 日志列表的最大记录数 */ private int recordsMaxSize = 1; /** * 日志刷新时间间隔(单位:秒) */ private int flushInterval = 1; /** * 日志队列 */ private BlockingQueue<AsynContext> asynQueue; /** * 开关 */ private volatile boolean activeFlag = true; private List<AsynContext> records = new ArrayList<AsynContext>(); private long timestamp = System.currentTimeMillis();
// Path: uncode-dal/src/main/java/cn/uncode/dal/core/MongoDAL.java // public interface MongoDAL { // // int NO_CACHE = -2; // // int PERSISTENT_CACHE = 0; // // String PAGE_INDEX_KEY = "pageIndex"; // String PAGE_SIZE_KEY = "pageSize"; // String PAGE_COUNT_KEY = "pageCount"; // String RECORD_TOTAL_KEY = "recordTotal"; // // //------------------------- // // selectByCriteria // //------------------------- // QueryResult selectByCriteria(List<String> fields, QueryCriteria queryCriteria); // // QueryResult selectByCriteria(String[] fields, QueryCriteria queryCriteria); // // QueryResult selectByCriteria(List<String> fields, QueryCriteria queryCriteria, int seconds); // // QueryResult selectByCriteria(String[] fields, QueryCriteria queryCriteria, int seconds); // // QueryResult selectByCriteria(QueryCriteria queryCriteria); // // QueryResult selectByCriteria(QueryCriteria queryCriteria, int seconds); // // QueryResult selectPageByCriteria(List<String> fields, QueryCriteria queryCriteria); // // QueryResult selectPageByCriteria(String[] fields, QueryCriteria queryCriteria); // // QueryResult selectPageByCriteria(List<String> fields, QueryCriteria queryCriteria, int seconds); // // QueryResult selectPageByCriteria(String[] fields, QueryCriteria queryCriteria, int seconds); // // QueryResult selectPageByCriteria(QueryCriteria queryCriteria); // // QueryResult selectPageByCriteria(QueryCriteria queryCriteria, int seconds); // // //------------------------- // // countByCriteria // //------------------------- // int countByCriteria(QueryCriteria queryCriteria); // // int countByCriteria(QueryCriteria queryCriteria, int seconds); // // //------------------------- // // selectByPrimaryKey // //------------------------- // QueryResult selectByPrimaryKey(Object obj); // // QueryResult selectByPrimaryKey(Object obj, int seconds); // // QueryResult selectByPrimaryKey(List<String> fields, Object obj); // // QueryResult selectByPrimaryKey(String[] fields, Object obj); // // QueryResult selectByPrimaryKey(List<String> fields, Object obj, int seconds); // // QueryResult selectByPrimaryKey(String[] fields, Object obj, int seconds); // // QueryResult selectByPrimaryKey(String[] fields, String database, Object obj, int seconds); // // QueryResult selectByPrimaryKey(Class<?> clazz, Object id); // // QueryResult selectByPrimaryKey(String table, Object id); // // QueryResult selectByPrimaryKey(Class<?> clazz, Object id, int seconds); // // QueryResult selectByPrimaryKey(String table, Object id, int seconds); // // QueryResult selectByPrimaryKey(List<String> fields, Class<?> clazz, Object id); // // QueryResult selectByPrimaryKey(List<String> fields, String table, Object id); // // QueryResult selectByPrimaryKey(List<String> fields, Class<?> clazz, Object id, int seconds); // // QueryResult selectByPrimaryKey(List<String> fields, String table, Object id, int seconds); // // //------------------------- // // insert // //------------------------- // Object insert(Object obj); // // Object insert(String table, Map<String, Object> obj); // // Object insert(String database, String table, Map<String, Object> obj); // // void asynInsert(Object obj); // // void asynInsert(String table, Map<String, Object> obj); // // void asynInsert(String database, String table, Map<String, Object> obj); // // //------------------------- // // update // //------------------------- // int updateByCriteria(Object obj, QueryCriteria queryCriteria); // // int updateByPrimaryKey(Object obj); // // int updateByPrimaryKey(String table, Map<String, Object> obj); // // int updateByPrimaryKey(String database, String table, Map<String, Object> obj); // // //------------------------- // // delete // //------------------------- // int deleteByPrimaryKey(Object obj); // // int deleteByPrimaryKey(String table, Map<String, Object> obj); // // int deleteByPrimaryKey(Class<?> clazz, Object id); // // int deleteByPrimaryKey(String table, Object id); // // int deleteByPrimaryKey(String database, String table, Object id); // // int deleteByCriteria(QueryCriteria queryCriteria); // // //------------------------- // // other // //------------------------- // void reloadTable(String tableName); // // void clearCache(String tableName); // // void reloadTable(String database, String tableName); // // void clearCache(String database, String tableName); // // public Object getTemplate(); // // public void runScript(String script); // // // } // Path: uncode-dal/src/main/java/cn/uncode/dal/asyn/AsynMongoTask.java import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cn.uncode.dal.core.MongoDAL; package cn.uncode.dal.asyn; /** * 日志写任务 * * @author juny.ye */ public class AsynMongoTask implements Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(AsynMongoTask.class); /** * 日志列表的最大记录数 */ private int recordsMaxSize = 1; /** * 日志刷新时间间隔(单位:秒) */ private int flushInterval = 1; /** * 日志队列 */ private BlockingQueue<AsynContext> asynQueue; /** * 开关 */ private volatile boolean activeFlag = true; private List<AsynContext> records = new ArrayList<AsynContext>(); private long timestamp = System.currentTimeMillis();
private MongoDAL mongoDAL;
uncodecn/uncode-dal-all
uncode-dal/src/main/java/cn/uncode/dal/criteria/QueryCriteria.java
// Path: uncode-dal/src/main/java/cn/uncode/dal/criteria/Criterion.java // public enum Condition{ // IS_NULL(1), // IS_NOT_NULL(2), // EQUAL(3), // NOT_EQUAL(4), // GREATER_THAN(5), // GREATER_THAN_OR_EQUAL(6), // LESS_THAN(7), // LESS_THAN_OR_EQUAL(8), // LIKE(9), // NOT_LIKE(10), // IN(11), // NOT_IN(12), // BETWEEN(13), // NOT_BETWEEN(14), // SQL(15); // // public final int type; // Condition(int type){ // this.type = type; // } // // public int getType(){ // return this.type; // } // // }
import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import cn.uncode.dal.criteria.Criterion.Condition;
return sb.toString(); } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String sql) { if (StringUtils.isEmpty(sql)) { throw new RuntimeException("Sql cannot be null"); } criteria.add(new Criterion(sql)); }
// Path: uncode-dal/src/main/java/cn/uncode/dal/criteria/Criterion.java // public enum Condition{ // IS_NULL(1), // IS_NOT_NULL(2), // EQUAL(3), // NOT_EQUAL(4), // GREATER_THAN(5), // GREATER_THAN_OR_EQUAL(6), // LESS_THAN(7), // LESS_THAN_OR_EQUAL(8), // LIKE(9), // NOT_LIKE(10), // IN(11), // NOT_IN(12), // BETWEEN(13), // NOT_BETWEEN(14), // SQL(15); // // public final int type; // Condition(int type){ // this.type = type; // } // // public int getType(){ // return this.type; // } // // } // Path: uncode-dal/src/main/java/cn/uncode/dal/criteria/QueryCriteria.java import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import cn.uncode.dal.criteria.Criterion.Condition; return sb.toString(); } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String sql) { if (StringUtils.isEmpty(sql)) { throw new RuntimeException("Sql cannot be null"); } criteria.add(new Criterion(sql)); }
protected void addCriterion(Condition condition, String column) {
uncodecn/uncode-dal-all
uncode-dal/src/main/java/cn/uncode/dal/jdbc/datasource/DataSourceTransactionManager.java
// Path: uncode-dal/src/main/java/cn/uncode/dal/datasource/DBContextHolder.java // public class DBContextHolder { // // public static final String WRITE = "write"; // public static final String READ = "read"; // public static final String STANDBY = "standby"; // public static final String REPORT = "report"; // public static final String TRANSACTION = "transaction"; // // private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<String>(); // // public static void swithToWrite() { // if(!TRANSACTION.equals(CONTEXT_HOLDER.get())){ // CONTEXT_HOLDER.set(WRITE); // } // } // // public static void swithToRead() { // if(!TRANSACTION.equals(CONTEXT_HOLDER.get())){ // CONTEXT_HOLDER.set(READ); // } // } // // public static void swithToReport() { // CONTEXT_HOLDER.set(REPORT); // } // // public static void swithTotransaction() { // CONTEXT_HOLDER.set(TRANSACTION); // } // // public static void swithTo(String dbType) { // CONTEXT_HOLDER.set(dbType); // } // // public static String getCurrentDataSourceKey() { // return CONTEXT_HOLDER.get(); // } // // public static void clear() { // CONTEXT_HOLDER.remove(); // } // // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.transaction.TransactionDefinition; import cn.uncode.dal.datasource.DBContextHolder;
package cn.uncode.dal.jdbc.datasource; public class DataSourceTransactionManager extends org.springframework.jdbc.datasource.DataSourceTransactionManager { /** * */ private static final long serialVersionUID = -8503950636535704538L; private static Logger LOG = LoggerFactory.getLogger(DataSourceTransactionManager.class); /** * This implementation sets the isolation level but ignores the timeout. */ @Override protected void doBegin(Object transaction, TransactionDefinition definition) {
// Path: uncode-dal/src/main/java/cn/uncode/dal/datasource/DBContextHolder.java // public class DBContextHolder { // // public static final String WRITE = "write"; // public static final String READ = "read"; // public static final String STANDBY = "standby"; // public static final String REPORT = "report"; // public static final String TRANSACTION = "transaction"; // // private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<String>(); // // public static void swithToWrite() { // if(!TRANSACTION.equals(CONTEXT_HOLDER.get())){ // CONTEXT_HOLDER.set(WRITE); // } // } // // public static void swithToRead() { // if(!TRANSACTION.equals(CONTEXT_HOLDER.get())){ // CONTEXT_HOLDER.set(READ); // } // } // // public static void swithToReport() { // CONTEXT_HOLDER.set(REPORT); // } // // public static void swithTotransaction() { // CONTEXT_HOLDER.set(TRANSACTION); // } // // public static void swithTo(String dbType) { // CONTEXT_HOLDER.set(dbType); // } // // public static String getCurrentDataSourceKey() { // return CONTEXT_HOLDER.get(); // } // // public static void clear() { // CONTEXT_HOLDER.remove(); // } // // } // Path: uncode-dal/src/main/java/cn/uncode/dal/jdbc/datasource/DataSourceTransactionManager.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.transaction.TransactionDefinition; import cn.uncode.dal.datasource.DBContextHolder; package cn.uncode.dal.jdbc.datasource; public class DataSourceTransactionManager extends org.springframework.jdbc.datasource.DataSourceTransactionManager { /** * */ private static final long serialVersionUID = -8503950636535704538L; private static Logger LOG = LoggerFactory.getLogger(DataSourceTransactionManager.class); /** * This implementation sets the isolation level but ignores the timeout. */ @Override protected void doBegin(Object transaction, TransactionDefinition definition) {
DBContextHolder.swithTotransaction();
uncodecn/uncode-dal-all
uncode-dal/src/main/java/cn/uncode/dal/internal/shards/strategy/AbstractShardStrategyFactory.java
// Path: uncode-dal/src/main/java/cn/uncode/dal/internal/shards/bo/Shard.java // public class Shard { // // private Map<Long, String> partition = new HashMap<Long, String>(); // private List<String> allPartition = new ArrayList<String>(); // // public Shard(String value){ // //one:1-2,two:2 // if(StringUtils.isNotEmpty(value)){ // String[] sds = value.split(","); // for(String item:sds){ // String[] its = item.split(":"); // String[] se = its[1].split("-"); // if(se.length > 1){ // for(int i = Integer.valueOf(se[0]);i <= Integer.valueOf(se[1]); i++){ // partition.put((long)i, its[0]); // } // }else{ // partition.put(Long.valueOf(se[0]), its[0]); // } // allPartition.add(its[0]); // } // } // } // // public Map<Long, String> getPartition() { // return partition; // } // // public List<String> getAllPartition() { // return allPartition; // } // // // }
import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.springframework.beans.factory.InitializingBean; import cn.uncode.dal.internal.shards.bo.Shard;
package cn.uncode.dal.internal.shards.strategy; public abstract class AbstractShardStrategyFactory implements ShardStrategyFactory, InitializingBean { protected Map<String, String> tableRules = new HashMap<String, String>();
// Path: uncode-dal/src/main/java/cn/uncode/dal/internal/shards/bo/Shard.java // public class Shard { // // private Map<Long, String> partition = new HashMap<Long, String>(); // private List<String> allPartition = new ArrayList<String>(); // // public Shard(String value){ // //one:1-2,two:2 // if(StringUtils.isNotEmpty(value)){ // String[] sds = value.split(","); // for(String item:sds){ // String[] its = item.split(":"); // String[] se = its[1].split("-"); // if(se.length > 1){ // for(int i = Integer.valueOf(se[0]);i <= Integer.valueOf(se[1]); i++){ // partition.put((long)i, its[0]); // } // }else{ // partition.put(Long.valueOf(se[0]), its[0]); // } // allPartition.add(its[0]); // } // } // } // // public Map<Long, String> getPartition() { // return partition; // } // // public List<String> getAllPartition() { // return allPartition; // } // // // } // Path: uncode-dal/src/main/java/cn/uncode/dal/internal/shards/strategy/AbstractShardStrategyFactory.java import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.springframework.beans.factory.InitializingBean; import cn.uncode.dal.internal.shards.bo.Shard; package cn.uncode.dal.internal.shards.strategy; public abstract class AbstractShardStrategyFactory implements ShardStrategyFactory, InitializingBean { protected Map<String, String> tableRules = new HashMap<String, String>();
protected Map<String, Shard> tableShard = new HashMap<String, Shard>();
uncodecn/uncode-dal-all
uncode-dal/src/main/java/cn/uncode/dal/internal/shards/strategy/impl/DefaultShardStrategyFactory.java
// Path: uncode-dal/src/main/java/cn/uncode/dal/internal/shards/bo/Shard.java // public class Shard { // // private Map<Long, String> partition = new HashMap<Long, String>(); // private List<String> allPartition = new ArrayList<String>(); // // public Shard(String value){ // //one:1-2,two:2 // if(StringUtils.isNotEmpty(value)){ // String[] sds = value.split(","); // for(String item:sds){ // String[] its = item.split(":"); // String[] se = its[1].split("-"); // if(se.length > 1){ // for(int i = Integer.valueOf(se[0]);i <= Integer.valueOf(se[1]); i++){ // partition.put((long)i, its[0]); // } // }else{ // partition.put(Long.valueOf(se[0]), its[0]); // } // allPartition.add(its[0]); // } // } // } // // public Map<Long, String> getPartition() { // return partition; // } // // public List<String> getAllPartition() { // return allPartition; // } // // // } // // Path: uncode-dal/src/main/java/cn/uncode/dal/internal/shards/strategy/AbstractShardStrategyFactory.java // public abstract class AbstractShardStrategyFactory implements ShardStrategyFactory, InitializingBean { // // protected Map<String, String> tableRules = new HashMap<String, String>(); // // protected Map<String, Shard> tableShard = new HashMap<String, Shard>(); // // public Map<String, Shard> getTableShard() { // return tableShard; // } // // public void setTableRules(Map<String, String> tableRules) { // this.tableRules = tableRules; // } // // @Override // public void afterPropertiesSet() throws Exception { // for (Entry<String, String> item:tableRules.entrySet()) { // tableShard.put(item.getKey(), new Shard(item.getValue())); // } // // } // // // } // // Path: uncode-dal/src/main/java/cn/uncode/dal/internal/shards/strategy/ShardStrategy.java // public interface ShardStrategy { // // int SHARDS_GROUP_TOTAL = 100; // // String[] selectShardForNewObject(long id); // String[] selectShardFromData(String table); // String[] selectShardForPrimaryKey(String table, Object id); // // // /* ShardSelectionStrategy getShardSelectionStrategy(); // // ShardResolutionStrategy getShardResolutionStrategy(); // // ShardAccessStrategy getShardAccessStrategy(); // // ShardReduceStrategy getShardReduceStrategy();*/ // // }
import cn.uncode.dal.internal.shards.bo.Shard; import cn.uncode.dal.internal.shards.strategy.AbstractShardStrategyFactory; import cn.uncode.dal.internal.shards.strategy.ShardStrategy;
package cn.uncode.dal.internal.shards.strategy.impl; public class DefaultShardStrategyFactory extends AbstractShardStrategyFactory{ @Override
// Path: uncode-dal/src/main/java/cn/uncode/dal/internal/shards/bo/Shard.java // public class Shard { // // private Map<Long, String> partition = new HashMap<Long, String>(); // private List<String> allPartition = new ArrayList<String>(); // // public Shard(String value){ // //one:1-2,two:2 // if(StringUtils.isNotEmpty(value)){ // String[] sds = value.split(","); // for(String item:sds){ // String[] its = item.split(":"); // String[] se = its[1].split("-"); // if(se.length > 1){ // for(int i = Integer.valueOf(se[0]);i <= Integer.valueOf(se[1]); i++){ // partition.put((long)i, its[0]); // } // }else{ // partition.put(Long.valueOf(se[0]), its[0]); // } // allPartition.add(its[0]); // } // } // } // // public Map<Long, String> getPartition() { // return partition; // } // // public List<String> getAllPartition() { // return allPartition; // } // // // } // // Path: uncode-dal/src/main/java/cn/uncode/dal/internal/shards/strategy/AbstractShardStrategyFactory.java // public abstract class AbstractShardStrategyFactory implements ShardStrategyFactory, InitializingBean { // // protected Map<String, String> tableRules = new HashMap<String, String>(); // // protected Map<String, Shard> tableShard = new HashMap<String, Shard>(); // // public Map<String, Shard> getTableShard() { // return tableShard; // } // // public void setTableRules(Map<String, String> tableRules) { // this.tableRules = tableRules; // } // // @Override // public void afterPropertiesSet() throws Exception { // for (Entry<String, String> item:tableRules.entrySet()) { // tableShard.put(item.getKey(), new Shard(item.getValue())); // } // // } // // // } // // Path: uncode-dal/src/main/java/cn/uncode/dal/internal/shards/strategy/ShardStrategy.java // public interface ShardStrategy { // // int SHARDS_GROUP_TOTAL = 100; // // String[] selectShardForNewObject(long id); // String[] selectShardFromData(String table); // String[] selectShardForPrimaryKey(String table, Object id); // // // /* ShardSelectionStrategy getShardSelectionStrategy(); // // ShardResolutionStrategy getShardResolutionStrategy(); // // ShardAccessStrategy getShardAccessStrategy(); // // ShardReduceStrategy getShardReduceStrategy();*/ // // } // Path: uncode-dal/src/main/java/cn/uncode/dal/internal/shards/strategy/impl/DefaultShardStrategyFactory.java import cn.uncode.dal.internal.shards.bo.Shard; import cn.uncode.dal.internal.shards.strategy.AbstractShardStrategyFactory; import cn.uncode.dal.internal.shards.strategy.ShardStrategy; package cn.uncode.dal.internal.shards.strategy.impl; public class DefaultShardStrategyFactory extends AbstractShardStrategyFactory{ @Override
public ShardStrategy newShardStrategy() {
uncodecn/uncode-dal-all
uncode-dal/src/main/java/cn/uncode/dal/internal/shards/strategy/impl/DefaultShardStrategyFactory.java
// Path: uncode-dal/src/main/java/cn/uncode/dal/internal/shards/bo/Shard.java // public class Shard { // // private Map<Long, String> partition = new HashMap<Long, String>(); // private List<String> allPartition = new ArrayList<String>(); // // public Shard(String value){ // //one:1-2,two:2 // if(StringUtils.isNotEmpty(value)){ // String[] sds = value.split(","); // for(String item:sds){ // String[] its = item.split(":"); // String[] se = its[1].split("-"); // if(se.length > 1){ // for(int i = Integer.valueOf(se[0]);i <= Integer.valueOf(se[1]); i++){ // partition.put((long)i, its[0]); // } // }else{ // partition.put(Long.valueOf(se[0]), its[0]); // } // allPartition.add(its[0]); // } // } // } // // public Map<Long, String> getPartition() { // return partition; // } // // public List<String> getAllPartition() { // return allPartition; // } // // // } // // Path: uncode-dal/src/main/java/cn/uncode/dal/internal/shards/strategy/AbstractShardStrategyFactory.java // public abstract class AbstractShardStrategyFactory implements ShardStrategyFactory, InitializingBean { // // protected Map<String, String> tableRules = new HashMap<String, String>(); // // protected Map<String, Shard> tableShard = new HashMap<String, Shard>(); // // public Map<String, Shard> getTableShard() { // return tableShard; // } // // public void setTableRules(Map<String, String> tableRules) { // this.tableRules = tableRules; // } // // @Override // public void afterPropertiesSet() throws Exception { // for (Entry<String, String> item:tableRules.entrySet()) { // tableShard.put(item.getKey(), new Shard(item.getValue())); // } // // } // // // } // // Path: uncode-dal/src/main/java/cn/uncode/dal/internal/shards/strategy/ShardStrategy.java // public interface ShardStrategy { // // int SHARDS_GROUP_TOTAL = 100; // // String[] selectShardForNewObject(long id); // String[] selectShardFromData(String table); // String[] selectShardForPrimaryKey(String table, Object id); // // // /* ShardSelectionStrategy getShardSelectionStrategy(); // // ShardResolutionStrategy getShardResolutionStrategy(); // // ShardAccessStrategy getShardAccessStrategy(); // // ShardReduceStrategy getShardReduceStrategy();*/ // // }
import cn.uncode.dal.internal.shards.bo.Shard; import cn.uncode.dal.internal.shards.strategy.AbstractShardStrategyFactory; import cn.uncode.dal.internal.shards.strategy.ShardStrategy;
package cn.uncode.dal.internal.shards.strategy.impl; public class DefaultShardStrategyFactory extends AbstractShardStrategyFactory{ @Override public ShardStrategy newShardStrategy() { return new ShardStrategy(){ @Override public String[] selectShardFromData(String table) { if(tableShard.containsKey(table)){
// Path: uncode-dal/src/main/java/cn/uncode/dal/internal/shards/bo/Shard.java // public class Shard { // // private Map<Long, String> partition = new HashMap<Long, String>(); // private List<String> allPartition = new ArrayList<String>(); // // public Shard(String value){ // //one:1-2,two:2 // if(StringUtils.isNotEmpty(value)){ // String[] sds = value.split(","); // for(String item:sds){ // String[] its = item.split(":"); // String[] se = its[1].split("-"); // if(se.length > 1){ // for(int i = Integer.valueOf(se[0]);i <= Integer.valueOf(se[1]); i++){ // partition.put((long)i, its[0]); // } // }else{ // partition.put(Long.valueOf(se[0]), its[0]); // } // allPartition.add(its[0]); // } // } // } // // public Map<Long, String> getPartition() { // return partition; // } // // public List<String> getAllPartition() { // return allPartition; // } // // // } // // Path: uncode-dal/src/main/java/cn/uncode/dal/internal/shards/strategy/AbstractShardStrategyFactory.java // public abstract class AbstractShardStrategyFactory implements ShardStrategyFactory, InitializingBean { // // protected Map<String, String> tableRules = new HashMap<String, String>(); // // protected Map<String, Shard> tableShard = new HashMap<String, Shard>(); // // public Map<String, Shard> getTableShard() { // return tableShard; // } // // public void setTableRules(Map<String, String> tableRules) { // this.tableRules = tableRules; // } // // @Override // public void afterPropertiesSet() throws Exception { // for (Entry<String, String> item:tableRules.entrySet()) { // tableShard.put(item.getKey(), new Shard(item.getValue())); // } // // } // // // } // // Path: uncode-dal/src/main/java/cn/uncode/dal/internal/shards/strategy/ShardStrategy.java // public interface ShardStrategy { // // int SHARDS_GROUP_TOTAL = 100; // // String[] selectShardForNewObject(long id); // String[] selectShardFromData(String table); // String[] selectShardForPrimaryKey(String table, Object id); // // // /* ShardSelectionStrategy getShardSelectionStrategy(); // // ShardResolutionStrategy getShardResolutionStrategy(); // // ShardAccessStrategy getShardAccessStrategy(); // // ShardReduceStrategy getShardReduceStrategy();*/ // // } // Path: uncode-dal/src/main/java/cn/uncode/dal/internal/shards/strategy/impl/DefaultShardStrategyFactory.java import cn.uncode.dal.internal.shards.bo.Shard; import cn.uncode.dal.internal.shards.strategy.AbstractShardStrategyFactory; import cn.uncode.dal.internal.shards.strategy.ShardStrategy; package cn.uncode.dal.internal.shards.strategy.impl; public class DefaultShardStrategyFactory extends AbstractShardStrategyFactory{ @Override public ShardStrategy newShardStrategy() { return new ShardStrategy(){ @Override public String[] selectShardFromData(String table) { if(tableShard.containsKey(table)){
Shard shard = tableShard.get(table);
uncodecn/uncode-dal-all
uncode-dal/src/main/java/cn/uncode/dal/event/EventObservable.java
// Path: uncode-dal/src/main/java/cn/uncode/dal/asyn/Method.java // public enum Method { // // SELECT_BY_CRITERIA(1), // // COUNT_BY_CRITERIA(5), // // SELECT_BY_PRIMARY_KEY(6), // // UPDATE(7), // // DELETE(8), // // INSERT(2), INSERT_TABLE(3), INSERT_DATABASE_TABLE(4); // // public final int type; // // Method(int type) { // this.type = type; // } // // }
import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import cn.uncode.dal.asyn.Method;
package cn.uncode.dal.event; /** * * @author juny.ye */ public class EventObservable { private Lock lock = new ReentrantLock(true); private List<EventListener> listeners = new ArrayList<EventListener>(); public void addListener(EventListener listener) { lock.lock(); try { if (listener != null) listeners.add(listener); } finally { lock.unlock(); } } public void deleteListener(EventListener listener) { lock.lock(); try { if (listener != null) listeners.remove(listener); } finally { lock.unlock(); } }
// Path: uncode-dal/src/main/java/cn/uncode/dal/asyn/Method.java // public enum Method { // // SELECT_BY_CRITERIA(1), // // COUNT_BY_CRITERIA(5), // // SELECT_BY_PRIMARY_KEY(6), // // UPDATE(7), // // DELETE(8), // // INSERT(2), INSERT_TABLE(3), INSERT_DATABASE_TABLE(4); // // public final int type; // // Method(int type) { // this.type = type; // } // // } // Path: uncode-dal/src/main/java/cn/uncode/dal/event/EventObservable.java import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import cn.uncode.dal.asyn.Method; package cn.uncode.dal.event; /** * * @author juny.ye */ public class EventObservable { private Lock lock = new ReentrantLock(true); private List<EventListener> listeners = new ArrayList<EventListener>(); public void addListener(EventListener listener) { lock.lock(); try { if (listener != null) listeners.add(listener); } finally { lock.unlock(); } } public void deleteListener(EventListener listener) { lock.lock(); try { if (listener != null) listeners.remove(listener); } finally { lock.unlock(); } }
public void notifyListenersBefore(Method method, Map<String, Object> content) {
uncodecn/uncode-dal-all
uncode-dal/src/main/java/cn/uncode/dal/router/DefaultMasterSlaveRouter.java
// Path: uncode-dal/src/main/java/cn/uncode/dal/datasource/DBContextHolder.java // public class DBContextHolder { // // public static final String WRITE = "write"; // public static final String READ = "read"; // public static final String STANDBY = "standby"; // public static final String REPORT = "report"; // public static final String TRANSACTION = "transaction"; // // private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<String>(); // // public static void swithToWrite() { // if(!TRANSACTION.equals(CONTEXT_HOLDER.get())){ // CONTEXT_HOLDER.set(WRITE); // } // } // // public static void swithToRead() { // if(!TRANSACTION.equals(CONTEXT_HOLDER.get())){ // CONTEXT_HOLDER.set(READ); // } // } // // public static void swithToReport() { // CONTEXT_HOLDER.set(REPORT); // } // // public static void swithTotransaction() { // CONTEXT_HOLDER.set(TRANSACTION); // } // // public static void swithTo(String dbType) { // CONTEXT_HOLDER.set(dbType); // } // // public static String getCurrentDataSourceKey() { // return CONTEXT_HOLDER.get(); // } // // public static void clear() { // CONTEXT_HOLDER.remove(); // } // // }
import cn.uncode.dal.datasource.DBContextHolder;
package cn.uncode.dal.router; public class DefaultMasterSlaveRouter implements MasterSlaveRouter { @Override public void routeToMaster() {
// Path: uncode-dal/src/main/java/cn/uncode/dal/datasource/DBContextHolder.java // public class DBContextHolder { // // public static final String WRITE = "write"; // public static final String READ = "read"; // public static final String STANDBY = "standby"; // public static final String REPORT = "report"; // public static final String TRANSACTION = "transaction"; // // private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<String>(); // // public static void swithToWrite() { // if(!TRANSACTION.equals(CONTEXT_HOLDER.get())){ // CONTEXT_HOLDER.set(WRITE); // } // } // // public static void swithToRead() { // if(!TRANSACTION.equals(CONTEXT_HOLDER.get())){ // CONTEXT_HOLDER.set(READ); // } // } // // public static void swithToReport() { // CONTEXT_HOLDER.set(REPORT); // } // // public static void swithTotransaction() { // CONTEXT_HOLDER.set(TRANSACTION); // } // // public static void swithTo(String dbType) { // CONTEXT_HOLDER.set(dbType); // } // // public static String getCurrentDataSourceKey() { // return CONTEXT_HOLDER.get(); // } // // public static void clear() { // CONTEXT_HOLDER.remove(); // } // // } // Path: uncode-dal/src/main/java/cn/uncode/dal/router/DefaultMasterSlaveRouter.java import cn.uncode.dal.datasource.DBContextHolder; package cn.uncode.dal.router; public class DefaultMasterSlaveRouter implements MasterSlaveRouter { @Override public void routeToMaster() {
DBContextHolder.swithToWrite();
uncodecn/uncode-dal-all
uncode-dal/src/main/java/cn/uncode/dal/event/asyn/NotifyTask.java
// Path: uncode-dal/src/main/java/cn/uncode/dal/event/EventObservable.java // public class EventObservable { // // private Lock lock = new ReentrantLock(true); // // private List<EventListener> listeners = new ArrayList<EventListener>(); // // public void addListener(EventListener listener) { // lock.lock(); // try { // if (listener != null) // listeners.add(listener); // } finally { // lock.unlock(); // } // } // // public void deleteListener(EventListener listener) { // lock.lock(); // try { // if (listener != null) // listeners.remove(listener); // } finally { // lock.unlock(); // } // } // // public void notifyListenersBefore(Method method, Map<String, Object> content) { // lock.lock(); // try { // if (listeners != null) { // for (EventListener obs : listeners) { // obs.before(method, content); // } // } // } finally { // lock.unlock(); // } // } // // public void notifyListenersAfter(Method method, Map<String, Object> content) { // lock.lock(); // try { // if (listeners != null) { // for (EventListener obs : listeners) { // obs.after(method, content); // } // } // } finally { // lock.unlock(); // } // } // // }
import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cn.uncode.dal.event.EventObservable;
package cn.uncode.dal.event.asyn; /** * 日志写任务 * * @author juny.ye */ public class NotifyTask implements Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(NotifyTask.class); /** * 日志列表的最大记录数 */ private int recordsMaxSize = 100; /** * 日志刷新时间间隔(单位:秒) */ private int flushInterval = 1; /** * 日志队列 */ private BlockingQueue<EventContext> logQueue; /** * 开关 */ private volatile boolean activeFlag = true; private List<EventContext> records = new ArrayList<EventContext>(); private long timestamp = System.currentTimeMillis();
// Path: uncode-dal/src/main/java/cn/uncode/dal/event/EventObservable.java // public class EventObservable { // // private Lock lock = new ReentrantLock(true); // // private List<EventListener> listeners = new ArrayList<EventListener>(); // // public void addListener(EventListener listener) { // lock.lock(); // try { // if (listener != null) // listeners.add(listener); // } finally { // lock.unlock(); // } // } // // public void deleteListener(EventListener listener) { // lock.lock(); // try { // if (listener != null) // listeners.remove(listener); // } finally { // lock.unlock(); // } // } // // public void notifyListenersBefore(Method method, Map<String, Object> content) { // lock.lock(); // try { // if (listeners != null) { // for (EventListener obs : listeners) { // obs.before(method, content); // } // } // } finally { // lock.unlock(); // } // } // // public void notifyListenersAfter(Method method, Map<String, Object> content) { // lock.lock(); // try { // if (listeners != null) { // for (EventListener obs : listeners) { // obs.after(method, content); // } // } // } finally { // lock.unlock(); // } // } // // } // Path: uncode-dal/src/main/java/cn/uncode/dal/event/asyn/NotifyTask.java import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cn.uncode.dal.event.EventObservable; package cn.uncode.dal.event.asyn; /** * 日志写任务 * * @author juny.ye */ public class NotifyTask implements Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(NotifyTask.class); /** * 日志列表的最大记录数 */ private int recordsMaxSize = 100; /** * 日志刷新时间间隔(单位:秒) */ private int flushInterval = 1; /** * 日志队列 */ private BlockingQueue<EventContext> logQueue; /** * 开关 */ private volatile boolean activeFlag = true; private List<EventContext> records = new ArrayList<EventContext>(); private long timestamp = System.currentTimeMillis();
private EventObservable observable;
Darkyenus/SBTHotswap
src/main/java/gnu/bytecode/Type.java
// Path: src/main/java/gnu/kawa/util/AbstractWeakHashTable.java // public abstract class AbstractWeakHashTable<K,V> // extends AbstractHashTable<AbstractWeakHashTable.WEntry<K,V>,K,V> // { // /* #ifdef JAVA2 */ // java.lang.ref.ReferenceQueue<V> rqueue // = new java.lang.ref.ReferenceQueue<V>(); // /* #endif */ // // public AbstractWeakHashTable () // { // super(64); // } // // public AbstractWeakHashTable (int capacity) // { // super(capacity); // } // // protected abstract K getKeyFromValue (V value); // // protected int getEntryHashCode (WEntry<K,V> entry) { return entry.hash; } // protected WEntry<K,V> getEntryNext (WEntry<K,V> entry) { return entry.next; } // protected void setEntryNext (WEntry<K,V> entry, WEntry<K,V> next) { entry.next = next; } // protected WEntry<K,V>[] allocEntries(int n) { return (WEntry<K,V>[]) new WEntry[n]; } // // protected V getValueIfMatching (WEntry<K,V> node, Object key) // { // V val = node.getValue(); // if (val != null && matches(getKeyFromValue(val), key)) // return val; // return null; // } // // public V get (Object key, V defaultValue) // { // cleanup(); // return super.get(key, defaultValue); // } // // public int hash (Object key) // { // return System.identityHashCode(key); // } // // protected boolean valuesEqual (V oldValue, V newValue) // { // return oldValue == newValue; // } // // protected WEntry<K,V> makeEntry (K key, int hash, V value) // { // return new WEntry<K,V>(value, this, hash); // } // // public V put (K key, V value) // { // cleanup(); // int hash = hash(key); // int index = hashToIndex(hash); // WEntry<K,V> first = table[index]; // WEntry<K,V> node = first; // WEntry<K,V> prev = null; // V oldValue = null; // for (;;) // { // if (node == null) // { // if (++num_bindings >= table.length) // { // rehash(); // index = hashToIndex(hash); // first = table[index]; // } // node = makeEntry(null, hash, value); // node.next = first; // table[index] = node; // return oldValue; // } // V curValue = node.getValue(); // if (curValue == value) // return curValue; // WEntry<K,V> next = node.next; // if (curValue != null && valuesEqual(curValue, value)) // { // if (prev == null) // table[index] = next; // else // prev.next = next; // oldValue = curValue; // } // else // prev = node; // node = next; // } // } // // protected void cleanup () // { // /* #ifdef JAVA2 */ // cleanup(this, rqueue); // /* #endif */ // } // // static <Entry extends Map.Entry<K,V>,K,V> void cleanup (AbstractHashTable<Entry,?,?> map, // java.lang.ref.ReferenceQueue<?> rqueue) // { // /* #ifdef JAVA2 */ // for (;;) // { // Entry oldref = (Entry) rqueue.poll(); // if (oldref == null) // break; // int index = map.hashToIndex(map.getEntryHashCode(oldref)); // Entry prev = null; // for (Entry node = map.table[index]; // node != null; ) // { // Entry next = map.getEntryNext(node); // if (node == oldref) // { // if (prev == null) // map.table[index] = next; // else // map.setEntryNext(prev, next); // break; // } // prev = node; // node = next; // } // map.num_bindings--; // } // /* #endif */ // } // // public static class WEntry<K,V> // /* #ifdef JAVA2 */ // extends java.lang.ref.WeakReference<V> // implements Map.Entry<K,V> // /* #endif */ // { // public WEntry next; // public int hash; // AbstractWeakHashTable<K,V> htable; // // public WEntry(V value, AbstractWeakHashTable<K,V> htable, int hash) // { // /* #ifdef JAVA2 */ // super(value, htable.rqueue); // /* #else */ // // this.value = value; // /* #endif */ // this.htable = htable; // this.hash = hash; // } // /* #ifndef JAVA2 */ // // K key; // // public K get() { return key; } // /* #endif */ // // public K getKey () // { // V v = get(); // return v == null ? null : htable.getKeyFromValue(v); // } // // public V getValue () // { // return get(); // } // // public V setValue (V value) // { // throw new UnsupportedOperationException(); // } // } // }
import java.util.*; import gnu.kawa.util.AbstractWeakHashTable;
protected Class reflectClass; /** Get the java.lang.Class object for the representation type. */ public java.lang.Class getReflectClass() { return reflectClass; } public void setReflectClass(java.lang.Class rclass) { reflectClass = rclass; } public String toString() { return "Type " + getName(); } public int hashCode() { String name = toString(); return name == null ? 0 : name.hashCode (); } /** A marker class, used for {@code Type.neverReturnsType}. */ public static class NeverReturns { private NeverReturns() { } }
// Path: src/main/java/gnu/kawa/util/AbstractWeakHashTable.java // public abstract class AbstractWeakHashTable<K,V> // extends AbstractHashTable<AbstractWeakHashTable.WEntry<K,V>,K,V> // { // /* #ifdef JAVA2 */ // java.lang.ref.ReferenceQueue<V> rqueue // = new java.lang.ref.ReferenceQueue<V>(); // /* #endif */ // // public AbstractWeakHashTable () // { // super(64); // } // // public AbstractWeakHashTable (int capacity) // { // super(capacity); // } // // protected abstract K getKeyFromValue (V value); // // protected int getEntryHashCode (WEntry<K,V> entry) { return entry.hash; } // protected WEntry<K,V> getEntryNext (WEntry<K,V> entry) { return entry.next; } // protected void setEntryNext (WEntry<K,V> entry, WEntry<K,V> next) { entry.next = next; } // protected WEntry<K,V>[] allocEntries(int n) { return (WEntry<K,V>[]) new WEntry[n]; } // // protected V getValueIfMatching (WEntry<K,V> node, Object key) // { // V val = node.getValue(); // if (val != null && matches(getKeyFromValue(val), key)) // return val; // return null; // } // // public V get (Object key, V defaultValue) // { // cleanup(); // return super.get(key, defaultValue); // } // // public int hash (Object key) // { // return System.identityHashCode(key); // } // // protected boolean valuesEqual (V oldValue, V newValue) // { // return oldValue == newValue; // } // // protected WEntry<K,V> makeEntry (K key, int hash, V value) // { // return new WEntry<K,V>(value, this, hash); // } // // public V put (K key, V value) // { // cleanup(); // int hash = hash(key); // int index = hashToIndex(hash); // WEntry<K,V> first = table[index]; // WEntry<K,V> node = first; // WEntry<K,V> prev = null; // V oldValue = null; // for (;;) // { // if (node == null) // { // if (++num_bindings >= table.length) // { // rehash(); // index = hashToIndex(hash); // first = table[index]; // } // node = makeEntry(null, hash, value); // node.next = first; // table[index] = node; // return oldValue; // } // V curValue = node.getValue(); // if (curValue == value) // return curValue; // WEntry<K,V> next = node.next; // if (curValue != null && valuesEqual(curValue, value)) // { // if (prev == null) // table[index] = next; // else // prev.next = next; // oldValue = curValue; // } // else // prev = node; // node = next; // } // } // // protected void cleanup () // { // /* #ifdef JAVA2 */ // cleanup(this, rqueue); // /* #endif */ // } // // static <Entry extends Map.Entry<K,V>,K,V> void cleanup (AbstractHashTable<Entry,?,?> map, // java.lang.ref.ReferenceQueue<?> rqueue) // { // /* #ifdef JAVA2 */ // for (;;) // { // Entry oldref = (Entry) rqueue.poll(); // if (oldref == null) // break; // int index = map.hashToIndex(map.getEntryHashCode(oldref)); // Entry prev = null; // for (Entry node = map.table[index]; // node != null; ) // { // Entry next = map.getEntryNext(node); // if (node == oldref) // { // if (prev == null) // map.table[index] = next; // else // map.setEntryNext(prev, next); // break; // } // prev = node; // node = next; // } // map.num_bindings--; // } // /* #endif */ // } // // public static class WEntry<K,V> // /* #ifdef JAVA2 */ // extends java.lang.ref.WeakReference<V> // implements Map.Entry<K,V> // /* #endif */ // { // public WEntry next; // public int hash; // AbstractWeakHashTable<K,V> htable; // // public WEntry(V value, AbstractWeakHashTable<K,V> htable, int hash) // { // /* #ifdef JAVA2 */ // super(value, htable.rqueue); // /* #else */ // // this.value = value; // /* #endif */ // this.htable = htable; // this.hash = hash; // } // /* #ifndef JAVA2 */ // // K key; // // public K get() { return key; } // /* #endif */ // // public K getKey () // { // V v = get(); // return v == null ? null : htable.getKeyFromValue(v); // } // // public V getValue () // { // return get(); // } // // public V setValue (V value) // { // throw new UnsupportedOperationException(); // } // } // } // Path: src/main/java/gnu/bytecode/Type.java import java.util.*; import gnu.kawa.util.AbstractWeakHashTable; protected Class reflectClass; /** Get the java.lang.Class object for the representation type. */ public java.lang.Class getReflectClass() { return reflectClass; } public void setReflectClass(java.lang.Class rclass) { reflectClass = rclass; } public String toString() { return "Type " + getName(); } public int hashCode() { String name = toString(); return name == null ? 0 : name.hashCode (); } /** A marker class, used for {@code Type.neverReturnsType}. */ public static class NeverReturns { private NeverReturns() { } }
static class ClassToTypeMap extends AbstractWeakHashTable<Class,Type>
springtestdbunit/spring-test-dbunit
spring-test-dbunit/src/test/java/com/github/springtestdbunit/teardown/DeleteTearDownOnClass.java
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/AfterTearDownDbUnitTestExecutionListener.java // public class AfterTearDownDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?> CHAIN[] = { TransactionalTestExecutionListener.class, // CallAfterTestMethodExecutionListener.class, DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseTearDown; import com.github.springtestdbunit.entity.EntityAssert; import com.github.springtestdbunit.testutils.AfterTearDownDbUnitTestExecutionListener;
/* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.teardown; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/AfterTearDownDbUnitTestExecutionListener.java // public class AfterTearDownDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?> CHAIN[] = { TransactionalTestExecutionListener.class, // CallAfterTestMethodExecutionListener.class, DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // } // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/teardown/DeleteTearDownOnClass.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseTearDown; import com.github.springtestdbunit.entity.EntityAssert; import com.github.springtestdbunit.testutils.AfterTearDownDbUnitTestExecutionListener; /* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.teardown; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
AfterTearDownDbUnitTestExecutionListener.class })
springtestdbunit/spring-test-dbunit
spring-test-dbunit/src/test/java/com/github/springtestdbunit/teardown/DeleteTearDownOnClass.java
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/AfterTearDownDbUnitTestExecutionListener.java // public class AfterTearDownDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?> CHAIN[] = { TransactionalTestExecutionListener.class, // CallAfterTestMethodExecutionListener.class, DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseTearDown; import com.github.springtestdbunit.entity.EntityAssert; import com.github.springtestdbunit.testutils.AfterTearDownDbUnitTestExecutionListener;
/* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.teardown; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, AfterTearDownDbUnitTestExecutionListener.class })
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/AfterTearDownDbUnitTestExecutionListener.java // public class AfterTearDownDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?> CHAIN[] = { TransactionalTestExecutionListener.class, // CallAfterTestMethodExecutionListener.class, DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // } // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/teardown/DeleteTearDownOnClass.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseTearDown; import com.github.springtestdbunit.entity.EntityAssert; import com.github.springtestdbunit.testutils.AfterTearDownDbUnitTestExecutionListener; /* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.teardown; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, AfterTearDownDbUnitTestExecutionListener.class })
@DatabaseTearDown(type = DatabaseOperation.DELETE_ALL, value = "/META-INF/db/delete.xml")
springtestdbunit/spring-test-dbunit
spring-test-dbunit/src/test/java/com/github/springtestdbunit/teardown/DeleteTearDownOnClass.java
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/AfterTearDownDbUnitTestExecutionListener.java // public class AfterTearDownDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?> CHAIN[] = { TransactionalTestExecutionListener.class, // CallAfterTestMethodExecutionListener.class, DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseTearDown; import com.github.springtestdbunit.entity.EntityAssert; import com.github.springtestdbunit.testutils.AfterTearDownDbUnitTestExecutionListener;
/* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.teardown; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, AfterTearDownDbUnitTestExecutionListener.class }) @DatabaseTearDown(type = DatabaseOperation.DELETE_ALL, value = "/META-INF/db/delete.xml") @Transactional public class DeleteTearDownOnClass { @Autowired
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/AfterTearDownDbUnitTestExecutionListener.java // public class AfterTearDownDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?> CHAIN[] = { TransactionalTestExecutionListener.class, // CallAfterTestMethodExecutionListener.class, DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // } // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/teardown/DeleteTearDownOnClass.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseTearDown; import com.github.springtestdbunit.entity.EntityAssert; import com.github.springtestdbunit.testutils.AfterTearDownDbUnitTestExecutionListener; /* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.teardown; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, AfterTearDownDbUnitTestExecutionListener.class }) @DatabaseTearDown(type = DatabaseOperation.DELETE_ALL, value = "/META-INF/db/delete.xml") @Transactional public class DeleteTearDownOnClass { @Autowired
private EntityAssert entityAssert;
springtestdbunit/spring-test-dbunit
spring-test-dbunit/src/test/java/com/github/springtestdbunit/expected/ExpectedFailureOnClassTest.java
// Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/MustFailDbUnitTestExecutionListener.java // public class MustFailDbUnitTestExecutionListener extends TransactionDbUnitTestExecutionListener { // // @Override // public void afterTestMethod(TestContext testContext) throws Exception { // Throwable caught = null; // try { // super.afterTestMethod(testContext); // } catch (Throwable ex) { // caught = ex; // } // Assert.assertNotNull("Test did not fail", caught); // } // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.annotation.ExpectedDatabase; import com.github.springtestdbunit.entity.EntityAssert; import com.github.springtestdbunit.testutils.MustFailDbUnitTestExecutionListener;
/* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.expected; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml")
// Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/MustFailDbUnitTestExecutionListener.java // public class MustFailDbUnitTestExecutionListener extends TransactionDbUnitTestExecutionListener { // // @Override // public void afterTestMethod(TestContext testContext) throws Exception { // Throwable caught = null; // try { // super.afterTestMethod(testContext); // } catch (Throwable ex) { // caught = ex; // } // Assert.assertNotNull("Test did not fail", caught); // } // // } // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/expected/ExpectedFailureOnClassTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.annotation.ExpectedDatabase; import com.github.springtestdbunit.entity.EntityAssert; import com.github.springtestdbunit.testutils.MustFailDbUnitTestExecutionListener; /* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.expected; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml")
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, MustFailDbUnitTestExecutionListener.class })
springtestdbunit/spring-test-dbunit
spring-test-dbunit/src/test/java/com/github/springtestdbunit/expected/ExpectedFailureOnClassTest.java
// Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/MustFailDbUnitTestExecutionListener.java // public class MustFailDbUnitTestExecutionListener extends TransactionDbUnitTestExecutionListener { // // @Override // public void afterTestMethod(TestContext testContext) throws Exception { // Throwable caught = null; // try { // super.afterTestMethod(testContext); // } catch (Throwable ex) { // caught = ex; // } // Assert.assertNotNull("Test did not fail", caught); // } // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.annotation.ExpectedDatabase; import com.github.springtestdbunit.entity.EntityAssert; import com.github.springtestdbunit.testutils.MustFailDbUnitTestExecutionListener;
/* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.expected; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, MustFailDbUnitTestExecutionListener.class }) @ExpectedDatabase("/META-INF/db/expectedfail.xml") @Transactional public class ExpectedFailureOnClassTest { @Autowired
// Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/MustFailDbUnitTestExecutionListener.java // public class MustFailDbUnitTestExecutionListener extends TransactionDbUnitTestExecutionListener { // // @Override // public void afterTestMethod(TestContext testContext) throws Exception { // Throwable caught = null; // try { // super.afterTestMethod(testContext); // } catch (Throwable ex) { // caught = ex; // } // Assert.assertNotNull("Test did not fail", caught); // } // // } // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/expected/ExpectedFailureOnClassTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.annotation.ExpectedDatabase; import com.github.springtestdbunit.entity.EntityAssert; import com.github.springtestdbunit.testutils.MustFailDbUnitTestExecutionListener; /* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.expected; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, MustFailDbUnitTestExecutionListener.class }) @ExpectedDatabase("/META-INF/db/expectedfail.xml") @Transactional public class ExpectedFailureOnClassTest { @Autowired
private EntityAssert entityAssert;
springtestdbunit/spring-test-dbunit
spring-test-dbunit/src/test/java/com/github/springtestdbunit/teardown/MultipleInsertTearDownOnClassTest.java
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/AfterTearDownDbUnitTestExecutionListener.java // public class AfterTearDownDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?> CHAIN[] = { TransactionalTestExecutionListener.class, // CallAfterTestMethodExecutionListener.class, DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseTearDown; import com.github.springtestdbunit.entity.EntityAssert; import com.github.springtestdbunit.testutils.AfterTearDownDbUnitTestExecutionListener;
/* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.teardown; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/AfterTearDownDbUnitTestExecutionListener.java // public class AfterTearDownDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?> CHAIN[] = { TransactionalTestExecutionListener.class, // CallAfterTestMethodExecutionListener.class, DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // } // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/teardown/MultipleInsertTearDownOnClassTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseTearDown; import com.github.springtestdbunit.entity.EntityAssert; import com.github.springtestdbunit.testutils.AfterTearDownDbUnitTestExecutionListener; /* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.teardown; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
AfterTearDownDbUnitTestExecutionListener.class })
springtestdbunit/spring-test-dbunit
spring-test-dbunit/src/test/java/com/github/springtestdbunit/teardown/MultipleInsertTearDownOnClassTest.java
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/AfterTearDownDbUnitTestExecutionListener.java // public class AfterTearDownDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?> CHAIN[] = { TransactionalTestExecutionListener.class, // CallAfterTestMethodExecutionListener.class, DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseTearDown; import com.github.springtestdbunit.entity.EntityAssert; import com.github.springtestdbunit.testutils.AfterTearDownDbUnitTestExecutionListener;
/* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.teardown; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, AfterTearDownDbUnitTestExecutionListener.class })
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/AfterTearDownDbUnitTestExecutionListener.java // public class AfterTearDownDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?> CHAIN[] = { TransactionalTestExecutionListener.class, // CallAfterTestMethodExecutionListener.class, DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // } // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/teardown/MultipleInsertTearDownOnClassTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseTearDown; import com.github.springtestdbunit.entity.EntityAssert; import com.github.springtestdbunit.testutils.AfterTearDownDbUnitTestExecutionListener; /* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.teardown; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, AfterTearDownDbUnitTestExecutionListener.class })
@DatabaseTearDown(type = DatabaseOperation.CLEAN_INSERT, value = { "/META-INF/db/insert.xml",
springtestdbunit/spring-test-dbunit
spring-test-dbunit/src/test/java/com/github/springtestdbunit/teardown/MultipleInsertTearDownOnClassTest.java
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/AfterTearDownDbUnitTestExecutionListener.java // public class AfterTearDownDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?> CHAIN[] = { TransactionalTestExecutionListener.class, // CallAfterTestMethodExecutionListener.class, DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseTearDown; import com.github.springtestdbunit.entity.EntityAssert; import com.github.springtestdbunit.testutils.AfterTearDownDbUnitTestExecutionListener;
/* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.teardown; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, AfterTearDownDbUnitTestExecutionListener.class }) @DatabaseTearDown(type = DatabaseOperation.CLEAN_INSERT, value = { "/META-INF/db/insert.xml", "/META-INF/db/insert2.xml" }) @Transactional public class MultipleInsertTearDownOnClassTest { @Autowired
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/AfterTearDownDbUnitTestExecutionListener.java // public class AfterTearDownDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?> CHAIN[] = { TransactionalTestExecutionListener.class, // CallAfterTestMethodExecutionListener.class, DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // } // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/teardown/MultipleInsertTearDownOnClassTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseTearDown; import com.github.springtestdbunit.entity.EntityAssert; import com.github.springtestdbunit.testutils.AfterTearDownDbUnitTestExecutionListener; /* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.teardown; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, AfterTearDownDbUnitTestExecutionListener.class }) @DatabaseTearDown(type = DatabaseOperation.CLEAN_INSERT, value = { "/META-INF/db/insert.xml", "/META-INF/db/insert2.xml" }) @Transactional public class MultipleInsertTearDownOnClassTest { @Autowired
private EntityAssert entityAssert;
springtestdbunit/spring-test-dbunit
spring-test-dbunit/src/test/java/com/github/springtestdbunit/expected/ExpectedFailureOnMethodTest.java
// Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/MustFailDbUnitTestExecutionListener.java // public class MustFailDbUnitTestExecutionListener extends TransactionDbUnitTestExecutionListener { // // @Override // public void afterTestMethod(TestContext testContext) throws Exception { // Throwable caught = null; // try { // super.afterTestMethod(testContext); // } catch (Throwable ex) { // caught = ex; // } // Assert.assertNotNull("Test did not fail", caught); // } // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.annotation.ExpectedDatabase; import com.github.springtestdbunit.entity.EntityAssert; import com.github.springtestdbunit.testutils.MustFailDbUnitTestExecutionListener;
/* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.expected; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml")
// Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/MustFailDbUnitTestExecutionListener.java // public class MustFailDbUnitTestExecutionListener extends TransactionDbUnitTestExecutionListener { // // @Override // public void afterTestMethod(TestContext testContext) throws Exception { // Throwable caught = null; // try { // super.afterTestMethod(testContext); // } catch (Throwable ex) { // caught = ex; // } // Assert.assertNotNull("Test did not fail", caught); // } // // } // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/expected/ExpectedFailureOnMethodTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.annotation.ExpectedDatabase; import com.github.springtestdbunit.entity.EntityAssert; import com.github.springtestdbunit.testutils.MustFailDbUnitTestExecutionListener; /* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.expected; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml")
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, MustFailDbUnitTestExecutionListener.class })
springtestdbunit/spring-test-dbunit
spring-test-dbunit/src/test/java/com/github/springtestdbunit/expected/ExpectedFailureOnMethodTest.java
// Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/MustFailDbUnitTestExecutionListener.java // public class MustFailDbUnitTestExecutionListener extends TransactionDbUnitTestExecutionListener { // // @Override // public void afterTestMethod(TestContext testContext) throws Exception { // Throwable caught = null; // try { // super.afterTestMethod(testContext); // } catch (Throwable ex) { // caught = ex; // } // Assert.assertNotNull("Test did not fail", caught); // } // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.annotation.ExpectedDatabase; import com.github.springtestdbunit.entity.EntityAssert; import com.github.springtestdbunit.testutils.MustFailDbUnitTestExecutionListener;
/* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.expected; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, MustFailDbUnitTestExecutionListener.class }) @Transactional public class ExpectedFailureOnMethodTest { @Autowired
// Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/MustFailDbUnitTestExecutionListener.java // public class MustFailDbUnitTestExecutionListener extends TransactionDbUnitTestExecutionListener { // // @Override // public void afterTestMethod(TestContext testContext) throws Exception { // Throwable caught = null; // try { // super.afterTestMethod(testContext); // } catch (Throwable ex) { // caught = ex; // } // Assert.assertNotNull("Test did not fail", caught); // } // // } // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/expected/ExpectedFailureOnMethodTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.annotation.ExpectedDatabase; import com.github.springtestdbunit.entity.EntityAssert; import com.github.springtestdbunit.testutils.MustFailDbUnitTestExecutionListener; /* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.expected; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, MustFailDbUnitTestExecutionListener.class }) @Transactional public class ExpectedFailureOnMethodTest { @Autowired
private EntityAssert entityAssert;
springtestdbunit/spring-test-dbunit
spring-test-dbunit/src/test/java/com/github/springtestdbunit/expected/ExpectedFailureOnMethodWithRepeatableReverseTest.java
// Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/MustFailDbUnitTestExecutionListener.java // public class MustFailDbUnitTestExecutionListener extends TransactionDbUnitTestExecutionListener { // // @Override // public void afterTestMethod(TestContext testContext) throws Exception { // Throwable caught = null; // try { // super.afterTestMethod(testContext); // } catch (Throwable ex) { // caught = ex; // } // Assert.assertNotNull("Test did not fail", caught); // } // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.annotation.ExpectedDatabase; import com.github.springtestdbunit.annotation.ExpectedDatabases; import com.github.springtestdbunit.entity.EntityAssert; import com.github.springtestdbunit.testutils.MustFailDbUnitTestExecutionListener;
/* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.expected; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml")
// Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/MustFailDbUnitTestExecutionListener.java // public class MustFailDbUnitTestExecutionListener extends TransactionDbUnitTestExecutionListener { // // @Override // public void afterTestMethod(TestContext testContext) throws Exception { // Throwable caught = null; // try { // super.afterTestMethod(testContext); // } catch (Throwable ex) { // caught = ex; // } // Assert.assertNotNull("Test did not fail", caught); // } // // } // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/expected/ExpectedFailureOnMethodWithRepeatableReverseTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.annotation.ExpectedDatabase; import com.github.springtestdbunit.annotation.ExpectedDatabases; import com.github.springtestdbunit.entity.EntityAssert; import com.github.springtestdbunit.testutils.MustFailDbUnitTestExecutionListener; /* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.expected; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml")
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, MustFailDbUnitTestExecutionListener.class })
springtestdbunit/spring-test-dbunit
spring-test-dbunit/src/test/java/com/github/springtestdbunit/expected/ExpectedFailureOnMethodWithRepeatableReverseTest.java
// Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/MustFailDbUnitTestExecutionListener.java // public class MustFailDbUnitTestExecutionListener extends TransactionDbUnitTestExecutionListener { // // @Override // public void afterTestMethod(TestContext testContext) throws Exception { // Throwable caught = null; // try { // super.afterTestMethod(testContext); // } catch (Throwable ex) { // caught = ex; // } // Assert.assertNotNull("Test did not fail", caught); // } // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.annotation.ExpectedDatabase; import com.github.springtestdbunit.annotation.ExpectedDatabases; import com.github.springtestdbunit.entity.EntityAssert; import com.github.springtestdbunit.testutils.MustFailDbUnitTestExecutionListener;
/* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.expected; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, MustFailDbUnitTestExecutionListener.class }) @Transactional public class ExpectedFailureOnMethodWithRepeatableReverseTest { @Autowired
// Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/MustFailDbUnitTestExecutionListener.java // public class MustFailDbUnitTestExecutionListener extends TransactionDbUnitTestExecutionListener { // // @Override // public void afterTestMethod(TestContext testContext) throws Exception { // Throwable caught = null; // try { // super.afterTestMethod(testContext); // } catch (Throwable ex) { // caught = ex; // } // Assert.assertNotNull("Test did not fail", caught); // } // // } // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/expected/ExpectedFailureOnMethodWithRepeatableReverseTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.annotation.ExpectedDatabase; import com.github.springtestdbunit.annotation.ExpectedDatabases; import com.github.springtestdbunit.entity.EntityAssert; import com.github.springtestdbunit.testutils.MustFailDbUnitTestExecutionListener; /* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.expected; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, MustFailDbUnitTestExecutionListener.class }) @Transactional public class ExpectedFailureOnMethodWithRepeatableReverseTest { @Autowired
private EntityAssert entityAssert;
springtestdbunit/spring-test-dbunit
spring-test-dbunit/src/test/java/com/github/springtestdbunit/operation/DefaultDatabaseOperationLookupTest.java
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // }
import static org.junit.Assert.assertSame; import org.junit.Test; import com.github.springtestdbunit.annotation.DatabaseOperation;
/* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.operation; /** * Tests for {@link DefaultDatabaseOperationLookup}. * * @author Phillip Webb */ public class DefaultDatabaseOperationLookupTest { @Test public void shouldLookup() throws Exception { DefaultDatabaseOperationLookup lookup = new DefaultDatabaseOperationLookup();
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/operation/DefaultDatabaseOperationLookupTest.java import static org.junit.Assert.assertSame; import org.junit.Test; import com.github.springtestdbunit.annotation.DatabaseOperation; /* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.operation; /** * Tests for {@link DefaultDatabaseOperationLookup}. * * @author Phillip Webb */ public class DefaultDatabaseOperationLookupTest { @Test public void shouldLookup() throws Exception { DefaultDatabaseOperationLookup lookup = new DefaultDatabaseOperationLookup();
assertSame(org.dbunit.operation.DatabaseOperation.UPDATE, lookup.get(DatabaseOperation.UPDATE));
springtestdbunit/spring-test-dbunit
spring-test-dbunit/src/test/java/com/github/springtestdbunit/setup/RefereshSetupOnClassTest.java
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/TransactionDbUnitTestExecutionListener.java // public class TransactionDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?>[] CHAIN = { TransactionalTestExecutionListener.class, // DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // } // // Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.TransactionDbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.entity.EntityAssert;
/* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.setup; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/TransactionDbUnitTestExecutionListener.java // public class TransactionDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?>[] CHAIN = { TransactionalTestExecutionListener.class, // DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // } // // Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/setup/RefereshSetupOnClassTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.TransactionDbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.entity.EntityAssert; /* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.setup; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
TransactionDbUnitTestExecutionListener.class })
springtestdbunit/spring-test-dbunit
spring-test-dbunit/src/test/java/com/github/springtestdbunit/setup/RefereshSetupOnClassTest.java
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/TransactionDbUnitTestExecutionListener.java // public class TransactionDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?>[] CHAIN = { TransactionalTestExecutionListener.class, // DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // } // // Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.TransactionDbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.entity.EntityAssert;
/* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.setup; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, TransactionDbUnitTestExecutionListener.class })
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/TransactionDbUnitTestExecutionListener.java // public class TransactionDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?>[] CHAIN = { TransactionalTestExecutionListener.class, // DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // } // // Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/setup/RefereshSetupOnClassTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.TransactionDbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.entity.EntityAssert; /* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.setup; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, TransactionDbUnitTestExecutionListener.class })
@DatabaseSetup(type = DatabaseOperation.REFRESH, value = "/META-INF/db/refresh.xml")
springtestdbunit/spring-test-dbunit
spring-test-dbunit/src/test/java/com/github/springtestdbunit/setup/RefereshSetupOnClassTest.java
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/TransactionDbUnitTestExecutionListener.java // public class TransactionDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?>[] CHAIN = { TransactionalTestExecutionListener.class, // DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // } // // Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.TransactionDbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.entity.EntityAssert;
/* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.setup; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, TransactionDbUnitTestExecutionListener.class }) @DatabaseSetup(type = DatabaseOperation.REFRESH, value = "/META-INF/db/refresh.xml") @Transactional public class RefereshSetupOnClassTest { @Autowired
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/TransactionDbUnitTestExecutionListener.java // public class TransactionDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?>[] CHAIN = { TransactionalTestExecutionListener.class, // DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // } // // Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/setup/RefereshSetupOnClassTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.TransactionDbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.entity.EntityAssert; /* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.setup; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, TransactionDbUnitTestExecutionListener.class }) @DatabaseSetup(type = DatabaseOperation.REFRESH, value = "/META-INF/db/refresh.xml") @Transactional public class RefereshSetupOnClassTest { @Autowired
private EntityAssert entityAssert;
springtestdbunit/spring-test-dbunit
spring-test-dbunit/src/test/java/com/github/springtestdbunit/dataset/FlatXmlDataSetLoaderTest.java
// Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/ExtendedTestContextManager.java // public class ExtendedTestContextManager extends TestContextManager { // // private Object testInstance; // // public ExtendedTestContextManager(Class<?> testClass) throws Exception { // super(testClass); // getTestContext().markApplicationContextDirty(HierarchyMode.CURRENT_LEVEL); // Constructor<?> constructor = testClass.getDeclaredConstructor(); // constructor.setAccessible(true); // this.testInstance = constructor.newInstance(); // } // // public void prepareTestInstance() throws Exception { // prepareTestInstance(this.testInstance); // } // // public Object getTestContextAttribute(String name) { // return getTestContext().getAttribute(name); // } // // public TestContext accessTestContext() { // return getTestContext(); // } // // }
import static org.junit.Assert.*; import org.dbunit.dataset.IDataSet; import org.junit.Before; import org.junit.Test; import org.springframework.test.context.TestContext; import com.github.springtestdbunit.testutils.ExtendedTestContextManager;
/* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.dataset; /** * Tests for {@link FlatXmlDataSetLoader}. * * @author Phillip Webb */ public class FlatXmlDataSetLoaderTest { private TestContext testContext; private FlatXmlDataSetLoader loader; @Before public void setup() throws Exception { this.loader = new FlatXmlDataSetLoader();
// Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/ExtendedTestContextManager.java // public class ExtendedTestContextManager extends TestContextManager { // // private Object testInstance; // // public ExtendedTestContextManager(Class<?> testClass) throws Exception { // super(testClass); // getTestContext().markApplicationContextDirty(HierarchyMode.CURRENT_LEVEL); // Constructor<?> constructor = testClass.getDeclaredConstructor(); // constructor.setAccessible(true); // this.testInstance = constructor.newInstance(); // } // // public void prepareTestInstance() throws Exception { // prepareTestInstance(this.testInstance); // } // // public Object getTestContextAttribute(String name) { // return getTestContext().getAttribute(name); // } // // public TestContext accessTestContext() { // return getTestContext(); // } // // } // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/dataset/FlatXmlDataSetLoaderTest.java import static org.junit.Assert.*; import org.dbunit.dataset.IDataSet; import org.junit.Before; import org.junit.Test; import org.springframework.test.context.TestContext; import com.github.springtestdbunit.testutils.ExtendedTestContextManager; /* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.dataset; /** * Tests for {@link FlatXmlDataSetLoader}. * * @author Phillip Webb */ public class FlatXmlDataSetLoaderTest { private TestContext testContext; private FlatXmlDataSetLoader loader; @Before public void setup() throws Exception { this.loader = new FlatXmlDataSetLoader();
ExtendedTestContextManager manager = new ExtendedTestContextManager(getClass());
springtestdbunit/spring-test-dbunit
spring-test-dbunit/src/test/java/com/github/springtestdbunit/setup/UpdateSetupOnMethodTest.java
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/TransactionDbUnitTestExecutionListener.java // public class TransactionDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?>[] CHAIN = { TransactionalTestExecutionListener.class, // DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // } // // Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.TransactionDbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.entity.EntityAssert;
/* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.setup; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/TransactionDbUnitTestExecutionListener.java // public class TransactionDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?>[] CHAIN = { TransactionalTestExecutionListener.class, // DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // } // // Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/setup/UpdateSetupOnMethodTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.TransactionDbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.entity.EntityAssert; /* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.setup; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
TransactionDbUnitTestExecutionListener.class })
springtestdbunit/spring-test-dbunit
spring-test-dbunit/src/test/java/com/github/springtestdbunit/setup/UpdateSetupOnMethodTest.java
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/TransactionDbUnitTestExecutionListener.java // public class TransactionDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?>[] CHAIN = { TransactionalTestExecutionListener.class, // DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // } // // Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.TransactionDbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.entity.EntityAssert;
/* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.setup; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, TransactionDbUnitTestExecutionListener.class }) @Transactional public class UpdateSetupOnMethodTest { @Autowired
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/TransactionDbUnitTestExecutionListener.java // public class TransactionDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?>[] CHAIN = { TransactionalTestExecutionListener.class, // DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // } // // Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/setup/UpdateSetupOnMethodTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.TransactionDbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.entity.EntityAssert; /* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.setup; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, TransactionDbUnitTestExecutionListener.class }) @Transactional public class UpdateSetupOnMethodTest { @Autowired
private EntityAssert entityAssert;
springtestdbunit/spring-test-dbunit
spring-test-dbunit/src/test/java/com/github/springtestdbunit/setup/UpdateSetupOnMethodTest.java
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/TransactionDbUnitTestExecutionListener.java // public class TransactionDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?>[] CHAIN = { TransactionalTestExecutionListener.class, // DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // } // // Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.TransactionDbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.entity.EntityAssert;
/* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.setup; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, TransactionDbUnitTestExecutionListener.class }) @Transactional public class UpdateSetupOnMethodTest { @Autowired private EntityAssert entityAssert; @Test
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/TransactionDbUnitTestExecutionListener.java // public class TransactionDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?>[] CHAIN = { TransactionalTestExecutionListener.class, // DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // } // // Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/setup/UpdateSetupOnMethodTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.TransactionDbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.entity.EntityAssert; /* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.setup; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, TransactionDbUnitTestExecutionListener.class }) @Transactional public class UpdateSetupOnMethodTest { @Autowired private EntityAssert entityAssert; @Test
@DatabaseSetup(type = DatabaseOperation.UPDATE, value = "/META-INF/db/update.xml")
springtestdbunit/spring-test-dbunit
spring-test-dbunit/src/test/java/com/github/springtestdbunit/setup/MultipleInsertSetupOnClassTest.java
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/TransactionDbUnitTestExecutionListener.java // public class TransactionDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?>[] CHAIN = { TransactionalTestExecutionListener.class, // DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // } // // Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.TransactionDbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.entity.EntityAssert;
/* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.setup; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/TransactionDbUnitTestExecutionListener.java // public class TransactionDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?>[] CHAIN = { TransactionalTestExecutionListener.class, // DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // } // // Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/setup/MultipleInsertSetupOnClassTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.TransactionDbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.entity.EntityAssert; /* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.setup; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
TransactionDbUnitTestExecutionListener.class })
springtestdbunit/spring-test-dbunit
spring-test-dbunit/src/test/java/com/github/springtestdbunit/setup/MultipleInsertSetupOnClassTest.java
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/TransactionDbUnitTestExecutionListener.java // public class TransactionDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?>[] CHAIN = { TransactionalTestExecutionListener.class, // DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // } // // Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.TransactionDbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.entity.EntityAssert;
/* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.setup; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, TransactionDbUnitTestExecutionListener.class })
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/TransactionDbUnitTestExecutionListener.java // public class TransactionDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?>[] CHAIN = { TransactionalTestExecutionListener.class, // DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // } // // Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/setup/MultipleInsertSetupOnClassTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.TransactionDbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.entity.EntityAssert; /* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.setup; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, TransactionDbUnitTestExecutionListener.class })
@DatabaseSetup(type = DatabaseOperation.CLEAN_INSERT, value = { "/META-INF/db/insert.xml", "/META-INF/db/insert2.xml" })
springtestdbunit/spring-test-dbunit
spring-test-dbunit/src/test/java/com/github/springtestdbunit/setup/MultipleInsertSetupOnClassTest.java
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/TransactionDbUnitTestExecutionListener.java // public class TransactionDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?>[] CHAIN = { TransactionalTestExecutionListener.class, // DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // } // // Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.TransactionDbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.entity.EntityAssert;
/* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.setup; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, TransactionDbUnitTestExecutionListener.class }) @DatabaseSetup(type = DatabaseOperation.CLEAN_INSERT, value = { "/META-INF/db/insert.xml", "/META-INF/db/insert2.xml" }) @Transactional public class MultipleInsertSetupOnClassTest { @Autowired
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/TransactionDbUnitTestExecutionListener.java // public class TransactionDbUnitTestExecutionListener extends TestExecutionListenerChain { // // private static final Class<?>[] CHAIN = { TransactionalTestExecutionListener.class, // DbUnitTestExecutionListener.class }; // // @Override // protected Class<?>[] getChain() { // return CHAIN; // } // // } // // Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/annotation/DatabaseOperation.java // public enum DatabaseOperation { // // /** // * Updates the contents of existing database tables from the dataset. // */ // UPDATE, // // /** // * Inserts new database tables and contents from the dataset. // */ // INSERT, // // /** // * Refresh the contents of existing database tables. Rows from the dataset will insert or replace existing data. Any // * database rows that are not in the dataset remain unaffected. // */ // REFRESH, // // /** // * Deletes database table rows that matches rows from the dataset. // */ // DELETE, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset remain unaffected. // * @see #TRUNCATE_TABLE // */ // DELETE_ALL, // // /** // * Deletes all rows from a database table when the table is specified in the dataset. Tables in the database but not // * in the dataset are unaffected. Identical to {@link #DELETE_ALL} expect this operation cannot be rolled back and // * is supported by less database vendors. // * @see #DELETE_ALL // */ // TRUNCATE_TABLE, // // /** // * Deletes all rows from a database table when the tables is specified in the dataset and subsequently insert new // * contents. Equivalent to calling {@link #DELETE_ALL} followed by {@link #INSERT}. // */ // CLEAN_INSERT; // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/entity/EntityAssert.java // public class EntityAssert implements InitializingBean { // // @PersistenceContext // private EntityManager entityManager; // // private CriteriaQuery<SampleEntity> criteriaQuery; // // public void afterPropertiesSet() throws Exception { // CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); // this.criteriaQuery = cb.createQuery(SampleEntity.class); // Root<SampleEntity> from = this.criteriaQuery.from(SampleEntity.class); // this.criteriaQuery.orderBy(cb.asc(from.get("value").as(String.class))); // } // // public void assertValues(String... values) { // SortedSet<String> expected = new TreeSet<String>(Arrays.asList(values)); // SortedSet<String> actual = new TreeSet<String>(); // TypedQuery<SampleEntity> query = this.entityManager.createQuery(this.criteriaQuery); // List<SampleEntity> results = query.getResultList(); // for (SampleEntity sampleEntity : results) { // actual.add(sampleEntity.getValue()); // this.entityManager.detach(sampleEntity); // } // assertEquals(expected, actual); // } // // } // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/setup/MultipleInsertSetupOnClassTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.TransactionDbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseOperation; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.github.springtestdbunit.entity.EntityAssert; /* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.setup; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, TransactionDbUnitTestExecutionListener.class }) @DatabaseSetup(type = DatabaseOperation.CLEAN_INSERT, value = { "/META-INF/db/insert.xml", "/META-INF/db/insert2.xml" }) @Transactional public class MultipleInsertSetupOnClassTest { @Autowired
private EntityAssert entityAssert;
springtestdbunit/spring-test-dbunit
spring-test-dbunit/src/test/java/com/github/springtestdbunit/expected/ExpectedQueryNonStrictFailureOnMethodTest.java
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/assertion/DatabaseAssertionMode.java // public enum DatabaseAssertionMode { // // /** // * Will use default DbUnit data sets assertions. // */ // DEFAULT(new DefaultDatabaseAssertion()), // // /** // * Allows specifying only specific columns and tables in expected data set. Unspecified tables and columns are // * ignored. // * <p> // * <strong>Notes:</strong> // * <ul> // * <li>Expected row order must match order in actual data set.</li> // * <li>Specified columns must match in all rows, e.g. specifying 'column1' value without 'column2' value in one row // * and only 'column2' value in another is not allowed - both 'column1' and 'column2' values must be specified in all // * rows.</li> // * </ul> // */ // NON_STRICT(new NonStrictDatabaseAssertion()), // // /** // * Allows specifying only specific columns and tables in expected data set and ignoring row orders in expected and // * actual data set. Unspecified tables and columns are ignored. Row orders in expected and actual data sets are // * ignored. // * <p> // * <strong>Notes:</strong> // * <ul> // * <li>Expected row order does not need to match order in actual data set.</li> // * <li>Specified columns must match in all rows, e.g. specifying 'column1' value without 'column2' value in one row // * and only 'column2' value in another is not allowed - both 'column1' and 'column2' values must be specified in all // * rows.</li> // * </ul> // */ // NON_STRICT_UNORDERED(new NonStrictUnorderedDatabaseAssertion()); // // private DatabaseAssertion databaseAssertion; // // private DatabaseAssertionMode(DatabaseAssertion databaseAssertion) { // this.databaseAssertion = databaseAssertion; // } // // public DatabaseAssertion getDatabaseAssertion() { // return this.databaseAssertion; // } // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/MustFailDbUnitTestExecutionListener.java // public class MustFailDbUnitTestExecutionListener extends TransactionDbUnitTestExecutionListener { // // @Override // public void afterTestMethod(TestContext testContext) throws Exception { // Throwable caught = null; // try { // super.afterTestMethod(testContext); // } catch (Throwable ex) { // caught = ex; // } // Assert.assertNotNull("Test did not fail", caught); // } // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.annotation.ExpectedDatabase; import com.github.springtestdbunit.assertion.DatabaseAssertionMode; import com.github.springtestdbunit.testutils.MustFailDbUnitTestExecutionListener;
/* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.expected; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml")
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/assertion/DatabaseAssertionMode.java // public enum DatabaseAssertionMode { // // /** // * Will use default DbUnit data sets assertions. // */ // DEFAULT(new DefaultDatabaseAssertion()), // // /** // * Allows specifying only specific columns and tables in expected data set. Unspecified tables and columns are // * ignored. // * <p> // * <strong>Notes:</strong> // * <ul> // * <li>Expected row order must match order in actual data set.</li> // * <li>Specified columns must match in all rows, e.g. specifying 'column1' value without 'column2' value in one row // * and only 'column2' value in another is not allowed - both 'column1' and 'column2' values must be specified in all // * rows.</li> // * </ul> // */ // NON_STRICT(new NonStrictDatabaseAssertion()), // // /** // * Allows specifying only specific columns and tables in expected data set and ignoring row orders in expected and // * actual data set. Unspecified tables and columns are ignored. Row orders in expected and actual data sets are // * ignored. // * <p> // * <strong>Notes:</strong> // * <ul> // * <li>Expected row order does not need to match order in actual data set.</li> // * <li>Specified columns must match in all rows, e.g. specifying 'column1' value without 'column2' value in one row // * and only 'column2' value in another is not allowed - both 'column1' and 'column2' values must be specified in all // * rows.</li> // * </ul> // */ // NON_STRICT_UNORDERED(new NonStrictUnorderedDatabaseAssertion()); // // private DatabaseAssertion databaseAssertion; // // private DatabaseAssertionMode(DatabaseAssertion databaseAssertion) { // this.databaseAssertion = databaseAssertion; // } // // public DatabaseAssertion getDatabaseAssertion() { // return this.databaseAssertion; // } // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/MustFailDbUnitTestExecutionListener.java // public class MustFailDbUnitTestExecutionListener extends TransactionDbUnitTestExecutionListener { // // @Override // public void afterTestMethod(TestContext testContext) throws Exception { // Throwable caught = null; // try { // super.afterTestMethod(testContext); // } catch (Throwable ex) { // caught = ex; // } // Assert.assertNotNull("Test did not fail", caught); // } // // } // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/expected/ExpectedQueryNonStrictFailureOnMethodTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.annotation.ExpectedDatabase; import com.github.springtestdbunit.assertion.DatabaseAssertionMode; import com.github.springtestdbunit.testutils.MustFailDbUnitTestExecutionListener; /* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.expected; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml")
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, MustFailDbUnitTestExecutionListener.class })
springtestdbunit/spring-test-dbunit
spring-test-dbunit/src/test/java/com/github/springtestdbunit/expected/ExpectedQueryNonStrictFailureOnMethodTest.java
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/assertion/DatabaseAssertionMode.java // public enum DatabaseAssertionMode { // // /** // * Will use default DbUnit data sets assertions. // */ // DEFAULT(new DefaultDatabaseAssertion()), // // /** // * Allows specifying only specific columns and tables in expected data set. Unspecified tables and columns are // * ignored. // * <p> // * <strong>Notes:</strong> // * <ul> // * <li>Expected row order must match order in actual data set.</li> // * <li>Specified columns must match in all rows, e.g. specifying 'column1' value without 'column2' value in one row // * and only 'column2' value in another is not allowed - both 'column1' and 'column2' values must be specified in all // * rows.</li> // * </ul> // */ // NON_STRICT(new NonStrictDatabaseAssertion()), // // /** // * Allows specifying only specific columns and tables in expected data set and ignoring row orders in expected and // * actual data set. Unspecified tables and columns are ignored. Row orders in expected and actual data sets are // * ignored. // * <p> // * <strong>Notes:</strong> // * <ul> // * <li>Expected row order does not need to match order in actual data set.</li> // * <li>Specified columns must match in all rows, e.g. specifying 'column1' value without 'column2' value in one row // * and only 'column2' value in another is not allowed - both 'column1' and 'column2' values must be specified in all // * rows.</li> // * </ul> // */ // NON_STRICT_UNORDERED(new NonStrictUnorderedDatabaseAssertion()); // // private DatabaseAssertion databaseAssertion; // // private DatabaseAssertionMode(DatabaseAssertion databaseAssertion) { // this.databaseAssertion = databaseAssertion; // } // // public DatabaseAssertion getDatabaseAssertion() { // return this.databaseAssertion; // } // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/MustFailDbUnitTestExecutionListener.java // public class MustFailDbUnitTestExecutionListener extends TransactionDbUnitTestExecutionListener { // // @Override // public void afterTestMethod(TestContext testContext) throws Exception { // Throwable caught = null; // try { // super.afterTestMethod(testContext); // } catch (Throwable ex) { // caught = ex; // } // Assert.assertNotNull("Test did not fail", caught); // } // // }
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.annotation.ExpectedDatabase; import com.github.springtestdbunit.assertion.DatabaseAssertionMode; import com.github.springtestdbunit.testutils.MustFailDbUnitTestExecutionListener;
/* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.expected; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, MustFailDbUnitTestExecutionListener.class }) @Transactional public class ExpectedQueryNonStrictFailureOnMethodTest { @Test
// Path: spring-test-dbunit/src/main/java/com/github/springtestdbunit/assertion/DatabaseAssertionMode.java // public enum DatabaseAssertionMode { // // /** // * Will use default DbUnit data sets assertions. // */ // DEFAULT(new DefaultDatabaseAssertion()), // // /** // * Allows specifying only specific columns and tables in expected data set. Unspecified tables and columns are // * ignored. // * <p> // * <strong>Notes:</strong> // * <ul> // * <li>Expected row order must match order in actual data set.</li> // * <li>Specified columns must match in all rows, e.g. specifying 'column1' value without 'column2' value in one row // * and only 'column2' value in another is not allowed - both 'column1' and 'column2' values must be specified in all // * rows.</li> // * </ul> // */ // NON_STRICT(new NonStrictDatabaseAssertion()), // // /** // * Allows specifying only specific columns and tables in expected data set and ignoring row orders in expected and // * actual data set. Unspecified tables and columns are ignored. Row orders in expected and actual data sets are // * ignored. // * <p> // * <strong>Notes:</strong> // * <ul> // * <li>Expected row order does not need to match order in actual data set.</li> // * <li>Specified columns must match in all rows, e.g. specifying 'column1' value without 'column2' value in one row // * and only 'column2' value in another is not allowed - both 'column1' and 'column2' values must be specified in all // * rows.</li> // * </ul> // */ // NON_STRICT_UNORDERED(new NonStrictUnorderedDatabaseAssertion()); // // private DatabaseAssertion databaseAssertion; // // private DatabaseAssertionMode(DatabaseAssertion databaseAssertion) { // this.databaseAssertion = databaseAssertion; // } // // public DatabaseAssertion getDatabaseAssertion() { // return this.databaseAssertion; // } // // } // // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/testutils/MustFailDbUnitTestExecutionListener.java // public class MustFailDbUnitTestExecutionListener extends TransactionDbUnitTestExecutionListener { // // @Override // public void afterTestMethod(TestContext testContext) throws Exception { // Throwable caught = null; // try { // super.afterTestMethod(testContext); // } catch (Throwable ex) { // caught = ex; // } // Assert.assertNotNull("Test did not fail", caught); // } // // } // Path: spring-test-dbunit/src/test/java/com/github/springtestdbunit/expected/ExpectedQueryNonStrictFailureOnMethodTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.transaction.annotation.Transactional; import com.github.springtestdbunit.annotation.ExpectedDatabase; import com.github.springtestdbunit.assertion.DatabaseAssertionMode; import com.github.springtestdbunit.testutils.MustFailDbUnitTestExecutionListener; /* * Copyright 2002-2016 the original author or authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.springtestdbunit.expected; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/META-INF/dbunit-context.xml") @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, MustFailDbUnitTestExecutionListener.class }) @Transactional public class ExpectedQueryNonStrictFailureOnMethodTest { @Test
@ExpectedDatabase(value = "/META-INF/db/expected_query_nonstrict.xml", assertionMode = DatabaseAssertionMode.NON_STRICT, query = "select * from SampleEntity where id=1", table = "SampleEntity")