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
sismics/home
home-core/src/main/java/com/sismics/home/core/dao/dbi/ConfigDao.java
// Path: home-core/src/main/java/com/sismics/home/core/constant/ConfigType.java // public enum ConfigType { // } // // Path: home-core/src/main/java/com/sismics/home/core/model/dbi/Config.java // public class Config { // /** // * Configuration parameter ID. // */ // private ConfigType id; // // /** // * Configuration parameter value. // */ // private String value; // // public Config() { // } // // public Config(ConfigType id, String value) { // this.id = id; // this.value = value; // } // // /** // * Getter of id. // * // * @return id // */ // public ConfigType getId() { // return id; // } // // /** // * Setter of id. // * // * @param id id // */ // public void setId(ConfigType id) { // this.id = id; // } // // /** // * Getter of value. // * // * @return value // */ // public String getValue() { // return value; // } // // /** // * Setter of value. // * // * @param value value // */ // public void setValue(String value) { // this.value = value; // } // // @Override // public String toString() { // return Objects.toStringHelper(this) // .add("id", id) // .toString(); // } // } // // Path: home-core/src/main/java/com/sismics/util/context/ThreadLocalContext.java // public class ThreadLocalContext { // /** // * ThreadLocal to store the context. // */ // public static final ThreadLocal<ThreadLocalContext> threadLocalContext = new ThreadLocal<ThreadLocalContext>(); // // /** // * JDBI handle. // */ // private Handle handle; // // /** // * Private constructor. // */ // private ThreadLocalContext() { // // NOP // } // // /** // * Returns an instance of this thread context. // * // * @return Thread local context // */ // public static ThreadLocalContext get() { // ThreadLocalContext context = threadLocalContext.get(); // if (context == null) { // context = new ThreadLocalContext(); // threadLocalContext.set(context); // } // return context; // } // // /** // * Cleans up the instance of this thread context. // */ // public static void cleanup() { // threadLocalContext.set(null); // } // // /** // * Getter of handle. // * // * @return handle // */ // public Handle getHandle() { // return handle; // } // // /** // * Setter of handle. // * // * @param handle handle // */ // public void setHandle(Handle handle) { // this.handle = handle; // } // }
import com.sismics.home.core.constant.ConfigType; import com.sismics.home.core.model.dbi.Config; import com.sismics.util.context.ThreadLocalContext; import org.skife.jdbi.v2.Handle;
package com.sismics.home.core.dao.dbi; /** * Configuration parameter DAO. * * @author jtremeaux */ public class ConfigDao { /** * Gets a configuration parameter by its ID. * * @param id Configuration parameter ID * @return Configuration parameter */ public Config getById(ConfigType id) {
// Path: home-core/src/main/java/com/sismics/home/core/constant/ConfigType.java // public enum ConfigType { // } // // Path: home-core/src/main/java/com/sismics/home/core/model/dbi/Config.java // public class Config { // /** // * Configuration parameter ID. // */ // private ConfigType id; // // /** // * Configuration parameter value. // */ // private String value; // // public Config() { // } // // public Config(ConfigType id, String value) { // this.id = id; // this.value = value; // } // // /** // * Getter of id. // * // * @return id // */ // public ConfigType getId() { // return id; // } // // /** // * Setter of id. // * // * @param id id // */ // public void setId(ConfigType id) { // this.id = id; // } // // /** // * Getter of value. // * // * @return value // */ // public String getValue() { // return value; // } // // /** // * Setter of value. // * // * @param value value // */ // public void setValue(String value) { // this.value = value; // } // // @Override // public String toString() { // return Objects.toStringHelper(this) // .add("id", id) // .toString(); // } // } // // Path: home-core/src/main/java/com/sismics/util/context/ThreadLocalContext.java // public class ThreadLocalContext { // /** // * ThreadLocal to store the context. // */ // public static final ThreadLocal<ThreadLocalContext> threadLocalContext = new ThreadLocal<ThreadLocalContext>(); // // /** // * JDBI handle. // */ // private Handle handle; // // /** // * Private constructor. // */ // private ThreadLocalContext() { // // NOP // } // // /** // * Returns an instance of this thread context. // * // * @return Thread local context // */ // public static ThreadLocalContext get() { // ThreadLocalContext context = threadLocalContext.get(); // if (context == null) { // context = new ThreadLocalContext(); // threadLocalContext.set(context); // } // return context; // } // // /** // * Cleans up the instance of this thread context. // */ // public static void cleanup() { // threadLocalContext.set(null); // } // // /** // * Getter of handle. // * // * @return handle // */ // public Handle getHandle() { // return handle; // } // // /** // * Setter of handle. // * // * @param handle handle // */ // public void setHandle(Handle handle) { // this.handle = handle; // } // } // Path: home-core/src/main/java/com/sismics/home/core/dao/dbi/ConfigDao.java import com.sismics.home.core.constant.ConfigType; import com.sismics.home.core.model.dbi.Config; import com.sismics.util.context.ThreadLocalContext; import org.skife.jdbi.v2.Handle; package com.sismics.home.core.dao.dbi; /** * Configuration parameter DAO. * * @author jtremeaux */ public class ConfigDao { /** * Gets a configuration parameter by its ID. * * @param id Configuration parameter ID * @return Configuration parameter */ public Config getById(ConfigType id) {
final Handle handle = ThreadLocalContext.get().getHandle();
sismics/home
home-web/src/test/java/com/sismics/home/rest/TestCameraResource.java
// Path: home-web-common/src/main/java/com/sismics/util/filter/TokenBasedSecurityFilter.java // public class TokenBasedSecurityFilter implements Filter { // /** // * Logger. // */ // private static final Logger log = LoggerFactory.getLogger(TokenBasedSecurityFilter.class); // // /** // * Name of the cookie used to store the authentication token. // */ // public static final String COOKIE_NAME = "auth_token"; // // /** // * Name of the attribute containing the principal. // */ // public static final String PRINCIPAL_ATTRIBUTE = "principal"; // // /** // * Lifetime of the authentication token in seconds, since login. // */ // public static final int TOKEN_LONG_LIFETIME = 3600 * 24 * 365 * 20; // // /** // * Lifetime of the authentication token in seconds, since last connection. // */ // public static final int TOKEN_SESSION_LIFETIME = 3600 * 24; // // @Override // public void init(FilterConfig filterConfig) throws ServletException { // // NOP // } // // @Override // public void destroy() { // // NOP // } // // @Override // public void doFilter(ServletRequest req, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { // // Get the value of the client authentication token // HttpServletRequest request = (HttpServletRequest) req; // String authToken = null; // if (request.getCookies() != null) { // for (Cookie cookie : request.getCookies()) { // if (COOKIE_NAME.equals(cookie.getName())) { // authToken = cookie.getValue(); // } // } // } // // // Get the corresponding server token // AuthenticationTokenDao authenticationTokenDao = new AuthenticationTokenDao(); // AuthenticationToken authenticationToken = null; // if (authToken != null) { // authenticationToken = authenticationTokenDao.get(authToken); // } // // if (authenticationToken == null) { // injectAnonymousUser(request); // } else { // // Check if the token is still valid // if (isTokenExpired(authenticationToken)) { // try { // injectAnonymousUser(request); // // // Destroy the expired token // authenticationTokenDao.delete(authToken); // } catch (Exception e) { // if (log.isErrorEnabled()) { // log.error(MessageFormat.format("Error deleting authentication token {0} ", authToken), e); // } // } // } else { // // Check if the user is still valid // UserDao userDao = new UserDao(); // User user = userDao.getActiveById(authenticationToken.getUserId()); // if (user != null) { // injectAuthenticatedUser(request, user); // // // Update the last connection date // authenticationTokenDao.updateLastConnectionDate(authenticationToken.getId()); // } else { // injectAnonymousUser(request); // } // } // } // // filterChain.doFilter(request, response); // } // // /** // * Returns true if the token is expired. // * // * @param authenticationToken Authentication token // * @return Token expired // */ // private boolean isTokenExpired(AuthenticationToken authenticationToken) { // final long now = new Date().getTime(); // final long creationDate = authenticationToken.getCreateDate().getTime(); // if (authenticationToken.isLongLasted()) { // return now >= creationDate + ((long) TOKEN_LONG_LIFETIME) * 1000L; // } else { // long date = authenticationToken.getLastConnectionDate() != null ? // authenticationToken.getLastConnectionDate().getTime() : creationDate; // return now >= date + ((long) TOKEN_SESSION_LIFETIME) * 1000L; // } // } // // /** // * Inject an authenticated user into the request attributes. // * // * @param request HTTP request // * @param user User to inject // */ // private void injectAuthenticatedUser(HttpServletRequest request, User user) { // UserPrincipal userPrincipal = new UserPrincipal(user.getId(), user.getUsername()); // // // Add base functions // RoleBaseFunctionDao userBaseFuction = new RoleBaseFunctionDao(); // Set<String> baseFunctionSet = userBaseFuction.findByRoleId(user.getRoleId()); // userPrincipal.setBaseFunctionSet(baseFunctionSet); // // request.setAttribute(PRINCIPAL_ATTRIBUTE, userPrincipal); // } // // /** // * Inject an anonymous user into the request attributes. // * // * @param request HTTP request // */ // private void injectAnonymousUser(HttpServletRequest request) { // AnonymousPrincipal anonymousPrincipal = new AnonymousPrincipal(); // anonymousPrincipal.setDateTimeZone(DateTimeZone.forID(Constants.DEFAULT_TIMEZONE_ID)); // // request.setAttribute(PRINCIPAL_ATTRIBUTE, anonymousPrincipal); // } // }
import javax.json.JsonArray; import javax.json.JsonObject; import javax.ws.rs.client.Entity; import javax.ws.rs.core.Form; import org.junit.Assert; import org.junit.Test; import com.google.common.io.Resources; import com.sismics.util.filter.TokenBasedSecurityFilter;
package com.sismics.home.rest; /** * Exhaustive test of the camera resource. * * @author bgamard */ public class TestCameraResource extends BaseJerseyTest { /** * Test the camera resource. * * @throws JSONException */ @Test public void testCameraResource() { // Login admin String adminAuthenticationToken = clientUtil.login("admin", "admin", false); // List all cameras JsonObject json = target().path("/camera").request()
// Path: home-web-common/src/main/java/com/sismics/util/filter/TokenBasedSecurityFilter.java // public class TokenBasedSecurityFilter implements Filter { // /** // * Logger. // */ // private static final Logger log = LoggerFactory.getLogger(TokenBasedSecurityFilter.class); // // /** // * Name of the cookie used to store the authentication token. // */ // public static final String COOKIE_NAME = "auth_token"; // // /** // * Name of the attribute containing the principal. // */ // public static final String PRINCIPAL_ATTRIBUTE = "principal"; // // /** // * Lifetime of the authentication token in seconds, since login. // */ // public static final int TOKEN_LONG_LIFETIME = 3600 * 24 * 365 * 20; // // /** // * Lifetime of the authentication token in seconds, since last connection. // */ // public static final int TOKEN_SESSION_LIFETIME = 3600 * 24; // // @Override // public void init(FilterConfig filterConfig) throws ServletException { // // NOP // } // // @Override // public void destroy() { // // NOP // } // // @Override // public void doFilter(ServletRequest req, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { // // Get the value of the client authentication token // HttpServletRequest request = (HttpServletRequest) req; // String authToken = null; // if (request.getCookies() != null) { // for (Cookie cookie : request.getCookies()) { // if (COOKIE_NAME.equals(cookie.getName())) { // authToken = cookie.getValue(); // } // } // } // // // Get the corresponding server token // AuthenticationTokenDao authenticationTokenDao = new AuthenticationTokenDao(); // AuthenticationToken authenticationToken = null; // if (authToken != null) { // authenticationToken = authenticationTokenDao.get(authToken); // } // // if (authenticationToken == null) { // injectAnonymousUser(request); // } else { // // Check if the token is still valid // if (isTokenExpired(authenticationToken)) { // try { // injectAnonymousUser(request); // // // Destroy the expired token // authenticationTokenDao.delete(authToken); // } catch (Exception e) { // if (log.isErrorEnabled()) { // log.error(MessageFormat.format("Error deleting authentication token {0} ", authToken), e); // } // } // } else { // // Check if the user is still valid // UserDao userDao = new UserDao(); // User user = userDao.getActiveById(authenticationToken.getUserId()); // if (user != null) { // injectAuthenticatedUser(request, user); // // // Update the last connection date // authenticationTokenDao.updateLastConnectionDate(authenticationToken.getId()); // } else { // injectAnonymousUser(request); // } // } // } // // filterChain.doFilter(request, response); // } // // /** // * Returns true if the token is expired. // * // * @param authenticationToken Authentication token // * @return Token expired // */ // private boolean isTokenExpired(AuthenticationToken authenticationToken) { // final long now = new Date().getTime(); // final long creationDate = authenticationToken.getCreateDate().getTime(); // if (authenticationToken.isLongLasted()) { // return now >= creationDate + ((long) TOKEN_LONG_LIFETIME) * 1000L; // } else { // long date = authenticationToken.getLastConnectionDate() != null ? // authenticationToken.getLastConnectionDate().getTime() : creationDate; // return now >= date + ((long) TOKEN_SESSION_LIFETIME) * 1000L; // } // } // // /** // * Inject an authenticated user into the request attributes. // * // * @param request HTTP request // * @param user User to inject // */ // private void injectAuthenticatedUser(HttpServletRequest request, User user) { // UserPrincipal userPrincipal = new UserPrincipal(user.getId(), user.getUsername()); // // // Add base functions // RoleBaseFunctionDao userBaseFuction = new RoleBaseFunctionDao(); // Set<String> baseFunctionSet = userBaseFuction.findByRoleId(user.getRoleId()); // userPrincipal.setBaseFunctionSet(baseFunctionSet); // // request.setAttribute(PRINCIPAL_ATTRIBUTE, userPrincipal); // } // // /** // * Inject an anonymous user into the request attributes. // * // * @param request HTTP request // */ // private void injectAnonymousUser(HttpServletRequest request) { // AnonymousPrincipal anonymousPrincipal = new AnonymousPrincipal(); // anonymousPrincipal.setDateTimeZone(DateTimeZone.forID(Constants.DEFAULT_TIMEZONE_ID)); // // request.setAttribute(PRINCIPAL_ATTRIBUTE, anonymousPrincipal); // } // } // Path: home-web/src/test/java/com/sismics/home/rest/TestCameraResource.java import javax.json.JsonArray; import javax.json.JsonObject; import javax.ws.rs.client.Entity; import javax.ws.rs.core.Form; import org.junit.Assert; import org.junit.Test; import com.google.common.io.Resources; import com.sismics.util.filter.TokenBasedSecurityFilter; package com.sismics.home.rest; /** * Exhaustive test of the camera resource. * * @author bgamard */ public class TestCameraResource extends BaseJerseyTest { /** * Test the camera resource. * * @throws JSONException */ @Test public void testCameraResource() { // Login admin String adminAuthenticationToken = clientUtil.login("admin", "admin", false); // List all cameras JsonObject json = target().path("/camera").request()
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, adminAuthenticationToken)
sismics/home
home-core/src/main/java/com/sismics/home/core/dao/dbi/RoleBaseFunctionDao.java
// Path: home-core/src/main/java/com/sismics/util/context/ThreadLocalContext.java // public class ThreadLocalContext { // /** // * ThreadLocal to store the context. // */ // public static final ThreadLocal<ThreadLocalContext> threadLocalContext = new ThreadLocal<ThreadLocalContext>(); // // /** // * JDBI handle. // */ // private Handle handle; // // /** // * Private constructor. // */ // private ThreadLocalContext() { // // NOP // } // // /** // * Returns an instance of this thread context. // * // * @return Thread local context // */ // public static ThreadLocalContext get() { // ThreadLocalContext context = threadLocalContext.get(); // if (context == null) { // context = new ThreadLocalContext(); // threadLocalContext.set(context); // } // return context; // } // // /** // * Cleans up the instance of this thread context. // */ // public static void cleanup() { // threadLocalContext.set(null); // } // // /** // * Getter of handle. // * // * @return handle // */ // public Handle getHandle() { // return handle; // } // // /** // * Setter of handle. // * // * @param handle handle // */ // public void setHandle(Handle handle) { // this.handle = handle; // } // }
import com.google.common.collect.Sets; import com.sismics.util.context.ThreadLocalContext; import org.skife.jdbi.v2.Handle; import java.util.List; import java.util.Map; import java.util.Set;
package com.sismics.home.core.dao.dbi; /** * Role base functions DAO. * * @author jtremeaux */ public class RoleBaseFunctionDao { /** * Find the set of base functions of a role. * * @param roleId Role ID * @return Set of base functions */ public Set<String> findByRoleId(String roleId) {
// Path: home-core/src/main/java/com/sismics/util/context/ThreadLocalContext.java // public class ThreadLocalContext { // /** // * ThreadLocal to store the context. // */ // public static final ThreadLocal<ThreadLocalContext> threadLocalContext = new ThreadLocal<ThreadLocalContext>(); // // /** // * JDBI handle. // */ // private Handle handle; // // /** // * Private constructor. // */ // private ThreadLocalContext() { // // NOP // } // // /** // * Returns an instance of this thread context. // * // * @return Thread local context // */ // public static ThreadLocalContext get() { // ThreadLocalContext context = threadLocalContext.get(); // if (context == null) { // context = new ThreadLocalContext(); // threadLocalContext.set(context); // } // return context; // } // // /** // * Cleans up the instance of this thread context. // */ // public static void cleanup() { // threadLocalContext.set(null); // } // // /** // * Getter of handle. // * // * @return handle // */ // public Handle getHandle() { // return handle; // } // // /** // * Setter of handle. // * // * @param handle handle // */ // public void setHandle(Handle handle) { // this.handle = handle; // } // } // Path: home-core/src/main/java/com/sismics/home/core/dao/dbi/RoleBaseFunctionDao.java import com.google.common.collect.Sets; import com.sismics.util.context.ThreadLocalContext; import org.skife.jdbi.v2.Handle; import java.util.List; import java.util.Map; import java.util.Set; package com.sismics.home.core.dao.dbi; /** * Role base functions DAO. * * @author jtremeaux */ public class RoleBaseFunctionDao { /** * Find the set of base functions of a role. * * @param roleId Role ID * @return Set of base functions */ public Set<String> findByRoleId(String roleId) {
final Handle handle = ThreadLocalContext.get().getHandle();
sismics/home
home-web-common/src/main/java/com/sismics/rest/util/ValidationUtil.java
// Path: home-web-common/src/main/java/com/sismics/rest/exception/ClientException.java // public class ClientException extends WebApplicationException { // /** // * Serial UID. // */ // private static final long serialVersionUID = 1L; // // /** // * Logger. // */ // private static final Logger log = LoggerFactory.getLogger(ClientException.class); // // /** // * Constructor of ClientException. // * // * @param type Error type (e.g. AlreadyExistingEmail, ValidationError) // * @param message Human readable error message // * @param e Readable error message // */ // public ClientException(String type, String message, Exception e) { // this(type, message); // log.error(type + ": " + message, e); // } // // /** // * Constructor of ClientException. // * // * @param type Error type (e.g. AlreadyExistingEmail, ValidationError) // * @param message Human readable error message // */ // public ClientException(String type, String message) { // super(Response.status(Status.BAD_REQUEST).entity(Json.createObjectBuilder() // .add("type", type) // .add("message", message).build()).build()); // } // }
import java.io.File; import java.text.MessageFormat; import java.util.Date; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.joda.time.DateTime; import com.google.common.base.Strings; import com.sismics.rest.exception.ClientException;
package com.sismics.rest.util; /** * Utility class to validate parameters. * * @author jtremeaux */ public class ValidationUtil { private static Pattern EMAIL_PATTERN = Pattern.compile(".+@.+\\..+"); private static Pattern HTTP_URL_PATTERN = Pattern.compile("https?://.+"); private static Pattern ALPHANUMERIC_PATTERN = Pattern.compile("[a-zA-Z0-9_]+"); /** * Checks that the argument is not null. * * @param s Object tu validate * @param name Name of the parameter * @throws ClientException */
// Path: home-web-common/src/main/java/com/sismics/rest/exception/ClientException.java // public class ClientException extends WebApplicationException { // /** // * Serial UID. // */ // private static final long serialVersionUID = 1L; // // /** // * Logger. // */ // private static final Logger log = LoggerFactory.getLogger(ClientException.class); // // /** // * Constructor of ClientException. // * // * @param type Error type (e.g. AlreadyExistingEmail, ValidationError) // * @param message Human readable error message // * @param e Readable error message // */ // public ClientException(String type, String message, Exception e) { // this(type, message); // log.error(type + ": " + message, e); // } // // /** // * Constructor of ClientException. // * // * @param type Error type (e.g. AlreadyExistingEmail, ValidationError) // * @param message Human readable error message // */ // public ClientException(String type, String message) { // super(Response.status(Status.BAD_REQUEST).entity(Json.createObjectBuilder() // .add("type", type) // .add("message", message).build()).build()); // } // } // Path: home-web-common/src/main/java/com/sismics/rest/util/ValidationUtil.java import java.io.File; import java.text.MessageFormat; import java.util.Date; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.joda.time.DateTime; import com.google.common.base.Strings; import com.sismics.rest.exception.ClientException; package com.sismics.rest.util; /** * Utility class to validate parameters. * * @author jtremeaux */ public class ValidationUtil { private static Pattern EMAIL_PATTERN = Pattern.compile(".+@.+\\..+"); private static Pattern HTTP_URL_PATTERN = Pattern.compile("https?://.+"); private static Pattern ALPHANUMERIC_PATTERN = Pattern.compile("[a-zA-Z0-9_]+"); /** * Checks that the argument is not null. * * @param s Object tu validate * @param name Name of the parameter * @throws ClientException */
public static void validateRequired(Object s, String name) throws ClientException {
sismics/home
home-core/src/main/java/com/sismics/home/core/util/TransactionUtil.java
// Path: home-core/src/main/java/com/sismics/util/context/ThreadLocalContext.java // public class ThreadLocalContext { // /** // * ThreadLocal to store the context. // */ // public static final ThreadLocal<ThreadLocalContext> threadLocalContext = new ThreadLocal<ThreadLocalContext>(); // // /** // * JDBI handle. // */ // private Handle handle; // // /** // * Private constructor. // */ // private ThreadLocalContext() { // // NOP // } // // /** // * Returns an instance of this thread context. // * // * @return Thread local context // */ // public static ThreadLocalContext get() { // ThreadLocalContext context = threadLocalContext.get(); // if (context == null) { // context = new ThreadLocalContext(); // threadLocalContext.set(context); // } // return context; // } // // /** // * Cleans up the instance of this thread context. // */ // public static void cleanup() { // threadLocalContext.set(null); // } // // /** // * Getter of handle. // * // * @return handle // */ // public Handle getHandle() { // return handle; // } // // /** // * Setter of handle. // * // * @param handle handle // */ // public void setHandle(Handle handle) { // this.handle = handle; // } // } // // Path: home-core/src/main/java/com/sismics/util/dbi/DBIF.java // public class DBIF { // private static final Logger log = LoggerFactory.getLogger(DBIF.class); // // private static ComboPooledDataSource cpds; // // private static DBI dbi; // // static { // if (dbi == null) { // createDbi(); // } // } // // public static void createDbi() { // try { // cpds = new ComboPooledDataSource(); // TODO use getDbProperties() // dbi = new DBI(cpds); // dbi.registerMapper(new AuthenticationTokenMapper()); // dbi.registerMapper(new BaseFunctionMapper()); // dbi.registerMapper(new ConfigMapper()); // dbi.registerMapper(new RoleBaseFunctionMapper()); // dbi.registerMapper(new RoleMapper()); // dbi.registerMapper(new UserMapper()); // dbi.registerMapper(new SensorMapper()); // dbi.registerMapper(new SensorSampleMapper()); // dbi.registerMapper(new CameraMapper()); // } catch (Throwable t) { // log.error("Error creating DBI", t); // } // // Handle handle = null; // try { // handle = dbi.open(); // DbOpenHelper openHelper = new DbOpenHelper(handle) { // // @Override // public void onCreate() throws Exception { // executeAllScript(0); // } // // @Override // public void onUpgrade(int oldVersion, int newVersion) throws Exception { // for (int version = oldVersion + 1; version <= newVersion; version++) { // executeAllScript(version); // } // } // }; // openHelper.open(); // } catch (Exception e) { // if (handle != null && handle.isInTransaction()) { // handle.rollback(); // handle.close(); // } // } // // } // // private static Map<Object, Object> getDbProperties() { // // Use properties file if exists // try { // URL dbPropertiesUrl = DBIF.class.getResource("/c3p0.properties"); // if (dbPropertiesUrl != null) { // log.info("Configuring connection pool from c3p0.properties"); // // InputStream is = dbPropertiesUrl.openStream(); // Properties properties = new Properties(); // properties.load(is); // return properties; // } // } catch (IOException e) { // log.error("Error reading c3p0.properties", e); // } // // // Use environment parameters // log.info("Configuring EntityManager from environment parameters"); // Map<Object, Object> props = new HashMap<Object, Object>(); // props.put("c3p0.driverClass", "org.h2.Driver"); // File dbDirectory = DirectoryUtil.getDbDirectory(); // String dbFile = dbDirectory.getAbsoluteFile() + File.separator + "home"; // props.put("c3p0.jdbcUrl", "jdbc:h2:file:" + dbFile + ";WRITE_DELAY=false;shutdown=true"); // props.put("c3p0.user", "sa"); // return props; // } // // /** // * Private constructor. // */ // private DBIF() { // } // // /** // * Returns an instance of DBIF. // * // * @return Instance of DBIF // */ // public static DBI get() { // return dbi; // } // // public static void reset() { // if (cpds != null) { // dbi.open().createStatement("DROP ALL OBJECTS").execute(); // cpds.close(); // cpds = null; // dbi = null; // createDbi(); // } // } // }
import com.sismics.util.context.ThreadLocalContext; import com.sismics.util.dbi.DBIF; import org.skife.jdbi.v2.Handle; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package com.sismics.home.core.util; /** * Database transaction utils. * * @author jtremeaux */ public class TransactionUtil { /** * Logger. */ private static final Logger log = LoggerFactory.getLogger(TransactionUtil.class); /** * Encapsulate a process into a transactional context. * * @param runnable Runnable */ public static void handle(Runnable runnable) {
// Path: home-core/src/main/java/com/sismics/util/context/ThreadLocalContext.java // public class ThreadLocalContext { // /** // * ThreadLocal to store the context. // */ // public static final ThreadLocal<ThreadLocalContext> threadLocalContext = new ThreadLocal<ThreadLocalContext>(); // // /** // * JDBI handle. // */ // private Handle handle; // // /** // * Private constructor. // */ // private ThreadLocalContext() { // // NOP // } // // /** // * Returns an instance of this thread context. // * // * @return Thread local context // */ // public static ThreadLocalContext get() { // ThreadLocalContext context = threadLocalContext.get(); // if (context == null) { // context = new ThreadLocalContext(); // threadLocalContext.set(context); // } // return context; // } // // /** // * Cleans up the instance of this thread context. // */ // public static void cleanup() { // threadLocalContext.set(null); // } // // /** // * Getter of handle. // * // * @return handle // */ // public Handle getHandle() { // return handle; // } // // /** // * Setter of handle. // * // * @param handle handle // */ // public void setHandle(Handle handle) { // this.handle = handle; // } // } // // Path: home-core/src/main/java/com/sismics/util/dbi/DBIF.java // public class DBIF { // private static final Logger log = LoggerFactory.getLogger(DBIF.class); // // private static ComboPooledDataSource cpds; // // private static DBI dbi; // // static { // if (dbi == null) { // createDbi(); // } // } // // public static void createDbi() { // try { // cpds = new ComboPooledDataSource(); // TODO use getDbProperties() // dbi = new DBI(cpds); // dbi.registerMapper(new AuthenticationTokenMapper()); // dbi.registerMapper(new BaseFunctionMapper()); // dbi.registerMapper(new ConfigMapper()); // dbi.registerMapper(new RoleBaseFunctionMapper()); // dbi.registerMapper(new RoleMapper()); // dbi.registerMapper(new UserMapper()); // dbi.registerMapper(new SensorMapper()); // dbi.registerMapper(new SensorSampleMapper()); // dbi.registerMapper(new CameraMapper()); // } catch (Throwable t) { // log.error("Error creating DBI", t); // } // // Handle handle = null; // try { // handle = dbi.open(); // DbOpenHelper openHelper = new DbOpenHelper(handle) { // // @Override // public void onCreate() throws Exception { // executeAllScript(0); // } // // @Override // public void onUpgrade(int oldVersion, int newVersion) throws Exception { // for (int version = oldVersion + 1; version <= newVersion; version++) { // executeAllScript(version); // } // } // }; // openHelper.open(); // } catch (Exception e) { // if (handle != null && handle.isInTransaction()) { // handle.rollback(); // handle.close(); // } // } // // } // // private static Map<Object, Object> getDbProperties() { // // Use properties file if exists // try { // URL dbPropertiesUrl = DBIF.class.getResource("/c3p0.properties"); // if (dbPropertiesUrl != null) { // log.info("Configuring connection pool from c3p0.properties"); // // InputStream is = dbPropertiesUrl.openStream(); // Properties properties = new Properties(); // properties.load(is); // return properties; // } // } catch (IOException e) { // log.error("Error reading c3p0.properties", e); // } // // // Use environment parameters // log.info("Configuring EntityManager from environment parameters"); // Map<Object, Object> props = new HashMap<Object, Object>(); // props.put("c3p0.driverClass", "org.h2.Driver"); // File dbDirectory = DirectoryUtil.getDbDirectory(); // String dbFile = dbDirectory.getAbsoluteFile() + File.separator + "home"; // props.put("c3p0.jdbcUrl", "jdbc:h2:file:" + dbFile + ";WRITE_DELAY=false;shutdown=true"); // props.put("c3p0.user", "sa"); // return props; // } // // /** // * Private constructor. // */ // private DBIF() { // } // // /** // * Returns an instance of DBIF. // * // * @return Instance of DBIF // */ // public static DBI get() { // return dbi; // } // // public static void reset() { // if (cpds != null) { // dbi.open().createStatement("DROP ALL OBJECTS").execute(); // cpds.close(); // cpds = null; // dbi = null; // createDbi(); // } // } // } // Path: home-core/src/main/java/com/sismics/home/core/util/TransactionUtil.java import com.sismics.util.context.ThreadLocalContext; import com.sismics.util.dbi.DBIF; import org.skife.jdbi.v2.Handle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package com.sismics.home.core.util; /** * Database transaction utils. * * @author jtremeaux */ public class TransactionUtil { /** * Logger. */ private static final Logger log = LoggerFactory.getLogger(TransactionUtil.class); /** * Encapsulate a process into a transactional context. * * @param runnable Runnable */ public static void handle(Runnable runnable) {
Handle handle = ThreadLocalContext.get().getHandle();
sismics/home
home-core/src/main/java/com/sismics/home/core/util/TransactionUtil.java
// Path: home-core/src/main/java/com/sismics/util/context/ThreadLocalContext.java // public class ThreadLocalContext { // /** // * ThreadLocal to store the context. // */ // public static final ThreadLocal<ThreadLocalContext> threadLocalContext = new ThreadLocal<ThreadLocalContext>(); // // /** // * JDBI handle. // */ // private Handle handle; // // /** // * Private constructor. // */ // private ThreadLocalContext() { // // NOP // } // // /** // * Returns an instance of this thread context. // * // * @return Thread local context // */ // public static ThreadLocalContext get() { // ThreadLocalContext context = threadLocalContext.get(); // if (context == null) { // context = new ThreadLocalContext(); // threadLocalContext.set(context); // } // return context; // } // // /** // * Cleans up the instance of this thread context. // */ // public static void cleanup() { // threadLocalContext.set(null); // } // // /** // * Getter of handle. // * // * @return handle // */ // public Handle getHandle() { // return handle; // } // // /** // * Setter of handle. // * // * @param handle handle // */ // public void setHandle(Handle handle) { // this.handle = handle; // } // } // // Path: home-core/src/main/java/com/sismics/util/dbi/DBIF.java // public class DBIF { // private static final Logger log = LoggerFactory.getLogger(DBIF.class); // // private static ComboPooledDataSource cpds; // // private static DBI dbi; // // static { // if (dbi == null) { // createDbi(); // } // } // // public static void createDbi() { // try { // cpds = new ComboPooledDataSource(); // TODO use getDbProperties() // dbi = new DBI(cpds); // dbi.registerMapper(new AuthenticationTokenMapper()); // dbi.registerMapper(new BaseFunctionMapper()); // dbi.registerMapper(new ConfigMapper()); // dbi.registerMapper(new RoleBaseFunctionMapper()); // dbi.registerMapper(new RoleMapper()); // dbi.registerMapper(new UserMapper()); // dbi.registerMapper(new SensorMapper()); // dbi.registerMapper(new SensorSampleMapper()); // dbi.registerMapper(new CameraMapper()); // } catch (Throwable t) { // log.error("Error creating DBI", t); // } // // Handle handle = null; // try { // handle = dbi.open(); // DbOpenHelper openHelper = new DbOpenHelper(handle) { // // @Override // public void onCreate() throws Exception { // executeAllScript(0); // } // // @Override // public void onUpgrade(int oldVersion, int newVersion) throws Exception { // for (int version = oldVersion + 1; version <= newVersion; version++) { // executeAllScript(version); // } // } // }; // openHelper.open(); // } catch (Exception e) { // if (handle != null && handle.isInTransaction()) { // handle.rollback(); // handle.close(); // } // } // // } // // private static Map<Object, Object> getDbProperties() { // // Use properties file if exists // try { // URL dbPropertiesUrl = DBIF.class.getResource("/c3p0.properties"); // if (dbPropertiesUrl != null) { // log.info("Configuring connection pool from c3p0.properties"); // // InputStream is = dbPropertiesUrl.openStream(); // Properties properties = new Properties(); // properties.load(is); // return properties; // } // } catch (IOException e) { // log.error("Error reading c3p0.properties", e); // } // // // Use environment parameters // log.info("Configuring EntityManager from environment parameters"); // Map<Object, Object> props = new HashMap<Object, Object>(); // props.put("c3p0.driverClass", "org.h2.Driver"); // File dbDirectory = DirectoryUtil.getDbDirectory(); // String dbFile = dbDirectory.getAbsoluteFile() + File.separator + "home"; // props.put("c3p0.jdbcUrl", "jdbc:h2:file:" + dbFile + ";WRITE_DELAY=false;shutdown=true"); // props.put("c3p0.user", "sa"); // return props; // } // // /** // * Private constructor. // */ // private DBIF() { // } // // /** // * Returns an instance of DBIF. // * // * @return Instance of DBIF // */ // public static DBI get() { // return dbi; // } // // public static void reset() { // if (cpds != null) { // dbi.open().createStatement("DROP ALL OBJECTS").execute(); // cpds.close(); // cpds = null; // dbi = null; // createDbi(); // } // } // }
import com.sismics.util.context.ThreadLocalContext; import com.sismics.util.dbi.DBIF; import org.skife.jdbi.v2.Handle; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package com.sismics.home.core.util; /** * Database transaction utils. * * @author jtremeaux */ public class TransactionUtil { /** * Logger. */ private static final Logger log = LoggerFactory.getLogger(TransactionUtil.class); /** * Encapsulate a process into a transactional context. * * @param runnable Runnable */ public static void handle(Runnable runnable) { Handle handle = ThreadLocalContext.get().getHandle(); if (handle != null && handle.isInTransaction()) { // We are already in a transactional context, nothing to do runnable.run(); return; } try {
// Path: home-core/src/main/java/com/sismics/util/context/ThreadLocalContext.java // public class ThreadLocalContext { // /** // * ThreadLocal to store the context. // */ // public static final ThreadLocal<ThreadLocalContext> threadLocalContext = new ThreadLocal<ThreadLocalContext>(); // // /** // * JDBI handle. // */ // private Handle handle; // // /** // * Private constructor. // */ // private ThreadLocalContext() { // // NOP // } // // /** // * Returns an instance of this thread context. // * // * @return Thread local context // */ // public static ThreadLocalContext get() { // ThreadLocalContext context = threadLocalContext.get(); // if (context == null) { // context = new ThreadLocalContext(); // threadLocalContext.set(context); // } // return context; // } // // /** // * Cleans up the instance of this thread context. // */ // public static void cleanup() { // threadLocalContext.set(null); // } // // /** // * Getter of handle. // * // * @return handle // */ // public Handle getHandle() { // return handle; // } // // /** // * Setter of handle. // * // * @param handle handle // */ // public void setHandle(Handle handle) { // this.handle = handle; // } // } // // Path: home-core/src/main/java/com/sismics/util/dbi/DBIF.java // public class DBIF { // private static final Logger log = LoggerFactory.getLogger(DBIF.class); // // private static ComboPooledDataSource cpds; // // private static DBI dbi; // // static { // if (dbi == null) { // createDbi(); // } // } // // public static void createDbi() { // try { // cpds = new ComboPooledDataSource(); // TODO use getDbProperties() // dbi = new DBI(cpds); // dbi.registerMapper(new AuthenticationTokenMapper()); // dbi.registerMapper(new BaseFunctionMapper()); // dbi.registerMapper(new ConfigMapper()); // dbi.registerMapper(new RoleBaseFunctionMapper()); // dbi.registerMapper(new RoleMapper()); // dbi.registerMapper(new UserMapper()); // dbi.registerMapper(new SensorMapper()); // dbi.registerMapper(new SensorSampleMapper()); // dbi.registerMapper(new CameraMapper()); // } catch (Throwable t) { // log.error("Error creating DBI", t); // } // // Handle handle = null; // try { // handle = dbi.open(); // DbOpenHelper openHelper = new DbOpenHelper(handle) { // // @Override // public void onCreate() throws Exception { // executeAllScript(0); // } // // @Override // public void onUpgrade(int oldVersion, int newVersion) throws Exception { // for (int version = oldVersion + 1; version <= newVersion; version++) { // executeAllScript(version); // } // } // }; // openHelper.open(); // } catch (Exception e) { // if (handle != null && handle.isInTransaction()) { // handle.rollback(); // handle.close(); // } // } // // } // // private static Map<Object, Object> getDbProperties() { // // Use properties file if exists // try { // URL dbPropertiesUrl = DBIF.class.getResource("/c3p0.properties"); // if (dbPropertiesUrl != null) { // log.info("Configuring connection pool from c3p0.properties"); // // InputStream is = dbPropertiesUrl.openStream(); // Properties properties = new Properties(); // properties.load(is); // return properties; // } // } catch (IOException e) { // log.error("Error reading c3p0.properties", e); // } // // // Use environment parameters // log.info("Configuring EntityManager from environment parameters"); // Map<Object, Object> props = new HashMap<Object, Object>(); // props.put("c3p0.driverClass", "org.h2.Driver"); // File dbDirectory = DirectoryUtil.getDbDirectory(); // String dbFile = dbDirectory.getAbsoluteFile() + File.separator + "home"; // props.put("c3p0.jdbcUrl", "jdbc:h2:file:" + dbFile + ";WRITE_DELAY=false;shutdown=true"); // props.put("c3p0.user", "sa"); // return props; // } // // /** // * Private constructor. // */ // private DBIF() { // } // // /** // * Returns an instance of DBIF. // * // * @return Instance of DBIF // */ // public static DBI get() { // return dbi; // } // // public static void reset() { // if (cpds != null) { // dbi.open().createStatement("DROP ALL OBJECTS").execute(); // cpds.close(); // cpds = null; // dbi = null; // createDbi(); // } // } // } // Path: home-core/src/main/java/com/sismics/home/core/util/TransactionUtil.java import com.sismics.util.context.ThreadLocalContext; import com.sismics.util.dbi.DBIF; import org.skife.jdbi.v2.Handle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package com.sismics.home.core.util; /** * Database transaction utils. * * @author jtremeaux */ public class TransactionUtil { /** * Logger. */ private static final Logger log = LoggerFactory.getLogger(TransactionUtil.class); /** * Encapsulate a process into a transactional context. * * @param runnable Runnable */ public static void handle(Runnable runnable) { Handle handle = ThreadLocalContext.get().getHandle(); if (handle != null && handle.isInTransaction()) { // We are already in a transactional context, nothing to do runnable.run(); return; } try {
handle = DBIF.get().open();
sismics/home
home-core/src/main/java/com/sismics/home/core/dao/dbi/mapper/ConfigMapper.java
// Path: home-core/src/main/java/com/sismics/home/core/constant/ConfigType.java // public enum ConfigType { // } // // Path: home-core/src/main/java/com/sismics/home/core/model/dbi/Config.java // public class Config { // /** // * Configuration parameter ID. // */ // private ConfigType id; // // /** // * Configuration parameter value. // */ // private String value; // // public Config() { // } // // public Config(ConfigType id, String value) { // this.id = id; // this.value = value; // } // // /** // * Getter of id. // * // * @return id // */ // public ConfigType getId() { // return id; // } // // /** // * Setter of id. // * // * @param id id // */ // public void setId(ConfigType id) { // this.id = id; // } // // /** // * Getter of value. // * // * @return value // */ // public String getValue() { // return value; // } // // /** // * Setter of value. // * // * @param value value // */ // public void setValue(String value) { // this.value = value; // } // // @Override // public String toString() { // return Objects.toStringHelper(this) // .add("id", id) // .toString(); // } // }
import com.sismics.home.core.constant.ConfigType; import com.sismics.home.core.model.dbi.Config; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.tweak.ResultSetMapper; import java.sql.ResultSet; import java.sql.SQLException;
package com.sismics.home.core.dao.dbi.mapper; /** * Config result set mapper. * * @author jtremeaux */ public class ConfigMapper implements ResultSetMapper<Config> { @Override public Config map(int index, ResultSet r, StatementContext ctx) throws SQLException { return new Config(
// Path: home-core/src/main/java/com/sismics/home/core/constant/ConfigType.java // public enum ConfigType { // } // // Path: home-core/src/main/java/com/sismics/home/core/model/dbi/Config.java // public class Config { // /** // * Configuration parameter ID. // */ // private ConfigType id; // // /** // * Configuration parameter value. // */ // private String value; // // public Config() { // } // // public Config(ConfigType id, String value) { // this.id = id; // this.value = value; // } // // /** // * Getter of id. // * // * @return id // */ // public ConfigType getId() { // return id; // } // // /** // * Setter of id. // * // * @param id id // */ // public void setId(ConfigType id) { // this.id = id; // } // // /** // * Getter of value. // * // * @return value // */ // public String getValue() { // return value; // } // // /** // * Setter of value. // * // * @param value value // */ // public void setValue(String value) { // this.value = value; // } // // @Override // public String toString() { // return Objects.toStringHelper(this) // .add("id", id) // .toString(); // } // } // Path: home-core/src/main/java/com/sismics/home/core/dao/dbi/mapper/ConfigMapper.java import com.sismics.home.core.constant.ConfigType; import com.sismics.home.core.model.dbi.Config; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.tweak.ResultSetMapper; import java.sql.ResultSet; import java.sql.SQLException; package com.sismics.home.core.dao.dbi.mapper; /** * Config result set mapper. * * @author jtremeaux */ public class ConfigMapper implements ResultSetMapper<Config> { @Override public Config map(int index, ResultSet r, StatementContext ctx) throws SQLException { return new Config(
ConfigType.valueOf(r.getString("CFG_ID_C")),
sismics/home
home-core/src/main/java/com/sismics/home/core/util/ConfigUtil.java
// Path: home-core/src/main/java/com/sismics/home/core/constant/ConfigType.java // public enum ConfigType { // } // // Path: home-core/src/main/java/com/sismics/home/core/dao/dbi/ConfigDao.java // public class ConfigDao { // /** // * Gets a configuration parameter by its ID. // * // * @param id Configuration parameter ID // * @return Configuration parameter // */ // public Config getById(ConfigType id) { // final Handle handle = ThreadLocalContext.get().getHandle(); // // // Prevents from getting parameters outside of a transactional context (e.g. jUnit) // if (handle == null) { // return null; // } // return handle.createQuery("select CFG_ID_C, CFG_VALUE_C" + // " from T_CONFIG" + // " where CFG_ID_C = :id") // .bind("id", id.name()) // .mapTo(Config.class) // .first(); // } // } // // Path: home-core/src/main/java/com/sismics/home/core/model/dbi/Config.java // public class Config { // /** // * Configuration parameter ID. // */ // private ConfigType id; // // /** // * Configuration parameter value. // */ // private String value; // // public Config() { // } // // public Config(ConfigType id, String value) { // this.id = id; // this.value = value; // } // // /** // * Getter of id. // * // * @return id // */ // public ConfigType getId() { // return id; // } // // /** // * Setter of id. // * // * @param id id // */ // public void setId(ConfigType id) { // this.id = id; // } // // /** // * Getter of value. // * // * @return value // */ // public String getValue() { // return value; // } // // /** // * Setter of value. // * // * @param value value // */ // public void setValue(String value) { // this.value = value; // } // // @Override // public String toString() { // return Objects.toStringHelper(this) // .add("id", id) // .toString(); // } // }
import com.sismics.home.core.constant.ConfigType; import com.sismics.home.core.dao.dbi.ConfigDao; import com.sismics.home.core.model.dbi.Config; import java.util.ResourceBundle;
package com.sismics.home.core.util; /** * Configuration parameter utilities. * * @author jtremeaux */ public class ConfigUtil { /** * Returns the textual value of a configuration parameter. * * @param configType Type of the configuration parameter * @return Textual value of the configuration parameter * @throws IllegalStateException Configuration parameter undefined */ public static String getConfigStringValue(ConfigType configType) {
// Path: home-core/src/main/java/com/sismics/home/core/constant/ConfigType.java // public enum ConfigType { // } // // Path: home-core/src/main/java/com/sismics/home/core/dao/dbi/ConfigDao.java // public class ConfigDao { // /** // * Gets a configuration parameter by its ID. // * // * @param id Configuration parameter ID // * @return Configuration parameter // */ // public Config getById(ConfigType id) { // final Handle handle = ThreadLocalContext.get().getHandle(); // // // Prevents from getting parameters outside of a transactional context (e.g. jUnit) // if (handle == null) { // return null; // } // return handle.createQuery("select CFG_ID_C, CFG_VALUE_C" + // " from T_CONFIG" + // " where CFG_ID_C = :id") // .bind("id", id.name()) // .mapTo(Config.class) // .first(); // } // } // // Path: home-core/src/main/java/com/sismics/home/core/model/dbi/Config.java // public class Config { // /** // * Configuration parameter ID. // */ // private ConfigType id; // // /** // * Configuration parameter value. // */ // private String value; // // public Config() { // } // // public Config(ConfigType id, String value) { // this.id = id; // this.value = value; // } // // /** // * Getter of id. // * // * @return id // */ // public ConfigType getId() { // return id; // } // // /** // * Setter of id. // * // * @param id id // */ // public void setId(ConfigType id) { // this.id = id; // } // // /** // * Getter of value. // * // * @return value // */ // public String getValue() { // return value; // } // // /** // * Setter of value. // * // * @param value value // */ // public void setValue(String value) { // this.value = value; // } // // @Override // public String toString() { // return Objects.toStringHelper(this) // .add("id", id) // .toString(); // } // } // Path: home-core/src/main/java/com/sismics/home/core/util/ConfigUtil.java import com.sismics.home.core.constant.ConfigType; import com.sismics.home.core.dao.dbi.ConfigDao; import com.sismics.home.core.model.dbi.Config; import java.util.ResourceBundle; package com.sismics.home.core.util; /** * Configuration parameter utilities. * * @author jtremeaux */ public class ConfigUtil { /** * Returns the textual value of a configuration parameter. * * @param configType Type of the configuration parameter * @return Textual value of the configuration parameter * @throws IllegalStateException Configuration parameter undefined */ public static String getConfigStringValue(ConfigType configType) {
ConfigDao configDao = new ConfigDao();
sismics/home
home-core/src/main/java/com/sismics/home/core/util/ConfigUtil.java
// Path: home-core/src/main/java/com/sismics/home/core/constant/ConfigType.java // public enum ConfigType { // } // // Path: home-core/src/main/java/com/sismics/home/core/dao/dbi/ConfigDao.java // public class ConfigDao { // /** // * Gets a configuration parameter by its ID. // * // * @param id Configuration parameter ID // * @return Configuration parameter // */ // public Config getById(ConfigType id) { // final Handle handle = ThreadLocalContext.get().getHandle(); // // // Prevents from getting parameters outside of a transactional context (e.g. jUnit) // if (handle == null) { // return null; // } // return handle.createQuery("select CFG_ID_C, CFG_VALUE_C" + // " from T_CONFIG" + // " where CFG_ID_C = :id") // .bind("id", id.name()) // .mapTo(Config.class) // .first(); // } // } // // Path: home-core/src/main/java/com/sismics/home/core/model/dbi/Config.java // public class Config { // /** // * Configuration parameter ID. // */ // private ConfigType id; // // /** // * Configuration parameter value. // */ // private String value; // // public Config() { // } // // public Config(ConfigType id, String value) { // this.id = id; // this.value = value; // } // // /** // * Getter of id. // * // * @return id // */ // public ConfigType getId() { // return id; // } // // /** // * Setter of id. // * // * @param id id // */ // public void setId(ConfigType id) { // this.id = id; // } // // /** // * Getter of value. // * // * @return value // */ // public String getValue() { // return value; // } // // /** // * Setter of value. // * // * @param value value // */ // public void setValue(String value) { // this.value = value; // } // // @Override // public String toString() { // return Objects.toStringHelper(this) // .add("id", id) // .toString(); // } // }
import com.sismics.home.core.constant.ConfigType; import com.sismics.home.core.dao.dbi.ConfigDao; import com.sismics.home.core.model.dbi.Config; import java.util.ResourceBundle;
package com.sismics.home.core.util; /** * Configuration parameter utilities. * * @author jtremeaux */ public class ConfigUtil { /** * Returns the textual value of a configuration parameter. * * @param configType Type of the configuration parameter * @return Textual value of the configuration parameter * @throws IllegalStateException Configuration parameter undefined */ public static String getConfigStringValue(ConfigType configType) { ConfigDao configDao = new ConfigDao();
// Path: home-core/src/main/java/com/sismics/home/core/constant/ConfigType.java // public enum ConfigType { // } // // Path: home-core/src/main/java/com/sismics/home/core/dao/dbi/ConfigDao.java // public class ConfigDao { // /** // * Gets a configuration parameter by its ID. // * // * @param id Configuration parameter ID // * @return Configuration parameter // */ // public Config getById(ConfigType id) { // final Handle handle = ThreadLocalContext.get().getHandle(); // // // Prevents from getting parameters outside of a transactional context (e.g. jUnit) // if (handle == null) { // return null; // } // return handle.createQuery("select CFG_ID_C, CFG_VALUE_C" + // " from T_CONFIG" + // " where CFG_ID_C = :id") // .bind("id", id.name()) // .mapTo(Config.class) // .first(); // } // } // // Path: home-core/src/main/java/com/sismics/home/core/model/dbi/Config.java // public class Config { // /** // * Configuration parameter ID. // */ // private ConfigType id; // // /** // * Configuration parameter value. // */ // private String value; // // public Config() { // } // // public Config(ConfigType id, String value) { // this.id = id; // this.value = value; // } // // /** // * Getter of id. // * // * @return id // */ // public ConfigType getId() { // return id; // } // // /** // * Setter of id. // * // * @param id id // */ // public void setId(ConfigType id) { // this.id = id; // } // // /** // * Getter of value. // * // * @return value // */ // public String getValue() { // return value; // } // // /** // * Setter of value. // * // * @param value value // */ // public void setValue(String value) { // this.value = value; // } // // @Override // public String toString() { // return Objects.toStringHelper(this) // .add("id", id) // .toString(); // } // } // Path: home-core/src/main/java/com/sismics/home/core/util/ConfigUtil.java import com.sismics.home.core.constant.ConfigType; import com.sismics.home.core.dao.dbi.ConfigDao; import com.sismics.home.core.model.dbi.Config; import java.util.ResourceBundle; package com.sismics.home.core.util; /** * Configuration parameter utilities. * * @author jtremeaux */ public class ConfigUtil { /** * Returns the textual value of a configuration parameter. * * @param configType Type of the configuration parameter * @return Textual value of the configuration parameter * @throws IllegalStateException Configuration parameter undefined */ public static String getConfigStringValue(ConfigType configType) { ConfigDao configDao = new ConfigDao();
Config config = configDao.getById(configType);
sismics/home
home-core/src/main/java/com/sismics/home/core/model/dbi/SensorSample.java
// Path: home-core/src/main/java/com/sismics/home/core/constant/SensorSampleType.java // public enum SensorSampleType { // // /** // * Raw sample from sensor input. // */ // RAW, // // /** // * Sample compacted from all samples from the same minute. // */ // MINUTE, // // /** // * Sample compacted from all samples from the same hour. // */ // HOUR, // // /** // * Sample compacted from all samples from the same day. // */ // DAY // }
import java.util.Date; import com.google.common.base.Objects; import com.sismics.home.core.constant.SensorSampleType;
package com.sismics.home.core.model.dbi; /** * Sensor sample. * * @author bgamard */ public class SensorSample { /** * ID. */ private String id; /** * Sensor ID. */ private String sensorId; /** * Value. */ private float value; /** * Creation date. */ private Date createDate; /** * Type. */
// Path: home-core/src/main/java/com/sismics/home/core/constant/SensorSampleType.java // public enum SensorSampleType { // // /** // * Raw sample from sensor input. // */ // RAW, // // /** // * Sample compacted from all samples from the same minute. // */ // MINUTE, // // /** // * Sample compacted from all samples from the same hour. // */ // HOUR, // // /** // * Sample compacted from all samples from the same day. // */ // DAY // } // Path: home-core/src/main/java/com/sismics/home/core/model/dbi/SensorSample.java import java.util.Date; import com.google.common.base.Objects; import com.sismics.home.core.constant.SensorSampleType; package com.sismics.home.core.model.dbi; /** * Sensor sample. * * @author bgamard */ public class SensorSample { /** * ID. */ private String id; /** * Sensor ID. */ private String sensorId; /** * Value. */ private float value; /** * Creation date. */ private Date createDate; /** * Type. */
private SensorSampleType type;
sismics/home
home-web/src/test/java/com/sismics/home/rest/TestSecurity.java
// Path: home-web-common/src/main/java/com/sismics/util/filter/TokenBasedSecurityFilter.java // public class TokenBasedSecurityFilter implements Filter { // /** // * Logger. // */ // private static final Logger log = LoggerFactory.getLogger(TokenBasedSecurityFilter.class); // // /** // * Name of the cookie used to store the authentication token. // */ // public static final String COOKIE_NAME = "auth_token"; // // /** // * Name of the attribute containing the principal. // */ // public static final String PRINCIPAL_ATTRIBUTE = "principal"; // // /** // * Lifetime of the authentication token in seconds, since login. // */ // public static final int TOKEN_LONG_LIFETIME = 3600 * 24 * 365 * 20; // // /** // * Lifetime of the authentication token in seconds, since last connection. // */ // public static final int TOKEN_SESSION_LIFETIME = 3600 * 24; // // @Override // public void init(FilterConfig filterConfig) throws ServletException { // // NOP // } // // @Override // public void destroy() { // // NOP // } // // @Override // public void doFilter(ServletRequest req, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { // // Get the value of the client authentication token // HttpServletRequest request = (HttpServletRequest) req; // String authToken = null; // if (request.getCookies() != null) { // for (Cookie cookie : request.getCookies()) { // if (COOKIE_NAME.equals(cookie.getName())) { // authToken = cookie.getValue(); // } // } // } // // // Get the corresponding server token // AuthenticationTokenDao authenticationTokenDao = new AuthenticationTokenDao(); // AuthenticationToken authenticationToken = null; // if (authToken != null) { // authenticationToken = authenticationTokenDao.get(authToken); // } // // if (authenticationToken == null) { // injectAnonymousUser(request); // } else { // // Check if the token is still valid // if (isTokenExpired(authenticationToken)) { // try { // injectAnonymousUser(request); // // // Destroy the expired token // authenticationTokenDao.delete(authToken); // } catch (Exception e) { // if (log.isErrorEnabled()) { // log.error(MessageFormat.format("Error deleting authentication token {0} ", authToken), e); // } // } // } else { // // Check if the user is still valid // UserDao userDao = new UserDao(); // User user = userDao.getActiveById(authenticationToken.getUserId()); // if (user != null) { // injectAuthenticatedUser(request, user); // // // Update the last connection date // authenticationTokenDao.updateLastConnectionDate(authenticationToken.getId()); // } else { // injectAnonymousUser(request); // } // } // } // // filterChain.doFilter(request, response); // } // // /** // * Returns true if the token is expired. // * // * @param authenticationToken Authentication token // * @return Token expired // */ // private boolean isTokenExpired(AuthenticationToken authenticationToken) { // final long now = new Date().getTime(); // final long creationDate = authenticationToken.getCreateDate().getTime(); // if (authenticationToken.isLongLasted()) { // return now >= creationDate + ((long) TOKEN_LONG_LIFETIME) * 1000L; // } else { // long date = authenticationToken.getLastConnectionDate() != null ? // authenticationToken.getLastConnectionDate().getTime() : creationDate; // return now >= date + ((long) TOKEN_SESSION_LIFETIME) * 1000L; // } // } // // /** // * Inject an authenticated user into the request attributes. // * // * @param request HTTP request // * @param user User to inject // */ // private void injectAuthenticatedUser(HttpServletRequest request, User user) { // UserPrincipal userPrincipal = new UserPrincipal(user.getId(), user.getUsername()); // // // Add base functions // RoleBaseFunctionDao userBaseFuction = new RoleBaseFunctionDao(); // Set<String> baseFunctionSet = userBaseFuction.findByRoleId(user.getRoleId()); // userPrincipal.setBaseFunctionSet(baseFunctionSet); // // request.setAttribute(PRINCIPAL_ATTRIBUTE, userPrincipal); // } // // /** // * Inject an anonymous user into the request attributes. // * // * @param request HTTP request // */ // private void injectAnonymousUser(HttpServletRequest request) { // AnonymousPrincipal anonymousPrincipal = new AnonymousPrincipal(); // anonymousPrincipal.setDateTimeZone(DateTimeZone.forID(Constants.DEFAULT_TIMEZONE_ID)); // // request.setAttribute(PRINCIPAL_ATTRIBUTE, anonymousPrincipal); // } // }
import javax.json.JsonObject; import javax.ws.rs.client.Entity; import javax.ws.rs.core.Form; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.apache.commons.lang.StringUtils; import org.junit.Assert; import org.junit.Test; import com.sismics.util.filter.TokenBasedSecurityFilter;
package com.sismics.home.rest; /** * Test of the security layer. * * @author jtremeaux */ public class TestSecurity extends BaseJerseyTest { /** * Test of the security layer. * * @throws JSONException */ @Test public void testSecurity() { // Create a user clientUtil.createUser("testsecurity"); // Changes a user's email KO : the user is not connected Response response = target().path("/user/update").request() .post(Entity.form(new Form().param("email", "testsecurity2@home.com"))); Assert.assertEquals(Status.FORBIDDEN, Status.fromStatusCode(response.getStatus())); JsonObject json = response.readEntity(JsonObject.class); Assert.assertEquals("ForbiddenError", json.getString("type")); Assert.assertEquals("You don't have access to this resource", json.getString("message")); // User testsecurity logs in String testSecurityAuthenticationToken = clientUtil.login("testsecurity"); // User testsecurity creates a new user KO : no permission response = target().path("/user").request()
// Path: home-web-common/src/main/java/com/sismics/util/filter/TokenBasedSecurityFilter.java // public class TokenBasedSecurityFilter implements Filter { // /** // * Logger. // */ // private static final Logger log = LoggerFactory.getLogger(TokenBasedSecurityFilter.class); // // /** // * Name of the cookie used to store the authentication token. // */ // public static final String COOKIE_NAME = "auth_token"; // // /** // * Name of the attribute containing the principal. // */ // public static final String PRINCIPAL_ATTRIBUTE = "principal"; // // /** // * Lifetime of the authentication token in seconds, since login. // */ // public static final int TOKEN_LONG_LIFETIME = 3600 * 24 * 365 * 20; // // /** // * Lifetime of the authentication token in seconds, since last connection. // */ // public static final int TOKEN_SESSION_LIFETIME = 3600 * 24; // // @Override // public void init(FilterConfig filterConfig) throws ServletException { // // NOP // } // // @Override // public void destroy() { // // NOP // } // // @Override // public void doFilter(ServletRequest req, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { // // Get the value of the client authentication token // HttpServletRequest request = (HttpServletRequest) req; // String authToken = null; // if (request.getCookies() != null) { // for (Cookie cookie : request.getCookies()) { // if (COOKIE_NAME.equals(cookie.getName())) { // authToken = cookie.getValue(); // } // } // } // // // Get the corresponding server token // AuthenticationTokenDao authenticationTokenDao = new AuthenticationTokenDao(); // AuthenticationToken authenticationToken = null; // if (authToken != null) { // authenticationToken = authenticationTokenDao.get(authToken); // } // // if (authenticationToken == null) { // injectAnonymousUser(request); // } else { // // Check if the token is still valid // if (isTokenExpired(authenticationToken)) { // try { // injectAnonymousUser(request); // // // Destroy the expired token // authenticationTokenDao.delete(authToken); // } catch (Exception e) { // if (log.isErrorEnabled()) { // log.error(MessageFormat.format("Error deleting authentication token {0} ", authToken), e); // } // } // } else { // // Check if the user is still valid // UserDao userDao = new UserDao(); // User user = userDao.getActiveById(authenticationToken.getUserId()); // if (user != null) { // injectAuthenticatedUser(request, user); // // // Update the last connection date // authenticationTokenDao.updateLastConnectionDate(authenticationToken.getId()); // } else { // injectAnonymousUser(request); // } // } // } // // filterChain.doFilter(request, response); // } // // /** // * Returns true if the token is expired. // * // * @param authenticationToken Authentication token // * @return Token expired // */ // private boolean isTokenExpired(AuthenticationToken authenticationToken) { // final long now = new Date().getTime(); // final long creationDate = authenticationToken.getCreateDate().getTime(); // if (authenticationToken.isLongLasted()) { // return now >= creationDate + ((long) TOKEN_LONG_LIFETIME) * 1000L; // } else { // long date = authenticationToken.getLastConnectionDate() != null ? // authenticationToken.getLastConnectionDate().getTime() : creationDate; // return now >= date + ((long) TOKEN_SESSION_LIFETIME) * 1000L; // } // } // // /** // * Inject an authenticated user into the request attributes. // * // * @param request HTTP request // * @param user User to inject // */ // private void injectAuthenticatedUser(HttpServletRequest request, User user) { // UserPrincipal userPrincipal = new UserPrincipal(user.getId(), user.getUsername()); // // // Add base functions // RoleBaseFunctionDao userBaseFuction = new RoleBaseFunctionDao(); // Set<String> baseFunctionSet = userBaseFuction.findByRoleId(user.getRoleId()); // userPrincipal.setBaseFunctionSet(baseFunctionSet); // // request.setAttribute(PRINCIPAL_ATTRIBUTE, userPrincipal); // } // // /** // * Inject an anonymous user into the request attributes. // * // * @param request HTTP request // */ // private void injectAnonymousUser(HttpServletRequest request) { // AnonymousPrincipal anonymousPrincipal = new AnonymousPrincipal(); // anonymousPrincipal.setDateTimeZone(DateTimeZone.forID(Constants.DEFAULT_TIMEZONE_ID)); // // request.setAttribute(PRINCIPAL_ATTRIBUTE, anonymousPrincipal); // } // } // Path: home-web/src/test/java/com/sismics/home/rest/TestSecurity.java import javax.json.JsonObject; import javax.ws.rs.client.Entity; import javax.ws.rs.core.Form; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.apache.commons.lang.StringUtils; import org.junit.Assert; import org.junit.Test; import com.sismics.util.filter.TokenBasedSecurityFilter; package com.sismics.home.rest; /** * Test of the security layer. * * @author jtremeaux */ public class TestSecurity extends BaseJerseyTest { /** * Test of the security layer. * * @throws JSONException */ @Test public void testSecurity() { // Create a user clientUtil.createUser("testsecurity"); // Changes a user's email KO : the user is not connected Response response = target().path("/user/update").request() .post(Entity.form(new Form().param("email", "testsecurity2@home.com"))); Assert.assertEquals(Status.FORBIDDEN, Status.fromStatusCode(response.getStatus())); JsonObject json = response.readEntity(JsonObject.class); Assert.assertEquals("ForbiddenError", json.getString("type")); Assert.assertEquals("You don't have access to this resource", json.getString("message")); // User testsecurity logs in String testSecurityAuthenticationToken = clientUtil.login("testsecurity"); // User testsecurity creates a new user KO : no permission response = target().path("/user").request()
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, testSecurityAuthenticationToken)
sismics/home
home-core/src/main/java/com/sismics/home/core/dao/dbi/AuthenticationTokenDao.java
// Path: home-core/src/main/java/com/sismics/home/core/model/dbi/AuthenticationToken.java // public class AuthenticationToken { // /** // * Token. // */ // private String id; // // /** // * User ID. // */ // private String userId; // // /** // * Remember the user next time (long lasted session). // */ // private boolean longLasted; // // /** // * Token creation date. // */ // private Date createDate; // // /** // * Last connection date using this token. // */ // private Date lastConnectionDate; // // public AuthenticationToken() { // } // // public AuthenticationToken(String id, String userId, boolean longLasted, Date createDate, Date lastConnectionDate) { // this.id = id; // this.userId = userId; // this.longLasted = longLasted; // this.createDate = createDate; // this.lastConnectionDate = lastConnectionDate; // } // // /** // * Getter of id. // * // * @return id // */ // public String getId() { // return id; // } // // /** // * Setter of id. // * // * @param id id // */ // public void setId(String id) { // this.id = id; // } // // /** // * Getter of userId. // * // * @return userId // */ // public String getUserId() { // return userId; // } // // /** // * Setter of userId. // * // * @param userId userId // */ // public void setUserId(String userId) { // this.userId = userId; // } // // /** // * Getter of longLasted. // * // * @return longLasted // */ // public boolean isLongLasted() { // return longLasted; // } // // /** // * Setter of longLasted. // * // * @param longLasted longLasted // */ // public void setLongLasted(boolean longLasted) { // this.longLasted = longLasted; // } // // /** // * Getter of createDate. // * // * @return createDate // */ // public Date getCreateDate() { // return createDate; // } // // /** // * Setter of createDate. // * // * @param createDate createDate // */ // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // /** // * Getter of lastConnectionDate. // * // * @return lastConnectionDate // */ // public Date getLastConnectionDate() { // return lastConnectionDate; // } // // /** // * Setter of lastConnectionDate. // * // * @param lastConnectionDate lastConnectionDate // */ // public void setLastConnectionDate(Date lastConnectionDate) { // this.lastConnectionDate = lastConnectionDate; // } // // @Override // public String toString() { // return Objects.toStringHelper(this) // .add("id", "**hidden**") // .add("userId", userId) // .add("longLasted", longLasted) // .toString(); // } // } // // Path: home-core/src/main/java/com/sismics/util/context/ThreadLocalContext.java // public class ThreadLocalContext { // /** // * ThreadLocal to store the context. // */ // public static final ThreadLocal<ThreadLocalContext> threadLocalContext = new ThreadLocal<ThreadLocalContext>(); // // /** // * JDBI handle. // */ // private Handle handle; // // /** // * Private constructor. // */ // private ThreadLocalContext() { // // NOP // } // // /** // * Returns an instance of this thread context. // * // * @return Thread local context // */ // public static ThreadLocalContext get() { // ThreadLocalContext context = threadLocalContext.get(); // if (context == null) { // context = new ThreadLocalContext(); // threadLocalContext.set(context); // } // return context; // } // // /** // * Cleans up the instance of this thread context. // */ // public static void cleanup() { // threadLocalContext.set(null); // } // // /** // * Getter of handle. // * // * @return handle // */ // public Handle getHandle() { // return handle; // } // // /** // * Setter of handle. // * // * @param handle handle // */ // public void setHandle(Handle handle) { // this.handle = handle; // } // }
import com.sismics.home.core.model.dbi.AuthenticationToken; import com.sismics.util.context.ThreadLocalContext; import org.joda.time.DateTime; import org.skife.jdbi.v2.Handle; import java.util.Date; import java.util.UUID;
package com.sismics.home.core.dao.dbi; /** * Authentication token DAO. * * @author jtremeaux */ public class AuthenticationTokenDao { /** * Gets an authentication token. * * @param id Authentication token ID * @return Authentication token */ public AuthenticationToken get(String id) {
// Path: home-core/src/main/java/com/sismics/home/core/model/dbi/AuthenticationToken.java // public class AuthenticationToken { // /** // * Token. // */ // private String id; // // /** // * User ID. // */ // private String userId; // // /** // * Remember the user next time (long lasted session). // */ // private boolean longLasted; // // /** // * Token creation date. // */ // private Date createDate; // // /** // * Last connection date using this token. // */ // private Date lastConnectionDate; // // public AuthenticationToken() { // } // // public AuthenticationToken(String id, String userId, boolean longLasted, Date createDate, Date lastConnectionDate) { // this.id = id; // this.userId = userId; // this.longLasted = longLasted; // this.createDate = createDate; // this.lastConnectionDate = lastConnectionDate; // } // // /** // * Getter of id. // * // * @return id // */ // public String getId() { // return id; // } // // /** // * Setter of id. // * // * @param id id // */ // public void setId(String id) { // this.id = id; // } // // /** // * Getter of userId. // * // * @return userId // */ // public String getUserId() { // return userId; // } // // /** // * Setter of userId. // * // * @param userId userId // */ // public void setUserId(String userId) { // this.userId = userId; // } // // /** // * Getter of longLasted. // * // * @return longLasted // */ // public boolean isLongLasted() { // return longLasted; // } // // /** // * Setter of longLasted. // * // * @param longLasted longLasted // */ // public void setLongLasted(boolean longLasted) { // this.longLasted = longLasted; // } // // /** // * Getter of createDate. // * // * @return createDate // */ // public Date getCreateDate() { // return createDate; // } // // /** // * Setter of createDate. // * // * @param createDate createDate // */ // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // /** // * Getter of lastConnectionDate. // * // * @return lastConnectionDate // */ // public Date getLastConnectionDate() { // return lastConnectionDate; // } // // /** // * Setter of lastConnectionDate. // * // * @param lastConnectionDate lastConnectionDate // */ // public void setLastConnectionDate(Date lastConnectionDate) { // this.lastConnectionDate = lastConnectionDate; // } // // @Override // public String toString() { // return Objects.toStringHelper(this) // .add("id", "**hidden**") // .add("userId", userId) // .add("longLasted", longLasted) // .toString(); // } // } // // Path: home-core/src/main/java/com/sismics/util/context/ThreadLocalContext.java // public class ThreadLocalContext { // /** // * ThreadLocal to store the context. // */ // public static final ThreadLocal<ThreadLocalContext> threadLocalContext = new ThreadLocal<ThreadLocalContext>(); // // /** // * JDBI handle. // */ // private Handle handle; // // /** // * Private constructor. // */ // private ThreadLocalContext() { // // NOP // } // // /** // * Returns an instance of this thread context. // * // * @return Thread local context // */ // public static ThreadLocalContext get() { // ThreadLocalContext context = threadLocalContext.get(); // if (context == null) { // context = new ThreadLocalContext(); // threadLocalContext.set(context); // } // return context; // } // // /** // * Cleans up the instance of this thread context. // */ // public static void cleanup() { // threadLocalContext.set(null); // } // // /** // * Getter of handle. // * // * @return handle // */ // public Handle getHandle() { // return handle; // } // // /** // * Setter of handle. // * // * @param handle handle // */ // public void setHandle(Handle handle) { // this.handle = handle; // } // } // Path: home-core/src/main/java/com/sismics/home/core/dao/dbi/AuthenticationTokenDao.java import com.sismics.home.core.model.dbi.AuthenticationToken; import com.sismics.util.context.ThreadLocalContext; import org.joda.time.DateTime; import org.skife.jdbi.v2.Handle; import java.util.Date; import java.util.UUID; package com.sismics.home.core.dao.dbi; /** * Authentication token DAO. * * @author jtremeaux */ public class AuthenticationTokenDao { /** * Gets an authentication token. * * @param id Authentication token ID * @return Authentication token */ public AuthenticationToken get(String id) {
final Handle handle = ThreadLocalContext.get().getHandle();
sismics/home
home-web/src/test/java/com/sismics/home/rest/TestUserResource.java
// Path: home-web-common/src/main/java/com/sismics/util/filter/TokenBasedSecurityFilter.java // public class TokenBasedSecurityFilter implements Filter { // /** // * Logger. // */ // private static final Logger log = LoggerFactory.getLogger(TokenBasedSecurityFilter.class); // // /** // * Name of the cookie used to store the authentication token. // */ // public static final String COOKIE_NAME = "auth_token"; // // /** // * Name of the attribute containing the principal. // */ // public static final String PRINCIPAL_ATTRIBUTE = "principal"; // // /** // * Lifetime of the authentication token in seconds, since login. // */ // public static final int TOKEN_LONG_LIFETIME = 3600 * 24 * 365 * 20; // // /** // * Lifetime of the authentication token in seconds, since last connection. // */ // public static final int TOKEN_SESSION_LIFETIME = 3600 * 24; // // @Override // public void init(FilterConfig filterConfig) throws ServletException { // // NOP // } // // @Override // public void destroy() { // // NOP // } // // @Override // public void doFilter(ServletRequest req, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { // // Get the value of the client authentication token // HttpServletRequest request = (HttpServletRequest) req; // String authToken = null; // if (request.getCookies() != null) { // for (Cookie cookie : request.getCookies()) { // if (COOKIE_NAME.equals(cookie.getName())) { // authToken = cookie.getValue(); // } // } // } // // // Get the corresponding server token // AuthenticationTokenDao authenticationTokenDao = new AuthenticationTokenDao(); // AuthenticationToken authenticationToken = null; // if (authToken != null) { // authenticationToken = authenticationTokenDao.get(authToken); // } // // if (authenticationToken == null) { // injectAnonymousUser(request); // } else { // // Check if the token is still valid // if (isTokenExpired(authenticationToken)) { // try { // injectAnonymousUser(request); // // // Destroy the expired token // authenticationTokenDao.delete(authToken); // } catch (Exception e) { // if (log.isErrorEnabled()) { // log.error(MessageFormat.format("Error deleting authentication token {0} ", authToken), e); // } // } // } else { // // Check if the user is still valid // UserDao userDao = new UserDao(); // User user = userDao.getActiveById(authenticationToken.getUserId()); // if (user != null) { // injectAuthenticatedUser(request, user); // // // Update the last connection date // authenticationTokenDao.updateLastConnectionDate(authenticationToken.getId()); // } else { // injectAnonymousUser(request); // } // } // } // // filterChain.doFilter(request, response); // } // // /** // * Returns true if the token is expired. // * // * @param authenticationToken Authentication token // * @return Token expired // */ // private boolean isTokenExpired(AuthenticationToken authenticationToken) { // final long now = new Date().getTime(); // final long creationDate = authenticationToken.getCreateDate().getTime(); // if (authenticationToken.isLongLasted()) { // return now >= creationDate + ((long) TOKEN_LONG_LIFETIME) * 1000L; // } else { // long date = authenticationToken.getLastConnectionDate() != null ? // authenticationToken.getLastConnectionDate().getTime() : creationDate; // return now >= date + ((long) TOKEN_SESSION_LIFETIME) * 1000L; // } // } // // /** // * Inject an authenticated user into the request attributes. // * // * @param request HTTP request // * @param user User to inject // */ // private void injectAuthenticatedUser(HttpServletRequest request, User user) { // UserPrincipal userPrincipal = new UserPrincipal(user.getId(), user.getUsername()); // // // Add base functions // RoleBaseFunctionDao userBaseFuction = new RoleBaseFunctionDao(); // Set<String> baseFunctionSet = userBaseFuction.findByRoleId(user.getRoleId()); // userPrincipal.setBaseFunctionSet(baseFunctionSet); // // request.setAttribute(PRINCIPAL_ATTRIBUTE, userPrincipal); // } // // /** // * Inject an anonymous user into the request attributes. // * // * @param request HTTP request // */ // private void injectAnonymousUser(HttpServletRequest request) { // AnonymousPrincipal anonymousPrincipal = new AnonymousPrincipal(); // anonymousPrincipal.setDateTimeZone(DateTimeZone.forID(Constants.DEFAULT_TIMEZONE_ID)); // // request.setAttribute(PRINCIPAL_ATTRIBUTE, anonymousPrincipal); // } // }
import javax.json.JsonArray; import javax.json.JsonObject; import javax.ws.rs.client.Entity; import javax.ws.rs.core.Form; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.junit.Assert; import org.junit.Test; import com.sismics.util.filter.TokenBasedSecurityFilter;
package com.sismics.home.rest; /** * Exhaustive test of the user resource. * * @author jtremeaux */ public class TestUserResource extends BaseJerseyTest { /** * Test the user resource. * * @throws JSONException */ @Test public void testUserResource() { // Check anonymous user information JsonObject json = target().path("/user").request() .get(JsonObject.class); Assert.assertTrue(json.getBoolean("is_default_password")); // Create alice user clientUtil.createUser("alice"); // Login admin String adminAuthenticationToken = clientUtil.login("admin", "admin", false); // List all users json = target().path("/user/list") .queryParam("sort_column", 2) .queryParam("asc", false) .request()
// Path: home-web-common/src/main/java/com/sismics/util/filter/TokenBasedSecurityFilter.java // public class TokenBasedSecurityFilter implements Filter { // /** // * Logger. // */ // private static final Logger log = LoggerFactory.getLogger(TokenBasedSecurityFilter.class); // // /** // * Name of the cookie used to store the authentication token. // */ // public static final String COOKIE_NAME = "auth_token"; // // /** // * Name of the attribute containing the principal. // */ // public static final String PRINCIPAL_ATTRIBUTE = "principal"; // // /** // * Lifetime of the authentication token in seconds, since login. // */ // public static final int TOKEN_LONG_LIFETIME = 3600 * 24 * 365 * 20; // // /** // * Lifetime of the authentication token in seconds, since last connection. // */ // public static final int TOKEN_SESSION_LIFETIME = 3600 * 24; // // @Override // public void init(FilterConfig filterConfig) throws ServletException { // // NOP // } // // @Override // public void destroy() { // // NOP // } // // @Override // public void doFilter(ServletRequest req, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { // // Get the value of the client authentication token // HttpServletRequest request = (HttpServletRequest) req; // String authToken = null; // if (request.getCookies() != null) { // for (Cookie cookie : request.getCookies()) { // if (COOKIE_NAME.equals(cookie.getName())) { // authToken = cookie.getValue(); // } // } // } // // // Get the corresponding server token // AuthenticationTokenDao authenticationTokenDao = new AuthenticationTokenDao(); // AuthenticationToken authenticationToken = null; // if (authToken != null) { // authenticationToken = authenticationTokenDao.get(authToken); // } // // if (authenticationToken == null) { // injectAnonymousUser(request); // } else { // // Check if the token is still valid // if (isTokenExpired(authenticationToken)) { // try { // injectAnonymousUser(request); // // // Destroy the expired token // authenticationTokenDao.delete(authToken); // } catch (Exception e) { // if (log.isErrorEnabled()) { // log.error(MessageFormat.format("Error deleting authentication token {0} ", authToken), e); // } // } // } else { // // Check if the user is still valid // UserDao userDao = new UserDao(); // User user = userDao.getActiveById(authenticationToken.getUserId()); // if (user != null) { // injectAuthenticatedUser(request, user); // // // Update the last connection date // authenticationTokenDao.updateLastConnectionDate(authenticationToken.getId()); // } else { // injectAnonymousUser(request); // } // } // } // // filterChain.doFilter(request, response); // } // // /** // * Returns true if the token is expired. // * // * @param authenticationToken Authentication token // * @return Token expired // */ // private boolean isTokenExpired(AuthenticationToken authenticationToken) { // final long now = new Date().getTime(); // final long creationDate = authenticationToken.getCreateDate().getTime(); // if (authenticationToken.isLongLasted()) { // return now >= creationDate + ((long) TOKEN_LONG_LIFETIME) * 1000L; // } else { // long date = authenticationToken.getLastConnectionDate() != null ? // authenticationToken.getLastConnectionDate().getTime() : creationDate; // return now >= date + ((long) TOKEN_SESSION_LIFETIME) * 1000L; // } // } // // /** // * Inject an authenticated user into the request attributes. // * // * @param request HTTP request // * @param user User to inject // */ // private void injectAuthenticatedUser(HttpServletRequest request, User user) { // UserPrincipal userPrincipal = new UserPrincipal(user.getId(), user.getUsername()); // // // Add base functions // RoleBaseFunctionDao userBaseFuction = new RoleBaseFunctionDao(); // Set<String> baseFunctionSet = userBaseFuction.findByRoleId(user.getRoleId()); // userPrincipal.setBaseFunctionSet(baseFunctionSet); // // request.setAttribute(PRINCIPAL_ATTRIBUTE, userPrincipal); // } // // /** // * Inject an anonymous user into the request attributes. // * // * @param request HTTP request // */ // private void injectAnonymousUser(HttpServletRequest request) { // AnonymousPrincipal anonymousPrincipal = new AnonymousPrincipal(); // anonymousPrincipal.setDateTimeZone(DateTimeZone.forID(Constants.DEFAULT_TIMEZONE_ID)); // // request.setAttribute(PRINCIPAL_ATTRIBUTE, anonymousPrincipal); // } // } // Path: home-web/src/test/java/com/sismics/home/rest/TestUserResource.java import javax.json.JsonArray; import javax.json.JsonObject; import javax.ws.rs.client.Entity; import javax.ws.rs.core.Form; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.junit.Assert; import org.junit.Test; import com.sismics.util.filter.TokenBasedSecurityFilter; package com.sismics.home.rest; /** * Exhaustive test of the user resource. * * @author jtremeaux */ public class TestUserResource extends BaseJerseyTest { /** * Test the user resource. * * @throws JSONException */ @Test public void testUserResource() { // Check anonymous user information JsonObject json = target().path("/user").request() .get(JsonObject.class); Assert.assertTrue(json.getBoolean("is_default_password")); // Create alice user clientUtil.createUser("alice"); // Login admin String adminAuthenticationToken = clientUtil.login("admin", "admin", false); // List all users json = target().path("/user/list") .queryParam("sort_column", 2) .queryParam("asc", false) .request()
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, adminAuthenticationToken)
sismics/home
home-web/src/test/java/com/sismics/home/rest/TestAppResource.java
// Path: home-web-common/src/main/java/com/sismics/util/filter/TokenBasedSecurityFilter.java // public class TokenBasedSecurityFilter implements Filter { // /** // * Logger. // */ // private static final Logger log = LoggerFactory.getLogger(TokenBasedSecurityFilter.class); // // /** // * Name of the cookie used to store the authentication token. // */ // public static final String COOKIE_NAME = "auth_token"; // // /** // * Name of the attribute containing the principal. // */ // public static final String PRINCIPAL_ATTRIBUTE = "principal"; // // /** // * Lifetime of the authentication token in seconds, since login. // */ // public static final int TOKEN_LONG_LIFETIME = 3600 * 24 * 365 * 20; // // /** // * Lifetime of the authentication token in seconds, since last connection. // */ // public static final int TOKEN_SESSION_LIFETIME = 3600 * 24; // // @Override // public void init(FilterConfig filterConfig) throws ServletException { // // NOP // } // // @Override // public void destroy() { // // NOP // } // // @Override // public void doFilter(ServletRequest req, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { // // Get the value of the client authentication token // HttpServletRequest request = (HttpServletRequest) req; // String authToken = null; // if (request.getCookies() != null) { // for (Cookie cookie : request.getCookies()) { // if (COOKIE_NAME.equals(cookie.getName())) { // authToken = cookie.getValue(); // } // } // } // // // Get the corresponding server token // AuthenticationTokenDao authenticationTokenDao = new AuthenticationTokenDao(); // AuthenticationToken authenticationToken = null; // if (authToken != null) { // authenticationToken = authenticationTokenDao.get(authToken); // } // // if (authenticationToken == null) { // injectAnonymousUser(request); // } else { // // Check if the token is still valid // if (isTokenExpired(authenticationToken)) { // try { // injectAnonymousUser(request); // // // Destroy the expired token // authenticationTokenDao.delete(authToken); // } catch (Exception e) { // if (log.isErrorEnabled()) { // log.error(MessageFormat.format("Error deleting authentication token {0} ", authToken), e); // } // } // } else { // // Check if the user is still valid // UserDao userDao = new UserDao(); // User user = userDao.getActiveById(authenticationToken.getUserId()); // if (user != null) { // injectAuthenticatedUser(request, user); // // // Update the last connection date // authenticationTokenDao.updateLastConnectionDate(authenticationToken.getId()); // } else { // injectAnonymousUser(request); // } // } // } // // filterChain.doFilter(request, response); // } // // /** // * Returns true if the token is expired. // * // * @param authenticationToken Authentication token // * @return Token expired // */ // private boolean isTokenExpired(AuthenticationToken authenticationToken) { // final long now = new Date().getTime(); // final long creationDate = authenticationToken.getCreateDate().getTime(); // if (authenticationToken.isLongLasted()) { // return now >= creationDate + ((long) TOKEN_LONG_LIFETIME) * 1000L; // } else { // long date = authenticationToken.getLastConnectionDate() != null ? // authenticationToken.getLastConnectionDate().getTime() : creationDate; // return now >= date + ((long) TOKEN_SESSION_LIFETIME) * 1000L; // } // } // // /** // * Inject an authenticated user into the request attributes. // * // * @param request HTTP request // * @param user User to inject // */ // private void injectAuthenticatedUser(HttpServletRequest request, User user) { // UserPrincipal userPrincipal = new UserPrincipal(user.getId(), user.getUsername()); // // // Add base functions // RoleBaseFunctionDao userBaseFuction = new RoleBaseFunctionDao(); // Set<String> baseFunctionSet = userBaseFuction.findByRoleId(user.getRoleId()); // userPrincipal.setBaseFunctionSet(baseFunctionSet); // // request.setAttribute(PRINCIPAL_ATTRIBUTE, userPrincipal); // } // // /** // * Inject an anonymous user into the request attributes. // * // * @param request HTTP request // */ // private void injectAnonymousUser(HttpServletRequest request) { // AnonymousPrincipal anonymousPrincipal = new AnonymousPrincipal(); // anonymousPrincipal.setDateTimeZone(DateTimeZone.forID(Constants.DEFAULT_TIMEZONE_ID)); // // request.setAttribute(PRINCIPAL_ATTRIBUTE, anonymousPrincipal); // } // }
import javax.json.JsonArray; import javax.json.JsonObject; import org.junit.Assert; import org.junit.Test; import com.sismics.util.filter.TokenBasedSecurityFilter;
package com.sismics.home.rest; /** * Test the app resource. * * @author jtremeaux */ public class TestAppResource extends BaseJerseyTest { /** * Test the API resource. * * @throws JSONException */ @Test public void testAppResource() { // Check the application info JsonObject json = target().path("/app").request().get(JsonObject.class); String currentVersion = json.getString("current_version"); Assert.assertNotNull(currentVersion); String minVersion = json.getString("min_version"); Assert.assertNotNull(minVersion); Long freeMemory = json.getJsonNumber("free_memory").longValue(); Assert.assertTrue(freeMemory > 0); Long totalMemory = json.getJsonNumber("total_memory").longValue(); Assert.assertTrue(totalMemory > 0 && totalMemory > freeMemory); } /** * Test the log resource. * * @throws JSONException */ @Test public void testLogResource() { // Login admin String adminAuthenticationToken = clientUtil.login("admin", "admin", false); // Check the logs (page 1) JsonObject json = target().path("/app/log").queryParam("level", "DEBUG").request()
// Path: home-web-common/src/main/java/com/sismics/util/filter/TokenBasedSecurityFilter.java // public class TokenBasedSecurityFilter implements Filter { // /** // * Logger. // */ // private static final Logger log = LoggerFactory.getLogger(TokenBasedSecurityFilter.class); // // /** // * Name of the cookie used to store the authentication token. // */ // public static final String COOKIE_NAME = "auth_token"; // // /** // * Name of the attribute containing the principal. // */ // public static final String PRINCIPAL_ATTRIBUTE = "principal"; // // /** // * Lifetime of the authentication token in seconds, since login. // */ // public static final int TOKEN_LONG_LIFETIME = 3600 * 24 * 365 * 20; // // /** // * Lifetime of the authentication token in seconds, since last connection. // */ // public static final int TOKEN_SESSION_LIFETIME = 3600 * 24; // // @Override // public void init(FilterConfig filterConfig) throws ServletException { // // NOP // } // // @Override // public void destroy() { // // NOP // } // // @Override // public void doFilter(ServletRequest req, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { // // Get the value of the client authentication token // HttpServletRequest request = (HttpServletRequest) req; // String authToken = null; // if (request.getCookies() != null) { // for (Cookie cookie : request.getCookies()) { // if (COOKIE_NAME.equals(cookie.getName())) { // authToken = cookie.getValue(); // } // } // } // // // Get the corresponding server token // AuthenticationTokenDao authenticationTokenDao = new AuthenticationTokenDao(); // AuthenticationToken authenticationToken = null; // if (authToken != null) { // authenticationToken = authenticationTokenDao.get(authToken); // } // // if (authenticationToken == null) { // injectAnonymousUser(request); // } else { // // Check if the token is still valid // if (isTokenExpired(authenticationToken)) { // try { // injectAnonymousUser(request); // // // Destroy the expired token // authenticationTokenDao.delete(authToken); // } catch (Exception e) { // if (log.isErrorEnabled()) { // log.error(MessageFormat.format("Error deleting authentication token {0} ", authToken), e); // } // } // } else { // // Check if the user is still valid // UserDao userDao = new UserDao(); // User user = userDao.getActiveById(authenticationToken.getUserId()); // if (user != null) { // injectAuthenticatedUser(request, user); // // // Update the last connection date // authenticationTokenDao.updateLastConnectionDate(authenticationToken.getId()); // } else { // injectAnonymousUser(request); // } // } // } // // filterChain.doFilter(request, response); // } // // /** // * Returns true if the token is expired. // * // * @param authenticationToken Authentication token // * @return Token expired // */ // private boolean isTokenExpired(AuthenticationToken authenticationToken) { // final long now = new Date().getTime(); // final long creationDate = authenticationToken.getCreateDate().getTime(); // if (authenticationToken.isLongLasted()) { // return now >= creationDate + ((long) TOKEN_LONG_LIFETIME) * 1000L; // } else { // long date = authenticationToken.getLastConnectionDate() != null ? // authenticationToken.getLastConnectionDate().getTime() : creationDate; // return now >= date + ((long) TOKEN_SESSION_LIFETIME) * 1000L; // } // } // // /** // * Inject an authenticated user into the request attributes. // * // * @param request HTTP request // * @param user User to inject // */ // private void injectAuthenticatedUser(HttpServletRequest request, User user) { // UserPrincipal userPrincipal = new UserPrincipal(user.getId(), user.getUsername()); // // // Add base functions // RoleBaseFunctionDao userBaseFuction = new RoleBaseFunctionDao(); // Set<String> baseFunctionSet = userBaseFuction.findByRoleId(user.getRoleId()); // userPrincipal.setBaseFunctionSet(baseFunctionSet); // // request.setAttribute(PRINCIPAL_ATTRIBUTE, userPrincipal); // } // // /** // * Inject an anonymous user into the request attributes. // * // * @param request HTTP request // */ // private void injectAnonymousUser(HttpServletRequest request) { // AnonymousPrincipal anonymousPrincipal = new AnonymousPrincipal(); // anonymousPrincipal.setDateTimeZone(DateTimeZone.forID(Constants.DEFAULT_TIMEZONE_ID)); // // request.setAttribute(PRINCIPAL_ATTRIBUTE, anonymousPrincipal); // } // } // Path: home-web/src/test/java/com/sismics/home/rest/TestAppResource.java import javax.json.JsonArray; import javax.json.JsonObject; import org.junit.Assert; import org.junit.Test; import com.sismics.util.filter.TokenBasedSecurityFilter; package com.sismics.home.rest; /** * Test the app resource. * * @author jtremeaux */ public class TestAppResource extends BaseJerseyTest { /** * Test the API resource. * * @throws JSONException */ @Test public void testAppResource() { // Check the application info JsonObject json = target().path("/app").request().get(JsonObject.class); String currentVersion = json.getString("current_version"); Assert.assertNotNull(currentVersion); String minVersion = json.getString("min_version"); Assert.assertNotNull(minVersion); Long freeMemory = json.getJsonNumber("free_memory").longValue(); Assert.assertTrue(freeMemory > 0); Long totalMemory = json.getJsonNumber("total_memory").longValue(); Assert.assertTrue(totalMemory > 0 && totalMemory > freeMemory); } /** * Test the log resource. * * @throws JSONException */ @Test public void testLogResource() { // Login admin String adminAuthenticationToken = clientUtil.login("admin", "admin", false); // Check the logs (page 1) JsonObject json = target().path("/app/log").queryParam("level", "DEBUG").request()
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, adminAuthenticationToken)
sismics/home
home-core/src/main/java/com/sismics/util/log4j/MemoryAppender.java
// Path: home-core/src/main/java/com/sismics/home/core/util/dbi/PaginatedList.java // public class PaginatedList<T> { // /** // * Size of a page. // */ // private int limit; // // /** // * Offset of the page (in number of records). // */ // private int offset; // // /** // * Total number of records. // */ // private int resultCount; // // /** // * List of records of the current page. // */ // private List<T> resultList; // // /** // * Constructor of PaginatedList. // * // * @param pageSize Page size // * @param offset Offset // */ // public PaginatedList(int pageSize, int offset) { // this.limit = pageSize; // this.offset = offset; // } // // /** // * Getter of resultCount. // * // * @return resultCount // */ // public int getResultCount() { // return resultCount; // } // // /** // * Setter of resultCount. // * // * @param resultCount resultCount // */ // public void setResultCount(int resultCount) { // this.resultCount = resultCount; // } // // /** // * Getter of resultList. // * // * @return resultList // */ // public List<T> getResultList() { // return resultList; // } // // /** // * Setter of resultList. // * // * @param resultList resultList // */ // public void setResultList(List<T> resultList) { // this.resultList = resultList; // } // // /** // * Getter of limit. // * // * @return limit // */ // public int getLimit() { // return limit; // } // // /** // * Getter of offset. // * // * @return offset // */ // public int getOffset() { // return offset; // } // }
import com.google.common.collect.Lists; import com.sismics.home.core.util.dbi.PaginatedList; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.spi.LoggingEvent; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue;
return (index > -1) ? event.getLoggerName().substring(index + 1) : event.getLoggerName(); } /** * Getter of logList. * * @return logList */ public Queue<LogEntry> getLogList() { return logQueue; } /** * Setter of size. * * @param size size */ public void setSize(int size) { this.size = size; } /** * Find some logs. * * @param criteria Search criteria * @param list Paginated list (modified by side effect) */
// Path: home-core/src/main/java/com/sismics/home/core/util/dbi/PaginatedList.java // public class PaginatedList<T> { // /** // * Size of a page. // */ // private int limit; // // /** // * Offset of the page (in number of records). // */ // private int offset; // // /** // * Total number of records. // */ // private int resultCount; // // /** // * List of records of the current page. // */ // private List<T> resultList; // // /** // * Constructor of PaginatedList. // * // * @param pageSize Page size // * @param offset Offset // */ // public PaginatedList(int pageSize, int offset) { // this.limit = pageSize; // this.offset = offset; // } // // /** // * Getter of resultCount. // * // * @return resultCount // */ // public int getResultCount() { // return resultCount; // } // // /** // * Setter of resultCount. // * // * @param resultCount resultCount // */ // public void setResultCount(int resultCount) { // this.resultCount = resultCount; // } // // /** // * Getter of resultList. // * // * @return resultList // */ // public List<T> getResultList() { // return resultList; // } // // /** // * Setter of resultList. // * // * @param resultList resultList // */ // public void setResultList(List<T> resultList) { // this.resultList = resultList; // } // // /** // * Getter of limit. // * // * @return limit // */ // public int getLimit() { // return limit; // } // // /** // * Getter of offset. // * // * @return offset // */ // public int getOffset() { // return offset; // } // } // Path: home-core/src/main/java/com/sismics/util/log4j/MemoryAppender.java import com.google.common.collect.Lists; import com.sismics.home.core.util.dbi.PaginatedList; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.spi.LoggingEvent; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; return (index > -1) ? event.getLoggerName().substring(index + 1) : event.getLoggerName(); } /** * Getter of logList. * * @return logList */ public Queue<LogEntry> getLogList() { return logQueue; } /** * Setter of size. * * @param size size */ public void setSize(int size) { this.size = size; } /** * Find some logs. * * @param criteria Search criteria * @param list Paginated list (modified by side effect) */
public void find(LogCriteria criteria, PaginatedList<LogEntry> list) {
sismics/home
home-core/src/main/java/com/sismics/home/core/dao/dbi/mapper/SensorSampleMapper.java
// Path: home-core/src/main/java/com/sismics/home/core/constant/SensorSampleType.java // public enum SensorSampleType { // // /** // * Raw sample from sensor input. // */ // RAW, // // /** // * Sample compacted from all samples from the same minute. // */ // MINUTE, // // /** // * Sample compacted from all samples from the same hour. // */ // HOUR, // // /** // * Sample compacted from all samples from the same day. // */ // DAY // } // // Path: home-core/src/main/java/com/sismics/home/core/model/dbi/SensorSample.java // public class SensorSample { // /** // * ID. // */ // private String id; // // /** // * Sensor ID. // */ // private String sensorId; // // /** // * Value. // */ // private float value; // // /** // * Creation date. // */ // private Date createDate; // // /** // * Type. // */ // private SensorSampleType type; // // public SensorSample() { // } // // public SensorSample(String id, String sensorId, Date createDate, float value, SensorSampleType type) { // this.id = id; // this.sensorId = sensorId; // this.createDate = createDate; // this.value = value; // this.type = type; // } // // /** // * Getter of id. // * // * @return id // */ // public String getId() { // return id; // } // // /** // * Setter of id. // * // * @param id id // */ // public void setId(String id) { // this.id = id; // } // // /** // * Getter of createDate. // * // * @return createDate // */ // public Date getCreateDate() { // return createDate; // } // // /** // * Setter of createDate. // * // * @param createDate createDate // */ // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // /** // * Getter of sensorId. // * // * @return the sensorId // */ // public String getSensorId() { // return sensorId; // } // // /** // * Setter of sensorId. // * // * @param sensorId sensorId // */ // public void setSensorId(String sensorId) { // this.sensorId = sensorId; // } // // /** // * Getter of value. // * // * @return the value // */ // public float getValue() { // return value; // } // // /** // * Setter of value. // * // * @param value value // */ // public void setValue(float value) { // this.value = value; // } // // /** // * Getter of type. // * // * @return the type // */ // public SensorSampleType getType() { // return type; // } // // /** // * Setter of type. // * // * @param type type // */ // public void setType(SensorSampleType type) { // this.type = type; // } // // @Override // public String toString() { // return Objects.toStringHelper(this) // .add("id", id) // .add("value", value) // .add("createDate", createDate) // .add("type", type) // .toString(); // } // }
import java.sql.ResultSet; import java.sql.SQLException; import org.skife.jdbi.v2.StatementContext; import com.sismics.home.core.constant.SensorSampleType; import com.sismics.home.core.model.dbi.SensorSample; import com.sismics.util.dbi.BaseResultSetMapper;
package com.sismics.home.core.dao.dbi.mapper; /** * Sensor sample result set mapper. * * @author bgamard */ public class SensorSampleMapper extends BaseResultSetMapper<SensorSample> { @Override public String[] getColumns() { return new String[] { "SES_ID_C", "SES_IDSEN_C", "SES_CREATEDATE_D", "SES_VALUE_N", "SES_TYPE_C" }; } @Override public SensorSample map(int index, ResultSet r, StatementContext ctx) throws SQLException { final String[] columns = getColumns(); int column = 0; return new SensorSample( r.getString(columns[column++]), r.getString(columns[column++]), r.getTimestamp(columns[column++]), r.getFloat(columns[column++]),
// Path: home-core/src/main/java/com/sismics/home/core/constant/SensorSampleType.java // public enum SensorSampleType { // // /** // * Raw sample from sensor input. // */ // RAW, // // /** // * Sample compacted from all samples from the same minute. // */ // MINUTE, // // /** // * Sample compacted from all samples from the same hour. // */ // HOUR, // // /** // * Sample compacted from all samples from the same day. // */ // DAY // } // // Path: home-core/src/main/java/com/sismics/home/core/model/dbi/SensorSample.java // public class SensorSample { // /** // * ID. // */ // private String id; // // /** // * Sensor ID. // */ // private String sensorId; // // /** // * Value. // */ // private float value; // // /** // * Creation date. // */ // private Date createDate; // // /** // * Type. // */ // private SensorSampleType type; // // public SensorSample() { // } // // public SensorSample(String id, String sensorId, Date createDate, float value, SensorSampleType type) { // this.id = id; // this.sensorId = sensorId; // this.createDate = createDate; // this.value = value; // this.type = type; // } // // /** // * Getter of id. // * // * @return id // */ // public String getId() { // return id; // } // // /** // * Setter of id. // * // * @param id id // */ // public void setId(String id) { // this.id = id; // } // // /** // * Getter of createDate. // * // * @return createDate // */ // public Date getCreateDate() { // return createDate; // } // // /** // * Setter of createDate. // * // * @param createDate createDate // */ // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // /** // * Getter of sensorId. // * // * @return the sensorId // */ // public String getSensorId() { // return sensorId; // } // // /** // * Setter of sensorId. // * // * @param sensorId sensorId // */ // public void setSensorId(String sensorId) { // this.sensorId = sensorId; // } // // /** // * Getter of value. // * // * @return the value // */ // public float getValue() { // return value; // } // // /** // * Setter of value. // * // * @param value value // */ // public void setValue(float value) { // this.value = value; // } // // /** // * Getter of type. // * // * @return the type // */ // public SensorSampleType getType() { // return type; // } // // /** // * Setter of type. // * // * @param type type // */ // public void setType(SensorSampleType type) { // this.type = type; // } // // @Override // public String toString() { // return Objects.toStringHelper(this) // .add("id", id) // .add("value", value) // .add("createDate", createDate) // .add("type", type) // .toString(); // } // } // Path: home-core/src/main/java/com/sismics/home/core/dao/dbi/mapper/SensorSampleMapper.java import java.sql.ResultSet; import java.sql.SQLException; import org.skife.jdbi.v2.StatementContext; import com.sismics.home.core.constant.SensorSampleType; import com.sismics.home.core.model.dbi.SensorSample; import com.sismics.util.dbi.BaseResultSetMapper; package com.sismics.home.core.dao.dbi.mapper; /** * Sensor sample result set mapper. * * @author bgamard */ public class SensorSampleMapper extends BaseResultSetMapper<SensorSample> { @Override public String[] getColumns() { return new String[] { "SES_ID_C", "SES_IDSEN_C", "SES_CREATEDATE_D", "SES_VALUE_N", "SES_TYPE_C" }; } @Override public SensorSample map(int index, ResultSet r, StatementContext ctx) throws SQLException { final String[] columns = getColumns(); int column = 0; return new SensorSample( r.getString(columns[column++]), r.getString(columns[column++]), r.getTimestamp(columns[column++]), r.getFloat(columns[column++]),
SensorSampleType.valueOf(r.getString(columns[column++])));
sismics/home
home-core/src/test/java/com/sismics/home/BaseTransactionalTest.java
// Path: home-core/src/main/java/com/sismics/util/context/ThreadLocalContext.java // public class ThreadLocalContext { // /** // * ThreadLocal to store the context. // */ // public static final ThreadLocal<ThreadLocalContext> threadLocalContext = new ThreadLocal<ThreadLocalContext>(); // // /** // * JDBI handle. // */ // private Handle handle; // // /** // * Private constructor. // */ // private ThreadLocalContext() { // // NOP // } // // /** // * Returns an instance of this thread context. // * // * @return Thread local context // */ // public static ThreadLocalContext get() { // ThreadLocalContext context = threadLocalContext.get(); // if (context == null) { // context = new ThreadLocalContext(); // threadLocalContext.set(context); // } // return context; // } // // /** // * Cleans up the instance of this thread context. // */ // public static void cleanup() { // threadLocalContext.set(null); // } // // /** // * Getter of handle. // * // * @return handle // */ // public Handle getHandle() { // return handle; // } // // /** // * Setter of handle. // * // * @param handle handle // */ // public void setHandle(Handle handle) { // this.handle = handle; // } // } // // Path: home-core/src/main/java/com/sismics/util/dbi/DBIF.java // public class DBIF { // private static final Logger log = LoggerFactory.getLogger(DBIF.class); // // private static ComboPooledDataSource cpds; // // private static DBI dbi; // // static { // if (dbi == null) { // createDbi(); // } // } // // public static void createDbi() { // try { // cpds = new ComboPooledDataSource(); // TODO use getDbProperties() // dbi = new DBI(cpds); // dbi.registerMapper(new AuthenticationTokenMapper()); // dbi.registerMapper(new BaseFunctionMapper()); // dbi.registerMapper(new ConfigMapper()); // dbi.registerMapper(new RoleBaseFunctionMapper()); // dbi.registerMapper(new RoleMapper()); // dbi.registerMapper(new UserMapper()); // dbi.registerMapper(new SensorMapper()); // dbi.registerMapper(new SensorSampleMapper()); // dbi.registerMapper(new CameraMapper()); // } catch (Throwable t) { // log.error("Error creating DBI", t); // } // // Handle handle = null; // try { // handle = dbi.open(); // DbOpenHelper openHelper = new DbOpenHelper(handle) { // // @Override // public void onCreate() throws Exception { // executeAllScript(0); // } // // @Override // public void onUpgrade(int oldVersion, int newVersion) throws Exception { // for (int version = oldVersion + 1; version <= newVersion; version++) { // executeAllScript(version); // } // } // }; // openHelper.open(); // } catch (Exception e) { // if (handle != null && handle.isInTransaction()) { // handle.rollback(); // handle.close(); // } // } // // } // // private static Map<Object, Object> getDbProperties() { // // Use properties file if exists // try { // URL dbPropertiesUrl = DBIF.class.getResource("/c3p0.properties"); // if (dbPropertiesUrl != null) { // log.info("Configuring connection pool from c3p0.properties"); // // InputStream is = dbPropertiesUrl.openStream(); // Properties properties = new Properties(); // properties.load(is); // return properties; // } // } catch (IOException e) { // log.error("Error reading c3p0.properties", e); // } // // // Use environment parameters // log.info("Configuring EntityManager from environment parameters"); // Map<Object, Object> props = new HashMap<Object, Object>(); // props.put("c3p0.driverClass", "org.h2.Driver"); // File dbDirectory = DirectoryUtil.getDbDirectory(); // String dbFile = dbDirectory.getAbsoluteFile() + File.separator + "home"; // props.put("c3p0.jdbcUrl", "jdbc:h2:file:" + dbFile + ";WRITE_DELAY=false;shutdown=true"); // props.put("c3p0.user", "sa"); // return props; // } // // /** // * Private constructor. // */ // private DBIF() { // } // // /** // * Returns an instance of DBIF. // * // * @return Instance of DBIF // */ // public static DBI get() { // return dbi; // } // // public static void reset() { // if (cpds != null) { // dbi.open().createStatement("DROP ALL OBJECTS").execute(); // cpds.close(); // cpds = null; // dbi = null; // createDbi(); // } // } // }
import com.sismics.util.context.ThreadLocalContext; import com.sismics.util.dbi.DBIF; import org.junit.After; import org.junit.Before; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle;
package com.sismics.home; /** * Base class of tests with a transactional context. * * @author jtremeaux */ public abstract class BaseTransactionalTest { @Before public void setUp() throws Exception { // Initialize the persistence layer
// Path: home-core/src/main/java/com/sismics/util/context/ThreadLocalContext.java // public class ThreadLocalContext { // /** // * ThreadLocal to store the context. // */ // public static final ThreadLocal<ThreadLocalContext> threadLocalContext = new ThreadLocal<ThreadLocalContext>(); // // /** // * JDBI handle. // */ // private Handle handle; // // /** // * Private constructor. // */ // private ThreadLocalContext() { // // NOP // } // // /** // * Returns an instance of this thread context. // * // * @return Thread local context // */ // public static ThreadLocalContext get() { // ThreadLocalContext context = threadLocalContext.get(); // if (context == null) { // context = new ThreadLocalContext(); // threadLocalContext.set(context); // } // return context; // } // // /** // * Cleans up the instance of this thread context. // */ // public static void cleanup() { // threadLocalContext.set(null); // } // // /** // * Getter of handle. // * // * @return handle // */ // public Handle getHandle() { // return handle; // } // // /** // * Setter of handle. // * // * @param handle handle // */ // public void setHandle(Handle handle) { // this.handle = handle; // } // } // // Path: home-core/src/main/java/com/sismics/util/dbi/DBIF.java // public class DBIF { // private static final Logger log = LoggerFactory.getLogger(DBIF.class); // // private static ComboPooledDataSource cpds; // // private static DBI dbi; // // static { // if (dbi == null) { // createDbi(); // } // } // // public static void createDbi() { // try { // cpds = new ComboPooledDataSource(); // TODO use getDbProperties() // dbi = new DBI(cpds); // dbi.registerMapper(new AuthenticationTokenMapper()); // dbi.registerMapper(new BaseFunctionMapper()); // dbi.registerMapper(new ConfigMapper()); // dbi.registerMapper(new RoleBaseFunctionMapper()); // dbi.registerMapper(new RoleMapper()); // dbi.registerMapper(new UserMapper()); // dbi.registerMapper(new SensorMapper()); // dbi.registerMapper(new SensorSampleMapper()); // dbi.registerMapper(new CameraMapper()); // } catch (Throwable t) { // log.error("Error creating DBI", t); // } // // Handle handle = null; // try { // handle = dbi.open(); // DbOpenHelper openHelper = new DbOpenHelper(handle) { // // @Override // public void onCreate() throws Exception { // executeAllScript(0); // } // // @Override // public void onUpgrade(int oldVersion, int newVersion) throws Exception { // for (int version = oldVersion + 1; version <= newVersion; version++) { // executeAllScript(version); // } // } // }; // openHelper.open(); // } catch (Exception e) { // if (handle != null && handle.isInTransaction()) { // handle.rollback(); // handle.close(); // } // } // // } // // private static Map<Object, Object> getDbProperties() { // // Use properties file if exists // try { // URL dbPropertiesUrl = DBIF.class.getResource("/c3p0.properties"); // if (dbPropertiesUrl != null) { // log.info("Configuring connection pool from c3p0.properties"); // // InputStream is = dbPropertiesUrl.openStream(); // Properties properties = new Properties(); // properties.load(is); // return properties; // } // } catch (IOException e) { // log.error("Error reading c3p0.properties", e); // } // // // Use environment parameters // log.info("Configuring EntityManager from environment parameters"); // Map<Object, Object> props = new HashMap<Object, Object>(); // props.put("c3p0.driverClass", "org.h2.Driver"); // File dbDirectory = DirectoryUtil.getDbDirectory(); // String dbFile = dbDirectory.getAbsoluteFile() + File.separator + "home"; // props.put("c3p0.jdbcUrl", "jdbc:h2:file:" + dbFile + ";WRITE_DELAY=false;shutdown=true"); // props.put("c3p0.user", "sa"); // return props; // } // // /** // * Private constructor. // */ // private DBIF() { // } // // /** // * Returns an instance of DBIF. // * // * @return Instance of DBIF // */ // public static DBI get() { // return dbi; // } // // public static void reset() { // if (cpds != null) { // dbi.open().createStatement("DROP ALL OBJECTS").execute(); // cpds.close(); // cpds = null; // dbi = null; // createDbi(); // } // } // } // Path: home-core/src/test/java/com/sismics/home/BaseTransactionalTest.java import com.sismics.util.context.ThreadLocalContext; import com.sismics.util.dbi.DBIF; import org.junit.After; import org.junit.Before; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; package com.sismics.home; /** * Base class of tests with a transactional context. * * @author jtremeaux */ public abstract class BaseTransactionalTest { @Before public void setUp() throws Exception { // Initialize the persistence layer
DBI dbi = DBIF.get();
sismics/home
home-core/src/test/java/com/sismics/home/BaseTransactionalTest.java
// Path: home-core/src/main/java/com/sismics/util/context/ThreadLocalContext.java // public class ThreadLocalContext { // /** // * ThreadLocal to store the context. // */ // public static final ThreadLocal<ThreadLocalContext> threadLocalContext = new ThreadLocal<ThreadLocalContext>(); // // /** // * JDBI handle. // */ // private Handle handle; // // /** // * Private constructor. // */ // private ThreadLocalContext() { // // NOP // } // // /** // * Returns an instance of this thread context. // * // * @return Thread local context // */ // public static ThreadLocalContext get() { // ThreadLocalContext context = threadLocalContext.get(); // if (context == null) { // context = new ThreadLocalContext(); // threadLocalContext.set(context); // } // return context; // } // // /** // * Cleans up the instance of this thread context. // */ // public static void cleanup() { // threadLocalContext.set(null); // } // // /** // * Getter of handle. // * // * @return handle // */ // public Handle getHandle() { // return handle; // } // // /** // * Setter of handle. // * // * @param handle handle // */ // public void setHandle(Handle handle) { // this.handle = handle; // } // } // // Path: home-core/src/main/java/com/sismics/util/dbi/DBIF.java // public class DBIF { // private static final Logger log = LoggerFactory.getLogger(DBIF.class); // // private static ComboPooledDataSource cpds; // // private static DBI dbi; // // static { // if (dbi == null) { // createDbi(); // } // } // // public static void createDbi() { // try { // cpds = new ComboPooledDataSource(); // TODO use getDbProperties() // dbi = new DBI(cpds); // dbi.registerMapper(new AuthenticationTokenMapper()); // dbi.registerMapper(new BaseFunctionMapper()); // dbi.registerMapper(new ConfigMapper()); // dbi.registerMapper(new RoleBaseFunctionMapper()); // dbi.registerMapper(new RoleMapper()); // dbi.registerMapper(new UserMapper()); // dbi.registerMapper(new SensorMapper()); // dbi.registerMapper(new SensorSampleMapper()); // dbi.registerMapper(new CameraMapper()); // } catch (Throwable t) { // log.error("Error creating DBI", t); // } // // Handle handle = null; // try { // handle = dbi.open(); // DbOpenHelper openHelper = new DbOpenHelper(handle) { // // @Override // public void onCreate() throws Exception { // executeAllScript(0); // } // // @Override // public void onUpgrade(int oldVersion, int newVersion) throws Exception { // for (int version = oldVersion + 1; version <= newVersion; version++) { // executeAllScript(version); // } // } // }; // openHelper.open(); // } catch (Exception e) { // if (handle != null && handle.isInTransaction()) { // handle.rollback(); // handle.close(); // } // } // // } // // private static Map<Object, Object> getDbProperties() { // // Use properties file if exists // try { // URL dbPropertiesUrl = DBIF.class.getResource("/c3p0.properties"); // if (dbPropertiesUrl != null) { // log.info("Configuring connection pool from c3p0.properties"); // // InputStream is = dbPropertiesUrl.openStream(); // Properties properties = new Properties(); // properties.load(is); // return properties; // } // } catch (IOException e) { // log.error("Error reading c3p0.properties", e); // } // // // Use environment parameters // log.info("Configuring EntityManager from environment parameters"); // Map<Object, Object> props = new HashMap<Object, Object>(); // props.put("c3p0.driverClass", "org.h2.Driver"); // File dbDirectory = DirectoryUtil.getDbDirectory(); // String dbFile = dbDirectory.getAbsoluteFile() + File.separator + "home"; // props.put("c3p0.jdbcUrl", "jdbc:h2:file:" + dbFile + ";WRITE_DELAY=false;shutdown=true"); // props.put("c3p0.user", "sa"); // return props; // } // // /** // * Private constructor. // */ // private DBIF() { // } // // /** // * Returns an instance of DBIF. // * // * @return Instance of DBIF // */ // public static DBI get() { // return dbi; // } // // public static void reset() { // if (cpds != null) { // dbi.open().createStatement("DROP ALL OBJECTS").execute(); // cpds.close(); // cpds = null; // dbi = null; // createDbi(); // } // } // }
import com.sismics.util.context.ThreadLocalContext; import com.sismics.util.dbi.DBIF; import org.junit.After; import org.junit.Before; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle;
package com.sismics.home; /** * Base class of tests with a transactional context. * * @author jtremeaux */ public abstract class BaseTransactionalTest { @Before public void setUp() throws Exception { // Initialize the persistence layer DBI dbi = DBIF.get(); Handle handle = dbi.open();
// Path: home-core/src/main/java/com/sismics/util/context/ThreadLocalContext.java // public class ThreadLocalContext { // /** // * ThreadLocal to store the context. // */ // public static final ThreadLocal<ThreadLocalContext> threadLocalContext = new ThreadLocal<ThreadLocalContext>(); // // /** // * JDBI handle. // */ // private Handle handle; // // /** // * Private constructor. // */ // private ThreadLocalContext() { // // NOP // } // // /** // * Returns an instance of this thread context. // * // * @return Thread local context // */ // public static ThreadLocalContext get() { // ThreadLocalContext context = threadLocalContext.get(); // if (context == null) { // context = new ThreadLocalContext(); // threadLocalContext.set(context); // } // return context; // } // // /** // * Cleans up the instance of this thread context. // */ // public static void cleanup() { // threadLocalContext.set(null); // } // // /** // * Getter of handle. // * // * @return handle // */ // public Handle getHandle() { // return handle; // } // // /** // * Setter of handle. // * // * @param handle handle // */ // public void setHandle(Handle handle) { // this.handle = handle; // } // } // // Path: home-core/src/main/java/com/sismics/util/dbi/DBIF.java // public class DBIF { // private static final Logger log = LoggerFactory.getLogger(DBIF.class); // // private static ComboPooledDataSource cpds; // // private static DBI dbi; // // static { // if (dbi == null) { // createDbi(); // } // } // // public static void createDbi() { // try { // cpds = new ComboPooledDataSource(); // TODO use getDbProperties() // dbi = new DBI(cpds); // dbi.registerMapper(new AuthenticationTokenMapper()); // dbi.registerMapper(new BaseFunctionMapper()); // dbi.registerMapper(new ConfigMapper()); // dbi.registerMapper(new RoleBaseFunctionMapper()); // dbi.registerMapper(new RoleMapper()); // dbi.registerMapper(new UserMapper()); // dbi.registerMapper(new SensorMapper()); // dbi.registerMapper(new SensorSampleMapper()); // dbi.registerMapper(new CameraMapper()); // } catch (Throwable t) { // log.error("Error creating DBI", t); // } // // Handle handle = null; // try { // handle = dbi.open(); // DbOpenHelper openHelper = new DbOpenHelper(handle) { // // @Override // public void onCreate() throws Exception { // executeAllScript(0); // } // // @Override // public void onUpgrade(int oldVersion, int newVersion) throws Exception { // for (int version = oldVersion + 1; version <= newVersion; version++) { // executeAllScript(version); // } // } // }; // openHelper.open(); // } catch (Exception e) { // if (handle != null && handle.isInTransaction()) { // handle.rollback(); // handle.close(); // } // } // // } // // private static Map<Object, Object> getDbProperties() { // // Use properties file if exists // try { // URL dbPropertiesUrl = DBIF.class.getResource("/c3p0.properties"); // if (dbPropertiesUrl != null) { // log.info("Configuring connection pool from c3p0.properties"); // // InputStream is = dbPropertiesUrl.openStream(); // Properties properties = new Properties(); // properties.load(is); // return properties; // } // } catch (IOException e) { // log.error("Error reading c3p0.properties", e); // } // // // Use environment parameters // log.info("Configuring EntityManager from environment parameters"); // Map<Object, Object> props = new HashMap<Object, Object>(); // props.put("c3p0.driverClass", "org.h2.Driver"); // File dbDirectory = DirectoryUtil.getDbDirectory(); // String dbFile = dbDirectory.getAbsoluteFile() + File.separator + "home"; // props.put("c3p0.jdbcUrl", "jdbc:h2:file:" + dbFile + ";WRITE_DELAY=false;shutdown=true"); // props.put("c3p0.user", "sa"); // return props; // } // // /** // * Private constructor. // */ // private DBIF() { // } // // /** // * Returns an instance of DBIF. // * // * @return Instance of DBIF // */ // public static DBI get() { // return dbi; // } // // public static void reset() { // if (cpds != null) { // dbi.open().createStatement("DROP ALL OBJECTS").execute(); // cpds.close(); // cpds = null; // dbi = null; // createDbi(); // } // } // } // Path: home-core/src/test/java/com/sismics/home/BaseTransactionalTest.java import com.sismics.util.context.ThreadLocalContext; import com.sismics.util.dbi.DBIF; import org.junit.After; import org.junit.Before; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; package com.sismics.home; /** * Base class of tests with a transactional context. * * @author jtremeaux */ public abstract class BaseTransactionalTest { @Before public void setUp() throws Exception { // Initialize the persistence layer DBI dbi = DBIF.get(); Handle handle = dbi.open();
ThreadLocalContext context = ThreadLocalContext.get();
sismics/home
home-web-common/src/test/java/com/sismics/home/rest/util/ClientUtil.java
// Path: home-web-common/src/main/java/com/sismics/util/filter/TokenBasedSecurityFilter.java // public class TokenBasedSecurityFilter implements Filter { // /** // * Logger. // */ // private static final Logger log = LoggerFactory.getLogger(TokenBasedSecurityFilter.class); // // /** // * Name of the cookie used to store the authentication token. // */ // public static final String COOKIE_NAME = "auth_token"; // // /** // * Name of the attribute containing the principal. // */ // public static final String PRINCIPAL_ATTRIBUTE = "principal"; // // /** // * Lifetime of the authentication token in seconds, since login. // */ // public static final int TOKEN_LONG_LIFETIME = 3600 * 24 * 365 * 20; // // /** // * Lifetime of the authentication token in seconds, since last connection. // */ // public static final int TOKEN_SESSION_LIFETIME = 3600 * 24; // // @Override // public void init(FilterConfig filterConfig) throws ServletException { // // NOP // } // // @Override // public void destroy() { // // NOP // } // // @Override // public void doFilter(ServletRequest req, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { // // Get the value of the client authentication token // HttpServletRequest request = (HttpServletRequest) req; // String authToken = null; // if (request.getCookies() != null) { // for (Cookie cookie : request.getCookies()) { // if (COOKIE_NAME.equals(cookie.getName())) { // authToken = cookie.getValue(); // } // } // } // // // Get the corresponding server token // AuthenticationTokenDao authenticationTokenDao = new AuthenticationTokenDao(); // AuthenticationToken authenticationToken = null; // if (authToken != null) { // authenticationToken = authenticationTokenDao.get(authToken); // } // // if (authenticationToken == null) { // injectAnonymousUser(request); // } else { // // Check if the token is still valid // if (isTokenExpired(authenticationToken)) { // try { // injectAnonymousUser(request); // // // Destroy the expired token // authenticationTokenDao.delete(authToken); // } catch (Exception e) { // if (log.isErrorEnabled()) { // log.error(MessageFormat.format("Error deleting authentication token {0} ", authToken), e); // } // } // } else { // // Check if the user is still valid // UserDao userDao = new UserDao(); // User user = userDao.getActiveById(authenticationToken.getUserId()); // if (user != null) { // injectAuthenticatedUser(request, user); // // // Update the last connection date // authenticationTokenDao.updateLastConnectionDate(authenticationToken.getId()); // } else { // injectAnonymousUser(request); // } // } // } // // filterChain.doFilter(request, response); // } // // /** // * Returns true if the token is expired. // * // * @param authenticationToken Authentication token // * @return Token expired // */ // private boolean isTokenExpired(AuthenticationToken authenticationToken) { // final long now = new Date().getTime(); // final long creationDate = authenticationToken.getCreateDate().getTime(); // if (authenticationToken.isLongLasted()) { // return now >= creationDate + ((long) TOKEN_LONG_LIFETIME) * 1000L; // } else { // long date = authenticationToken.getLastConnectionDate() != null ? // authenticationToken.getLastConnectionDate().getTime() : creationDate; // return now >= date + ((long) TOKEN_SESSION_LIFETIME) * 1000L; // } // } // // /** // * Inject an authenticated user into the request attributes. // * // * @param request HTTP request // * @param user User to inject // */ // private void injectAuthenticatedUser(HttpServletRequest request, User user) { // UserPrincipal userPrincipal = new UserPrincipal(user.getId(), user.getUsername()); // // // Add base functions // RoleBaseFunctionDao userBaseFuction = new RoleBaseFunctionDao(); // Set<String> baseFunctionSet = userBaseFuction.findByRoleId(user.getRoleId()); // userPrincipal.setBaseFunctionSet(baseFunctionSet); // // request.setAttribute(PRINCIPAL_ATTRIBUTE, userPrincipal); // } // // /** // * Inject an anonymous user into the request attributes. // * // * @param request HTTP request // */ // private void injectAnonymousUser(HttpServletRequest request) { // AnonymousPrincipal anonymousPrincipal = new AnonymousPrincipal(); // anonymousPrincipal.setDateTimeZone(DateTimeZone.forID(Constants.DEFAULT_TIMEZONE_ID)); // // request.setAttribute(PRINCIPAL_ATTRIBUTE, anonymousPrincipal); // } // }
import javax.json.JsonObject; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Form; import javax.ws.rs.core.NewCookie; import javax.ws.rs.core.Response; import com.sismics.util.filter.TokenBasedSecurityFilter;
package com.sismics.home.rest.util; /** * REST client utilities. * * @author jtremeaux */ public class ClientUtil { private WebTarget resource; /** * Constructor of ClientUtil. * * @param resource Resource corresponding to the base URI of REST resources. */ public ClientUtil(WebTarget resource) { this.resource = resource; } /** * Creates a user. * * @param username Username */ public void createUser(String username) { // Login admin to create the user String adminAuthenticationToken = login("admin", "admin", false); // Create the user Form form = new Form(); form.param("username", username); form.param("email", username + "@home.com"); form.param("password", "12345678"); form.param("time_zone", "Asia/Tokyo"); resource.path("/user").request()
// Path: home-web-common/src/main/java/com/sismics/util/filter/TokenBasedSecurityFilter.java // public class TokenBasedSecurityFilter implements Filter { // /** // * Logger. // */ // private static final Logger log = LoggerFactory.getLogger(TokenBasedSecurityFilter.class); // // /** // * Name of the cookie used to store the authentication token. // */ // public static final String COOKIE_NAME = "auth_token"; // // /** // * Name of the attribute containing the principal. // */ // public static final String PRINCIPAL_ATTRIBUTE = "principal"; // // /** // * Lifetime of the authentication token in seconds, since login. // */ // public static final int TOKEN_LONG_LIFETIME = 3600 * 24 * 365 * 20; // // /** // * Lifetime of the authentication token in seconds, since last connection. // */ // public static final int TOKEN_SESSION_LIFETIME = 3600 * 24; // // @Override // public void init(FilterConfig filterConfig) throws ServletException { // // NOP // } // // @Override // public void destroy() { // // NOP // } // // @Override // public void doFilter(ServletRequest req, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { // // Get the value of the client authentication token // HttpServletRequest request = (HttpServletRequest) req; // String authToken = null; // if (request.getCookies() != null) { // for (Cookie cookie : request.getCookies()) { // if (COOKIE_NAME.equals(cookie.getName())) { // authToken = cookie.getValue(); // } // } // } // // // Get the corresponding server token // AuthenticationTokenDao authenticationTokenDao = new AuthenticationTokenDao(); // AuthenticationToken authenticationToken = null; // if (authToken != null) { // authenticationToken = authenticationTokenDao.get(authToken); // } // // if (authenticationToken == null) { // injectAnonymousUser(request); // } else { // // Check if the token is still valid // if (isTokenExpired(authenticationToken)) { // try { // injectAnonymousUser(request); // // // Destroy the expired token // authenticationTokenDao.delete(authToken); // } catch (Exception e) { // if (log.isErrorEnabled()) { // log.error(MessageFormat.format("Error deleting authentication token {0} ", authToken), e); // } // } // } else { // // Check if the user is still valid // UserDao userDao = new UserDao(); // User user = userDao.getActiveById(authenticationToken.getUserId()); // if (user != null) { // injectAuthenticatedUser(request, user); // // // Update the last connection date // authenticationTokenDao.updateLastConnectionDate(authenticationToken.getId()); // } else { // injectAnonymousUser(request); // } // } // } // // filterChain.doFilter(request, response); // } // // /** // * Returns true if the token is expired. // * // * @param authenticationToken Authentication token // * @return Token expired // */ // private boolean isTokenExpired(AuthenticationToken authenticationToken) { // final long now = new Date().getTime(); // final long creationDate = authenticationToken.getCreateDate().getTime(); // if (authenticationToken.isLongLasted()) { // return now >= creationDate + ((long) TOKEN_LONG_LIFETIME) * 1000L; // } else { // long date = authenticationToken.getLastConnectionDate() != null ? // authenticationToken.getLastConnectionDate().getTime() : creationDate; // return now >= date + ((long) TOKEN_SESSION_LIFETIME) * 1000L; // } // } // // /** // * Inject an authenticated user into the request attributes. // * // * @param request HTTP request // * @param user User to inject // */ // private void injectAuthenticatedUser(HttpServletRequest request, User user) { // UserPrincipal userPrincipal = new UserPrincipal(user.getId(), user.getUsername()); // // // Add base functions // RoleBaseFunctionDao userBaseFuction = new RoleBaseFunctionDao(); // Set<String> baseFunctionSet = userBaseFuction.findByRoleId(user.getRoleId()); // userPrincipal.setBaseFunctionSet(baseFunctionSet); // // request.setAttribute(PRINCIPAL_ATTRIBUTE, userPrincipal); // } // // /** // * Inject an anonymous user into the request attributes. // * // * @param request HTTP request // */ // private void injectAnonymousUser(HttpServletRequest request) { // AnonymousPrincipal anonymousPrincipal = new AnonymousPrincipal(); // anonymousPrincipal.setDateTimeZone(DateTimeZone.forID(Constants.DEFAULT_TIMEZONE_ID)); // // request.setAttribute(PRINCIPAL_ATTRIBUTE, anonymousPrincipal); // } // } // Path: home-web-common/src/test/java/com/sismics/home/rest/util/ClientUtil.java import javax.json.JsonObject; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Form; import javax.ws.rs.core.NewCookie; import javax.ws.rs.core.Response; import com.sismics.util.filter.TokenBasedSecurityFilter; package com.sismics.home.rest.util; /** * REST client utilities. * * @author jtremeaux */ public class ClientUtil { private WebTarget resource; /** * Constructor of ClientUtil. * * @param resource Resource corresponding to the base URI of REST resources. */ public ClientUtil(WebTarget resource) { this.resource = resource; } /** * Creates a user. * * @param username Username */ public void createUser(String username) { // Login admin to create the user String adminAuthenticationToken = login("admin", "admin", false); // Create the user Form form = new Form(); form.param("username", username); form.param("email", username + "@home.com"); form.param("password", "12345678"); form.param("time_zone", "Asia/Tokyo"); resource.path("/user").request()
.cookie(TokenBasedSecurityFilter.COOKIE_NAME, adminAuthenticationToken)
JianyangZhang/Contact-Crawler
src/main/resources/java/crawler/service/DriveLinkedinService.java
// Path: src/main/resources/java/crawler/EmailCrawlerConfig.java // public class EmailCrawlerConfig { // private static final EmailCrawlerConfig CONFIG = new EmailCrawlerConfig(); // private EmailCrawlerConfig() {}; // public static EmailCrawlerConfig getConfig() { // return CONFIG; // } // // public static int readInt(String propName) { // Properties prop = new Properties(); // InputStream input = null; // try { // input = new FileInputStream("config.properties"); // prop.load(input); // //System.out.println("config: " + propName + ": " + prop.getProperty(propName)); // return Integer.parseInt(prop.getProperty(propName)); // } catch (IOException ex) { // ex.printStackTrace(); // } finally { // if (input != null) { // try { // input.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // return -1; // } // // public static String readString(String propName) { // Properties prop = new Properties(); // InputStream input = null; // try { // input = new FileInputStream("config.properties"); // prop.load(input); // //System.out.println("config: " + propName + ": " + prop.getProperty(propName)); // return prop.getProperty(propName); // } catch (IOException ex) { // ex.printStackTrace(); // } finally { // if (input != null) { // try { // input.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // return ""; // } // } // // Path: src/main/resources/java/crawler/model/Customer.java // public class Customer { // String customer_linkedin_url; // String customer_name; // String customer_title; // String customer_location; // String customer_keywords; // String customer_create_time; // String customer_touch_time; // String internal_company_id; // String compaign_step; // public String getCustomer_linkedin_url() { // return customer_linkedin_url; // } // public void setCustomer_linkedin_url(String customer_linkedin_url) { // this.customer_linkedin_url = customer_linkedin_url; // } // public String getCustomer_name() { // return customer_name; // } // public void setCustomer_name(String customer_name) { // this.customer_name = customer_name; // } // public String getCustomer_title() { // return customer_title; // } // public void setCustomer_title(String customer_title) { // this.customer_title = customer_title; // } // public String getCustomer_location() { // return customer_location; // } // public void setCustomer_location(String customer_location) { // this.customer_location = customer_location; // } // public String getCustomer_keywords() { // return customer_keywords; // } // public void setCustomer_keywords(String customer_keywords) { // this.customer_keywords = customer_keywords; // } // public String getCustomer_create_time() { // return customer_create_time; // } // public void setCustomer_create_time(String customer_create_time) { // this.customer_create_time = customer_create_time; // } // public String getCustomer_touch_time() { // return customer_touch_time; // } // public void setCustomer_touch_time(String customer_touch_time) { // this.customer_touch_time = customer_touch_time; // } // public String getInternal_company_id() { // return internal_company_id; // } // public void setInternal_company_id(String internal_company_id) { // this.internal_company_id = internal_company_id; // } // public String getCompaign_step() { // return compaign_step; // } // public void setCompaign_step(String compaign_step) { // this.compaign_step = compaign_step; // } // @Override // public String toString() { // return "Customer [customer_linkedin_url=" + customer_linkedin_url + ", customer_name=" + customer_name // + ", customer_title=" + customer_title + ", customer_location=" + customer_location // + ", customer_keywords=" + customer_keywords + ", customer_create_time=" + customer_create_time // + ", customer_touch_time=" + customer_touch_time + ", internal_company_id=" + internal_company_id // + ", compaign_step=" + compaign_step + "]"; // } // }
import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.io.IOException; import java.text.SimpleDateFormat; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebElement; import crawler.EmailCrawlerConfig; import crawler.model.Customer; import org.jsoup.*; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements;
package crawler.service; public class DriveLinkedinService extends DriveBrowserService { private String baseURL; private int pagesAccess = 0; private int pageLimit = 800; DriveLinkedinService() {
// Path: src/main/resources/java/crawler/EmailCrawlerConfig.java // public class EmailCrawlerConfig { // private static final EmailCrawlerConfig CONFIG = new EmailCrawlerConfig(); // private EmailCrawlerConfig() {}; // public static EmailCrawlerConfig getConfig() { // return CONFIG; // } // // public static int readInt(String propName) { // Properties prop = new Properties(); // InputStream input = null; // try { // input = new FileInputStream("config.properties"); // prop.load(input); // //System.out.println("config: " + propName + ": " + prop.getProperty(propName)); // return Integer.parseInt(prop.getProperty(propName)); // } catch (IOException ex) { // ex.printStackTrace(); // } finally { // if (input != null) { // try { // input.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // return -1; // } // // public static String readString(String propName) { // Properties prop = new Properties(); // InputStream input = null; // try { // input = new FileInputStream("config.properties"); // prop.load(input); // //System.out.println("config: " + propName + ": " + prop.getProperty(propName)); // return prop.getProperty(propName); // } catch (IOException ex) { // ex.printStackTrace(); // } finally { // if (input != null) { // try { // input.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // return ""; // } // } // // Path: src/main/resources/java/crawler/model/Customer.java // public class Customer { // String customer_linkedin_url; // String customer_name; // String customer_title; // String customer_location; // String customer_keywords; // String customer_create_time; // String customer_touch_time; // String internal_company_id; // String compaign_step; // public String getCustomer_linkedin_url() { // return customer_linkedin_url; // } // public void setCustomer_linkedin_url(String customer_linkedin_url) { // this.customer_linkedin_url = customer_linkedin_url; // } // public String getCustomer_name() { // return customer_name; // } // public void setCustomer_name(String customer_name) { // this.customer_name = customer_name; // } // public String getCustomer_title() { // return customer_title; // } // public void setCustomer_title(String customer_title) { // this.customer_title = customer_title; // } // public String getCustomer_location() { // return customer_location; // } // public void setCustomer_location(String customer_location) { // this.customer_location = customer_location; // } // public String getCustomer_keywords() { // return customer_keywords; // } // public void setCustomer_keywords(String customer_keywords) { // this.customer_keywords = customer_keywords; // } // public String getCustomer_create_time() { // return customer_create_time; // } // public void setCustomer_create_time(String customer_create_time) { // this.customer_create_time = customer_create_time; // } // public String getCustomer_touch_time() { // return customer_touch_time; // } // public void setCustomer_touch_time(String customer_touch_time) { // this.customer_touch_time = customer_touch_time; // } // public String getInternal_company_id() { // return internal_company_id; // } // public void setInternal_company_id(String internal_company_id) { // this.internal_company_id = internal_company_id; // } // public String getCompaign_step() { // return compaign_step; // } // public void setCompaign_step(String compaign_step) { // this.compaign_step = compaign_step; // } // @Override // public String toString() { // return "Customer [customer_linkedin_url=" + customer_linkedin_url + ", customer_name=" + customer_name // + ", customer_title=" + customer_title + ", customer_location=" + customer_location // + ", customer_keywords=" + customer_keywords + ", customer_create_time=" + customer_create_time // + ", customer_touch_time=" + customer_touch_time + ", internal_company_id=" + internal_company_id // + ", compaign_step=" + compaign_step + "]"; // } // } // Path: src/main/resources/java/crawler/service/DriveLinkedinService.java import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.io.IOException; import java.text.SimpleDateFormat; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebElement; import crawler.EmailCrawlerConfig; import crawler.model.Customer; import org.jsoup.*; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; package crawler.service; public class DriveLinkedinService extends DriveBrowserService { private String baseURL; private int pagesAccess = 0; private int pageLimit = 800; DriveLinkedinService() {
super(Boolean.parseBoolean(EmailCrawlerConfig.getConfig().readString("show-gui")));
JianyangZhang/Contact-Crawler
src/main/resources/java/crawler/service/GenerateAccurateEmailsService.java
// Path: src/main/resources/java/crawler/thread/CrawlCompanyThread.java // public class CrawlCompanyThread implements Runnable{ // private Thread t; // private String threadName; // private ArrayList<String> usernames; // private String company; // private String domain; // private HashMap<String, String> results; // private EmailVerifyService ev; // // public CrawlCompanyThread(String name, ArrayList<String> usernames, String company, String domain, HashMap<String, String> results, EmailVerifyService ev){ // threadName = name; // this.usernames = usernames; // this.company = company; // this.domain = domain; // this.results = results; // this.ev = ev; // } // @Override // public void run() { // // TODO Auto-generated method stub // for (String username : usernames) { // String email = username + "@" + domain; // if (ev.valid(email, "gmail.com")) { // results.put(email, company); // System.out.println(email); // } else { // // System.out.println(email + "(invalid)"); // } // } // } // public void start () { // System.out.println("Starting " + threadName ); // if (t == null) { // t = new Thread (this, threadName); // t.start (); // } // } // // public void join () throws InterruptedException { // System.out.println("Joining " + threadName ); // if (t != null) { // t.join(); // } // } // }
import java.util.ArrayList; import java.util.HashMap; import crawler.thread.CrawlCompanyThread;
} public String getName() { return name; } public void setName(String name) { this.name = name; } public HashMap<String, String> getDomainMap() { return domainMap; } public void setDomainMap(HashMap<String, String> domainMap) { this.domainMap = domainMap; } @Override public String toString() { String result = name + " | "; for (String key : domainMap.keySet()) { result = result + key + " - " + domainMap.get(key) + " | "; } return result; } public HashMap<String, String> getEmails() throws InterruptedException { HashMap<String, String> result = new HashMap<String, String>(); ArrayList<String> usernames = guessPrefix(name);
// Path: src/main/resources/java/crawler/thread/CrawlCompanyThread.java // public class CrawlCompanyThread implements Runnable{ // private Thread t; // private String threadName; // private ArrayList<String> usernames; // private String company; // private String domain; // private HashMap<String, String> results; // private EmailVerifyService ev; // // public CrawlCompanyThread(String name, ArrayList<String> usernames, String company, String domain, HashMap<String, String> results, EmailVerifyService ev){ // threadName = name; // this.usernames = usernames; // this.company = company; // this.domain = domain; // this.results = results; // this.ev = ev; // } // @Override // public void run() { // // TODO Auto-generated method stub // for (String username : usernames) { // String email = username + "@" + domain; // if (ev.valid(email, "gmail.com")) { // results.put(email, company); // System.out.println(email); // } else { // // System.out.println(email + "(invalid)"); // } // } // } // public void start () { // System.out.println("Starting " + threadName ); // if (t == null) { // t = new Thread (this, threadName); // t.start (); // } // } // // public void join () throws InterruptedException { // System.out.println("Joining " + threadName ); // if (t != null) { // t.join(); // } // } // } // Path: src/main/resources/java/crawler/service/GenerateAccurateEmailsService.java import java.util.ArrayList; import java.util.HashMap; import crawler.thread.CrawlCompanyThread; } public String getName() { return name; } public void setName(String name) { this.name = name; } public HashMap<String, String> getDomainMap() { return domainMap; } public void setDomainMap(HashMap<String, String> domainMap) { this.domainMap = domainMap; } @Override public String toString() { String result = name + " | "; for (String key : domainMap.keySet()) { result = result + key + " - " + domainMap.get(key) + " | "; } return result; } public HashMap<String, String> getEmails() throws InterruptedException { HashMap<String, String> result = new HashMap<String, String>(); ArrayList<String> usernames = guessPrefix(name);
ArrayList<CrawlCompanyThread> threadlist = new ArrayList<CrawlCompanyThread>();
JianyangZhang/Contact-Crawler
src/main/resources/java/crawler/thread/CrawlCompanyThread.java
// Path: src/main/resources/java/crawler/service/EmailVerifyService.java // public class EmailVerifyService { // // // /** // * verify the email address whether is exist // * // * @param toMail: // * the email need to be verified // * @param domain: // * the domain send the request(can be anyone) // * @return whether the email is available // */ // public boolean valid(String toMail, String domain) { // if (StringUtils.isBlank(toMail) || StringUtils.isBlank(domain)) { // return false; // } // if (!StringUtils.contains(toMail, '@')) { // return false; // } // if (StringUtils.contains(toMail, ' ')) { // return false; // } // String host = toMail.substring(toMail.indexOf('@') + 1); // if (host.equals(domain)) { // return false; // } // Socket socket = new Socket(); // try { // // find the mx records // Record[] mxRecords = new Lookup(host, Type.MX).run(); // if (ArrayUtils.isEmpty(mxRecords)) { // return false; // } // // the email server address // String mxHost = ((MXRecord) mxRecords[0]).getTarget().toString(); // if (mxRecords.length > 1) { // sort by priority // List<Record> arrRecords = new ArrayList<Record>(); // Collections.addAll(arrRecords, mxRecords); // Collections.sort(arrRecords, new Comparator<Record>() { // // public int compare(Record o1, Record o2) { // return new CompareToBuilder() // .append(((MXRecord) o1).getPriority(), ((MXRecord) o2).getPriority()).toComparison(); // } // // }); // mxHost = ((MXRecord) arrRecords.get(0)).getTarget().toString(); // } // // start smtp // socket.setReuseAddress(true); // socket.connect(new InetSocketAddress(mxHost, 25)); // //System.out.println("Socket port "+socket.getLocalPort()); // BufferedReader bufferedReader = new BufferedReader( // new InputStreamReader(new BufferedInputStream(socket.getInputStream()))); // BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); // // the overtime(ms) // long timeout = 6000; // // the sleep time // int sleepSect = 50; // // // connect // if (getResponseCode(timeout, sleepSect, bufferedReader) != 220) { // socket.close(); // return false; // } // // // handshake // bufferedWriter.write("HELO " + domain + "\r\n"); // bufferedWriter.flush(); // if (getResponseCode(timeout, sleepSect, bufferedReader) != 250) { // socket.close(); // return false; // } // // id // bufferedWriter.write("MAIL FROM: <check@" + domain + ">\r\n"); // bufferedWriter.flush(); // if (getResponseCode(timeout, sleepSect, bufferedReader) != 250) { // socket.close(); // return false; // } // // verify // bufferedWriter.write("RCPT TO: <" + toMail + ">\r\n"); // bufferedWriter.flush(); // if (getResponseCode(timeout, sleepSect, bufferedReader) != 250) { // socket.close(); // return false; // } // // disconnect // bufferedWriter.write("QUIT\r\n"); // bufferedWriter.flush(); // socket.close(); // return true; // } catch (NumberFormatException e) { // } catch (TextParseException e) { // } catch (IOException e) { // //System.out.println("too many ports"); // //e.printStackTrace(); // } catch (InterruptedException e) { // } // // try { // socket.close(); // } catch (IOException e) { // } // //System.out.println("Other issue."); // return false; // } // // private int getResponseCode(long timeout, int sleepSect, BufferedReader bufferedReader) // throws InterruptedException, NumberFormatException, IOException { // int code = 0; // for (long i = sleepSect; i < timeout; i += sleepSect) { // Thread.sleep(sleepSect); // if (bufferedReader.ready()) { // String outline = bufferedReader.readLine(); // // FIXME read // while (bufferedReader.ready()) // /* System.out.println( */bufferedReader.readLine()/* ) */; // /* System.out.println(outline); */ // code = Integer.parseInt(outline.substring(0, 3)); // break; // } // } // return code; // } // }
import java.util.ArrayList; import java.util.HashMap; import crawler.service.EmailVerifyService;
package crawler.thread; public class CrawlCompanyThread implements Runnable{ private Thread t; private String threadName; private ArrayList<String> usernames; private String company; private String domain; private HashMap<String, String> results;
// Path: src/main/resources/java/crawler/service/EmailVerifyService.java // public class EmailVerifyService { // // // /** // * verify the email address whether is exist // * // * @param toMail: // * the email need to be verified // * @param domain: // * the domain send the request(can be anyone) // * @return whether the email is available // */ // public boolean valid(String toMail, String domain) { // if (StringUtils.isBlank(toMail) || StringUtils.isBlank(domain)) { // return false; // } // if (!StringUtils.contains(toMail, '@')) { // return false; // } // if (StringUtils.contains(toMail, ' ')) { // return false; // } // String host = toMail.substring(toMail.indexOf('@') + 1); // if (host.equals(domain)) { // return false; // } // Socket socket = new Socket(); // try { // // find the mx records // Record[] mxRecords = new Lookup(host, Type.MX).run(); // if (ArrayUtils.isEmpty(mxRecords)) { // return false; // } // // the email server address // String mxHost = ((MXRecord) mxRecords[0]).getTarget().toString(); // if (mxRecords.length > 1) { // sort by priority // List<Record> arrRecords = new ArrayList<Record>(); // Collections.addAll(arrRecords, mxRecords); // Collections.sort(arrRecords, new Comparator<Record>() { // // public int compare(Record o1, Record o2) { // return new CompareToBuilder() // .append(((MXRecord) o1).getPriority(), ((MXRecord) o2).getPriority()).toComparison(); // } // // }); // mxHost = ((MXRecord) arrRecords.get(0)).getTarget().toString(); // } // // start smtp // socket.setReuseAddress(true); // socket.connect(new InetSocketAddress(mxHost, 25)); // //System.out.println("Socket port "+socket.getLocalPort()); // BufferedReader bufferedReader = new BufferedReader( // new InputStreamReader(new BufferedInputStream(socket.getInputStream()))); // BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); // // the overtime(ms) // long timeout = 6000; // // the sleep time // int sleepSect = 50; // // // connect // if (getResponseCode(timeout, sleepSect, bufferedReader) != 220) { // socket.close(); // return false; // } // // // handshake // bufferedWriter.write("HELO " + domain + "\r\n"); // bufferedWriter.flush(); // if (getResponseCode(timeout, sleepSect, bufferedReader) != 250) { // socket.close(); // return false; // } // // id // bufferedWriter.write("MAIL FROM: <check@" + domain + ">\r\n"); // bufferedWriter.flush(); // if (getResponseCode(timeout, sleepSect, bufferedReader) != 250) { // socket.close(); // return false; // } // // verify // bufferedWriter.write("RCPT TO: <" + toMail + ">\r\n"); // bufferedWriter.flush(); // if (getResponseCode(timeout, sleepSect, bufferedReader) != 250) { // socket.close(); // return false; // } // // disconnect // bufferedWriter.write("QUIT\r\n"); // bufferedWriter.flush(); // socket.close(); // return true; // } catch (NumberFormatException e) { // } catch (TextParseException e) { // } catch (IOException e) { // //System.out.println("too many ports"); // //e.printStackTrace(); // } catch (InterruptedException e) { // } // // try { // socket.close(); // } catch (IOException e) { // } // //System.out.println("Other issue."); // return false; // } // // private int getResponseCode(long timeout, int sleepSect, BufferedReader bufferedReader) // throws InterruptedException, NumberFormatException, IOException { // int code = 0; // for (long i = sleepSect; i < timeout; i += sleepSect) { // Thread.sleep(sleepSect); // if (bufferedReader.ready()) { // String outline = bufferedReader.readLine(); // // FIXME read // while (bufferedReader.ready()) // /* System.out.println( */bufferedReader.readLine()/* ) */; // /* System.out.println(outline); */ // code = Integer.parseInt(outline.substring(0, 3)); // break; // } // } // return code; // } // } // Path: src/main/resources/java/crawler/thread/CrawlCompanyThread.java import java.util.ArrayList; import java.util.HashMap; import crawler.service.EmailVerifyService; package crawler.thread; public class CrawlCompanyThread implements Runnable{ private Thread t; private String threadName; private ArrayList<String> usernames; private String company; private String domain; private HashMap<String, String> results;
private EmailVerifyService ev;
JianyangZhang/Contact-Crawler
src/main/resources/java/crawler/DAO/MySQLConnector.java
// Path: src/main/resources/java/crawler/EmailCrawlerConfig.java // public class EmailCrawlerConfig { // private static final EmailCrawlerConfig CONFIG = new EmailCrawlerConfig(); // private EmailCrawlerConfig() {}; // public static EmailCrawlerConfig getConfig() { // return CONFIG; // } // // public static int readInt(String propName) { // Properties prop = new Properties(); // InputStream input = null; // try { // input = new FileInputStream("config.properties"); // prop.load(input); // //System.out.println("config: " + propName + ": " + prop.getProperty(propName)); // return Integer.parseInt(prop.getProperty(propName)); // } catch (IOException ex) { // ex.printStackTrace(); // } finally { // if (input != null) { // try { // input.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // return -1; // } // // public static String readString(String propName) { // Properties prop = new Properties(); // InputStream input = null; // try { // input = new FileInputStream("config.properties"); // prop.load(input); // //System.out.println("config: " + propName + ": " + prop.getProperty(propName)); // return prop.getProperty(propName); // } catch (IOException ex) { // ex.printStackTrace(); // } finally { // if (input != null) { // try { // input.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // return ""; // } // }
import java.sql.*; import java.text.SimpleDateFormat; import crawler.EmailCrawlerConfig;
package crawler.DAO; /** * Connect to MySQL database and execute queries. **/ public class MySQLConnector { public static Connection createConnection(String schema, String username, String password) { try {
// Path: src/main/resources/java/crawler/EmailCrawlerConfig.java // public class EmailCrawlerConfig { // private static final EmailCrawlerConfig CONFIG = new EmailCrawlerConfig(); // private EmailCrawlerConfig() {}; // public static EmailCrawlerConfig getConfig() { // return CONFIG; // } // // public static int readInt(String propName) { // Properties prop = new Properties(); // InputStream input = null; // try { // input = new FileInputStream("config.properties"); // prop.load(input); // //System.out.println("config: " + propName + ": " + prop.getProperty(propName)); // return Integer.parseInt(prop.getProperty(propName)); // } catch (IOException ex) { // ex.printStackTrace(); // } finally { // if (input != null) { // try { // input.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // return -1; // } // // public static String readString(String propName) { // Properties prop = new Properties(); // InputStream input = null; // try { // input = new FileInputStream("config.properties"); // prop.load(input); // //System.out.println("config: " + propName + ": " + prop.getProperty(propName)); // return prop.getProperty(propName); // } catch (IOException ex) { // ex.printStackTrace(); // } finally { // if (input != null) { // try { // input.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // return ""; // } // } // Path: src/main/resources/java/crawler/DAO/MySQLConnector.java import java.sql.*; import java.text.SimpleDateFormat; import crawler.EmailCrawlerConfig; package crawler.DAO; /** * Connect to MySQL database and execute queries. **/ public class MySQLConnector { public static Connection createConnection(String schema, String username, String password) { try {
Class.forName(EmailCrawlerConfig.getConfig().readString("db-driver"));
JianyangZhang/Contact-Crawler
src/main/resources/java/crawler/DAO/CompanyDAO.java
// Path: src/main/resources/java/crawler/EmailCrawlerConfig.java // public class EmailCrawlerConfig { // private static final EmailCrawlerConfig CONFIG = new EmailCrawlerConfig(); // private EmailCrawlerConfig() {}; // public static EmailCrawlerConfig getConfig() { // return CONFIG; // } // // public static int readInt(String propName) { // Properties prop = new Properties(); // InputStream input = null; // try { // input = new FileInputStream("config.properties"); // prop.load(input); // //System.out.println("config: " + propName + ": " + prop.getProperty(propName)); // return Integer.parseInt(prop.getProperty(propName)); // } catch (IOException ex) { // ex.printStackTrace(); // } finally { // if (input != null) { // try { // input.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // return -1; // } // // public static String readString(String propName) { // Properties prop = new Properties(); // InputStream input = null; // try { // input = new FileInputStream("config.properties"); // prop.load(input); // //System.out.println("config: " + propName + ": " + prop.getProperty(propName)); // return prop.getProperty(propName); // } catch (IOException ex) { // ex.printStackTrace(); // } finally { // if (input != null) { // try { // input.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // return ""; // } // }
import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import crawler.EmailCrawlerConfig;
package crawler.DAO; public class CompanyDAO { private static Connection connection = MySQLConnector.createConnection("EmailCrawlerDB",
// Path: src/main/resources/java/crawler/EmailCrawlerConfig.java // public class EmailCrawlerConfig { // private static final EmailCrawlerConfig CONFIG = new EmailCrawlerConfig(); // private EmailCrawlerConfig() {}; // public static EmailCrawlerConfig getConfig() { // return CONFIG; // } // // public static int readInt(String propName) { // Properties prop = new Properties(); // InputStream input = null; // try { // input = new FileInputStream("config.properties"); // prop.load(input); // //System.out.println("config: " + propName + ": " + prop.getProperty(propName)); // return Integer.parseInt(prop.getProperty(propName)); // } catch (IOException ex) { // ex.printStackTrace(); // } finally { // if (input != null) { // try { // input.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // return -1; // } // // public static String readString(String propName) { // Properties prop = new Properties(); // InputStream input = null; // try { // input = new FileInputStream("config.properties"); // prop.load(input); // //System.out.println("config: " + propName + ": " + prop.getProperty(propName)); // return prop.getProperty(propName); // } catch (IOException ex) { // ex.printStackTrace(); // } finally { // if (input != null) { // try { // input.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // return ""; // } // } // Path: src/main/resources/java/crawler/DAO/CompanyDAO.java import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import crawler.EmailCrawlerConfig; package crawler.DAO; public class CompanyDAO { private static Connection connection = MySQLConnector.createConnection("EmailCrawlerDB",
EmailCrawlerConfig.getConfig().readString("db-username"),
JianyangZhang/Contact-Crawler
src/main/resources/java/crawler/service/DriveBrowserService.java
// Path: src/main/resources/java/crawler/EmailCrawlerConfig.java // public class EmailCrawlerConfig { // private static final EmailCrawlerConfig CONFIG = new EmailCrawlerConfig(); // private EmailCrawlerConfig() {}; // public static EmailCrawlerConfig getConfig() { // return CONFIG; // } // // public static int readInt(String propName) { // Properties prop = new Properties(); // InputStream input = null; // try { // input = new FileInputStream("config.properties"); // prop.load(input); // //System.out.println("config: " + propName + ": " + prop.getProperty(propName)); // return Integer.parseInt(prop.getProperty(propName)); // } catch (IOException ex) { // ex.printStackTrace(); // } finally { // if (input != null) { // try { // input.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // return -1; // } // // public static String readString(String propName) { // Properties prop = new Properties(); // InputStream input = null; // try { // input = new FileInputStream("config.properties"); // prop.load(input); // //System.out.println("config: " + propName + ": " + prop.getProperty(propName)); // return prop.getProperty(propName); // } catch (IOException ex) { // ex.printStackTrace(); // } finally { // if (input != null) { // try { // input.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // return ""; // } // }
import java.awt.AWTException; import java.awt.Robot; import java.awt.event.KeyEvent; import java.io.File; import java.io.IOException; import java.net.SocketTimeoutException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLDecoder; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import org.jsoup.Jsoup; import org.jsoup.select.Elements; import org.openqa.selenium.net.UrlChecker; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.openqa.selenium.phantomjs.PhantomJSDriver; import org.openqa.selenium.phantomjs.PhantomJSDriverService; import org.openqa.selenium.remote.DesiredCapabilities; import com.gargoylesoftware.htmlunit.BrowserVersion; import crawler.EmailCrawlerConfig;
package crawler.service; public class DriveBrowserService { protected static WebDriver dr; protected int screen_height; DriveBrowserService(boolean hasGUI) { if (hasGUI) {
// Path: src/main/resources/java/crawler/EmailCrawlerConfig.java // public class EmailCrawlerConfig { // private static final EmailCrawlerConfig CONFIG = new EmailCrawlerConfig(); // private EmailCrawlerConfig() {}; // public static EmailCrawlerConfig getConfig() { // return CONFIG; // } // // public static int readInt(String propName) { // Properties prop = new Properties(); // InputStream input = null; // try { // input = new FileInputStream("config.properties"); // prop.load(input); // //System.out.println("config: " + propName + ": " + prop.getProperty(propName)); // return Integer.parseInt(prop.getProperty(propName)); // } catch (IOException ex) { // ex.printStackTrace(); // } finally { // if (input != null) { // try { // input.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // return -1; // } // // public static String readString(String propName) { // Properties prop = new Properties(); // InputStream input = null; // try { // input = new FileInputStream("config.properties"); // prop.load(input); // //System.out.println("config: " + propName + ": " + prop.getProperty(propName)); // return prop.getProperty(propName); // } catch (IOException ex) { // ex.printStackTrace(); // } finally { // if (input != null) { // try { // input.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // return ""; // } // } // Path: src/main/resources/java/crawler/service/DriveBrowserService.java import java.awt.AWTException; import java.awt.Robot; import java.awt.event.KeyEvent; import java.io.File; import java.io.IOException; import java.net.SocketTimeoutException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLDecoder; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import org.jsoup.Jsoup; import org.jsoup.select.Elements; import org.openqa.selenium.net.UrlChecker; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.openqa.selenium.phantomjs.PhantomJSDriver; import org.openqa.selenium.phantomjs.PhantomJSDriverService; import org.openqa.selenium.remote.DesiredCapabilities; import com.gargoylesoftware.htmlunit.BrowserVersion; import crawler.EmailCrawlerConfig; package crawler.service; public class DriveBrowserService { protected static WebDriver dr; protected int screen_height; DriveBrowserService(boolean hasGUI) { if (hasGUI) {
System.setProperty("webdriver.chrome.driver", EmailCrawlerConfig.getConfig().readString("chrome-driver-path"));
JianyangZhang/Contact-Crawler
src/main/resources/java/crawler/service/PollSearchQueryService.java
// Path: src/main/resources/java/crawler/DAO/SearchQueryDAO.java // public class SearchQueryDAO { // // private static Connection connection = MySQLConnector.createConnection("EmailCrawlerDB", EmailCrawlerConfig.getConfig().readString("db-username"), EmailCrawlerConfig.getConfig().readString("db-password")); // // public static void reconnect() throws SQLException { // connection.close(); // connection = MySQLConnector.createConnection("EmailCrawlerDB", EmailCrawlerConfig.getConfig().readString("db-username"), EmailCrawlerConfig.getConfig().readString("db-password")); // } // // public static ResultSet getPendingQuery() { // return MySQLConnector.executeQuery(connection, "SELECT * FROM Search WHERE search_progress = 'pending' AND has_deleted = 0 ORDER BY search_id LIMIT 1;", false); // } // // public static void updateToProcessing(String search_id) { // MySQLConnector.executeQuery(connection, "UPDATE Search SET search_progress = 'processing' WHERE search_id = '" + search_id + "';", true); // } // // public static void updateToComplete(String search_id) { // MySQLConnector.executeQuery(connection, "UPDATE Search SET search_progress = 'completed' WHERE search_id = '" + search_id + "';", true); // } // // public static void updateToFailed(String search_id) { // MySQLConnector.executeQuery(connection, "UPDATE Search SET search_progress = 'completed' WHERE search_id = '" + search_id + "';", true); // } // public static ResultSet hasDeleted(String search_id) { // return MySQLConnector.executeQuery(connection, "SELECT has_deleted FROM Search WHERE search_id = '" + search_id + "';", false); // } // } // // Path: src/main/resources/java/crawler/model/CrawlerQuery.java // @Entity // public class CrawlerQuery { // @Id // private String searchID; // private String keyword; // private int count; // private String location; // private String linkedinID; // private String internalCompanyID; // private String lkedin_email; // private String lkedin_passoword; // // // public String getSearchID() { // return searchID; // } // public void setSearchID(String searchID) { // this.searchID = searchID; // } // public String getKeyword() { // return keyword; // } // public void setKeyword(String keyword) { // this.keyword = keyword; // } // public int getCount() { // return count; // } // public void setCount(int count) { // this.count = count; // } // public String getLinkedinID() { // return linkedinID; // } // public void setLinkedinID(String linkedinID) { // this.linkedinID = linkedinID; // } // public String getInternalCompanyID() { // return internalCompanyID; // } // public void setInternalCompanyID(String internalCompanyID) { // this.internalCompanyID = internalCompanyID; // } // @Override // public String toString() { // return "CrawlerQuery [searchID=" + searchID + ", keyword=" + keyword + ", count=" + count + ", linkedinID=" // + linkedinID + ", internalCompanyID=" + internalCompanyID + "]"; // } // public String getLocation() { // return location; // } // public void setLocation(String location) { // this.location = location; // } // public String getLkedin_email() { // return lkedin_email; // } // public void setLkedin_email(String lkedin_email) { // this.lkedin_email = lkedin_email; // } // public String getLkedin_passoword() { // return lkedin_passoword; // } // public void setLkedin_passoword(String lkedin_passoword) { // this.lkedin_passoword = lkedin_passoword; // } // }
import java.sql.ResultSet; import java.sql.SQLException; import java.util.TimerTask; import crawler.DAO.SearchQueryDAO; import crawler.model.CrawlerQuery;
package crawler.service; public class PollSearchQueryService extends TimerTask { private static boolean CRAWLER_IS_FREE = true; static final int NO_RESULT = 0; static final int COMPLETED = 1; public static final int FAILED = 2; // poll and crawl one pending query from database @Override public void run() { //System.out.println("polling search query from database..."); if (CRAWLER_IS_FREE) { CRAWLER_IS_FREE = false; MyCallback myCallback = new MyCallback();
// Path: src/main/resources/java/crawler/DAO/SearchQueryDAO.java // public class SearchQueryDAO { // // private static Connection connection = MySQLConnector.createConnection("EmailCrawlerDB", EmailCrawlerConfig.getConfig().readString("db-username"), EmailCrawlerConfig.getConfig().readString("db-password")); // // public static void reconnect() throws SQLException { // connection.close(); // connection = MySQLConnector.createConnection("EmailCrawlerDB", EmailCrawlerConfig.getConfig().readString("db-username"), EmailCrawlerConfig.getConfig().readString("db-password")); // } // // public static ResultSet getPendingQuery() { // return MySQLConnector.executeQuery(connection, "SELECT * FROM Search WHERE search_progress = 'pending' AND has_deleted = 0 ORDER BY search_id LIMIT 1;", false); // } // // public static void updateToProcessing(String search_id) { // MySQLConnector.executeQuery(connection, "UPDATE Search SET search_progress = 'processing' WHERE search_id = '" + search_id + "';", true); // } // // public static void updateToComplete(String search_id) { // MySQLConnector.executeQuery(connection, "UPDATE Search SET search_progress = 'completed' WHERE search_id = '" + search_id + "';", true); // } // // public static void updateToFailed(String search_id) { // MySQLConnector.executeQuery(connection, "UPDATE Search SET search_progress = 'completed' WHERE search_id = '" + search_id + "';", true); // } // public static ResultSet hasDeleted(String search_id) { // return MySQLConnector.executeQuery(connection, "SELECT has_deleted FROM Search WHERE search_id = '" + search_id + "';", false); // } // } // // Path: src/main/resources/java/crawler/model/CrawlerQuery.java // @Entity // public class CrawlerQuery { // @Id // private String searchID; // private String keyword; // private int count; // private String location; // private String linkedinID; // private String internalCompanyID; // private String lkedin_email; // private String lkedin_passoword; // // // public String getSearchID() { // return searchID; // } // public void setSearchID(String searchID) { // this.searchID = searchID; // } // public String getKeyword() { // return keyword; // } // public void setKeyword(String keyword) { // this.keyword = keyword; // } // public int getCount() { // return count; // } // public void setCount(int count) { // this.count = count; // } // public String getLinkedinID() { // return linkedinID; // } // public void setLinkedinID(String linkedinID) { // this.linkedinID = linkedinID; // } // public String getInternalCompanyID() { // return internalCompanyID; // } // public void setInternalCompanyID(String internalCompanyID) { // this.internalCompanyID = internalCompanyID; // } // @Override // public String toString() { // return "CrawlerQuery [searchID=" + searchID + ", keyword=" + keyword + ", count=" + count + ", linkedinID=" // + linkedinID + ", internalCompanyID=" + internalCompanyID + "]"; // } // public String getLocation() { // return location; // } // public void setLocation(String location) { // this.location = location; // } // public String getLkedin_email() { // return lkedin_email; // } // public void setLkedin_email(String lkedin_email) { // this.lkedin_email = lkedin_email; // } // public String getLkedin_passoword() { // return lkedin_passoword; // } // public void setLkedin_passoword(String lkedin_passoword) { // this.lkedin_passoword = lkedin_passoword; // } // } // Path: src/main/resources/java/crawler/service/PollSearchQueryService.java import java.sql.ResultSet; import java.sql.SQLException; import java.util.TimerTask; import crawler.DAO.SearchQueryDAO; import crawler.model.CrawlerQuery; package crawler.service; public class PollSearchQueryService extends TimerTask { private static boolean CRAWLER_IS_FREE = true; static final int NO_RESULT = 0; static final int COMPLETED = 1; public static final int FAILED = 2; // poll and crawl one pending query from database @Override public void run() { //System.out.println("polling search query from database..."); if (CRAWLER_IS_FREE) { CRAWLER_IS_FREE = false; MyCallback myCallback = new MyCallback();
ResultSet resultSet = SearchQueryDAO.getPendingQuery();
JianyangZhang/Contact-Crawler
src/main/resources/java/crawler/service/PollSearchQueryService.java
// Path: src/main/resources/java/crawler/DAO/SearchQueryDAO.java // public class SearchQueryDAO { // // private static Connection connection = MySQLConnector.createConnection("EmailCrawlerDB", EmailCrawlerConfig.getConfig().readString("db-username"), EmailCrawlerConfig.getConfig().readString("db-password")); // // public static void reconnect() throws SQLException { // connection.close(); // connection = MySQLConnector.createConnection("EmailCrawlerDB", EmailCrawlerConfig.getConfig().readString("db-username"), EmailCrawlerConfig.getConfig().readString("db-password")); // } // // public static ResultSet getPendingQuery() { // return MySQLConnector.executeQuery(connection, "SELECT * FROM Search WHERE search_progress = 'pending' AND has_deleted = 0 ORDER BY search_id LIMIT 1;", false); // } // // public static void updateToProcessing(String search_id) { // MySQLConnector.executeQuery(connection, "UPDATE Search SET search_progress = 'processing' WHERE search_id = '" + search_id + "';", true); // } // // public static void updateToComplete(String search_id) { // MySQLConnector.executeQuery(connection, "UPDATE Search SET search_progress = 'completed' WHERE search_id = '" + search_id + "';", true); // } // // public static void updateToFailed(String search_id) { // MySQLConnector.executeQuery(connection, "UPDATE Search SET search_progress = 'completed' WHERE search_id = '" + search_id + "';", true); // } // public static ResultSet hasDeleted(String search_id) { // return MySQLConnector.executeQuery(connection, "SELECT has_deleted FROM Search WHERE search_id = '" + search_id + "';", false); // } // } // // Path: src/main/resources/java/crawler/model/CrawlerQuery.java // @Entity // public class CrawlerQuery { // @Id // private String searchID; // private String keyword; // private int count; // private String location; // private String linkedinID; // private String internalCompanyID; // private String lkedin_email; // private String lkedin_passoword; // // // public String getSearchID() { // return searchID; // } // public void setSearchID(String searchID) { // this.searchID = searchID; // } // public String getKeyword() { // return keyword; // } // public void setKeyword(String keyword) { // this.keyword = keyword; // } // public int getCount() { // return count; // } // public void setCount(int count) { // this.count = count; // } // public String getLinkedinID() { // return linkedinID; // } // public void setLinkedinID(String linkedinID) { // this.linkedinID = linkedinID; // } // public String getInternalCompanyID() { // return internalCompanyID; // } // public void setInternalCompanyID(String internalCompanyID) { // this.internalCompanyID = internalCompanyID; // } // @Override // public String toString() { // return "CrawlerQuery [searchID=" + searchID + ", keyword=" + keyword + ", count=" + count + ", linkedinID=" // + linkedinID + ", internalCompanyID=" + internalCompanyID + "]"; // } // public String getLocation() { // return location; // } // public void setLocation(String location) { // this.location = location; // } // public String getLkedin_email() { // return lkedin_email; // } // public void setLkedin_email(String lkedin_email) { // this.lkedin_email = lkedin_email; // } // public String getLkedin_passoword() { // return lkedin_passoword; // } // public void setLkedin_passoword(String lkedin_passoword) { // this.lkedin_passoword = lkedin_passoword; // } // }
import java.sql.ResultSet; import java.sql.SQLException; import java.util.TimerTask; import crawler.DAO.SearchQueryDAO; import crawler.model.CrawlerQuery;
package crawler.service; public class PollSearchQueryService extends TimerTask { private static boolean CRAWLER_IS_FREE = true; static final int NO_RESULT = 0; static final int COMPLETED = 1; public static final int FAILED = 2; // poll and crawl one pending query from database @Override public void run() { //System.out.println("polling search query from database..."); if (CRAWLER_IS_FREE) { CRAWLER_IS_FREE = false; MyCallback myCallback = new MyCallback(); ResultSet resultSet = SearchQueryDAO.getPendingQuery(); // MySQLConnector.printResultSet(resultSet); try { if (resultSet.next()) { String search_id = resultSet.getString(1); SearchQueryDAO.updateToProcessing(search_id);
// Path: src/main/resources/java/crawler/DAO/SearchQueryDAO.java // public class SearchQueryDAO { // // private static Connection connection = MySQLConnector.createConnection("EmailCrawlerDB", EmailCrawlerConfig.getConfig().readString("db-username"), EmailCrawlerConfig.getConfig().readString("db-password")); // // public static void reconnect() throws SQLException { // connection.close(); // connection = MySQLConnector.createConnection("EmailCrawlerDB", EmailCrawlerConfig.getConfig().readString("db-username"), EmailCrawlerConfig.getConfig().readString("db-password")); // } // // public static ResultSet getPendingQuery() { // return MySQLConnector.executeQuery(connection, "SELECT * FROM Search WHERE search_progress = 'pending' AND has_deleted = 0 ORDER BY search_id LIMIT 1;", false); // } // // public static void updateToProcessing(String search_id) { // MySQLConnector.executeQuery(connection, "UPDATE Search SET search_progress = 'processing' WHERE search_id = '" + search_id + "';", true); // } // // public static void updateToComplete(String search_id) { // MySQLConnector.executeQuery(connection, "UPDATE Search SET search_progress = 'completed' WHERE search_id = '" + search_id + "';", true); // } // // public static void updateToFailed(String search_id) { // MySQLConnector.executeQuery(connection, "UPDATE Search SET search_progress = 'completed' WHERE search_id = '" + search_id + "';", true); // } // public static ResultSet hasDeleted(String search_id) { // return MySQLConnector.executeQuery(connection, "SELECT has_deleted FROM Search WHERE search_id = '" + search_id + "';", false); // } // } // // Path: src/main/resources/java/crawler/model/CrawlerQuery.java // @Entity // public class CrawlerQuery { // @Id // private String searchID; // private String keyword; // private int count; // private String location; // private String linkedinID; // private String internalCompanyID; // private String lkedin_email; // private String lkedin_passoword; // // // public String getSearchID() { // return searchID; // } // public void setSearchID(String searchID) { // this.searchID = searchID; // } // public String getKeyword() { // return keyword; // } // public void setKeyword(String keyword) { // this.keyword = keyword; // } // public int getCount() { // return count; // } // public void setCount(int count) { // this.count = count; // } // public String getLinkedinID() { // return linkedinID; // } // public void setLinkedinID(String linkedinID) { // this.linkedinID = linkedinID; // } // public String getInternalCompanyID() { // return internalCompanyID; // } // public void setInternalCompanyID(String internalCompanyID) { // this.internalCompanyID = internalCompanyID; // } // @Override // public String toString() { // return "CrawlerQuery [searchID=" + searchID + ", keyword=" + keyword + ", count=" + count + ", linkedinID=" // + linkedinID + ", internalCompanyID=" + internalCompanyID + "]"; // } // public String getLocation() { // return location; // } // public void setLocation(String location) { // this.location = location; // } // public String getLkedin_email() { // return lkedin_email; // } // public void setLkedin_email(String lkedin_email) { // this.lkedin_email = lkedin_email; // } // public String getLkedin_passoword() { // return lkedin_passoword; // } // public void setLkedin_passoword(String lkedin_passoword) { // this.lkedin_passoword = lkedin_passoword; // } // } // Path: src/main/resources/java/crawler/service/PollSearchQueryService.java import java.sql.ResultSet; import java.sql.SQLException; import java.util.TimerTask; import crawler.DAO.SearchQueryDAO; import crawler.model.CrawlerQuery; package crawler.service; public class PollSearchQueryService extends TimerTask { private static boolean CRAWLER_IS_FREE = true; static final int NO_RESULT = 0; static final int COMPLETED = 1; public static final int FAILED = 2; // poll and crawl one pending query from database @Override public void run() { //System.out.println("polling search query from database..."); if (CRAWLER_IS_FREE) { CRAWLER_IS_FREE = false; MyCallback myCallback = new MyCallback(); ResultSet resultSet = SearchQueryDAO.getPendingQuery(); // MySQLConnector.printResultSet(resultSet); try { if (resultSet.next()) { String search_id = resultSet.getString(1); SearchQueryDAO.updateToProcessing(search_id);
CrawlerQuery query = new CrawlerQuery();
loehndorf/scengen
src/main/java/scengen/paper/MakeGraphs.java
// Path: src/main/java/scengen/distribution/DISTRIBUTION.java // public enum DISTRIBUTION { // Lognormal, Normal, Student, Uniform // } // // Path: src/main/java/scengen/methods/METHOD.java // public enum METHOD { // MonteCarlo, QuasiMonteCarlo, MomentMatching, QuantizationLearning, QuantizationGrids, Scenred2, VoronoiCellSampling // } // // Path: src/main/java/scengen/tools/Xorshift.java // public class Xorshift extends Random { // private static final long serialVersionUID = 1L; // // /** 2<sup>-53</sup>. */ // private static final double NORM_53 = 1. / ( 1L << 53 ); // /** 2<sup>-24</sup>. */ // private static final double NORM_24 = 1. / ( 1L << 24 ); // // /** The internal state of the algorithm. */ // private long[] s; // private int p; // // /** Creates a new generator seeded using {@link #randomSeed()}. */ // public Xorshift() { // this( randomSeed() ); // } // // /** Creates a new generator using a given seed. // * // * @param seed a nonzero seed for the generator (if zero, the generator will be seeded with -1). // */ // public Xorshift( final long seed ) { // super( seed ); // } // // @Override // protected int next( int bits ) { // return (int)( nextLong() >>> 64 - bits ); // } // // @Override // public synchronized long nextLong() { // long s0 = s[ p ]; // long s1 = s[ p = ( p + 1 ) & 15 ]; // s1 ^= s1 << 1; // return 1181783497276652981L * ( s[ p ] = s1 ^ s0 ^ ( s1 >>> 13 ) ^ ( s0 >>> 7 ) ); // } // // @Override // public int nextInt() { // return (int)nextLong(); // } // // @Override // public int nextInt( final int n ) { // return (int)nextLong( n ); // } // // /** Returns a pseudorandom uniformly distributed {@code long} value // * between 0 (inclusive) and the specified value (exclusive), drawn from // * this random number generator's sequence. The algorithm used to generate // * the value guarantees that the result is uniform, provided that the // * sequence of 64-bit values produced by this generator is. // * // * @param n the positive bound on the random number to be returned. // * @return the next pseudorandom {@code long} value between {@code 0} (inclusive) and {@code n} (exclusive). // */ // public long nextLong( final long n ) { // if ( n <= 0 ) throw new IllegalArgumentException(); // // No special provision for n power of two: all our bits are good. // for(;;) { // final long bits = nextLong() >>> 1; // final long value = bits % n; // if ( bits - value + ( n - 1 ) >= 0 ) return value; // } // } // // @Override // public double nextDouble() { // return ( nextLong() >>> 11 ) * NORM_53; // } // // @Override // public float nextFloat() { // return (float)( ( nextLong() >>> 40 ) * NORM_24 ); // } // // @Override // public boolean nextBoolean() { // return ( nextLong() & 1 ) != 0; // } // // @Override // public void nextBytes( final byte[] bytes ) { // int i = bytes.length, n = 0; // while( i != 0 ) { // n = Math.min( i, 8 ); // for ( long bits = nextLong(); n-- != 0; bits >>= 8 ) bytes[ --i ] = (byte)bits; // } // } // // /** Returns a random seed generated by taking a unique increasing long, adding // * {@link System#nanoTime()} and scrambling the result using the finalisation step of Austin // * Appleby's <a href="http://sites.google.com/site/murmurhash/">MurmurHash3</a>. // * // * @return a reasonably good random seed. // */ // private static final AtomicLong seedUniquifier = new AtomicLong(); // public static long randomSeed() { // long seed = seedUniquifier.incrementAndGet() + System.nanoTime(); // // seed ^= seed >>> 33; // seed *= 0xff51afd7ed558ccdL; // seed ^= seed >>> 33; // seed *= 0xc4ceb9fe1a85ec53L; // seed ^= seed >>> 33; // // return seed; // } // // /** Sets the seed of this generator. // * // * @param seed a nonzero seed for the generator (if zero, the generator will be seeded with -1). // */ // @Override // public synchronized void setSeed( final long seed ) { // if ( s == null ) s = new long[ 16 ]; // for( int i = s.length; i-- != 0; ) s[ i ] = seed == 0 ? -1 : seed; // for( int i = s.length * 4; i-- != 0; ) nextLong(); // Warmup. // } // }
import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import scengen.distribution.DISTRIBUTION; import scengen.methods.METHOD; import scengen.tools.Xorshift;
package scengen.paper; public class MakeGraphs { public static void main(String... args) { int numScen = 100;
// Path: src/main/java/scengen/distribution/DISTRIBUTION.java // public enum DISTRIBUTION { // Lognormal, Normal, Student, Uniform // } // // Path: src/main/java/scengen/methods/METHOD.java // public enum METHOD { // MonteCarlo, QuasiMonteCarlo, MomentMatching, QuantizationLearning, QuantizationGrids, Scenred2, VoronoiCellSampling // } // // Path: src/main/java/scengen/tools/Xorshift.java // public class Xorshift extends Random { // private static final long serialVersionUID = 1L; // // /** 2<sup>-53</sup>. */ // private static final double NORM_53 = 1. / ( 1L << 53 ); // /** 2<sup>-24</sup>. */ // private static final double NORM_24 = 1. / ( 1L << 24 ); // // /** The internal state of the algorithm. */ // private long[] s; // private int p; // // /** Creates a new generator seeded using {@link #randomSeed()}. */ // public Xorshift() { // this( randomSeed() ); // } // // /** Creates a new generator using a given seed. // * // * @param seed a nonzero seed for the generator (if zero, the generator will be seeded with -1). // */ // public Xorshift( final long seed ) { // super( seed ); // } // // @Override // protected int next( int bits ) { // return (int)( nextLong() >>> 64 - bits ); // } // // @Override // public synchronized long nextLong() { // long s0 = s[ p ]; // long s1 = s[ p = ( p + 1 ) & 15 ]; // s1 ^= s1 << 1; // return 1181783497276652981L * ( s[ p ] = s1 ^ s0 ^ ( s1 >>> 13 ) ^ ( s0 >>> 7 ) ); // } // // @Override // public int nextInt() { // return (int)nextLong(); // } // // @Override // public int nextInt( final int n ) { // return (int)nextLong( n ); // } // // /** Returns a pseudorandom uniformly distributed {@code long} value // * between 0 (inclusive) and the specified value (exclusive), drawn from // * this random number generator's sequence. The algorithm used to generate // * the value guarantees that the result is uniform, provided that the // * sequence of 64-bit values produced by this generator is. // * // * @param n the positive bound on the random number to be returned. // * @return the next pseudorandom {@code long} value between {@code 0} (inclusive) and {@code n} (exclusive). // */ // public long nextLong( final long n ) { // if ( n <= 0 ) throw new IllegalArgumentException(); // // No special provision for n power of two: all our bits are good. // for(;;) { // final long bits = nextLong() >>> 1; // final long value = bits % n; // if ( bits - value + ( n - 1 ) >= 0 ) return value; // } // } // // @Override // public double nextDouble() { // return ( nextLong() >>> 11 ) * NORM_53; // } // // @Override // public float nextFloat() { // return (float)( ( nextLong() >>> 40 ) * NORM_24 ); // } // // @Override // public boolean nextBoolean() { // return ( nextLong() & 1 ) != 0; // } // // @Override // public void nextBytes( final byte[] bytes ) { // int i = bytes.length, n = 0; // while( i != 0 ) { // n = Math.min( i, 8 ); // for ( long bits = nextLong(); n-- != 0; bits >>= 8 ) bytes[ --i ] = (byte)bits; // } // } // // /** Returns a random seed generated by taking a unique increasing long, adding // * {@link System#nanoTime()} and scrambling the result using the finalisation step of Austin // * Appleby's <a href="http://sites.google.com/site/murmurhash/">MurmurHash3</a>. // * // * @return a reasonably good random seed. // */ // private static final AtomicLong seedUniquifier = new AtomicLong(); // public static long randomSeed() { // long seed = seedUniquifier.incrementAndGet() + System.nanoTime(); // // seed ^= seed >>> 33; // seed *= 0xff51afd7ed558ccdL; // seed ^= seed >>> 33; // seed *= 0xc4ceb9fe1a85ec53L; // seed ^= seed >>> 33; // // return seed; // } // // /** Sets the seed of this generator. // * // * @param seed a nonzero seed for the generator (if zero, the generator will be seeded with -1). // */ // @Override // public synchronized void setSeed( final long seed ) { // if ( s == null ) s = new long[ 16 ]; // for( int i = s.length; i-- != 0; ) s[ i ] = seed == 0 ? -1 : seed; // for( int i = s.length * 4; i-- != 0; ) nextLong(); // Warmup. // } // } // Path: src/main/java/scengen/paper/MakeGraphs.java import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import scengen.distribution.DISTRIBUTION; import scengen.methods.METHOD; import scengen.tools.Xorshift; package scengen.paper; public class MakeGraphs { public static void main(String... args) { int numScen = 100;
Random r = new Xorshift(11);
loehndorf/scengen
src/main/java/scengen/paper/MakeGraphs.java
// Path: src/main/java/scengen/distribution/DISTRIBUTION.java // public enum DISTRIBUTION { // Lognormal, Normal, Student, Uniform // } // // Path: src/main/java/scengen/methods/METHOD.java // public enum METHOD { // MonteCarlo, QuasiMonteCarlo, MomentMatching, QuantizationLearning, QuantizationGrids, Scenred2, VoronoiCellSampling // } // // Path: src/main/java/scengen/tools/Xorshift.java // public class Xorshift extends Random { // private static final long serialVersionUID = 1L; // // /** 2<sup>-53</sup>. */ // private static final double NORM_53 = 1. / ( 1L << 53 ); // /** 2<sup>-24</sup>. */ // private static final double NORM_24 = 1. / ( 1L << 24 ); // // /** The internal state of the algorithm. */ // private long[] s; // private int p; // // /** Creates a new generator seeded using {@link #randomSeed()}. */ // public Xorshift() { // this( randomSeed() ); // } // // /** Creates a new generator using a given seed. // * // * @param seed a nonzero seed for the generator (if zero, the generator will be seeded with -1). // */ // public Xorshift( final long seed ) { // super( seed ); // } // // @Override // protected int next( int bits ) { // return (int)( nextLong() >>> 64 - bits ); // } // // @Override // public synchronized long nextLong() { // long s0 = s[ p ]; // long s1 = s[ p = ( p + 1 ) & 15 ]; // s1 ^= s1 << 1; // return 1181783497276652981L * ( s[ p ] = s1 ^ s0 ^ ( s1 >>> 13 ) ^ ( s0 >>> 7 ) ); // } // // @Override // public int nextInt() { // return (int)nextLong(); // } // // @Override // public int nextInt( final int n ) { // return (int)nextLong( n ); // } // // /** Returns a pseudorandom uniformly distributed {@code long} value // * between 0 (inclusive) and the specified value (exclusive), drawn from // * this random number generator's sequence. The algorithm used to generate // * the value guarantees that the result is uniform, provided that the // * sequence of 64-bit values produced by this generator is. // * // * @param n the positive bound on the random number to be returned. // * @return the next pseudorandom {@code long} value between {@code 0} (inclusive) and {@code n} (exclusive). // */ // public long nextLong( final long n ) { // if ( n <= 0 ) throw new IllegalArgumentException(); // // No special provision for n power of two: all our bits are good. // for(;;) { // final long bits = nextLong() >>> 1; // final long value = bits % n; // if ( bits - value + ( n - 1 ) >= 0 ) return value; // } // } // // @Override // public double nextDouble() { // return ( nextLong() >>> 11 ) * NORM_53; // } // // @Override // public float nextFloat() { // return (float)( ( nextLong() >>> 40 ) * NORM_24 ); // } // // @Override // public boolean nextBoolean() { // return ( nextLong() & 1 ) != 0; // } // // @Override // public void nextBytes( final byte[] bytes ) { // int i = bytes.length, n = 0; // while( i != 0 ) { // n = Math.min( i, 8 ); // for ( long bits = nextLong(); n-- != 0; bits >>= 8 ) bytes[ --i ] = (byte)bits; // } // } // // /** Returns a random seed generated by taking a unique increasing long, adding // * {@link System#nanoTime()} and scrambling the result using the finalisation step of Austin // * Appleby's <a href="http://sites.google.com/site/murmurhash/">MurmurHash3</a>. // * // * @return a reasonably good random seed. // */ // private static final AtomicLong seedUniquifier = new AtomicLong(); // public static long randomSeed() { // long seed = seedUniquifier.incrementAndGet() + System.nanoTime(); // // seed ^= seed >>> 33; // seed *= 0xff51afd7ed558ccdL; // seed ^= seed >>> 33; // seed *= 0xc4ceb9fe1a85ec53L; // seed ^= seed >>> 33; // // return seed; // } // // /** Sets the seed of this generator. // * // * @param seed a nonzero seed for the generator (if zero, the generator will be seeded with -1). // */ // @Override // public synchronized void setSeed( final long seed ) { // if ( s == null ) s = new long[ 16 ]; // for( int i = s.length; i-- != 0; ) s[ i ] = seed == 0 ? -1 : seed; // for( int i = s.length * 4; i-- != 0; ) nextLong(); // Warmup. // } // }
import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import scengen.distribution.DISTRIBUTION; import scengen.methods.METHOD; import scengen.tools.Xorshift;
package scengen.paper; public class MakeGraphs { public static void main(String... args) { int numScen = 100; Random r = new Xorshift(11); List<File> files = new ArrayList<>();
// Path: src/main/java/scengen/distribution/DISTRIBUTION.java // public enum DISTRIBUTION { // Lognormal, Normal, Student, Uniform // } // // Path: src/main/java/scengen/methods/METHOD.java // public enum METHOD { // MonteCarlo, QuasiMonteCarlo, MomentMatching, QuantizationLearning, QuantizationGrids, Scenred2, VoronoiCellSampling // } // // Path: src/main/java/scengen/tools/Xorshift.java // public class Xorshift extends Random { // private static final long serialVersionUID = 1L; // // /** 2<sup>-53</sup>. */ // private static final double NORM_53 = 1. / ( 1L << 53 ); // /** 2<sup>-24</sup>. */ // private static final double NORM_24 = 1. / ( 1L << 24 ); // // /** The internal state of the algorithm. */ // private long[] s; // private int p; // // /** Creates a new generator seeded using {@link #randomSeed()}. */ // public Xorshift() { // this( randomSeed() ); // } // // /** Creates a new generator using a given seed. // * // * @param seed a nonzero seed for the generator (if zero, the generator will be seeded with -1). // */ // public Xorshift( final long seed ) { // super( seed ); // } // // @Override // protected int next( int bits ) { // return (int)( nextLong() >>> 64 - bits ); // } // // @Override // public synchronized long nextLong() { // long s0 = s[ p ]; // long s1 = s[ p = ( p + 1 ) & 15 ]; // s1 ^= s1 << 1; // return 1181783497276652981L * ( s[ p ] = s1 ^ s0 ^ ( s1 >>> 13 ) ^ ( s0 >>> 7 ) ); // } // // @Override // public int nextInt() { // return (int)nextLong(); // } // // @Override // public int nextInt( final int n ) { // return (int)nextLong( n ); // } // // /** Returns a pseudorandom uniformly distributed {@code long} value // * between 0 (inclusive) and the specified value (exclusive), drawn from // * this random number generator's sequence. The algorithm used to generate // * the value guarantees that the result is uniform, provided that the // * sequence of 64-bit values produced by this generator is. // * // * @param n the positive bound on the random number to be returned. // * @return the next pseudorandom {@code long} value between {@code 0} (inclusive) and {@code n} (exclusive). // */ // public long nextLong( final long n ) { // if ( n <= 0 ) throw new IllegalArgumentException(); // // No special provision for n power of two: all our bits are good. // for(;;) { // final long bits = nextLong() >>> 1; // final long value = bits % n; // if ( bits - value + ( n - 1 ) >= 0 ) return value; // } // } // // @Override // public double nextDouble() { // return ( nextLong() >>> 11 ) * NORM_53; // } // // @Override // public float nextFloat() { // return (float)( ( nextLong() >>> 40 ) * NORM_24 ); // } // // @Override // public boolean nextBoolean() { // return ( nextLong() & 1 ) != 0; // } // // @Override // public void nextBytes( final byte[] bytes ) { // int i = bytes.length, n = 0; // while( i != 0 ) { // n = Math.min( i, 8 ); // for ( long bits = nextLong(); n-- != 0; bits >>= 8 ) bytes[ --i ] = (byte)bits; // } // } // // /** Returns a random seed generated by taking a unique increasing long, adding // * {@link System#nanoTime()} and scrambling the result using the finalisation step of Austin // * Appleby's <a href="http://sites.google.com/site/murmurhash/">MurmurHash3</a>. // * // * @return a reasonably good random seed. // */ // private static final AtomicLong seedUniquifier = new AtomicLong(); // public static long randomSeed() { // long seed = seedUniquifier.incrementAndGet() + System.nanoTime(); // // seed ^= seed >>> 33; // seed *= 0xff51afd7ed558ccdL; // seed ^= seed >>> 33; // seed *= 0xc4ceb9fe1a85ec53L; // seed ^= seed >>> 33; // // return seed; // } // // /** Sets the seed of this generator. // * // * @param seed a nonzero seed for the generator (if zero, the generator will be seeded with -1). // */ // @Override // public synchronized void setSeed( final long seed ) { // if ( s == null ) s = new long[ 16 ]; // for( int i = s.length; i-- != 0; ) s[ i ] = seed == 0 ? -1 : seed; // for( int i = s.length * 4; i-- != 0; ) nextLong(); // Warmup. // } // } // Path: src/main/java/scengen/paper/MakeGraphs.java import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import scengen.distribution.DISTRIBUTION; import scengen.methods.METHOD; import scengen.tools.Xorshift; package scengen.paper; public class MakeGraphs { public static void main(String... args) { int numScen = 100; Random r = new Xorshift(11); List<File> files = new ArrayList<>();
files.add(makeScen(8, numScen, DISTRIBUTION.Normal, METHOD.QuantizationLearning, r));
loehndorf/scengen
src/main/java/scengen/paper/MakeGraphs.java
// Path: src/main/java/scengen/distribution/DISTRIBUTION.java // public enum DISTRIBUTION { // Lognormal, Normal, Student, Uniform // } // // Path: src/main/java/scengen/methods/METHOD.java // public enum METHOD { // MonteCarlo, QuasiMonteCarlo, MomentMatching, QuantizationLearning, QuantizationGrids, Scenred2, VoronoiCellSampling // } // // Path: src/main/java/scengen/tools/Xorshift.java // public class Xorshift extends Random { // private static final long serialVersionUID = 1L; // // /** 2<sup>-53</sup>. */ // private static final double NORM_53 = 1. / ( 1L << 53 ); // /** 2<sup>-24</sup>. */ // private static final double NORM_24 = 1. / ( 1L << 24 ); // // /** The internal state of the algorithm. */ // private long[] s; // private int p; // // /** Creates a new generator seeded using {@link #randomSeed()}. */ // public Xorshift() { // this( randomSeed() ); // } // // /** Creates a new generator using a given seed. // * // * @param seed a nonzero seed for the generator (if zero, the generator will be seeded with -1). // */ // public Xorshift( final long seed ) { // super( seed ); // } // // @Override // protected int next( int bits ) { // return (int)( nextLong() >>> 64 - bits ); // } // // @Override // public synchronized long nextLong() { // long s0 = s[ p ]; // long s1 = s[ p = ( p + 1 ) & 15 ]; // s1 ^= s1 << 1; // return 1181783497276652981L * ( s[ p ] = s1 ^ s0 ^ ( s1 >>> 13 ) ^ ( s0 >>> 7 ) ); // } // // @Override // public int nextInt() { // return (int)nextLong(); // } // // @Override // public int nextInt( final int n ) { // return (int)nextLong( n ); // } // // /** Returns a pseudorandom uniformly distributed {@code long} value // * between 0 (inclusive) and the specified value (exclusive), drawn from // * this random number generator's sequence. The algorithm used to generate // * the value guarantees that the result is uniform, provided that the // * sequence of 64-bit values produced by this generator is. // * // * @param n the positive bound on the random number to be returned. // * @return the next pseudorandom {@code long} value between {@code 0} (inclusive) and {@code n} (exclusive). // */ // public long nextLong( final long n ) { // if ( n <= 0 ) throw new IllegalArgumentException(); // // No special provision for n power of two: all our bits are good. // for(;;) { // final long bits = nextLong() >>> 1; // final long value = bits % n; // if ( bits - value + ( n - 1 ) >= 0 ) return value; // } // } // // @Override // public double nextDouble() { // return ( nextLong() >>> 11 ) * NORM_53; // } // // @Override // public float nextFloat() { // return (float)( ( nextLong() >>> 40 ) * NORM_24 ); // } // // @Override // public boolean nextBoolean() { // return ( nextLong() & 1 ) != 0; // } // // @Override // public void nextBytes( final byte[] bytes ) { // int i = bytes.length, n = 0; // while( i != 0 ) { // n = Math.min( i, 8 ); // for ( long bits = nextLong(); n-- != 0; bits >>= 8 ) bytes[ --i ] = (byte)bits; // } // } // // /** Returns a random seed generated by taking a unique increasing long, adding // * {@link System#nanoTime()} and scrambling the result using the finalisation step of Austin // * Appleby's <a href="http://sites.google.com/site/murmurhash/">MurmurHash3</a>. // * // * @return a reasonably good random seed. // */ // private static final AtomicLong seedUniquifier = new AtomicLong(); // public static long randomSeed() { // long seed = seedUniquifier.incrementAndGet() + System.nanoTime(); // // seed ^= seed >>> 33; // seed *= 0xff51afd7ed558ccdL; // seed ^= seed >>> 33; // seed *= 0xc4ceb9fe1a85ec53L; // seed ^= seed >>> 33; // // return seed; // } // // /** Sets the seed of this generator. // * // * @param seed a nonzero seed for the generator (if zero, the generator will be seeded with -1). // */ // @Override // public synchronized void setSeed( final long seed ) { // if ( s == null ) s = new long[ 16 ]; // for( int i = s.length; i-- != 0; ) s[ i ] = seed == 0 ? -1 : seed; // for( int i = s.length * 4; i-- != 0; ) nextLong(); // Warmup. // } // }
import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import scengen.distribution.DISTRIBUTION; import scengen.methods.METHOD; import scengen.tools.Xorshift;
package scengen.paper; public class MakeGraphs { public static void main(String... args) { int numScen = 100; Random r = new Xorshift(11); List<File> files = new ArrayList<>();
// Path: src/main/java/scengen/distribution/DISTRIBUTION.java // public enum DISTRIBUTION { // Lognormal, Normal, Student, Uniform // } // // Path: src/main/java/scengen/methods/METHOD.java // public enum METHOD { // MonteCarlo, QuasiMonteCarlo, MomentMatching, QuantizationLearning, QuantizationGrids, Scenred2, VoronoiCellSampling // } // // Path: src/main/java/scengen/tools/Xorshift.java // public class Xorshift extends Random { // private static final long serialVersionUID = 1L; // // /** 2<sup>-53</sup>. */ // private static final double NORM_53 = 1. / ( 1L << 53 ); // /** 2<sup>-24</sup>. */ // private static final double NORM_24 = 1. / ( 1L << 24 ); // // /** The internal state of the algorithm. */ // private long[] s; // private int p; // // /** Creates a new generator seeded using {@link #randomSeed()}. */ // public Xorshift() { // this( randomSeed() ); // } // // /** Creates a new generator using a given seed. // * // * @param seed a nonzero seed for the generator (if zero, the generator will be seeded with -1). // */ // public Xorshift( final long seed ) { // super( seed ); // } // // @Override // protected int next( int bits ) { // return (int)( nextLong() >>> 64 - bits ); // } // // @Override // public synchronized long nextLong() { // long s0 = s[ p ]; // long s1 = s[ p = ( p + 1 ) & 15 ]; // s1 ^= s1 << 1; // return 1181783497276652981L * ( s[ p ] = s1 ^ s0 ^ ( s1 >>> 13 ) ^ ( s0 >>> 7 ) ); // } // // @Override // public int nextInt() { // return (int)nextLong(); // } // // @Override // public int nextInt( final int n ) { // return (int)nextLong( n ); // } // // /** Returns a pseudorandom uniformly distributed {@code long} value // * between 0 (inclusive) and the specified value (exclusive), drawn from // * this random number generator's sequence. The algorithm used to generate // * the value guarantees that the result is uniform, provided that the // * sequence of 64-bit values produced by this generator is. // * // * @param n the positive bound on the random number to be returned. // * @return the next pseudorandom {@code long} value between {@code 0} (inclusive) and {@code n} (exclusive). // */ // public long nextLong( final long n ) { // if ( n <= 0 ) throw new IllegalArgumentException(); // // No special provision for n power of two: all our bits are good. // for(;;) { // final long bits = nextLong() >>> 1; // final long value = bits % n; // if ( bits - value + ( n - 1 ) >= 0 ) return value; // } // } // // @Override // public double nextDouble() { // return ( nextLong() >>> 11 ) * NORM_53; // } // // @Override // public float nextFloat() { // return (float)( ( nextLong() >>> 40 ) * NORM_24 ); // } // // @Override // public boolean nextBoolean() { // return ( nextLong() & 1 ) != 0; // } // // @Override // public void nextBytes( final byte[] bytes ) { // int i = bytes.length, n = 0; // while( i != 0 ) { // n = Math.min( i, 8 ); // for ( long bits = nextLong(); n-- != 0; bits >>= 8 ) bytes[ --i ] = (byte)bits; // } // } // // /** Returns a random seed generated by taking a unique increasing long, adding // * {@link System#nanoTime()} and scrambling the result using the finalisation step of Austin // * Appleby's <a href="http://sites.google.com/site/murmurhash/">MurmurHash3</a>. // * // * @return a reasonably good random seed. // */ // private static final AtomicLong seedUniquifier = new AtomicLong(); // public static long randomSeed() { // long seed = seedUniquifier.incrementAndGet() + System.nanoTime(); // // seed ^= seed >>> 33; // seed *= 0xff51afd7ed558ccdL; // seed ^= seed >>> 33; // seed *= 0xc4ceb9fe1a85ec53L; // seed ^= seed >>> 33; // // return seed; // } // // /** Sets the seed of this generator. // * // * @param seed a nonzero seed for the generator (if zero, the generator will be seeded with -1). // */ // @Override // public synchronized void setSeed( final long seed ) { // if ( s == null ) s = new long[ 16 ]; // for( int i = s.length; i-- != 0; ) s[ i ] = seed == 0 ? -1 : seed; // for( int i = s.length * 4; i-- != 0; ) nextLong(); // Warmup. // } // } // Path: src/main/java/scengen/paper/MakeGraphs.java import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import scengen.distribution.DISTRIBUTION; import scengen.methods.METHOD; import scengen.tools.Xorshift; package scengen.paper; public class MakeGraphs { public static void main(String... args) { int numScen = 100; Random r = new Xorshift(11); List<File> files = new ArrayList<>();
files.add(makeScen(8, numScen, DISTRIBUTION.Normal, METHOD.QuantizationLearning, r));
loehndorf/scengen
src/main/java/scengen/methods/QuantizationLearning.java
// Path: src/main/java/scengen/distribution/MultivariateDistribution.java // public interface MultivariateDistribution { // // public double[] getRealization(); // // public double[] getRealization(double[] u); // // public int getDim(); // // public List<double[]> getSample(int size); // // public void setGenerator(Random generator); // // public Random getGenerator(); // // public double[] getMean(); // // public double[] getVariance(); // // public double[][] getCov(); // // public double[] getSkewness(); // // public double[] getKurtosis(); // // public DISTRIBUTION getType(); // // } // // Path: src/main/java/scengen/tools/Metrics.java // public final class Metrics { // // public static final double FortetMourier(double[] d1, double[] d2) { // double x1 = 0; // double x2 = 0; // double d = 0; // for (int i = 0; i < d1.length; i++) { // double diff = (d1[i] - d2[i]); // if (!Double.isNaN(diff)) { // d += diff * diff; // } // x1 += d1[i]*d1[i]; // x2 += d2[i]*d2[i]; // } // return Math.sqrt(d)*Math.max(1,Math.max(Math.sqrt(x1),Math.sqrt(x2))); // } // // public static final double WeightedEuclidean(double[] weights, double[] d1, double[] d2) { // if (d1==d2) return 0.; // double sumSq = 0.; // for (int i=0; i<d1.length; i++) { // double d = d1[i]-d2[i]; // sumSq += d*d; // } // return Math.sqrt(sumSq); // } // // public static final double Euclidean(double[] d1, double[] d2) { // if (d1==d2) return 0.; // double sumSq = 0.; // for (int i=0; i<d1.length; i++) { // double d = d1[i]-d2[i]; // sumSq += d*d; // } // return Math.sqrt(sumSq); // } // // public static final double squaredDistance(double[] d1, double[] d2) { // if (d1==d2) return 0.; // double sumSq = 0.; // for (int i=0; i<d1.length; i++) { // double d = d1[i]-d2[i]; // sumSq += d*d; // } // return sumSq; // } // // public static final double manhattanDistance(double[] d1, double[] d2) { // if (d1==d2) return 0.; // double sumSq = 0.; // for (int i=0; i<d1.length; i++) { // double d = Math.abs(d1[i]-d2[i]); // sumSq += d; // } // return sumSq; // } // // public static final double squaredDistance(double[] d1, double[] d2, double[] weights) { // if (d1==d2) return 0.; // double sumSq = 0.; // for (int i=0; i<d1.length; i++) { // double d = d1[i]-d2[i]; // sumSq += d*d*weights[i]; // } // return sumSq; // } // // public static final double infDistance(double[] d1, double[] d2, double[] weights) { // if (d1==d2) return 0.; // double maxDist = 0.; // for (int i=0; i<d1.length; i++) { // double d = Math.abs(d1[i]-d2[i])*weights[i]; // if (d>maxDist) // maxDist = d; // } // return maxDist; // } // // }
import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import scengen.distribution.MultivariateDistribution; import scengen.tools.Metrics;
package scengen.methods; public class QuantizationLearning extends ReductionMethod { MultivariateDistribution _mvdist; public QuantizationLearning (MultivariateDistribution dist) { _mvdist = dist; } @Override public Map<double[], Double> getScenarios(int numScen) { int dim = _mvdist.getDim(); double a = 100*numScen; int sampleSize = 10000*numScen; double[][] scenarios = new double[numScen][]; double[] probs = new double[numScen]; Arrays.fill(probs, 1); MonteCarlo rand = new MonteCarlo(_mvdist); Iterator<double[]> iter = rand.getScenarios(numScen).keySet().iterator(); for (int j=0; j<numScen; j++) scenarios[j] = iter.next(); for (int i=0; i<sampleSize; i++) { double[] point = _mvdist.getRealization(); int nearest = 0; double minDist = Double.MAX_VALUE; for (int j=0; j<numScen; j++) {
// Path: src/main/java/scengen/distribution/MultivariateDistribution.java // public interface MultivariateDistribution { // // public double[] getRealization(); // // public double[] getRealization(double[] u); // // public int getDim(); // // public List<double[]> getSample(int size); // // public void setGenerator(Random generator); // // public Random getGenerator(); // // public double[] getMean(); // // public double[] getVariance(); // // public double[][] getCov(); // // public double[] getSkewness(); // // public double[] getKurtosis(); // // public DISTRIBUTION getType(); // // } // // Path: src/main/java/scengen/tools/Metrics.java // public final class Metrics { // // public static final double FortetMourier(double[] d1, double[] d2) { // double x1 = 0; // double x2 = 0; // double d = 0; // for (int i = 0; i < d1.length; i++) { // double diff = (d1[i] - d2[i]); // if (!Double.isNaN(diff)) { // d += diff * diff; // } // x1 += d1[i]*d1[i]; // x2 += d2[i]*d2[i]; // } // return Math.sqrt(d)*Math.max(1,Math.max(Math.sqrt(x1),Math.sqrt(x2))); // } // // public static final double WeightedEuclidean(double[] weights, double[] d1, double[] d2) { // if (d1==d2) return 0.; // double sumSq = 0.; // for (int i=0; i<d1.length; i++) { // double d = d1[i]-d2[i]; // sumSq += d*d; // } // return Math.sqrt(sumSq); // } // // public static final double Euclidean(double[] d1, double[] d2) { // if (d1==d2) return 0.; // double sumSq = 0.; // for (int i=0; i<d1.length; i++) { // double d = d1[i]-d2[i]; // sumSq += d*d; // } // return Math.sqrt(sumSq); // } // // public static final double squaredDistance(double[] d1, double[] d2) { // if (d1==d2) return 0.; // double sumSq = 0.; // for (int i=0; i<d1.length; i++) { // double d = d1[i]-d2[i]; // sumSq += d*d; // } // return sumSq; // } // // public static final double manhattanDistance(double[] d1, double[] d2) { // if (d1==d2) return 0.; // double sumSq = 0.; // for (int i=0; i<d1.length; i++) { // double d = Math.abs(d1[i]-d2[i]); // sumSq += d; // } // return sumSq; // } // // public static final double squaredDistance(double[] d1, double[] d2, double[] weights) { // if (d1==d2) return 0.; // double sumSq = 0.; // for (int i=0; i<d1.length; i++) { // double d = d1[i]-d2[i]; // sumSq += d*d*weights[i]; // } // return sumSq; // } // // public static final double infDistance(double[] d1, double[] d2, double[] weights) { // if (d1==d2) return 0.; // double maxDist = 0.; // for (int i=0; i<d1.length; i++) { // double d = Math.abs(d1[i]-d2[i])*weights[i]; // if (d>maxDist) // maxDist = d; // } // return maxDist; // } // // } // Path: src/main/java/scengen/methods/QuantizationLearning.java import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import scengen.distribution.MultivariateDistribution; import scengen.tools.Metrics; package scengen.methods; public class QuantizationLearning extends ReductionMethod { MultivariateDistribution _mvdist; public QuantizationLearning (MultivariateDistribution dist) { _mvdist = dist; } @Override public Map<double[], Double> getScenarios(int numScen) { int dim = _mvdist.getDim(); double a = 100*numScen; int sampleSize = 10000*numScen; double[][] scenarios = new double[numScen][]; double[] probs = new double[numScen]; Arrays.fill(probs, 1); MonteCarlo rand = new MonteCarlo(_mvdist); Iterator<double[]> iter = rand.getScenarios(numScen).keySet().iterator(); for (int j=0; j<numScen; j++) scenarios[j] = iter.next(); for (int i=0; i<sampleSize; i++) { double[] point = _mvdist.getRealization(); int nearest = 0; double minDist = Double.MAX_VALUE; for (int j=0; j<numScen; j++) {
double dist = Metrics.squaredDistance(scenarios[j], point);
loehndorf/scengen
src/main/java/scengen/distribution/MultivariateNormal.java
// Path: src/main/java/scengen/methods/MonteCarlo.java // public class MonteCarlo extends ReductionMethod { // // MultivariateDistribution _mvDist; // // public MonteCarlo (MultivariateDistribution mvDist) { // _mvDist = mvDist; // // } // // @Override // public Map<double[], Double> getScenarios(int numScen) { // Map<double[],Double> resultMap = new LinkedHashMap<>(); // for (int i=0; i<numScen; i++) // resultMap.put(_mvDist.getRealization(),1./numScen); // return resultMap; // } // } // // Path: src/main/java/scengen/methods/ReductionMethod.java // public abstract class ReductionMethod { // // public abstract Map<double[],Double> getScenarios(int numScen); // // /** // * @param dim // * @param scenarios // * @return Returns the scenario along one particular dimension. // */ // public static double[] getScenarios(int dim, Map<double[],Double> scenarios) { // double[] scen = new double[scenarios.size()]; // int i=0; // for (double[] x : scenarios.keySet()) // scen[i++] = x[dim]; // return scen; // } // // public static double[] getWeights(Map<double[],Double> scenarios) { // double[] weights = new double[scenarios.size()]; // int i=0; // for (double[] x : scenarios.keySet()) // weights[i++] = scenarios.get(x); // return weights; // } // // }
import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import umontreal.ssj.probdist.NormalDistQuick; import scengen.methods.MonteCarlo; import scengen.methods.ReductionMethod;
package scengen.distribution; public class MultivariateNormal implements MultivariateDistribution { double[][] _chol; double[][] _cov; double[] _var; double[] _mean; int _dim; Random _generator; public MultivariateNormal(double[] mean, double[][] covariance, Random generator) { if (covariance.length != mean.length || covariance[0].length != mean.length) throw new IllegalArgumentException("Covariance matrix dimensions invalid."); _mean = mean; _chol = choleskyDecomposition(covariance); _cov = covariance; _dim = mean.length; _var = new double[_dim]; for (int i=0; i<_dim; i++) _var[i] = _cov[i][i]; _generator = generator; } public static void main (String... args) { int dim = 1; double[] mean = new double[dim]; double[][] correl = new double[dim][dim]; for (int i=0; i<dim; i++) { mean[i] = 10; correl[i][i] = 2.5*2.5; }
// Path: src/main/java/scengen/methods/MonteCarlo.java // public class MonteCarlo extends ReductionMethod { // // MultivariateDistribution _mvDist; // // public MonteCarlo (MultivariateDistribution mvDist) { // _mvDist = mvDist; // // } // // @Override // public Map<double[], Double> getScenarios(int numScen) { // Map<double[],Double> resultMap = new LinkedHashMap<>(); // for (int i=0; i<numScen; i++) // resultMap.put(_mvDist.getRealization(),1./numScen); // return resultMap; // } // } // // Path: src/main/java/scengen/methods/ReductionMethod.java // public abstract class ReductionMethod { // // public abstract Map<double[],Double> getScenarios(int numScen); // // /** // * @param dim // * @param scenarios // * @return Returns the scenario along one particular dimension. // */ // public static double[] getScenarios(int dim, Map<double[],Double> scenarios) { // double[] scen = new double[scenarios.size()]; // int i=0; // for (double[] x : scenarios.keySet()) // scen[i++] = x[dim]; // return scen; // } // // public static double[] getWeights(Map<double[],Double> scenarios) { // double[] weights = new double[scenarios.size()]; // int i=0; // for (double[] x : scenarios.keySet()) // weights[i++] = scenarios.get(x); // return weights; // } // // } // Path: src/main/java/scengen/distribution/MultivariateNormal.java import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import umontreal.ssj.probdist.NormalDistQuick; import scengen.methods.MonteCarlo; import scengen.methods.ReductionMethod; package scengen.distribution; public class MultivariateNormal implements MultivariateDistribution { double[][] _chol; double[][] _cov; double[] _var; double[] _mean; int _dim; Random _generator; public MultivariateNormal(double[] mean, double[][] covariance, Random generator) { if (covariance.length != mean.length || covariance[0].length != mean.length) throw new IllegalArgumentException("Covariance matrix dimensions invalid."); _mean = mean; _chol = choleskyDecomposition(covariance); _cov = covariance; _dim = mean.length; _var = new double[_dim]; for (int i=0; i<_dim; i++) _var[i] = _cov[i][i]; _generator = generator; } public static void main (String... args) { int dim = 1; double[] mean = new double[dim]; double[][] correl = new double[dim][dim]; for (int i=0; i<dim; i++) { mean[i] = 10; correl[i][i] = 2.5*2.5; }
ReductionMethod mm = new MonteCarlo(new MultivariateNormal(mean,correl,new Random()));
loehndorf/scengen
src/main/java/scengen/distribution/MultivariateNormal.java
// Path: src/main/java/scengen/methods/MonteCarlo.java // public class MonteCarlo extends ReductionMethod { // // MultivariateDistribution _mvDist; // // public MonteCarlo (MultivariateDistribution mvDist) { // _mvDist = mvDist; // // } // // @Override // public Map<double[], Double> getScenarios(int numScen) { // Map<double[],Double> resultMap = new LinkedHashMap<>(); // for (int i=0; i<numScen; i++) // resultMap.put(_mvDist.getRealization(),1./numScen); // return resultMap; // } // } // // Path: src/main/java/scengen/methods/ReductionMethod.java // public abstract class ReductionMethod { // // public abstract Map<double[],Double> getScenarios(int numScen); // // /** // * @param dim // * @param scenarios // * @return Returns the scenario along one particular dimension. // */ // public static double[] getScenarios(int dim, Map<double[],Double> scenarios) { // double[] scen = new double[scenarios.size()]; // int i=0; // for (double[] x : scenarios.keySet()) // scen[i++] = x[dim]; // return scen; // } // // public static double[] getWeights(Map<double[],Double> scenarios) { // double[] weights = new double[scenarios.size()]; // int i=0; // for (double[] x : scenarios.keySet()) // weights[i++] = scenarios.get(x); // return weights; // } // // }
import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import umontreal.ssj.probdist.NormalDistQuick; import scengen.methods.MonteCarlo; import scengen.methods.ReductionMethod;
package scengen.distribution; public class MultivariateNormal implements MultivariateDistribution { double[][] _chol; double[][] _cov; double[] _var; double[] _mean; int _dim; Random _generator; public MultivariateNormal(double[] mean, double[][] covariance, Random generator) { if (covariance.length != mean.length || covariance[0].length != mean.length) throw new IllegalArgumentException("Covariance matrix dimensions invalid."); _mean = mean; _chol = choleskyDecomposition(covariance); _cov = covariance; _dim = mean.length; _var = new double[_dim]; for (int i=0; i<_dim; i++) _var[i] = _cov[i][i]; _generator = generator; } public static void main (String... args) { int dim = 1; double[] mean = new double[dim]; double[][] correl = new double[dim][dim]; for (int i=0; i<dim; i++) { mean[i] = 10; correl[i][i] = 2.5*2.5; }
// Path: src/main/java/scengen/methods/MonteCarlo.java // public class MonteCarlo extends ReductionMethod { // // MultivariateDistribution _mvDist; // // public MonteCarlo (MultivariateDistribution mvDist) { // _mvDist = mvDist; // // } // // @Override // public Map<double[], Double> getScenarios(int numScen) { // Map<double[],Double> resultMap = new LinkedHashMap<>(); // for (int i=0; i<numScen; i++) // resultMap.put(_mvDist.getRealization(),1./numScen); // return resultMap; // } // } // // Path: src/main/java/scengen/methods/ReductionMethod.java // public abstract class ReductionMethod { // // public abstract Map<double[],Double> getScenarios(int numScen); // // /** // * @param dim // * @param scenarios // * @return Returns the scenario along one particular dimension. // */ // public static double[] getScenarios(int dim, Map<double[],Double> scenarios) { // double[] scen = new double[scenarios.size()]; // int i=0; // for (double[] x : scenarios.keySet()) // scen[i++] = x[dim]; // return scen; // } // // public static double[] getWeights(Map<double[],Double> scenarios) { // double[] weights = new double[scenarios.size()]; // int i=0; // for (double[] x : scenarios.keySet()) // weights[i++] = scenarios.get(x); // return weights; // } // // } // Path: src/main/java/scengen/distribution/MultivariateNormal.java import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import umontreal.ssj.probdist.NormalDistQuick; import scengen.methods.MonteCarlo; import scengen.methods.ReductionMethod; package scengen.distribution; public class MultivariateNormal implements MultivariateDistribution { double[][] _chol; double[][] _cov; double[] _var; double[] _mean; int _dim; Random _generator; public MultivariateNormal(double[] mean, double[][] covariance, Random generator) { if (covariance.length != mean.length || covariance[0].length != mean.length) throw new IllegalArgumentException("Covariance matrix dimensions invalid."); _mean = mean; _chol = choleskyDecomposition(covariance); _cov = covariance; _dim = mean.length; _var = new double[_dim]; for (int i=0; i<_dim; i++) _var[i] = _cov[i][i]; _generator = generator; } public static void main (String... args) { int dim = 1; double[] mean = new double[dim]; double[][] correl = new double[dim][dim]; for (int i=0; i<dim; i++) { mean[i] = 10; correl[i][i] = 2.5*2.5; }
ReductionMethod mm = new MonteCarlo(new MultivariateNormal(mean,correl,new Random()));
loehndorf/scengen
src/main/java/scengen/methods/VoronoiCellSampling.java
// Path: src/main/java/scengen/distribution/MultivariateDistribution.java // public interface MultivariateDistribution { // // public double[] getRealization(); // // public double[] getRealization(double[] u); // // public int getDim(); // // public List<double[]> getSample(int size); // // public void setGenerator(Random generator); // // public Random getGenerator(); // // public double[] getMean(); // // public double[] getVariance(); // // public double[][] getCov(); // // public double[] getSkewness(); // // public double[] getKurtosis(); // // public DISTRIBUTION getType(); // // } // // Path: src/main/java/scengen/tools/Metrics.java // public final class Metrics { // // public static final double FortetMourier(double[] d1, double[] d2) { // double x1 = 0; // double x2 = 0; // double d = 0; // for (int i = 0; i < d1.length; i++) { // double diff = (d1[i] - d2[i]); // if (!Double.isNaN(diff)) { // d += diff * diff; // } // x1 += d1[i]*d1[i]; // x2 += d2[i]*d2[i]; // } // return Math.sqrt(d)*Math.max(1,Math.max(Math.sqrt(x1),Math.sqrt(x2))); // } // // public static final double WeightedEuclidean(double[] weights, double[] d1, double[] d2) { // if (d1==d2) return 0.; // double sumSq = 0.; // for (int i=0; i<d1.length; i++) { // double d = d1[i]-d2[i]; // sumSq += d*d; // } // return Math.sqrt(sumSq); // } // // public static final double Euclidean(double[] d1, double[] d2) { // if (d1==d2) return 0.; // double sumSq = 0.; // for (int i=0; i<d1.length; i++) { // double d = d1[i]-d2[i]; // sumSq += d*d; // } // return Math.sqrt(sumSq); // } // // public static final double squaredDistance(double[] d1, double[] d2) { // if (d1==d2) return 0.; // double sumSq = 0.; // for (int i=0; i<d1.length; i++) { // double d = d1[i]-d2[i]; // sumSq += d*d; // } // return sumSq; // } // // public static final double manhattanDistance(double[] d1, double[] d2) { // if (d1==d2) return 0.; // double sumSq = 0.; // for (int i=0; i<d1.length; i++) { // double d = Math.abs(d1[i]-d2[i]); // sumSq += d; // } // return sumSq; // } // // public static final double squaredDistance(double[] d1, double[] d2, double[] weights) { // if (d1==d2) return 0.; // double sumSq = 0.; // for (int i=0; i<d1.length; i++) { // double d = d1[i]-d2[i]; // sumSq += d*d*weights[i]; // } // return sumSq; // } // // public static final double infDistance(double[] d1, double[] d2, double[] weights) { // if (d1==d2) return 0.; // double maxDist = 0.; // for (int i=0; i<d1.length; i++) { // double d = Math.abs(d1[i]-d2[i])*weights[i]; // if (d>maxDist) // maxDist = d; // } // return maxDist; // } // // }
import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import scengen.distribution.MultivariateDistribution; import scengen.tools.Metrics;
package scengen.methods; public class VoronoiCellSampling extends QuantizationLearning { public VoronoiCellSampling(MultivariateDistribution dist) { super(dist); } public Map<double[], Double> getScenarios(int numScen) { int dim = _mvdist.getDim(); double a = 100*numScen; int sampleSize = 10000*numScen; double[][] scenarios1 = new double[numScen][]; double[][] scenarios2 = new double[numScen][]; double[] probs = new double[numScen]; Arrays.fill(probs, 1); MonteCarlo rand = new MonteCarlo(_mvdist); Iterator<double[]> iter = rand.getScenarios(numScen).keySet().iterator(); for (int j=0; j<numScen; j++) { double[] x = iter.next(); scenarios1[j] = x; scenarios2[j] = x; } for (int i=0; i<sampleSize; i++) { double[] point = _mvdist.getRealization(); int nearest = 0; double minDist = Double.MAX_VALUE; for (int j=0; j<numScen; j++) {
// Path: src/main/java/scengen/distribution/MultivariateDistribution.java // public interface MultivariateDistribution { // // public double[] getRealization(); // // public double[] getRealization(double[] u); // // public int getDim(); // // public List<double[]> getSample(int size); // // public void setGenerator(Random generator); // // public Random getGenerator(); // // public double[] getMean(); // // public double[] getVariance(); // // public double[][] getCov(); // // public double[] getSkewness(); // // public double[] getKurtosis(); // // public DISTRIBUTION getType(); // // } // // Path: src/main/java/scengen/tools/Metrics.java // public final class Metrics { // // public static final double FortetMourier(double[] d1, double[] d2) { // double x1 = 0; // double x2 = 0; // double d = 0; // for (int i = 0; i < d1.length; i++) { // double diff = (d1[i] - d2[i]); // if (!Double.isNaN(diff)) { // d += diff * diff; // } // x1 += d1[i]*d1[i]; // x2 += d2[i]*d2[i]; // } // return Math.sqrt(d)*Math.max(1,Math.max(Math.sqrt(x1),Math.sqrt(x2))); // } // // public static final double WeightedEuclidean(double[] weights, double[] d1, double[] d2) { // if (d1==d2) return 0.; // double sumSq = 0.; // for (int i=0; i<d1.length; i++) { // double d = d1[i]-d2[i]; // sumSq += d*d; // } // return Math.sqrt(sumSq); // } // // public static final double Euclidean(double[] d1, double[] d2) { // if (d1==d2) return 0.; // double sumSq = 0.; // for (int i=0; i<d1.length; i++) { // double d = d1[i]-d2[i]; // sumSq += d*d; // } // return Math.sqrt(sumSq); // } // // public static final double squaredDistance(double[] d1, double[] d2) { // if (d1==d2) return 0.; // double sumSq = 0.; // for (int i=0; i<d1.length; i++) { // double d = d1[i]-d2[i]; // sumSq += d*d; // } // return sumSq; // } // // public static final double manhattanDistance(double[] d1, double[] d2) { // if (d1==d2) return 0.; // double sumSq = 0.; // for (int i=0; i<d1.length; i++) { // double d = Math.abs(d1[i]-d2[i]); // sumSq += d; // } // return sumSq; // } // // public static final double squaredDistance(double[] d1, double[] d2, double[] weights) { // if (d1==d2) return 0.; // double sumSq = 0.; // for (int i=0; i<d1.length; i++) { // double d = d1[i]-d2[i]; // sumSq += d*d*weights[i]; // } // return sumSq; // } // // public static final double infDistance(double[] d1, double[] d2, double[] weights) { // if (d1==d2) return 0.; // double maxDist = 0.; // for (int i=0; i<d1.length; i++) { // double d = Math.abs(d1[i]-d2[i])*weights[i]; // if (d>maxDist) // maxDist = d; // } // return maxDist; // } // // } // Path: src/main/java/scengen/methods/VoronoiCellSampling.java import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import scengen.distribution.MultivariateDistribution; import scengen.tools.Metrics; package scengen.methods; public class VoronoiCellSampling extends QuantizationLearning { public VoronoiCellSampling(MultivariateDistribution dist) { super(dist); } public Map<double[], Double> getScenarios(int numScen) { int dim = _mvdist.getDim(); double a = 100*numScen; int sampleSize = 10000*numScen; double[][] scenarios1 = new double[numScen][]; double[][] scenarios2 = new double[numScen][]; double[] probs = new double[numScen]; Arrays.fill(probs, 1); MonteCarlo rand = new MonteCarlo(_mvdist); Iterator<double[]> iter = rand.getScenarios(numScen).keySet().iterator(); for (int j=0; j<numScen; j++) { double[] x = iter.next(); scenarios1[j] = x; scenarios2[j] = x; } for (int i=0; i<sampleSize; i++) { double[] point = _mvdist.getRealization(); int nearest = 0; double minDist = Double.MAX_VALUE; for (int j=0; j<numScen; j++) {
double dist = Metrics.squaredDistance(scenarios1[j], point);
loehndorf/scengen
src/main/java/scengen/tools/MetricTree.java
// Path: src/main/java/scengen/tools/kdtree/KdTree.java // public class KdTree<T> extends KdNode<T> { // public KdTree(int dimensions) { // this(dimensions, 24); // } // // public KdTree(int dimensions, int bucketCapacity) { // super(dimensions, bucketCapacity); // } // // public NearestNeighborIterator<T> getNearestNeighborIterator(double[] searchPoint, int maxPointsReturned, DistanceFunction distanceFunction) { // return new NearestNeighborIterator<T>(this, searchPoint, maxPointsReturned, distanceFunction); // } // // public MaxHeap<T> findNearestNeighbors(double[] searchPoint, int maxPointsReturned, DistanceFunction distanceFunction) { // BinaryHeap.Min<KdNode<T>> pendingPaths = new BinaryHeap.Min<KdNode<T>>(); // BinaryHeap.Max<T> evaluatedPoints = new BinaryHeap.Max<T>(); // int pointsRemaining = Math.min(maxPointsReturned, size()); // pendingPaths.offer(0, this); // // while (pendingPaths.size() > 0 && (evaluatedPoints.size() < pointsRemaining || (pendingPaths.getMinKey() < evaluatedPoints.getMaxKey()))) { // nearestNeighborSearchStep(pendingPaths, evaluatedPoints, pointsRemaining, distanceFunction, searchPoint); // } // // return evaluatedPoints; // } // // @SuppressWarnings("unchecked") // protected static <T> void nearestNeighborSearchStep ( // MinHeap<KdNode<T>> pendingPaths, MaxHeap<T> evaluatedPoints, int desiredPoints, // DistanceFunction distanceFunction, double[] searchPoint) { // // If there are pending paths possibly closer than the nearest evaluated point, check it out // KdNode<T> cursor = pendingPaths.getMin(); // pendingPaths.removeMin(); // // // Descend the tree, recording paths not taken // while (!cursor.isLeaf()) { // KdNode<T> pathNotTaken; // if (searchPoint[cursor.splitDimension] > cursor.splitValue) { // pathNotTaken = cursor.left; // cursor = cursor.right; // } // else { // pathNotTaken = cursor.right; // cursor = cursor.left; // } // double otherDistance = distanceFunction.distanceToRect(searchPoint, pathNotTaken.minBound, pathNotTaken.maxBound); // // Only add a path if we either need more points or it's closer than furthest point on list so far // if (evaluatedPoints.size() < desiredPoints || otherDistance <= evaluatedPoints.getMaxKey()) { // pendingPaths.offer(otherDistance, pathNotTaken); // } // } // // if (cursor.singlePoint) { // double nodeDistance = distanceFunction.distance(cursor.points[0], searchPoint); // // Only add a point if either need more points or it's closer than furthest on list so far // if (evaluatedPoints.size() < desiredPoints || nodeDistance <= evaluatedPoints.getMaxKey()) { // for (int i = 0; i < cursor.size(); i++) { // T value = (T) cursor.data[i]; // // // If we don't need any more, replace max // if (evaluatedPoints.size() == desiredPoints) { // evaluatedPoints.replaceMax(nodeDistance, value); // } else { // evaluatedPoints.offer(nodeDistance, value); // } // } // } // } else { // // Add the points at the cursor // for (int i = 0; i < cursor.size(); i++) { // double[] point = cursor.points[i]; // T value = (T) cursor.data[i]; // double distance = distanceFunction.distance(point, searchPoint); // // Only add a point if either need more points or it's closer than furthest on list so far // if (evaluatedPoints.size() < desiredPoints) { // evaluatedPoints.offer(distance, value); // } else if (distance < evaluatedPoints.getMaxKey()) { // evaluatedPoints.replaceMax(distance, value); // } // } // } // } // } // // Path: src/main/java/scengen/tools/kdtree/SquaredEuclidean.java // public class SquaredEuclidean implements DistanceFunction { // @Override // public double distance(double[] p1, double[] p2) { // double d = 0; // // for (int i = 0; i < p1.length; i++) { // double diff = (p1[i] - p2[i]); // d += diff * diff; // } // // return d; // } // // @Override // public double distanceToRect(double[] point, double[] min, double[] max) { // double d = 0; // // for (int i = 0; i < point.length; i++) { // double diff = 0; // if (point[i] > max[i]) { // diff = (point[i] - max[i]); // } // else if (point[i] < min[i]) { // diff = (point[i] - min[i]); // } // d += diff * diff; // } // // return d; // } // }
import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import scengen.tools.kdtree.KdTree; import scengen.tools.kdtree.SquaredEuclidean;
package scengen.tools; /** * Wrapper class for a metric tree to facilitate nearest neighbor queries over a fixed set of points. * @author Nils Loehndorf * * @param <E> */ public class MetricTree<E> implements Serializable { private static final long serialVersionUID = 5100441495706307337L;
// Path: src/main/java/scengen/tools/kdtree/KdTree.java // public class KdTree<T> extends KdNode<T> { // public KdTree(int dimensions) { // this(dimensions, 24); // } // // public KdTree(int dimensions, int bucketCapacity) { // super(dimensions, bucketCapacity); // } // // public NearestNeighborIterator<T> getNearestNeighborIterator(double[] searchPoint, int maxPointsReturned, DistanceFunction distanceFunction) { // return new NearestNeighborIterator<T>(this, searchPoint, maxPointsReturned, distanceFunction); // } // // public MaxHeap<T> findNearestNeighbors(double[] searchPoint, int maxPointsReturned, DistanceFunction distanceFunction) { // BinaryHeap.Min<KdNode<T>> pendingPaths = new BinaryHeap.Min<KdNode<T>>(); // BinaryHeap.Max<T> evaluatedPoints = new BinaryHeap.Max<T>(); // int pointsRemaining = Math.min(maxPointsReturned, size()); // pendingPaths.offer(0, this); // // while (pendingPaths.size() > 0 && (evaluatedPoints.size() < pointsRemaining || (pendingPaths.getMinKey() < evaluatedPoints.getMaxKey()))) { // nearestNeighborSearchStep(pendingPaths, evaluatedPoints, pointsRemaining, distanceFunction, searchPoint); // } // // return evaluatedPoints; // } // // @SuppressWarnings("unchecked") // protected static <T> void nearestNeighborSearchStep ( // MinHeap<KdNode<T>> pendingPaths, MaxHeap<T> evaluatedPoints, int desiredPoints, // DistanceFunction distanceFunction, double[] searchPoint) { // // If there are pending paths possibly closer than the nearest evaluated point, check it out // KdNode<T> cursor = pendingPaths.getMin(); // pendingPaths.removeMin(); // // // Descend the tree, recording paths not taken // while (!cursor.isLeaf()) { // KdNode<T> pathNotTaken; // if (searchPoint[cursor.splitDimension] > cursor.splitValue) { // pathNotTaken = cursor.left; // cursor = cursor.right; // } // else { // pathNotTaken = cursor.right; // cursor = cursor.left; // } // double otherDistance = distanceFunction.distanceToRect(searchPoint, pathNotTaken.minBound, pathNotTaken.maxBound); // // Only add a path if we either need more points or it's closer than furthest point on list so far // if (evaluatedPoints.size() < desiredPoints || otherDistance <= evaluatedPoints.getMaxKey()) { // pendingPaths.offer(otherDistance, pathNotTaken); // } // } // // if (cursor.singlePoint) { // double nodeDistance = distanceFunction.distance(cursor.points[0], searchPoint); // // Only add a point if either need more points or it's closer than furthest on list so far // if (evaluatedPoints.size() < desiredPoints || nodeDistance <= evaluatedPoints.getMaxKey()) { // for (int i = 0; i < cursor.size(); i++) { // T value = (T) cursor.data[i]; // // // If we don't need any more, replace max // if (evaluatedPoints.size() == desiredPoints) { // evaluatedPoints.replaceMax(nodeDistance, value); // } else { // evaluatedPoints.offer(nodeDistance, value); // } // } // } // } else { // // Add the points at the cursor // for (int i = 0; i < cursor.size(); i++) { // double[] point = cursor.points[i]; // T value = (T) cursor.data[i]; // double distance = distanceFunction.distance(point, searchPoint); // // Only add a point if either need more points or it's closer than furthest on list so far // if (evaluatedPoints.size() < desiredPoints) { // evaluatedPoints.offer(distance, value); // } else if (distance < evaluatedPoints.getMaxKey()) { // evaluatedPoints.replaceMax(distance, value); // } // } // } // } // } // // Path: src/main/java/scengen/tools/kdtree/SquaredEuclidean.java // public class SquaredEuclidean implements DistanceFunction { // @Override // public double distance(double[] p1, double[] p2) { // double d = 0; // // for (int i = 0; i < p1.length; i++) { // double diff = (p1[i] - p2[i]); // d += diff * diff; // } // // return d; // } // // @Override // public double distanceToRect(double[] point, double[] min, double[] max) { // double d = 0; // // for (int i = 0; i < point.length; i++) { // double diff = 0; // if (point[i] > max[i]) { // diff = (point[i] - max[i]); // } // else if (point[i] < min[i]) { // diff = (point[i] - min[i]); // } // d += diff * diff; // } // // return d; // } // } // Path: src/main/java/scengen/tools/MetricTree.java import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import scengen.tools.kdtree.KdTree; import scengen.tools.kdtree.SquaredEuclidean; package scengen.tools; /** * Wrapper class for a metric tree to facilitate nearest neighbor queries over a fixed set of points. * @author Nils Loehndorf * * @param <E> */ public class MetricTree<E> implements Serializable { private static final long serialVersionUID = 5100441495706307337L;
KdTree<E> kdtree;
loehndorf/scengen
src/main/java/scengen/tools/MetricTree.java
// Path: src/main/java/scengen/tools/kdtree/KdTree.java // public class KdTree<T> extends KdNode<T> { // public KdTree(int dimensions) { // this(dimensions, 24); // } // // public KdTree(int dimensions, int bucketCapacity) { // super(dimensions, bucketCapacity); // } // // public NearestNeighborIterator<T> getNearestNeighborIterator(double[] searchPoint, int maxPointsReturned, DistanceFunction distanceFunction) { // return new NearestNeighborIterator<T>(this, searchPoint, maxPointsReturned, distanceFunction); // } // // public MaxHeap<T> findNearestNeighbors(double[] searchPoint, int maxPointsReturned, DistanceFunction distanceFunction) { // BinaryHeap.Min<KdNode<T>> pendingPaths = new BinaryHeap.Min<KdNode<T>>(); // BinaryHeap.Max<T> evaluatedPoints = new BinaryHeap.Max<T>(); // int pointsRemaining = Math.min(maxPointsReturned, size()); // pendingPaths.offer(0, this); // // while (pendingPaths.size() > 0 && (evaluatedPoints.size() < pointsRemaining || (pendingPaths.getMinKey() < evaluatedPoints.getMaxKey()))) { // nearestNeighborSearchStep(pendingPaths, evaluatedPoints, pointsRemaining, distanceFunction, searchPoint); // } // // return evaluatedPoints; // } // // @SuppressWarnings("unchecked") // protected static <T> void nearestNeighborSearchStep ( // MinHeap<KdNode<T>> pendingPaths, MaxHeap<T> evaluatedPoints, int desiredPoints, // DistanceFunction distanceFunction, double[] searchPoint) { // // If there are pending paths possibly closer than the nearest evaluated point, check it out // KdNode<T> cursor = pendingPaths.getMin(); // pendingPaths.removeMin(); // // // Descend the tree, recording paths not taken // while (!cursor.isLeaf()) { // KdNode<T> pathNotTaken; // if (searchPoint[cursor.splitDimension] > cursor.splitValue) { // pathNotTaken = cursor.left; // cursor = cursor.right; // } // else { // pathNotTaken = cursor.right; // cursor = cursor.left; // } // double otherDistance = distanceFunction.distanceToRect(searchPoint, pathNotTaken.minBound, pathNotTaken.maxBound); // // Only add a path if we either need more points or it's closer than furthest point on list so far // if (evaluatedPoints.size() < desiredPoints || otherDistance <= evaluatedPoints.getMaxKey()) { // pendingPaths.offer(otherDistance, pathNotTaken); // } // } // // if (cursor.singlePoint) { // double nodeDistance = distanceFunction.distance(cursor.points[0], searchPoint); // // Only add a point if either need more points or it's closer than furthest on list so far // if (evaluatedPoints.size() < desiredPoints || nodeDistance <= evaluatedPoints.getMaxKey()) { // for (int i = 0; i < cursor.size(); i++) { // T value = (T) cursor.data[i]; // // // If we don't need any more, replace max // if (evaluatedPoints.size() == desiredPoints) { // evaluatedPoints.replaceMax(nodeDistance, value); // } else { // evaluatedPoints.offer(nodeDistance, value); // } // } // } // } else { // // Add the points at the cursor // for (int i = 0; i < cursor.size(); i++) { // double[] point = cursor.points[i]; // T value = (T) cursor.data[i]; // double distance = distanceFunction.distance(point, searchPoint); // // Only add a point if either need more points or it's closer than furthest on list so far // if (evaluatedPoints.size() < desiredPoints) { // evaluatedPoints.offer(distance, value); // } else if (distance < evaluatedPoints.getMaxKey()) { // evaluatedPoints.replaceMax(distance, value); // } // } // } // } // } // // Path: src/main/java/scengen/tools/kdtree/SquaredEuclidean.java // public class SquaredEuclidean implements DistanceFunction { // @Override // public double distance(double[] p1, double[] p2) { // double d = 0; // // for (int i = 0; i < p1.length; i++) { // double diff = (p1[i] - p2[i]); // d += diff * diff; // } // // return d; // } // // @Override // public double distanceToRect(double[] point, double[] min, double[] max) { // double d = 0; // // for (int i = 0; i < point.length; i++) { // double diff = 0; // if (point[i] > max[i]) { // diff = (point[i] - max[i]); // } // else if (point[i] < min[i]) { // diff = (point[i] - min[i]); // } // d += diff * diff; // } // // return d; // } // }
import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import scengen.tools.kdtree.KdTree; import scengen.tools.kdtree.SquaredEuclidean;
package scengen.tools; /** * Wrapper class for a metric tree to facilitate nearest neighbor queries over a fixed set of points. * @author Nils Loehndorf * * @param <E> */ public class MetricTree<E> implements Serializable { private static final long serialVersionUID = 5100441495706307337L; KdTree<E> kdtree;
// Path: src/main/java/scengen/tools/kdtree/KdTree.java // public class KdTree<T> extends KdNode<T> { // public KdTree(int dimensions) { // this(dimensions, 24); // } // // public KdTree(int dimensions, int bucketCapacity) { // super(dimensions, bucketCapacity); // } // // public NearestNeighborIterator<T> getNearestNeighborIterator(double[] searchPoint, int maxPointsReturned, DistanceFunction distanceFunction) { // return new NearestNeighborIterator<T>(this, searchPoint, maxPointsReturned, distanceFunction); // } // // public MaxHeap<T> findNearestNeighbors(double[] searchPoint, int maxPointsReturned, DistanceFunction distanceFunction) { // BinaryHeap.Min<KdNode<T>> pendingPaths = new BinaryHeap.Min<KdNode<T>>(); // BinaryHeap.Max<T> evaluatedPoints = new BinaryHeap.Max<T>(); // int pointsRemaining = Math.min(maxPointsReturned, size()); // pendingPaths.offer(0, this); // // while (pendingPaths.size() > 0 && (evaluatedPoints.size() < pointsRemaining || (pendingPaths.getMinKey() < evaluatedPoints.getMaxKey()))) { // nearestNeighborSearchStep(pendingPaths, evaluatedPoints, pointsRemaining, distanceFunction, searchPoint); // } // // return evaluatedPoints; // } // // @SuppressWarnings("unchecked") // protected static <T> void nearestNeighborSearchStep ( // MinHeap<KdNode<T>> pendingPaths, MaxHeap<T> evaluatedPoints, int desiredPoints, // DistanceFunction distanceFunction, double[] searchPoint) { // // If there are pending paths possibly closer than the nearest evaluated point, check it out // KdNode<T> cursor = pendingPaths.getMin(); // pendingPaths.removeMin(); // // // Descend the tree, recording paths not taken // while (!cursor.isLeaf()) { // KdNode<T> pathNotTaken; // if (searchPoint[cursor.splitDimension] > cursor.splitValue) { // pathNotTaken = cursor.left; // cursor = cursor.right; // } // else { // pathNotTaken = cursor.right; // cursor = cursor.left; // } // double otherDistance = distanceFunction.distanceToRect(searchPoint, pathNotTaken.minBound, pathNotTaken.maxBound); // // Only add a path if we either need more points or it's closer than furthest point on list so far // if (evaluatedPoints.size() < desiredPoints || otherDistance <= evaluatedPoints.getMaxKey()) { // pendingPaths.offer(otherDistance, pathNotTaken); // } // } // // if (cursor.singlePoint) { // double nodeDistance = distanceFunction.distance(cursor.points[0], searchPoint); // // Only add a point if either need more points or it's closer than furthest on list so far // if (evaluatedPoints.size() < desiredPoints || nodeDistance <= evaluatedPoints.getMaxKey()) { // for (int i = 0; i < cursor.size(); i++) { // T value = (T) cursor.data[i]; // // // If we don't need any more, replace max // if (evaluatedPoints.size() == desiredPoints) { // evaluatedPoints.replaceMax(nodeDistance, value); // } else { // evaluatedPoints.offer(nodeDistance, value); // } // } // } // } else { // // Add the points at the cursor // for (int i = 0; i < cursor.size(); i++) { // double[] point = cursor.points[i]; // T value = (T) cursor.data[i]; // double distance = distanceFunction.distance(point, searchPoint); // // Only add a point if either need more points or it's closer than furthest on list so far // if (evaluatedPoints.size() < desiredPoints) { // evaluatedPoints.offer(distance, value); // } else if (distance < evaluatedPoints.getMaxKey()) { // evaluatedPoints.replaceMax(distance, value); // } // } // } // } // } // // Path: src/main/java/scengen/tools/kdtree/SquaredEuclidean.java // public class SquaredEuclidean implements DistanceFunction { // @Override // public double distance(double[] p1, double[] p2) { // double d = 0; // // for (int i = 0; i < p1.length; i++) { // double diff = (p1[i] - p2[i]); // d += diff * diff; // } // // return d; // } // // @Override // public double distanceToRect(double[] point, double[] min, double[] max) { // double d = 0; // // for (int i = 0; i < point.length; i++) { // double diff = 0; // if (point[i] > max[i]) { // diff = (point[i] - max[i]); // } // else if (point[i] < min[i]) { // diff = (point[i] - min[i]); // } // d += diff * diff; // } // // return d; // } // } // Path: src/main/java/scengen/tools/MetricTree.java import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import scengen.tools.kdtree.KdTree; import scengen.tools.kdtree.SquaredEuclidean; package scengen.tools; /** * Wrapper class for a metric tree to facilitate nearest neighbor queries over a fixed set of points. * @author Nils Loehndorf * * @param <E> */ public class MetricTree<E> implements Serializable { private static final long serialVersionUID = 5100441495706307337L; KdTree<E> kdtree;
SquaredEuclidean dist;
otto-de/edison-hal
src/test/java/de/otto/edison/hal/HalRepresentationAttributesTest.java
// Path: src/main/java/de/otto/edison/hal/HalParser.java // public static HalParser parse(final String json) { // return new HalParser(json, DEFAULT_JSON_MAPPER); // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.IOException; import java.util.List; import static de.otto.edison.hal.HalParser.parse; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.is;
package de.otto.edison.hal; public class HalRepresentationAttributesTest { static class NestedHalRepresentation extends HalRepresentation { @JsonProperty public List<HalRepresentation> nested; } @Test public void shouldParseExtraAttributes() throws IOException { // given final String json = "{" + "\"foo\":\"Hello World\"," + "\"bar\":[\"Hello\", \"World\"]" + "}"; // when
// Path: src/main/java/de/otto/edison/hal/HalParser.java // public static HalParser parse(final String json) { // return new HalParser(json, DEFAULT_JSON_MAPPER); // } // Path: src/test/java/de/otto/edison/hal/HalRepresentationAttributesTest.java import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.IOException; import java.util.List; import static de.otto.edison.hal.HalParser.parse; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.is; package de.otto.edison.hal; public class HalRepresentationAttributesTest { static class NestedHalRepresentation extends HalRepresentation { @JsonProperty public List<HalRepresentation> nested; } @Test public void shouldParseExtraAttributes() throws IOException { // given final String json = "{" + "\"foo\":\"Hello World\"," + "\"bar\":[\"Hello\", \"World\"]" + "}"; // when
HalRepresentation resource = parse(json).as(HalRepresentation.class);
otto-de/edison-hal
src/test/java/de/otto/edison/hal/HalRepresentationCuriesTest.java
// Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies curies(final Links links) { // List<Link> curies = links.getLinksBy("curies"); // return curies(curies); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded embedded(final String rel, // final HalRepresentation embeddedItem) { // return new Embedded(singletonMap(rel, embeddedItem)); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded emptyEmbedded() { // return new Embedded(null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link curi(final String name, final String relTemplate) { // if (!relTemplate.contains("{rel}")) { // throw new IllegalArgumentException("Not a CURI template. Template is required to contain a {rel} placeholder"); // } // return new Link("curies", relTemplate, null, null, null, name, null, null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // }
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import static de.otto.edison.hal.Curies.curies; import static de.otto.edison.hal.Embedded.embedded; import static de.otto.edison.hal.Embedded.emptyEmbedded; import static de.otto.edison.hal.Link.curi; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Links.emptyLinks; import static de.otto.edison.hal.Links.linkingTo; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*;
package de.otto.edison.hal; public class HalRepresentationCuriesTest { @Test public void shouldRenderSingleCuriAsArray() throws JsonProcessingException { // given final HalRepresentation representation = new HalRepresentation(
// Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies curies(final Links links) { // List<Link> curies = links.getLinksBy("curies"); // return curies(curies); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded embedded(final String rel, // final HalRepresentation embeddedItem) { // return new Embedded(singletonMap(rel, embeddedItem)); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded emptyEmbedded() { // return new Embedded(null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link curi(final String name, final String relTemplate) { // if (!relTemplate.contains("{rel}")) { // throw new IllegalArgumentException("Not a CURI template. Template is required to contain a {rel} placeholder"); // } // return new Link("curies", relTemplate, null, null, null, name, null, null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // } // Path: src/test/java/de/otto/edison/hal/HalRepresentationCuriesTest.java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import static de.otto.edison.hal.Curies.curies; import static de.otto.edison.hal.Embedded.embedded; import static de.otto.edison.hal.Embedded.emptyEmbedded; import static de.otto.edison.hal.Link.curi; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Links.emptyLinks; import static de.otto.edison.hal.Links.linkingTo; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; package de.otto.edison.hal; public class HalRepresentationCuriesTest { @Test public void shouldRenderSingleCuriAsArray() throws JsonProcessingException { // given final HalRepresentation representation = new HalRepresentation(
linkingTo()
otto-de/edison-hal
src/test/java/de/otto/edison/hal/HalRepresentationCuriesTest.java
// Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies curies(final Links links) { // List<Link> curies = links.getLinksBy("curies"); // return curies(curies); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded embedded(final String rel, // final HalRepresentation embeddedItem) { // return new Embedded(singletonMap(rel, embeddedItem)); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded emptyEmbedded() { // return new Embedded(null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link curi(final String name, final String relTemplate) { // if (!relTemplate.contains("{rel}")) { // throw new IllegalArgumentException("Not a CURI template. Template is required to contain a {rel} placeholder"); // } // return new Link("curies", relTemplate, null, null, null, name, null, null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // }
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import static de.otto.edison.hal.Curies.curies; import static de.otto.edison.hal.Embedded.embedded; import static de.otto.edison.hal.Embedded.emptyEmbedded; import static de.otto.edison.hal.Link.curi; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Links.emptyLinks; import static de.otto.edison.hal.Links.linkingTo; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*;
package de.otto.edison.hal; public class HalRepresentationCuriesTest { @Test public void shouldRenderSingleCuriAsArray() throws JsonProcessingException { // given final HalRepresentation representation = new HalRepresentation( linkingTo()
// Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies curies(final Links links) { // List<Link> curies = links.getLinksBy("curies"); // return curies(curies); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded embedded(final String rel, // final HalRepresentation embeddedItem) { // return new Embedded(singletonMap(rel, embeddedItem)); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded emptyEmbedded() { // return new Embedded(null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link curi(final String name, final String relTemplate) { // if (!relTemplate.contains("{rel}")) { // throw new IllegalArgumentException("Not a CURI template. Template is required to contain a {rel} placeholder"); // } // return new Link("curies", relTemplate, null, null, null, name, null, null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // } // Path: src/test/java/de/otto/edison/hal/HalRepresentationCuriesTest.java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import static de.otto.edison.hal.Curies.curies; import static de.otto.edison.hal.Embedded.embedded; import static de.otto.edison.hal.Embedded.emptyEmbedded; import static de.otto.edison.hal.Link.curi; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Links.emptyLinks; import static de.otto.edison.hal.Links.linkingTo; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; package de.otto.edison.hal; public class HalRepresentationCuriesTest { @Test public void shouldRenderSingleCuriAsArray() throws JsonProcessingException { // given final HalRepresentation representation = new HalRepresentation( linkingTo()
.curi("x", "http://example.org/rels/{rel}")
otto-de/edison-hal
src/test/java/de/otto/edison/hal/HalRepresentationCuriesTest.java
// Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies curies(final Links links) { // List<Link> curies = links.getLinksBy("curies"); // return curies(curies); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded embedded(final String rel, // final HalRepresentation embeddedItem) { // return new Embedded(singletonMap(rel, embeddedItem)); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded emptyEmbedded() { // return new Embedded(null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link curi(final String name, final String relTemplate) { // if (!relTemplate.contains("{rel}")) { // throw new IllegalArgumentException("Not a CURI template. Template is required to contain a {rel} placeholder"); // } // return new Link("curies", relTemplate, null, null, null, name, null, null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // }
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import static de.otto.edison.hal.Curies.curies; import static de.otto.edison.hal.Embedded.embedded; import static de.otto.edison.hal.Embedded.emptyEmbedded; import static de.otto.edison.hal.Link.curi; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Links.emptyLinks; import static de.otto.edison.hal.Links.linkingTo; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*;
package de.otto.edison.hal; public class HalRepresentationCuriesTest { @Test public void shouldRenderSingleCuriAsArray() throws JsonProcessingException { // given final HalRepresentation representation = new HalRepresentation( linkingTo() .curi("x", "http://example.org/rels/{rel}") .single(
// Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies curies(final Links links) { // List<Link> curies = links.getLinksBy("curies"); // return curies(curies); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded embedded(final String rel, // final HalRepresentation embeddedItem) { // return new Embedded(singletonMap(rel, embeddedItem)); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded emptyEmbedded() { // return new Embedded(null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link curi(final String name, final String relTemplate) { // if (!relTemplate.contains("{rel}")) { // throw new IllegalArgumentException("Not a CURI template. Template is required to contain a {rel} placeholder"); // } // return new Link("curies", relTemplate, null, null, null, name, null, null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // } // Path: src/test/java/de/otto/edison/hal/HalRepresentationCuriesTest.java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import static de.otto.edison.hal.Curies.curies; import static de.otto.edison.hal.Embedded.embedded; import static de.otto.edison.hal.Embedded.emptyEmbedded; import static de.otto.edison.hal.Link.curi; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Links.emptyLinks; import static de.otto.edison.hal.Links.linkingTo; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; package de.otto.edison.hal; public class HalRepresentationCuriesTest { @Test public void shouldRenderSingleCuriAsArray() throws JsonProcessingException { // given final HalRepresentation representation = new HalRepresentation( linkingTo() .curi("x", "http://example.org/rels/{rel}") .single(
link("x:foo", "http://example.org/test"),
otto-de/edison-hal
src/test/java/de/otto/edison/hal/HalRepresentationCuriesTest.java
// Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies curies(final Links links) { // List<Link> curies = links.getLinksBy("curies"); // return curies(curies); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded embedded(final String rel, // final HalRepresentation embeddedItem) { // return new Embedded(singletonMap(rel, embeddedItem)); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded emptyEmbedded() { // return new Embedded(null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link curi(final String name, final String relTemplate) { // if (!relTemplate.contains("{rel}")) { // throw new IllegalArgumentException("Not a CURI template. Template is required to contain a {rel} placeholder"); // } // return new Link("curies", relTemplate, null, null, null, name, null, null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // }
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import static de.otto.edison.hal.Curies.curies; import static de.otto.edison.hal.Embedded.embedded; import static de.otto.edison.hal.Embedded.emptyEmbedded; import static de.otto.edison.hal.Link.curi; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Links.emptyLinks; import static de.otto.edison.hal.Links.linkingTo; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*;
package de.otto.edison.hal; public class HalRepresentationCuriesTest { @Test public void shouldRenderSingleCuriAsArray() throws JsonProcessingException { // given final HalRepresentation representation = new HalRepresentation( linkingTo() .curi("x", "http://example.org/rels/{rel}") .single( link("x:foo", "http://example.org/test"), link("x:bar", "http://example.org/test")) .build() ); // when final String json = new ObjectMapper().writeValueAsString(representation); // then
// Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies curies(final Links links) { // List<Link> curies = links.getLinksBy("curies"); // return curies(curies); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded embedded(final String rel, // final HalRepresentation embeddedItem) { // return new Embedded(singletonMap(rel, embeddedItem)); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded emptyEmbedded() { // return new Embedded(null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link curi(final String name, final String relTemplate) { // if (!relTemplate.contains("{rel}")) { // throw new IllegalArgumentException("Not a CURI template. Template is required to contain a {rel} placeholder"); // } // return new Link("curies", relTemplate, null, null, null, name, null, null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // } // Path: src/test/java/de/otto/edison/hal/HalRepresentationCuriesTest.java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import static de.otto.edison.hal.Curies.curies; import static de.otto.edison.hal.Embedded.embedded; import static de.otto.edison.hal.Embedded.emptyEmbedded; import static de.otto.edison.hal.Link.curi; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Links.emptyLinks; import static de.otto.edison.hal.Links.linkingTo; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; package de.otto.edison.hal; public class HalRepresentationCuriesTest { @Test public void shouldRenderSingleCuriAsArray() throws JsonProcessingException { // given final HalRepresentation representation = new HalRepresentation( linkingTo() .curi("x", "http://example.org/rels/{rel}") .single( link("x:foo", "http://example.org/test"), link("x:bar", "http://example.org/test")) .build() ); // when final String json = new ObjectMapper().writeValueAsString(representation); // then
assertThat(json, is("{\"_links\":{\"curies\":[{\"href\":\"http://example.org/rels/{rel}\",\"templated\":true,\"name\":\"x\"}],\"x:foo\":{\"href\":\"http://example.org/test\"},\"x:bar\":{\"href\":\"http://example.org/test\"}}}"));
otto-de/edison-hal
src/test/java/de/otto/edison/hal/HalRepresentationCuriesTest.java
// Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies curies(final Links links) { // List<Link> curies = links.getLinksBy("curies"); // return curies(curies); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded embedded(final String rel, // final HalRepresentation embeddedItem) { // return new Embedded(singletonMap(rel, embeddedItem)); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded emptyEmbedded() { // return new Embedded(null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link curi(final String name, final String relTemplate) { // if (!relTemplate.contains("{rel}")) { // throw new IllegalArgumentException("Not a CURI template. Template is required to contain a {rel} placeholder"); // } // return new Link("curies", relTemplate, null, null, null, name, null, null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // }
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import static de.otto.edison.hal.Curies.curies; import static de.otto.edison.hal.Embedded.embedded; import static de.otto.edison.hal.Embedded.emptyEmbedded; import static de.otto.edison.hal.Link.curi; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Links.emptyLinks; import static de.otto.edison.hal.Links.linkingTo; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*;
.curi("x", "http://example.org/rels/{rel}") .curi("y", "http://example.com/rels/{rel}") .single(link("x:foo", "http://example.org/test")) .single(link("y:bar", "http://example.org/test")) .build() ); // when final String json = new ObjectMapper().writeValueAsString(representation); // then assertThat(json, is("{\"_links\":{\"curies\":[{\"href\":\"http://example.org/rels/{rel}\",\"templated\":true,\"name\":\"x\"},{\"href\":\"http://example.com/rels/{rel}\",\"templated\":true,\"name\":\"y\"}],\"x:foo\":{\"href\":\"http://example.org/test\"},\"y:bar\":{\"href\":\"http://example.org/test\"}}}")); } @Test public void shouldReplaceFullRelWithCuri() throws JsonProcessingException { // given final HalRepresentation representation = new HalRepresentation( linkingTo() .curi("x", "http://example.org/rels/{rel}") .single(link("http://example.org/rels/foo", "http://example.org/test")) .build() ); // when final String json = new ObjectMapper().writeValueAsString(representation); // then assertThat(json, is("{\"_links\":{\"curies\":[{\"href\":\"http://example.org/rels/{rel}\",\"templated\":true,\"name\":\"x\"}],\"x:foo\":{\"href\":\"http://example.org/test\"}}}")); } @Test public void shouldConstructWithCuries() { final Curies curies = curies(asList(curi("x", "http://example.com/rels/{rel}")));
// Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies curies(final Links links) { // List<Link> curies = links.getLinksBy("curies"); // return curies(curies); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded embedded(final String rel, // final HalRepresentation embeddedItem) { // return new Embedded(singletonMap(rel, embeddedItem)); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded emptyEmbedded() { // return new Embedded(null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link curi(final String name, final String relTemplate) { // if (!relTemplate.contains("{rel}")) { // throw new IllegalArgumentException("Not a CURI template. Template is required to contain a {rel} placeholder"); // } // return new Link("curies", relTemplate, null, null, null, name, null, null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // } // Path: src/test/java/de/otto/edison/hal/HalRepresentationCuriesTest.java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import static de.otto.edison.hal.Curies.curies; import static de.otto.edison.hal.Embedded.embedded; import static de.otto.edison.hal.Embedded.emptyEmbedded; import static de.otto.edison.hal.Link.curi; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Links.emptyLinks; import static de.otto.edison.hal.Links.linkingTo; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; .curi("x", "http://example.org/rels/{rel}") .curi("y", "http://example.com/rels/{rel}") .single(link("x:foo", "http://example.org/test")) .single(link("y:bar", "http://example.org/test")) .build() ); // when final String json = new ObjectMapper().writeValueAsString(representation); // then assertThat(json, is("{\"_links\":{\"curies\":[{\"href\":\"http://example.org/rels/{rel}\",\"templated\":true,\"name\":\"x\"},{\"href\":\"http://example.com/rels/{rel}\",\"templated\":true,\"name\":\"y\"}],\"x:foo\":{\"href\":\"http://example.org/test\"},\"y:bar\":{\"href\":\"http://example.org/test\"}}}")); } @Test public void shouldReplaceFullRelWithCuri() throws JsonProcessingException { // given final HalRepresentation representation = new HalRepresentation( linkingTo() .curi("x", "http://example.org/rels/{rel}") .single(link("http://example.org/rels/foo", "http://example.org/test")) .build() ); // when final String json = new ObjectMapper().writeValueAsString(representation); // then assertThat(json, is("{\"_links\":{\"curies\":[{\"href\":\"http://example.org/rels/{rel}\",\"templated\":true,\"name\":\"x\"}],\"x:foo\":{\"href\":\"http://example.org/test\"}}}")); } @Test public void shouldConstructWithCuries() { final Curies curies = curies(asList(curi("x", "http://example.com/rels/{rel}")));
final HalRepresentation hal = new HalRepresentation(emptyLinks(), emptyEmbedded(), curies);
otto-de/edison-hal
src/test/java/de/otto/edison/hal/HalRepresentationCuriesTest.java
// Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies curies(final Links links) { // List<Link> curies = links.getLinksBy("curies"); // return curies(curies); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded embedded(final String rel, // final HalRepresentation embeddedItem) { // return new Embedded(singletonMap(rel, embeddedItem)); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded emptyEmbedded() { // return new Embedded(null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link curi(final String name, final String relTemplate) { // if (!relTemplate.contains("{rel}")) { // throw new IllegalArgumentException("Not a CURI template. Template is required to contain a {rel} placeholder"); // } // return new Link("curies", relTemplate, null, null, null, name, null, null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // }
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import static de.otto.edison.hal.Curies.curies; import static de.otto.edison.hal.Embedded.embedded; import static de.otto.edison.hal.Embedded.emptyEmbedded; import static de.otto.edison.hal.Link.curi; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Links.emptyLinks; import static de.otto.edison.hal.Links.linkingTo; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*;
.curi("x", "http://example.org/rels/{rel}") .curi("y", "http://example.com/rels/{rel}") .single(link("x:foo", "http://example.org/test")) .single(link("y:bar", "http://example.org/test")) .build() ); // when final String json = new ObjectMapper().writeValueAsString(representation); // then assertThat(json, is("{\"_links\":{\"curies\":[{\"href\":\"http://example.org/rels/{rel}\",\"templated\":true,\"name\":\"x\"},{\"href\":\"http://example.com/rels/{rel}\",\"templated\":true,\"name\":\"y\"}],\"x:foo\":{\"href\":\"http://example.org/test\"},\"y:bar\":{\"href\":\"http://example.org/test\"}}}")); } @Test public void shouldReplaceFullRelWithCuri() throws JsonProcessingException { // given final HalRepresentation representation = new HalRepresentation( linkingTo() .curi("x", "http://example.org/rels/{rel}") .single(link("http://example.org/rels/foo", "http://example.org/test")) .build() ); // when final String json = new ObjectMapper().writeValueAsString(representation); // then assertThat(json, is("{\"_links\":{\"curies\":[{\"href\":\"http://example.org/rels/{rel}\",\"templated\":true,\"name\":\"x\"}],\"x:foo\":{\"href\":\"http://example.org/test\"}}}")); } @Test public void shouldConstructWithCuries() { final Curies curies = curies(asList(curi("x", "http://example.com/rels/{rel}")));
// Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies curies(final Links links) { // List<Link> curies = links.getLinksBy("curies"); // return curies(curies); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded embedded(final String rel, // final HalRepresentation embeddedItem) { // return new Embedded(singletonMap(rel, embeddedItem)); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded emptyEmbedded() { // return new Embedded(null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link curi(final String name, final String relTemplate) { // if (!relTemplate.contains("{rel}")) { // throw new IllegalArgumentException("Not a CURI template. Template is required to contain a {rel} placeholder"); // } // return new Link("curies", relTemplate, null, null, null, name, null, null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // } // Path: src/test/java/de/otto/edison/hal/HalRepresentationCuriesTest.java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import static de.otto.edison.hal.Curies.curies; import static de.otto.edison.hal.Embedded.embedded; import static de.otto.edison.hal.Embedded.emptyEmbedded; import static de.otto.edison.hal.Link.curi; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Links.emptyLinks; import static de.otto.edison.hal.Links.linkingTo; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; .curi("x", "http://example.org/rels/{rel}") .curi("y", "http://example.com/rels/{rel}") .single(link("x:foo", "http://example.org/test")) .single(link("y:bar", "http://example.org/test")) .build() ); // when final String json = new ObjectMapper().writeValueAsString(representation); // then assertThat(json, is("{\"_links\":{\"curies\":[{\"href\":\"http://example.org/rels/{rel}\",\"templated\":true,\"name\":\"x\"},{\"href\":\"http://example.com/rels/{rel}\",\"templated\":true,\"name\":\"y\"}],\"x:foo\":{\"href\":\"http://example.org/test\"},\"y:bar\":{\"href\":\"http://example.org/test\"}}}")); } @Test public void shouldReplaceFullRelWithCuri() throws JsonProcessingException { // given final HalRepresentation representation = new HalRepresentation( linkingTo() .curi("x", "http://example.org/rels/{rel}") .single(link("http://example.org/rels/foo", "http://example.org/test")) .build() ); // when final String json = new ObjectMapper().writeValueAsString(representation); // then assertThat(json, is("{\"_links\":{\"curies\":[{\"href\":\"http://example.org/rels/{rel}\",\"templated\":true,\"name\":\"x\"}],\"x:foo\":{\"href\":\"http://example.org/test\"}}}")); } @Test public void shouldConstructWithCuries() { final Curies curies = curies(asList(curi("x", "http://example.com/rels/{rel}")));
final HalRepresentation hal = new HalRepresentation(emptyLinks(), emptyEmbedded(), curies);
otto-de/edison-hal
src/test/java/de/otto/edison/hal/HalRepresentationCuriesTest.java
// Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies curies(final Links links) { // List<Link> curies = links.getLinksBy("curies"); // return curies(curies); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded embedded(final String rel, // final HalRepresentation embeddedItem) { // return new Embedded(singletonMap(rel, embeddedItem)); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded emptyEmbedded() { // return new Embedded(null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link curi(final String name, final String relTemplate) { // if (!relTemplate.contains("{rel}")) { // throw new IllegalArgumentException("Not a CURI template. Template is required to contain a {rel} placeholder"); // } // return new Link("curies", relTemplate, null, null, null, name, null, null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // }
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import static de.otto.edison.hal.Curies.curies; import static de.otto.edison.hal.Embedded.embedded; import static de.otto.edison.hal.Embedded.emptyEmbedded; import static de.otto.edison.hal.Link.curi; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Links.emptyLinks; import static de.otto.edison.hal.Links.linkingTo; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*;
// when final String json = new ObjectMapper().writeValueAsString(representation); // then assertThat(json, is("{\"_links\":{\"curies\":[{\"href\":\"http://example.org/rels/{rel}\",\"templated\":true,\"name\":\"x\"}],\"x:foo\":{\"href\":\"http://example.org/test\"}}}")); } @Test public void shouldConstructWithCuries() { final Curies curies = curies(asList(curi("x", "http://example.com/rels/{rel}"))); final HalRepresentation hal = new HalRepresentation(emptyLinks(), emptyEmbedded(), curies); assertThat(hal.getCuries().resolve("http://example.com/rels/foo"), is("x:foo")); } @Test public void shouldConstructWithLinksAndCuries() { final Curies curies = curies(asList(curi("x", "http://example.com/rels/{rel}"))); final HalRepresentation hal = new HalRepresentation( linkingTo().single(link("http://example.com/rels/foo", "http://example.com")).build(), emptyEmbedded(), curies); assertThat(hal.getLinks().getRels(), contains("x:foo")); assertThat(hal.getLinks().getLinkBy("x:foo").isPresent(), is(true)); assertThat(hal.getLinks().getLinkBy("http://example.com/rels/foo").isPresent(), is(true)); } @Test public void shouldConstructWithEmbeddedAndCuries() { final Curies curies = curies(asList(curi("x", "http://example.com/rels/{rel}"))); final HalRepresentation hal = new HalRepresentation( emptyLinks(),
// Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies curies(final Links links) { // List<Link> curies = links.getLinksBy("curies"); // return curies(curies); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded embedded(final String rel, // final HalRepresentation embeddedItem) { // return new Embedded(singletonMap(rel, embeddedItem)); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded emptyEmbedded() { // return new Embedded(null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link curi(final String name, final String relTemplate) { // if (!relTemplate.contains("{rel}")) { // throw new IllegalArgumentException("Not a CURI template. Template is required to contain a {rel} placeholder"); // } // return new Link("curies", relTemplate, null, null, null, name, null, null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // } // Path: src/test/java/de/otto/edison/hal/HalRepresentationCuriesTest.java import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import static de.otto.edison.hal.Curies.curies; import static de.otto.edison.hal.Embedded.embedded; import static de.otto.edison.hal.Embedded.emptyEmbedded; import static de.otto.edison.hal.Link.curi; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Links.emptyLinks; import static de.otto.edison.hal.Links.linkingTo; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; // when final String json = new ObjectMapper().writeValueAsString(representation); // then assertThat(json, is("{\"_links\":{\"curies\":[{\"href\":\"http://example.org/rels/{rel}\",\"templated\":true,\"name\":\"x\"}],\"x:foo\":{\"href\":\"http://example.org/test\"}}}")); } @Test public void shouldConstructWithCuries() { final Curies curies = curies(asList(curi("x", "http://example.com/rels/{rel}"))); final HalRepresentation hal = new HalRepresentation(emptyLinks(), emptyEmbedded(), curies); assertThat(hal.getCuries().resolve("http://example.com/rels/foo"), is("x:foo")); } @Test public void shouldConstructWithLinksAndCuries() { final Curies curies = curies(asList(curi("x", "http://example.com/rels/{rel}"))); final HalRepresentation hal = new HalRepresentation( linkingTo().single(link("http://example.com/rels/foo", "http://example.com")).build(), emptyEmbedded(), curies); assertThat(hal.getLinks().getRels(), contains("x:foo")); assertThat(hal.getLinks().getLinkBy("x:foo").isPresent(), is(true)); assertThat(hal.getLinks().getLinkBy("http://example.com/rels/foo").isPresent(), is(true)); } @Test public void shouldConstructWithEmbeddedAndCuries() { final Curies curies = curies(asList(curi("x", "http://example.com/rels/{rel}"))); final HalRepresentation hal = new HalRepresentation( emptyLinks(),
embedded(
otto-de/edison-hal
src/main/java/de/otto/edison/hal/Curies.java
// Path: src/main/java/de/otto/edison/hal/CuriTemplate.java // public static Optional<CuriTemplate> matchingCuriTemplateFor(final List<Link> curies, final String rel) { // return curies // .stream() // .map(CuriTemplate::curiTemplateFor) // .filter(t->t.isMatching(rel)) // .findAny(); // }
import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; import static de.otto.edison.hal.CuriTemplate.matchingCuriTemplateFor;
final boolean alreadyRegistered = curies .stream() .anyMatch(link -> link.getHref().equals(curi.getHref())); if (alreadyRegistered) { curies.removeIf(link -> link.getName().equals(curi.getName())); curies.replaceAll(link -> link.getName().equals(curi.getName()) ? curi : link); } curies.add(curi); } /** * Merges this Curies with another instance of Curies and returns the merged instance. * * @param other merged Curies * @return a merged copy of this and other */ public Curies mergeWith(final Curies other) { final Curies merged = copyOf(this); other.curies.forEach(merged::register); return merged; } /** * Resolves a link-relation type (curied or full rel) and returns the curied form, or * the unchanged rel, if no matching CURI is registered. * * @param rel link-relation type * @return curied link-relation type */ public String resolve(final String rel) {
// Path: src/main/java/de/otto/edison/hal/CuriTemplate.java // public static Optional<CuriTemplate> matchingCuriTemplateFor(final List<Link> curies, final String rel) { // return curies // .stream() // .map(CuriTemplate::curiTemplateFor) // .filter(t->t.isMatching(rel)) // .findAny(); // } // Path: src/main/java/de/otto/edison/hal/Curies.java import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; import static de.otto.edison.hal.CuriTemplate.matchingCuriTemplateFor; final boolean alreadyRegistered = curies .stream() .anyMatch(link -> link.getHref().equals(curi.getHref())); if (alreadyRegistered) { curies.removeIf(link -> link.getName().equals(curi.getName())); curies.replaceAll(link -> link.getName().equals(curi.getName()) ? curi : link); } curies.add(curi); } /** * Merges this Curies with another instance of Curies and returns the merged instance. * * @param other merged Curies * @return a merged copy of this and other */ public Curies mergeWith(final Curies other) { final Curies merged = copyOf(this); other.curies.forEach(merged::register); return merged; } /** * Resolves a link-relation type (curied or full rel) and returns the curied form, or * the unchanged rel, if no matching CURI is registered. * * @param rel link-relation type * @return curied link-relation type */ public String resolve(final String rel) {
final Optional<CuriTemplate> curiTemplate = matchingCuriTemplateFor(curies, rel);
otto-de/edison-hal
src/main/java/de/otto/edison/hal/Embedded.java
// Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies emptyCuries() { // return new Curies(); // }
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import java.io.IOException; import java.util.*; import static de.otto.edison.hal.Curies.emptyCuries; import static java.util.Collections.*; import static java.util.stream.Collectors.toList;
package de.otto.edison.hal; /** * <p> * The embedded items of a HalResource. * </p> * <pre><code> * { * "_links": { * ... * }, * "_embedded": { * "item" : [ * {"description" : "first embedded item (resource object)"}, * {"description" : "second embedded item (resource object"} * ], * "example" : { * "description" : "A single resource object" * } * }, * "someAttribute" : "Foo" * } * </code></pre> * * @see <a href="https://tools.ietf.org/html/draft-kelly-json-hal-08#section-4.1.2">draft-kelly-json-hal-08#section-4.1.2</a> * @since 0.1.0 */ @JsonSerialize(using = Embedded.EmbeddedSerializer.class) @JsonDeserialize(using = Embedded.EmbeddedDeserializer.class) public class Embedded { /** * The embedded items, mapped by link-relation type. * * <p> * The values are either List&lt;HalRepresentation&gt; or single HalRepresentation instances. * </p> */ private final Map<String,Object> items; /** * The Curies instance used to resolve curies */ private final Curies curies; /** * Used by Jackson to parse/create Embedded instances. * * @since 0.1.0 */ Embedded() { items = null;
// Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies emptyCuries() { // return new Curies(); // } // Path: src/main/java/de/otto/edison/hal/Embedded.java import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import java.io.IOException; import java.util.*; import static de.otto.edison.hal.Curies.emptyCuries; import static java.util.Collections.*; import static java.util.stream.Collectors.toList; package de.otto.edison.hal; /** * <p> * The embedded items of a HalResource. * </p> * <pre><code> * { * "_links": { * ... * }, * "_embedded": { * "item" : [ * {"description" : "first embedded item (resource object)"}, * {"description" : "second embedded item (resource object"} * ], * "example" : { * "description" : "A single resource object" * } * }, * "someAttribute" : "Foo" * } * </code></pre> * * @see <a href="https://tools.ietf.org/html/draft-kelly-json-hal-08#section-4.1.2">draft-kelly-json-hal-08#section-4.1.2</a> * @since 0.1.0 */ @JsonSerialize(using = Embedded.EmbeddedSerializer.class) @JsonDeserialize(using = Embedded.EmbeddedDeserializer.class) public class Embedded { /** * The embedded items, mapped by link-relation type. * * <p> * The values are either List&lt;HalRepresentation&gt; or single HalRepresentation instances. * </p> */ private final Map<String,Object> items; /** * The Curies instance used to resolve curies */ private final Curies curies; /** * Used by Jackson to parse/create Embedded instances. * * @since 0.1.0 */ Embedded() { items = null;
curies = emptyCuries();
otto-de/edison-hal
src/test/java/de/otto/edison/hal/HalRepresentationTest.java
// Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded emptyEmbedded() { // return new Embedded(null); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // }
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; import static de.otto.edison.hal.Embedded.emptyEmbedded; import static de.otto.edison.hal.Links.linkingTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
package de.otto.edison.hal; public class HalRepresentationTest { @Test public void shouldRenderNullAttributes() throws JsonProcessingException { // given final HalRepresentation representation = new HalRepresentation(
// Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded emptyEmbedded() { // return new Embedded(null); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // } // Path: src/test/java/de/otto/edison/hal/HalRepresentationTest.java import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; import static de.otto.edison.hal.Embedded.emptyEmbedded; import static de.otto.edison.hal.Links.linkingTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; package de.otto.edison.hal; public class HalRepresentationTest { @Test public void shouldRenderNullAttributes() throws JsonProcessingException { // given final HalRepresentation representation = new HalRepresentation(
linkingTo().self("http://example.org/test/bar").build(),
otto-de/edison-hal
src/test/java/de/otto/edison/hal/HalRepresentationTest.java
// Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded emptyEmbedded() { // return new Embedded(null); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // }
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; import static de.otto.edison.hal.Embedded.emptyEmbedded; import static de.otto.edison.hal.Links.linkingTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
package de.otto.edison.hal; public class HalRepresentationTest { @Test public void shouldRenderNullAttributes() throws JsonProcessingException { // given final HalRepresentation representation = new HalRepresentation( linkingTo().self("http://example.org/test/bar").build(),
// Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded emptyEmbedded() { // return new Embedded(null); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // } // Path: src/test/java/de/otto/edison/hal/HalRepresentationTest.java import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; import static de.otto.edison.hal.Embedded.emptyEmbedded; import static de.otto.edison.hal.Links.linkingTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; package de.otto.edison.hal; public class HalRepresentationTest { @Test public void shouldRenderNullAttributes() throws JsonProcessingException { // given final HalRepresentation representation = new HalRepresentation( linkingTo().self("http://example.org/test/bar").build(),
emptyEmbedded())
otto-de/edison-hal
src/main/java/de/otto/edison/hal/Links.java
// Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies emptyCuries() { // return new Curies(); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Builder linkBuilder(final String rel, final String href) { // return new Builder(rel, href); // }
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import java.io.IOException; import java.util.*; import java.util.function.Predicate; import java.util.stream.Stream; import static de.otto.edison.hal.Curies.emptyCuries; import static de.otto.edison.hal.Link.linkBuilder; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap;
package de.otto.edison.hal; /** * Representation of a number of HAL _links. * <p> * Links can be created using the {@link Links.Builder} using the factory-method {@link Links#linkingTo()}: * </p> * <pre><code> * final Links someLinks = Links.linkingTo() * .self("http://example.com/shopping-cart/42") * .curi("ex", "http://example.com/rels/{rel}") * .item("http://example.com/products/1"), * .item("http://example.com/products/2"), * .single( * Link.link("ex:customer", "http://example.com/customers/4711")) * .build() * * </code></pre> * * @see <a href="https://tools.ietf.org/html/draft-kelly-json-hal-08#section-4.1.1">draft-kelly-json-hal-08#section-4.1.1</a> * @since 0.1.0 */ @JsonSerialize(using = Links.LinksSerializer.class) @JsonDeserialize(using = Links.LinksDeserializer.class) public class Links { private static final String CURIES_REL = "curies"; private final Map<String, Object> links = new LinkedHashMap<>(); private final Curies curies; /** * * @since 0.1.0 */ Links() {
// Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies emptyCuries() { // return new Curies(); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Builder linkBuilder(final String rel, final String href) { // return new Builder(rel, href); // } // Path: src/main/java/de/otto/edison/hal/Links.java import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import java.io.IOException; import java.util.*; import java.util.function.Predicate; import java.util.stream.Stream; import static de.otto.edison.hal.Curies.emptyCuries; import static de.otto.edison.hal.Link.linkBuilder; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; package de.otto.edison.hal; /** * Representation of a number of HAL _links. * <p> * Links can be created using the {@link Links.Builder} using the factory-method {@link Links#linkingTo()}: * </p> * <pre><code> * final Links someLinks = Links.linkingTo() * .self("http://example.com/shopping-cart/42") * .curi("ex", "http://example.com/rels/{rel}") * .item("http://example.com/products/1"), * .item("http://example.com/products/2"), * .single( * Link.link("ex:customer", "http://example.com/customers/4711")) * .build() * * </code></pre> * * @see <a href="https://tools.ietf.org/html/draft-kelly-json-hal-08#section-4.1.1">draft-kelly-json-hal-08#section-4.1.1</a> * @since 0.1.0 */ @JsonSerialize(using = Links.LinksSerializer.class) @JsonDeserialize(using = Links.LinksDeserializer.class) public class Links { private static final String CURIES_REL = "curies"; private final Map<String, Object> links = new LinkedHashMap<>(); private final Curies curies; /** * * @since 0.1.0 */ Links() {
this.curies = emptyCuries();
otto-de/edison-hal
src/main/java/de/otto/edison/hal/Links.java
// Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies emptyCuries() { // return new Curies(); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Builder linkBuilder(final String rel, final String href) { // return new Builder(rel, href); // }
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import java.io.IOException; import java.util.*; import java.util.function.Predicate; import java.util.stream.Stream; import static de.otto.edison.hal.Curies.emptyCuries; import static de.otto.edison.hal.Link.linkBuilder; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap;
emptyCuries() ); } private void fixPossibleIssueWithCuriesAsSingleLinkObject(Map<String, Object> links) { // CURIES should always have a List of Links. Because this might not aways be the case, we have to fix this: if (links.containsKey(CURIES_REL)) { if (links.get(CURIES_REL) instanceof Link) { links.put(CURIES_REL, new ArrayList<Link>() {{ add((Link) links.get(CURIES_REL)); }}); } } } @SuppressWarnings({"unchecked", "rawtypes"}) private Object asArrayOrObject(final String rel, final Object value) { if (value instanceof Map) { return asLink(rel, (Map)value); } else { try { return ((List<Map>) value).stream().map(o -> asLink(rel, o)).collect(toList()); } catch (final ClassCastException e) { throw new IllegalStateException("Expected a single Link or a List of Links: rel=" + rel + " value=" + value); } } } @SuppressWarnings("rawtypes") private Link asLink(final String rel, final Map value) {
// Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies emptyCuries() { // return new Curies(); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Builder linkBuilder(final String rel, final String href) { // return new Builder(rel, href); // } // Path: src/main/java/de/otto/edison/hal/Links.java import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import java.io.IOException; import java.util.*; import java.util.function.Predicate; import java.util.stream.Stream; import static de.otto.edison.hal.Curies.emptyCuries; import static de.otto.edison.hal.Link.linkBuilder; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; emptyCuries() ); } private void fixPossibleIssueWithCuriesAsSingleLinkObject(Map<String, Object> links) { // CURIES should always have a List of Links. Because this might not aways be the case, we have to fix this: if (links.containsKey(CURIES_REL)) { if (links.get(CURIES_REL) instanceof Link) { links.put(CURIES_REL, new ArrayList<Link>() {{ add((Link) links.get(CURIES_REL)); }}); } } } @SuppressWarnings({"unchecked", "rawtypes"}) private Object asArrayOrObject(final String rel, final Object value) { if (value instanceof Map) { return asLink(rel, (Map)value); } else { try { return ((List<Map>) value).stream().map(o -> asLink(rel, o)).collect(toList()); } catch (final ClassCastException e) { throw new IllegalStateException("Expected a single Link or a List of Links: rel=" + rel + " value=" + value); } } } @SuppressWarnings("rawtypes") private Link asLink(final String rel, final Map value) {
Link.Builder builder = linkBuilder(rel, value.get("href").toString())
otto-de/edison-hal
src/main/java/de/otto/edison/hal/traverson/Traverson.java
// Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/HalParser.java // public static HalParser parse(final String json) { // return new HalParser(json, DEFAULT_JSON_MAPPER); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Builder copyOf(final Link prototype) { // return new Builder(prototype.rel, prototype.href) // .withType(prototype.type) // .withProfile(prototype.profile) // .withTitle(prototype.title) // .withName(prototype.name) // .withDeprecation(prototype.deprecation) // .withHrefLang(prototype.hreflang); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/LinkPredicates.java // public static Predicate<Link> always() { // return link -> true; // }
import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonPointer; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import de.otto.edison.hal.*; import org.slf4j.Logger; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import static com.damnhandy.uri.template.UriTemplate.fromTemplate; import static com.fasterxml.jackson.databind.DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.HalParser.parse; import static de.otto.edison.hal.Link.copyOf; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.LinkPredicates.always; import static java.lang.String.format; import static java.util.Arrays.asList; import static java.util.Collections.*; import static java.util.Objects.requireNonNull; import static org.slf4j.LoggerFactory.getLogger;
} /** * Start traversal at the application/hal+json resource idenfied by {@code uri}. * * @param uri the {@code URI} of the initial HAL resource. * @return Traverson initialized with the {@link HalRepresentation} identified by {@code uri}. */ public Traverson startWith(final String uri) { startWith = hrefToUrl(uri); contextUrl = startWith; lastResult = null; return this; } /** * Start traversal at the given HAL resource. * * <p> * It is expected, that the HalRepresentation has an absolute 'self' link, or that all links to other * resources are absolute links. If this is not assured, {@link #startWith(URL, HalRepresentation)} must * be used, so relative links can be resolved. * </p> * * @param resource the initial HAL resource. * @return Traverson initialized with the specified {@link HalRepresentation}. */ public Traverson startWith(final HalRepresentation resource) { this.startWith = null; this.lastResult = singletonList(requireNonNull(resource));
// Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/HalParser.java // public static HalParser parse(final String json) { // return new HalParser(json, DEFAULT_JSON_MAPPER); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Builder copyOf(final Link prototype) { // return new Builder(prototype.rel, prototype.href) // .withType(prototype.type) // .withProfile(prototype.profile) // .withTitle(prototype.title) // .withName(prototype.name) // .withDeprecation(prototype.deprecation) // .withHrefLang(prototype.hreflang); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/LinkPredicates.java // public static Predicate<Link> always() { // return link -> true; // } // Path: src/main/java/de/otto/edison/hal/traverson/Traverson.java import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonPointer; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import de.otto.edison.hal.*; import org.slf4j.Logger; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import static com.damnhandy.uri.template.UriTemplate.fromTemplate; import static com.fasterxml.jackson.databind.DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.HalParser.parse; import static de.otto.edison.hal.Link.copyOf; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.LinkPredicates.always; import static java.lang.String.format; import static java.util.Arrays.asList; import static java.util.Collections.*; import static java.util.Objects.requireNonNull; import static org.slf4j.LoggerFactory.getLogger; } /** * Start traversal at the application/hal+json resource idenfied by {@code uri}. * * @param uri the {@code URI} of the initial HAL resource. * @return Traverson initialized with the {@link HalRepresentation} identified by {@code uri}. */ public Traverson startWith(final String uri) { startWith = hrefToUrl(uri); contextUrl = startWith; lastResult = null; return this; } /** * Start traversal at the given HAL resource. * * <p> * It is expected, that the HalRepresentation has an absolute 'self' link, or that all links to other * resources are absolute links. If this is not assured, {@link #startWith(URL, HalRepresentation)} must * be used, so relative links can be resolved. * </p> * * @param resource the initial HAL resource. * @return Traverson initialized with the specified {@link HalRepresentation}. */ public Traverson startWith(final HalRepresentation resource) { this.startWith = null; this.lastResult = singletonList(requireNonNull(resource));
Optional<Link> self = resource.getLinks().getLinkBy("self");
otto-de/edison-hal
src/main/java/de/otto/edison/hal/traverson/Traverson.java
// Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/HalParser.java // public static HalParser parse(final String json) { // return new HalParser(json, DEFAULT_JSON_MAPPER); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Builder copyOf(final Link prototype) { // return new Builder(prototype.rel, prototype.href) // .withType(prototype.type) // .withProfile(prototype.profile) // .withTitle(prototype.title) // .withName(prototype.name) // .withDeprecation(prototype.deprecation) // .withHrefLang(prototype.hreflang); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/LinkPredicates.java // public static Predicate<Link> always() { // return link -> true; // }
import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonPointer; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import de.otto.edison.hal.*; import org.slf4j.Logger; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import static com.damnhandy.uri.template.UriTemplate.fromTemplate; import static com.fasterxml.jackson.databind.DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.HalParser.parse; import static de.otto.edison.hal.Link.copyOf; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.LinkPredicates.always; import static java.lang.String.format; import static java.util.Arrays.asList; import static java.util.Collections.*; import static java.util.Objects.requireNonNull; import static org.slf4j.LoggerFactory.getLogger;
* can be called to get this URL. * </p> * * @param contextUrl URL of the Traverson's current context, used to resolve relative links * @param resource the initial HAL resource. * @return Traverson initialized with the specified {@link HalRepresentation} and {@code contextUrl}. * @since 1.0.0 */ public Traverson startWith(final URL contextUrl, final HalRepresentation resource) { this.startWith = null; this.contextUrl = requireNonNull(contextUrl); this.lastResult = singletonList(requireNonNull(resource)); return this; } /** * Follow the first {@link Link} of the current resource, selected by its link-relation type. * <p> * If the current node has {@link Embedded embedded} items with the specified {@code rel}, * these items are used instead of resolving the associated {@link Link}. * </p> * <p> * Sometimes, only a subset of a linked resource is embedded into the resource. In this case, * embedded items can be ignored by using {@link #followLink(String)} instead of this method. * </p> * * @param rel the link-relation type of the followed link * @return this */ public Traverson follow(final String rel) {
// Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/HalParser.java // public static HalParser parse(final String json) { // return new HalParser(json, DEFAULT_JSON_MAPPER); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Builder copyOf(final Link prototype) { // return new Builder(prototype.rel, prototype.href) // .withType(prototype.type) // .withProfile(prototype.profile) // .withTitle(prototype.title) // .withName(prototype.name) // .withDeprecation(prototype.deprecation) // .withHrefLang(prototype.hreflang); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/LinkPredicates.java // public static Predicate<Link> always() { // return link -> true; // } // Path: src/main/java/de/otto/edison/hal/traverson/Traverson.java import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonPointer; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import de.otto.edison.hal.*; import org.slf4j.Logger; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import static com.damnhandy.uri.template.UriTemplate.fromTemplate; import static com.fasterxml.jackson.databind.DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.HalParser.parse; import static de.otto.edison.hal.Link.copyOf; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.LinkPredicates.always; import static java.lang.String.format; import static java.util.Arrays.asList; import static java.util.Collections.*; import static java.util.Objects.requireNonNull; import static org.slf4j.LoggerFactory.getLogger; * can be called to get this URL. * </p> * * @param contextUrl URL of the Traverson's current context, used to resolve relative links * @param resource the initial HAL resource. * @return Traverson initialized with the specified {@link HalRepresentation} and {@code contextUrl}. * @since 1.0.0 */ public Traverson startWith(final URL contextUrl, final HalRepresentation resource) { this.startWith = null; this.contextUrl = requireNonNull(contextUrl); this.lastResult = singletonList(requireNonNull(resource)); return this; } /** * Follow the first {@link Link} of the current resource, selected by its link-relation type. * <p> * If the current node has {@link Embedded embedded} items with the specified {@code rel}, * these items are used instead of resolving the associated {@link Link}. * </p> * <p> * Sometimes, only a subset of a linked resource is embedded into the resource. In this case, * embedded items can be ignored by using {@link #followLink(String)} instead of this method. * </p> * * @param rel the link-relation type of the followed link * @return this */ public Traverson follow(final String rel) {
return follow(rel, always(), emptyMap());
otto-de/edison-hal
src/main/java/de/otto/edison/hal/traverson/Traverson.java
// Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/HalParser.java // public static HalParser parse(final String json) { // return new HalParser(json, DEFAULT_JSON_MAPPER); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Builder copyOf(final Link prototype) { // return new Builder(prototype.rel, prototype.href) // .withType(prototype.type) // .withProfile(prototype.profile) // .withTitle(prototype.title) // .withName(prototype.name) // .withDeprecation(prototype.deprecation) // .withHrefLang(prototype.hreflang); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/LinkPredicates.java // public static Predicate<Link> always() { // return link -> true; // }
import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonPointer; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import de.otto.edison.hal.*; import org.slf4j.Logger; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import static com.damnhandy.uri.template.UriTemplate.fromTemplate; import static com.fasterxml.jackson.databind.DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.HalParser.parse; import static de.otto.edison.hal.Link.copyOf; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.LinkPredicates.always; import static java.lang.String.format; import static java.util.Arrays.asList; import static java.util.Collections.*; import static java.util.Objects.requireNonNull; import static org.slf4j.LoggerFactory.getLogger;
#hops = N; N > 0 max nesting-level in embeddedTypeInfo = M; M >= 0 */ final Link initial = self(startWith.toString()); LOG.trace("Starting with {}", startWith); this.startWith = null; if (hops.isEmpty()) { /* 0. N=0, M=0: getResource(startwith, pageType) */ return singletonList( getResource(initial, resultType, embeddedTypeInfo) ); } else { final HalRepresentation firstHop; // Follow startWith URL, but have a look at the next hop, so we can parse the resource // with respect to pageType and embeddedTypeInfo: if (hops.size() == 1) { final Hop hop = hops.get(0); if (embeddedTypeInfo == null || embeddedTypeInfo.isEmpty()) { /* 1. N=1, M=0 (keine TypeInfos): Die zurückgegebene Representation soll vom Typ resultType sein. startWith könnte hop 0 embedden, oder es könnten zwei Resourcen angefragt werden. a) getResource(startwith, HalRepresentation.class, embeddedTypeInfo(hop-0-rel, pageType)) b) getResource(current, pageType) */
// Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/HalParser.java // public static HalParser parse(final String json) { // return new HalParser(json, DEFAULT_JSON_MAPPER); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Builder copyOf(final Link prototype) { // return new Builder(prototype.rel, prototype.href) // .withType(prototype.type) // .withProfile(prototype.profile) // .withTitle(prototype.title) // .withName(prototype.name) // .withDeprecation(prototype.deprecation) // .withHrefLang(prototype.hreflang); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/LinkPredicates.java // public static Predicate<Link> always() { // return link -> true; // } // Path: src/main/java/de/otto/edison/hal/traverson/Traverson.java import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonPointer; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import de.otto.edison.hal.*; import org.slf4j.Logger; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import static com.damnhandy.uri.template.UriTemplate.fromTemplate; import static com.fasterxml.jackson.databind.DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.HalParser.parse; import static de.otto.edison.hal.Link.copyOf; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.LinkPredicates.always; import static java.lang.String.format; import static java.util.Arrays.asList; import static java.util.Collections.*; import static java.util.Objects.requireNonNull; import static org.slf4j.LoggerFactory.getLogger; #hops = N; N > 0 max nesting-level in embeddedTypeInfo = M; M >= 0 */ final Link initial = self(startWith.toString()); LOG.trace("Starting with {}", startWith); this.startWith = null; if (hops.isEmpty()) { /* 0. N=0, M=0: getResource(startwith, pageType) */ return singletonList( getResource(initial, resultType, embeddedTypeInfo) ); } else { final HalRepresentation firstHop; // Follow startWith URL, but have a look at the next hop, so we can parse the resource // with respect to pageType and embeddedTypeInfo: if (hops.size() == 1) { final Hop hop = hops.get(0); if (embeddedTypeInfo == null || embeddedTypeInfo.isEmpty()) { /* 1. N=1, M=0 (keine TypeInfos): Die zurückgegebene Representation soll vom Typ resultType sein. startWith könnte hop 0 embedden, oder es könnten zwei Resourcen angefragt werden. a) getResource(startwith, HalRepresentation.class, embeddedTypeInfo(hop-0-rel, pageType)) b) getResource(current, pageType) */
firstHop = getResource(initial, HalRepresentation.class, withEmbedded(hop.rel, resultType));
otto-de/edison-hal
src/main/java/de/otto/edison/hal/traverson/Traverson.java
// Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/HalParser.java // public static HalParser parse(final String json) { // return new HalParser(json, DEFAULT_JSON_MAPPER); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Builder copyOf(final Link prototype) { // return new Builder(prototype.rel, prototype.href) // .withType(prototype.type) // .withProfile(prototype.profile) // .withTitle(prototype.title) // .withName(prototype.name) // .withDeprecation(prototype.deprecation) // .withHrefLang(prototype.hreflang); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/LinkPredicates.java // public static Predicate<Link> always() { // return link -> true; // }
import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonPointer; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import de.otto.edison.hal.*; import org.slf4j.Logger; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import static com.damnhandy.uri.template.UriTemplate.fromTemplate; import static com.fasterxml.jackson.databind.DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.HalParser.parse; import static de.otto.edison.hal.Link.copyOf; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.LinkPredicates.always; import static java.lang.String.format; import static java.util.Arrays.asList; import static java.util.Collections.*; import static java.util.Objects.requireNonNull; import static org.slf4j.LoggerFactory.getLogger;
final Link expandedLink = resolve(this.contextUrl, expand(links.get(0), currentHop.vars)); if (hops.isEmpty()) { // last hop if (retrieveAll) { LOG.trace("Following {} {} links", links.size(), currentHop.rel); final List<T> representations = new ArrayList<>(); for (final Link link : links) { representations.add(getResource(resolve(this.contextUrl, expand(link, currentHop.vars)), resultType, embeddedTypeInfo)); } response = representations; } else { this.contextUrl = linkToUrl(expandedLink); response = singletonList(getResource(expandedLink, resultType, embeddedTypeInfo)); } } else { this.contextUrl = linkToUrl(expandedLink); final HalRepresentation resource = getResource(expandedLink, HalRepresentation.class, embeddedTypeInfoFor(hops, resultType, embeddedTypeInfo)); response = traverseHop(resource, resultType, embeddedTypeInfo, retrieveAll); } } else { final String msg = format("Can not follow hop %s: no matching links found in resource %s", currentHop.rel, current); LOG.error(msg); response = emptyList(); } return response; } private Link expand(final Link link, final Map<String,Object> vars) { if (link.isTemplated()) { final String href = fromTemplate(link.getHref()).expand(vars);
// Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/HalParser.java // public static HalParser parse(final String json) { // return new HalParser(json, DEFAULT_JSON_MAPPER); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Builder copyOf(final Link prototype) { // return new Builder(prototype.rel, prototype.href) // .withType(prototype.type) // .withProfile(prototype.profile) // .withTitle(prototype.title) // .withName(prototype.name) // .withDeprecation(prototype.deprecation) // .withHrefLang(prototype.hreflang); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/LinkPredicates.java // public static Predicate<Link> always() { // return link -> true; // } // Path: src/main/java/de/otto/edison/hal/traverson/Traverson.java import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonPointer; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import de.otto.edison.hal.*; import org.slf4j.Logger; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import static com.damnhandy.uri.template.UriTemplate.fromTemplate; import static com.fasterxml.jackson.databind.DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.HalParser.parse; import static de.otto.edison.hal.Link.copyOf; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.LinkPredicates.always; import static java.lang.String.format; import static java.util.Arrays.asList; import static java.util.Collections.*; import static java.util.Objects.requireNonNull; import static org.slf4j.LoggerFactory.getLogger; final Link expandedLink = resolve(this.contextUrl, expand(links.get(0), currentHop.vars)); if (hops.isEmpty()) { // last hop if (retrieveAll) { LOG.trace("Following {} {} links", links.size(), currentHop.rel); final List<T> representations = new ArrayList<>(); for (final Link link : links) { representations.add(getResource(resolve(this.contextUrl, expand(link, currentHop.vars)), resultType, embeddedTypeInfo)); } response = representations; } else { this.contextUrl = linkToUrl(expandedLink); response = singletonList(getResource(expandedLink, resultType, embeddedTypeInfo)); } } else { this.contextUrl = linkToUrl(expandedLink); final HalRepresentation resource = getResource(expandedLink, HalRepresentation.class, embeddedTypeInfoFor(hops, resultType, embeddedTypeInfo)); response = traverseHop(resource, resultType, embeddedTypeInfo, retrieveAll); } } else { final String msg = format("Can not follow hop %s: no matching links found in resource %s", currentHop.rel, current); LOG.error(msg); response = emptyList(); } return response; } private Link expand(final Link link, final Map<String,Object> vars) { if (link.isTemplated()) { final String href = fromTemplate(link.getHref()).expand(vars);
return copyOf(link)
otto-de/edison-hal
src/main/java/de/otto/edison/hal/traverson/Traverson.java
// Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/HalParser.java // public static HalParser parse(final String json) { // return new HalParser(json, DEFAULT_JSON_MAPPER); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Builder copyOf(final Link prototype) { // return new Builder(prototype.rel, prototype.href) // .withType(prototype.type) // .withProfile(prototype.profile) // .withTitle(prototype.title) // .withName(prototype.name) // .withDeprecation(prototype.deprecation) // .withHrefLang(prototype.hreflang); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/LinkPredicates.java // public static Predicate<Link> always() { // return link -> true; // }
import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonPointer; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import de.otto.edison.hal.*; import org.slf4j.Logger; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import static com.damnhandy.uri.template.UriTemplate.fromTemplate; import static com.fasterxml.jackson.databind.DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.HalParser.parse; import static de.otto.edison.hal.Link.copyOf; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.LinkPredicates.always; import static java.lang.String.format; import static java.util.Arrays.asList; import static java.util.Collections.*; import static java.util.Objects.requireNonNull; import static org.slf4j.LoggerFactory.getLogger;
return getResource(link, resultType, singletonList(embeddedTypeInfo)); } /** * Retrieve the HAL resource identified by {@code uri} and return the representation as a HalRepresentation. * * @param link the Link of the resource to retrieve, or null, if the contextUrl should be resolved. * @param type the expected type of the returned resource * @param embeddedType type information to specify the type of embedded resources. * @param <T> the type of the returned HalRepresentation * @return HalRepresentation * @throws IllegalArgumentException if resolving URLs is failing * @throws IOException if a low-level I/O problem (unexpected end-of-input, network error) occurs. * @throws JsonParseException if the json document can not be parsed by Jackson's ObjectMapper * @throws JsonMappingException if the input JSON structure can not be mapped to the specified HalRepresentation type */ private <T extends HalRepresentation> T getResource(final Link link, final Class<T> type, final List<EmbeddedTypeInfo> embeddedType) throws IOException { LOG.trace("Fetching resource href={} rel={} as type={} with embeddedType={}", link.getHref(), link.getRel(), type.getSimpleName(), embeddedType); final String json; try { json = linkResolver.apply(link); LOG.trace("Got {}", json); } catch (final IOException | RuntimeException e) { LOG.error("Failed to fetch resource href={}: {}", link.getHref(), e.getMessage()); throw e; } try { return embeddedType != null && !embeddedType.isEmpty()
// Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/HalParser.java // public static HalParser parse(final String json) { // return new HalParser(json, DEFAULT_JSON_MAPPER); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Builder copyOf(final Link prototype) { // return new Builder(prototype.rel, prototype.href) // .withType(prototype.type) // .withProfile(prototype.profile) // .withTitle(prototype.title) // .withName(prototype.name) // .withDeprecation(prototype.deprecation) // .withHrefLang(prototype.hreflang); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/LinkPredicates.java // public static Predicate<Link> always() { // return link -> true; // } // Path: src/main/java/de/otto/edison/hal/traverson/Traverson.java import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonPointer; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import de.otto.edison.hal.*; import org.slf4j.Logger; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import static com.damnhandy.uri.template.UriTemplate.fromTemplate; import static com.fasterxml.jackson.databind.DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.HalParser.parse; import static de.otto.edison.hal.Link.copyOf; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.LinkPredicates.always; import static java.lang.String.format; import static java.util.Arrays.asList; import static java.util.Collections.*; import static java.util.Objects.requireNonNull; import static org.slf4j.LoggerFactory.getLogger; return getResource(link, resultType, singletonList(embeddedTypeInfo)); } /** * Retrieve the HAL resource identified by {@code uri} and return the representation as a HalRepresentation. * * @param link the Link of the resource to retrieve, or null, if the contextUrl should be resolved. * @param type the expected type of the returned resource * @param embeddedType type information to specify the type of embedded resources. * @param <T> the type of the returned HalRepresentation * @return HalRepresentation * @throws IllegalArgumentException if resolving URLs is failing * @throws IOException if a low-level I/O problem (unexpected end-of-input, network error) occurs. * @throws JsonParseException if the json document can not be parsed by Jackson's ObjectMapper * @throws JsonMappingException if the input JSON structure can not be mapped to the specified HalRepresentation type */ private <T extends HalRepresentation> T getResource(final Link link, final Class<T> type, final List<EmbeddedTypeInfo> embeddedType) throws IOException { LOG.trace("Fetching resource href={} rel={} as type={} with embeddedType={}", link.getHref(), link.getRel(), type.getSimpleName(), embeddedType); final String json; try { json = linkResolver.apply(link); LOG.trace("Got {}", json); } catch (final IOException | RuntimeException e) { LOG.error("Failed to fetch resource href={}: {}", link.getHref(), e.getMessage()); throw e; } try { return embeddedType != null && !embeddedType.isEmpty()
? parse(json, objectMapper).as(type, embeddedType)
otto-de/edison-hal
src/test/java/de/otto/edison/hal/UserGuideExamples.java
// Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded embedded(final String rel, // final HalRepresentation embeddedItem) { // return new Embedded(singletonMap(rel, embeddedItem)); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Builder embeddedBuilder() { // return new Builder(); // } // // Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.IOException; import java.util.List; import static com.fasterxml.jackson.databind.SerializationFeature.INDENT_OUTPUT; import static de.otto.edison.hal.Embedded.embedded; import static de.otto.edison.hal.Embedded.embeddedBuilder; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.Links.linkingTo; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.core.Is.is;
package de.otto.edison.hal; /** * Simple Tests to prove that the examples used in the README.md are compiling and working */ public class UserGuideExamples { private static final ObjectMapper objectMapper; private static final ObjectMapper prettyObjectMapper; static { objectMapper = new ObjectMapper(); prettyObjectMapper = new ObjectMapper(); prettyObjectMapper.enable(INDENT_OUTPUT); } @Test public void Example_1_1() { // snippet final HalRepresentation representation = new HalRepresentation(
// Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded embedded(final String rel, // final HalRepresentation embeddedItem) { // return new Embedded(singletonMap(rel, embeddedItem)); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Builder embeddedBuilder() { // return new Builder(); // } // // Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // } // Path: src/test/java/de/otto/edison/hal/UserGuideExamples.java import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.IOException; import java.util.List; import static com.fasterxml.jackson.databind.SerializationFeature.INDENT_OUTPUT; import static de.otto.edison.hal.Embedded.embedded; import static de.otto.edison.hal.Embedded.embeddedBuilder; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.Links.linkingTo; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.core.Is.is; package de.otto.edison.hal; /** * Simple Tests to prove that the examples used in the README.md are compiling and working */ public class UserGuideExamples { private static final ObjectMapper objectMapper; private static final ObjectMapper prettyObjectMapper; static { objectMapper = new ObjectMapper(); prettyObjectMapper = new ObjectMapper(); prettyObjectMapper.enable(INDENT_OUTPUT); } @Test public void Example_1_1() { // snippet final HalRepresentation representation = new HalRepresentation(
linkingTo()
otto-de/edison-hal
src/test/java/de/otto/edison/hal/UserGuideExamples.java
// Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded embedded(final String rel, // final HalRepresentation embeddedItem) { // return new Embedded(singletonMap(rel, embeddedItem)); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Builder embeddedBuilder() { // return new Builder(); // } // // Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.IOException; import java.util.List; import static com.fasterxml.jackson.databind.SerializationFeature.INDENT_OUTPUT; import static de.otto.edison.hal.Embedded.embedded; import static de.otto.edison.hal.Embedded.embeddedBuilder; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.Links.linkingTo; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.core.Is.is;
package de.otto.edison.hal; /** * Simple Tests to prove that the examples used in the README.md are compiling and working */ public class UserGuideExamples { private static final ObjectMapper objectMapper; private static final ObjectMapper prettyObjectMapper; static { objectMapper = new ObjectMapper(); prettyObjectMapper = new ObjectMapper(); prettyObjectMapper.enable(INDENT_OUTPUT); } @Test public void Example_1_1() { // snippet final HalRepresentation representation = new HalRepresentation( linkingTo()
// Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded embedded(final String rel, // final HalRepresentation embeddedItem) { // return new Embedded(singletonMap(rel, embeddedItem)); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Builder embeddedBuilder() { // return new Builder(); // } // // Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // } // Path: src/test/java/de/otto/edison/hal/UserGuideExamples.java import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.IOException; import java.util.List; import static com.fasterxml.jackson.databind.SerializationFeature.INDENT_OUTPUT; import static de.otto.edison.hal.Embedded.embedded; import static de.otto.edison.hal.Embedded.embeddedBuilder; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.Links.linkingTo; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.core.Is.is; package de.otto.edison.hal; /** * Simple Tests to prove that the examples used in the README.md are compiling and working */ public class UserGuideExamples { private static final ObjectMapper objectMapper; private static final ObjectMapper prettyObjectMapper; static { objectMapper = new ObjectMapper(); prettyObjectMapper = new ObjectMapper(); prettyObjectMapper.enable(INDENT_OUTPUT); } @Test public void Example_1_1() { // snippet final HalRepresentation representation = new HalRepresentation( linkingTo()
.self("http://example.org/test/bar")
otto-de/edison-hal
src/test/java/de/otto/edison/hal/UserGuideExamples.java
// Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded embedded(final String rel, // final HalRepresentation embeddedItem) { // return new Embedded(singletonMap(rel, embeddedItem)); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Builder embeddedBuilder() { // return new Builder(); // } // // Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.IOException; import java.util.List; import static com.fasterxml.jackson.databind.SerializationFeature.INDENT_OUTPUT; import static de.otto.edison.hal.Embedded.embedded; import static de.otto.edison.hal.Embedded.embeddedBuilder; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.Links.linkingTo; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.core.Is.is;
package de.otto.edison.hal; /** * Simple Tests to prove that the examples used in the README.md are compiling and working */ public class UserGuideExamples { private static final ObjectMapper objectMapper; private static final ObjectMapper prettyObjectMapper; static { objectMapper = new ObjectMapper(); prettyObjectMapper = new ObjectMapper(); prettyObjectMapper.enable(INDENT_OUTPUT); } @Test public void Example_1_1() { // snippet final HalRepresentation representation = new HalRepresentation( linkingTo() .self("http://example.org/test/bar") .item("http://example.org/test/foo/01") .item("http://example.org/test/foo/02") .build(),
// Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded embedded(final String rel, // final HalRepresentation embeddedItem) { // return new Embedded(singletonMap(rel, embeddedItem)); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Builder embeddedBuilder() { // return new Builder(); // } // // Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // } // Path: src/test/java/de/otto/edison/hal/UserGuideExamples.java import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.IOException; import java.util.List; import static com.fasterxml.jackson.databind.SerializationFeature.INDENT_OUTPUT; import static de.otto.edison.hal.Embedded.embedded; import static de.otto.edison.hal.Embedded.embeddedBuilder; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.Links.linkingTo; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.core.Is.is; package de.otto.edison.hal; /** * Simple Tests to prove that the examples used in the README.md are compiling and working */ public class UserGuideExamples { private static final ObjectMapper objectMapper; private static final ObjectMapper prettyObjectMapper; static { objectMapper = new ObjectMapper(); prettyObjectMapper = new ObjectMapper(); prettyObjectMapper.enable(INDENT_OUTPUT); } @Test public void Example_1_1() { // snippet final HalRepresentation representation = new HalRepresentation( linkingTo() .self("http://example.org/test/bar") .item("http://example.org/test/foo/01") .item("http://example.org/test/foo/02") .build(),
embeddedBuilder()
otto-de/edison-hal
src/test/java/de/otto/edison/hal/UserGuideExamples.java
// Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded embedded(final String rel, // final HalRepresentation embeddedItem) { // return new Embedded(singletonMap(rel, embeddedItem)); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Builder embeddedBuilder() { // return new Builder(); // } // // Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.IOException; import java.util.List; import static com.fasterxml.jackson.databind.SerializationFeature.INDENT_OUTPUT; import static de.otto.edison.hal.Embedded.embedded; import static de.otto.edison.hal.Embedded.embeddedBuilder; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.Links.linkingTo; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.core.Is.is;
assertThat(jsonOf("Example_1_1", representation), is("{\"_links\":{\"self\":{\"href\":\"http://example.org/test/bar\"},\"item\":[{\"href\":\"http://example.org/test/foo/01\"},{\"href\":\"http://example.org/test/foo/02\"}]},\"_embedded\":{\"item\":[{\"_links\":{\"self\":{\"href\":\"http://example.org/test/foo/01\"}}},{\"_links\":{\"self\":{\"href\":\"http://example.org/test/foo/02\"}}}]}}")); } @Test public void Example_1_2() { // snippet class Example_1_2 extends HalRepresentation { @JsonProperty("someProperty") private String someProperty = "some value"; @JsonProperty("someOtherProperty") private String someOtherProperty = "some other value"; Example_1_2() { super(linkingTo() .self("http://example.org/test/bar") .build() ); } } // /snippet Example_1_2 representation = new Example_1_2(); assertThat(jsonOf("Example_1_2", representation), is("{\"_links\":{\"self\":{\"href\":\"http://example.org/test/bar\"}},\"someProperty\":\"some value\",\"someOtherProperty\":\"some other value\"}")); } @Test public void Example_2_1() { // snippet final HalRepresentation representation = new HalRepresentation( linkingTo() .self("http://example.com/foo/42")
// Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded embedded(final String rel, // final HalRepresentation embeddedItem) { // return new Embedded(singletonMap(rel, embeddedItem)); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Builder embeddedBuilder() { // return new Builder(); // } // // Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // } // Path: src/test/java/de/otto/edison/hal/UserGuideExamples.java import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.IOException; import java.util.List; import static com.fasterxml.jackson.databind.SerializationFeature.INDENT_OUTPUT; import static de.otto.edison.hal.Embedded.embedded; import static de.otto.edison.hal.Embedded.embeddedBuilder; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.Links.linkingTo; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.core.Is.is; assertThat(jsonOf("Example_1_1", representation), is("{\"_links\":{\"self\":{\"href\":\"http://example.org/test/bar\"},\"item\":[{\"href\":\"http://example.org/test/foo/01\"},{\"href\":\"http://example.org/test/foo/02\"}]},\"_embedded\":{\"item\":[{\"_links\":{\"self\":{\"href\":\"http://example.org/test/foo/01\"}}},{\"_links\":{\"self\":{\"href\":\"http://example.org/test/foo/02\"}}}]}}")); } @Test public void Example_1_2() { // snippet class Example_1_2 extends HalRepresentation { @JsonProperty("someProperty") private String someProperty = "some value"; @JsonProperty("someOtherProperty") private String someOtherProperty = "some other value"; Example_1_2() { super(linkingTo() .self("http://example.org/test/bar") .build() ); } } // /snippet Example_1_2 representation = new Example_1_2(); assertThat(jsonOf("Example_1_2", representation), is("{\"_links\":{\"self\":{\"href\":\"http://example.org/test/bar\"}},\"someProperty\":\"some value\",\"someOtherProperty\":\"some other value\"}")); } @Test public void Example_2_1() { // snippet final HalRepresentation representation = new HalRepresentation( linkingTo() .self("http://example.com/foo/42")
.single(link("next", "http://example.com/foo/43"))
otto-de/edison-hal
src/test/java/de/otto/edison/hal/UserGuideExamples.java
// Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded embedded(final String rel, // final HalRepresentation embeddedItem) { // return new Embedded(singletonMap(rel, embeddedItem)); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Builder embeddedBuilder() { // return new Builder(); // } // // Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.IOException; import java.util.List; import static com.fasterxml.jackson.databind.SerializationFeature.INDENT_OUTPUT; import static de.otto.edison.hal.Embedded.embedded; import static de.otto.edison.hal.Embedded.embeddedBuilder; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.Links.linkingTo; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.core.Is.is;
assertThat(result.someProperty, is("1")); assertThat(result.someOtherProperty, is("2")); // and final Links links = result.getLinks(); assertThat(links.getLinkBy("self").get(), is(self("http://example.org/test/foo"))); // and final List<HalRepresentation> embeddedItems = result.getEmbedded().getItemsBy("bar"); assertThat(embeddedItems, hasSize(1)); assertThat(embeddedItems.get(0).getLinks().getLinkBy("self").get(), is(link("self", "http://example.org/test/bar/01"))); } @Test public void Example_4_2() throws IOException { // given final String json = "{" + " \"_embedded\":{\"bar\":[" + " {" + " \"someProperty\":\"3\"," + " \"someOtherProperty\":\"3\"," + " \"_links\":{\"self\":[{\"href\":\"http://example.org/test/bar/01\"}]}" + " }" + " ]}" + "}"; // when final HalRepresentation result = HalParser .parse(json)
// Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded embedded(final String rel, // final HalRepresentation embeddedItem) { // return new Embedded(singletonMap(rel, embeddedItem)); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Builder embeddedBuilder() { // return new Builder(); // } // // Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // } // Path: src/test/java/de/otto/edison/hal/UserGuideExamples.java import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.IOException; import java.util.List; import static com.fasterxml.jackson.databind.SerializationFeature.INDENT_OUTPUT; import static de.otto.edison.hal.Embedded.embedded; import static de.otto.edison.hal.Embedded.embeddedBuilder; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.Links.linkingTo; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.core.Is.is; assertThat(result.someProperty, is("1")); assertThat(result.someOtherProperty, is("2")); // and final Links links = result.getLinks(); assertThat(links.getLinkBy("self").get(), is(self("http://example.org/test/foo"))); // and final List<HalRepresentation> embeddedItems = result.getEmbedded().getItemsBy("bar"); assertThat(embeddedItems, hasSize(1)); assertThat(embeddedItems.get(0).getLinks().getLinkBy("self").get(), is(link("self", "http://example.org/test/bar/01"))); } @Test public void Example_4_2() throws IOException { // given final String json = "{" + " \"_embedded\":{\"bar\":[" + " {" + " \"someProperty\":\"3\"," + " \"someOtherProperty\":\"3\"," + " \"_links\":{\"self\":[{\"href\":\"http://example.org/test/bar/01\"}]}" + " }" + " ]}" + "}"; // when final HalRepresentation result = HalParser .parse(json)
.as(HalRepresentation.class, withEmbedded("bar", TestHalRepresentation.class));
otto-de/edison-hal
src/test/java/de/otto/edison/hal/UserGuideExamples.java
// Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded embedded(final String rel, // final HalRepresentation embeddedItem) { // return new Embedded(singletonMap(rel, embeddedItem)); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Builder embeddedBuilder() { // return new Builder(); // } // // Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.IOException; import java.util.List; import static com.fasterxml.jackson.databind.SerializationFeature.INDENT_OUTPUT; import static de.otto.edison.hal.Embedded.embedded; import static de.otto.edison.hal.Embedded.embeddedBuilder; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.Links.linkingTo; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.core.Is.is;
" }" + " ]}" + "}"; // when final HalRepresentation result = HalParser .parse(json) .as(HalRepresentation.class, withEmbedded("bar", TestHalRepresentation.class)); // then final List<TestHalRepresentation> embeddedItems = result .getEmbedded() .getItemsBy("bar", TestHalRepresentation.class); assertThat(embeddedItems, hasSize(1)); assertThat(embeddedItems.get(0).getClass(), equalTo(TestHalRepresentation.class)); assertThat(embeddedItems.get(0).getLinks().getLinkBy("self").get(), is(link("self", "http://example.org/test/bar/01"))); } static class TestHalRepresentation extends HalRepresentation { @JsonProperty("someProperty") private String someProperty; @JsonProperty("someOtherProperty") private String someOtherProperty; TestHalRepresentation() { super( linkingTo() .self("http://example.org/test/foo") .build(),
// Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded embedded(final String rel, // final HalRepresentation embeddedItem) { // return new Embedded(singletonMap(rel, embeddedItem)); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Builder embeddedBuilder() { // return new Builder(); // } // // Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // } // Path: src/test/java/de/otto/edison/hal/UserGuideExamples.java import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.IOException; import java.util.List; import static com.fasterxml.jackson.databind.SerializationFeature.INDENT_OUTPUT; import static de.otto.edison.hal.Embedded.embedded; import static de.otto.edison.hal.Embedded.embeddedBuilder; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.Links.linkingTo; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.core.Is.is; " }" + " ]}" + "}"; // when final HalRepresentation result = HalParser .parse(json) .as(HalRepresentation.class, withEmbedded("bar", TestHalRepresentation.class)); // then final List<TestHalRepresentation> embeddedItems = result .getEmbedded() .getItemsBy("bar", TestHalRepresentation.class); assertThat(embeddedItems, hasSize(1)); assertThat(embeddedItems.get(0).getClass(), equalTo(TestHalRepresentation.class)); assertThat(embeddedItems.get(0).getLinks().getLinkBy("self").get(), is(link("self", "http://example.org/test/bar/01"))); } static class TestHalRepresentation extends HalRepresentation { @JsonProperty("someProperty") private String someProperty; @JsonProperty("someOtherProperty") private String someOtherProperty; TestHalRepresentation() { super( linkingTo() .self("http://example.org/test/foo") .build(),
embedded("bar", singletonList(new HalRepresentation(
otto-de/edison-hal
src/test/java/de/otto/edison/hal/CuriesTest.java
// Path: src/main/java/de/otto/edison/hal/Link.java // public static Link curi(final String name, final String relTemplate) { // if (!relTemplate.contains("{rel}")) { // throw new IllegalArgumentException("Not a CURI template. Template is required to contain a {rel} placeholder"); // } // return new Link("curies", relTemplate, null, null, null, name, null, null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // } // // Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies emptyCuries() { // return new Curies(); // } // // Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies curies(final Links links) { // List<Link> curies = links.getLinksBy("curies"); // return curies(curies); // }
import org.junit.Test; import static de.otto.edison.hal.Link.curi; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Links.linkingTo; import static de.otto.edison.hal.Curies.emptyCuries; import static de.otto.edison.hal.Curies.curies; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
package de.otto.edison.hal; public class CuriesTest { @Test public void shouldBuildRegistryWithCuries() { // given
// Path: src/main/java/de/otto/edison/hal/Link.java // public static Link curi(final String name, final String relTemplate) { // if (!relTemplate.contains("{rel}")) { // throw new IllegalArgumentException("Not a CURI template. Template is required to contain a {rel} placeholder"); // } // return new Link("curies", relTemplate, null, null, null, name, null, null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // } // // Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies emptyCuries() { // return new Curies(); // } // // Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies curies(final Links links) { // List<Link> curies = links.getLinksBy("curies"); // return curies(curies); // } // Path: src/test/java/de/otto/edison/hal/CuriesTest.java import org.junit.Test; import static de.otto.edison.hal.Link.curi; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Links.linkingTo; import static de.otto.edison.hal.Curies.emptyCuries; import static de.otto.edison.hal.Curies.curies; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; package de.otto.edison.hal; public class CuriesTest { @Test public void shouldBuildRegistryWithCuries() { // given
final Curies curies = Curies.curies(
otto-de/edison-hal
src/test/java/de/otto/edison/hal/CuriesTest.java
// Path: src/main/java/de/otto/edison/hal/Link.java // public static Link curi(final String name, final String relTemplate) { // if (!relTemplate.contains("{rel}")) { // throw new IllegalArgumentException("Not a CURI template. Template is required to contain a {rel} placeholder"); // } // return new Link("curies", relTemplate, null, null, null, name, null, null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // } // // Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies emptyCuries() { // return new Curies(); // } // // Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies curies(final Links links) { // List<Link> curies = links.getLinksBy("curies"); // return curies(curies); // }
import org.junit.Test; import static de.otto.edison.hal.Link.curi; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Links.linkingTo; import static de.otto.edison.hal.Curies.emptyCuries; import static de.otto.edison.hal.Curies.curies; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
package de.otto.edison.hal; public class CuriesTest { @Test public void shouldBuildRegistryWithCuries() { // given final Curies curies = Curies.curies(
// Path: src/main/java/de/otto/edison/hal/Link.java // public static Link curi(final String name, final String relTemplate) { // if (!relTemplate.contains("{rel}")) { // throw new IllegalArgumentException("Not a CURI template. Template is required to contain a {rel} placeholder"); // } // return new Link("curies", relTemplate, null, null, null, name, null, null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // } // // Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies emptyCuries() { // return new Curies(); // } // // Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies curies(final Links links) { // List<Link> curies = links.getLinksBy("curies"); // return curies(curies); // } // Path: src/test/java/de/otto/edison/hal/CuriesTest.java import org.junit.Test; import static de.otto.edison.hal.Link.curi; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Links.linkingTo; import static de.otto.edison.hal.Curies.emptyCuries; import static de.otto.edison.hal.Curies.curies; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; package de.otto.edison.hal; public class CuriesTest { @Test public void shouldBuildRegistryWithCuries() { // given final Curies curies = Curies.curies(
linkingTo()
otto-de/edison-hal
src/test/java/de/otto/edison/hal/CuriesTest.java
// Path: src/main/java/de/otto/edison/hal/Link.java // public static Link curi(final String name, final String relTemplate) { // if (!relTemplate.contains("{rel}")) { // throw new IllegalArgumentException("Not a CURI template. Template is required to contain a {rel} placeholder"); // } // return new Link("curies", relTemplate, null, null, null, name, null, null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // } // // Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies emptyCuries() { // return new Curies(); // } // // Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies curies(final Links links) { // List<Link> curies = links.getLinksBy("curies"); // return curies(curies); // }
import org.junit.Test; import static de.otto.edison.hal.Link.curi; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Links.linkingTo; import static de.otto.edison.hal.Curies.emptyCuries; import static de.otto.edison.hal.Curies.curies; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
package de.otto.edison.hal; public class CuriesTest { @Test public void shouldBuildRegistryWithCuries() { // given final Curies curies = Curies.curies( linkingTo()
// Path: src/main/java/de/otto/edison/hal/Link.java // public static Link curi(final String name, final String relTemplate) { // if (!relTemplate.contains("{rel}")) { // throw new IllegalArgumentException("Not a CURI template. Template is required to contain a {rel} placeholder"); // } // return new Link("curies", relTemplate, null, null, null, name, null, null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // } // // Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies emptyCuries() { // return new Curies(); // } // // Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies curies(final Links links) { // List<Link> curies = links.getLinksBy("curies"); // return curies(curies); // } // Path: src/test/java/de/otto/edison/hal/CuriesTest.java import org.junit.Test; import static de.otto.edison.hal.Link.curi; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Links.linkingTo; import static de.otto.edison.hal.Curies.emptyCuries; import static de.otto.edison.hal.Curies.curies; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; package de.otto.edison.hal; public class CuriesTest { @Test public void shouldBuildRegistryWithCuries() { // given final Curies curies = Curies.curies( linkingTo()
.curi("x", "http://example.com/rels/{rel}")
otto-de/edison-hal
src/test/java/de/otto/edison/hal/CuriesTest.java
// Path: src/main/java/de/otto/edison/hal/Link.java // public static Link curi(final String name, final String relTemplate) { // if (!relTemplate.contains("{rel}")) { // throw new IllegalArgumentException("Not a CURI template. Template is required to contain a {rel} placeholder"); // } // return new Link("curies", relTemplate, null, null, null, name, null, null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // } // // Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies emptyCuries() { // return new Curies(); // } // // Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies curies(final Links links) { // List<Link> curies = links.getLinksBy("curies"); // return curies(curies); // }
import org.junit.Test; import static de.otto.edison.hal.Link.curi; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Links.linkingTo; import static de.otto.edison.hal.Curies.emptyCuries; import static de.otto.edison.hal.Curies.curies; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
package de.otto.edison.hal; public class CuriesTest { @Test public void shouldBuildRegistryWithCuries() { // given final Curies curies = Curies.curies( linkingTo() .curi("x", "http://example.com/rels/{rel}") .curi("y", "http://example.org/rels/{rel}").build() ); // then assertThat(curies.resolve("http://example.com/rels/foo"), is("x:foo")); assertThat(curies.resolve("http://example.org/rels/bar"), is("y:bar")); } @Test public void shouldExpandFullRel() { // given final Curies curies = Curies.curies(linkingTo().curi("x", "http://example.com/rels/{rel}").build()); // when final String first = curies.expand("http://example.com/rels/foo"); final String second = curies.expand("item"); // then assertThat(first, is("http://example.com/rels/foo")); assertThat(second, is("item")); } @Test(expected = IllegalArgumentException.class) public void shouldFailToRegisterNonCuriLink() {
// Path: src/main/java/de/otto/edison/hal/Link.java // public static Link curi(final String name, final String relTemplate) { // if (!relTemplate.contains("{rel}")) { // throw new IllegalArgumentException("Not a CURI template. Template is required to contain a {rel} placeholder"); // } // return new Link("curies", relTemplate, null, null, null, name, null, null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // } // // Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies emptyCuries() { // return new Curies(); // } // // Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies curies(final Links links) { // List<Link> curies = links.getLinksBy("curies"); // return curies(curies); // } // Path: src/test/java/de/otto/edison/hal/CuriesTest.java import org.junit.Test; import static de.otto.edison.hal.Link.curi; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Links.linkingTo; import static de.otto.edison.hal.Curies.emptyCuries; import static de.otto.edison.hal.Curies.curies; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; package de.otto.edison.hal; public class CuriesTest { @Test public void shouldBuildRegistryWithCuries() { // given final Curies curies = Curies.curies( linkingTo() .curi("x", "http://example.com/rels/{rel}") .curi("y", "http://example.org/rels/{rel}").build() ); // then assertThat(curies.resolve("http://example.com/rels/foo"), is("x:foo")); assertThat(curies.resolve("http://example.org/rels/bar"), is("y:bar")); } @Test public void shouldExpandFullRel() { // given final Curies curies = Curies.curies(linkingTo().curi("x", "http://example.com/rels/{rel}").build()); // when final String first = curies.expand("http://example.com/rels/foo"); final String second = curies.expand("item"); // then assertThat(first, is("http://example.com/rels/foo")); assertThat(second, is("item")); } @Test(expected = IllegalArgumentException.class) public void shouldFailToRegisterNonCuriLink() {
emptyCuries().register(link("foo", "http://example.com/foo"));
otto-de/edison-hal
src/test/java/de/otto/edison/hal/CuriesTest.java
// Path: src/main/java/de/otto/edison/hal/Link.java // public static Link curi(final String name, final String relTemplate) { // if (!relTemplate.contains("{rel}")) { // throw new IllegalArgumentException("Not a CURI template. Template is required to contain a {rel} placeholder"); // } // return new Link("curies", relTemplate, null, null, null, name, null, null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // } // // Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies emptyCuries() { // return new Curies(); // } // // Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies curies(final Links links) { // List<Link> curies = links.getLinksBy("curies"); // return curies(curies); // }
import org.junit.Test; import static de.otto.edison.hal.Link.curi; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Links.linkingTo; import static de.otto.edison.hal.Curies.emptyCuries; import static de.otto.edison.hal.Curies.curies; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is;
package de.otto.edison.hal; public class CuriesTest { @Test public void shouldBuildRegistryWithCuries() { // given final Curies curies = Curies.curies( linkingTo() .curi("x", "http://example.com/rels/{rel}") .curi("y", "http://example.org/rels/{rel}").build() ); // then assertThat(curies.resolve("http://example.com/rels/foo"), is("x:foo")); assertThat(curies.resolve("http://example.org/rels/bar"), is("y:bar")); } @Test public void shouldExpandFullRel() { // given final Curies curies = Curies.curies(linkingTo().curi("x", "http://example.com/rels/{rel}").build()); // when final String first = curies.expand("http://example.com/rels/foo"); final String second = curies.expand("item"); // then assertThat(first, is("http://example.com/rels/foo")); assertThat(second, is("item")); } @Test(expected = IllegalArgumentException.class) public void shouldFailToRegisterNonCuriLink() {
// Path: src/main/java/de/otto/edison/hal/Link.java // public static Link curi(final String name, final String relTemplate) { // if (!relTemplate.contains("{rel}")) { // throw new IllegalArgumentException("Not a CURI template. Template is required to contain a {rel} placeholder"); // } // return new Link("curies", relTemplate, null, null, null, name, null, null); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder linkingTo() { // return new Builder(); // } // // Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies emptyCuries() { // return new Curies(); // } // // Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies curies(final Links links) { // List<Link> curies = links.getLinksBy("curies"); // return curies(curies); // } // Path: src/test/java/de/otto/edison/hal/CuriesTest.java import org.junit.Test; import static de.otto.edison.hal.Link.curi; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Links.linkingTo; import static de.otto.edison.hal.Curies.emptyCuries; import static de.otto.edison.hal.Curies.curies; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; package de.otto.edison.hal; public class CuriesTest { @Test public void shouldBuildRegistryWithCuries() { // given final Curies curies = Curies.curies( linkingTo() .curi("x", "http://example.com/rels/{rel}") .curi("y", "http://example.org/rels/{rel}").build() ); // then assertThat(curies.resolve("http://example.com/rels/foo"), is("x:foo")); assertThat(curies.resolve("http://example.org/rels/bar"), is("y:bar")); } @Test public void shouldExpandFullRel() { // given final Curies curies = Curies.curies(linkingTo().curi("x", "http://example.com/rels/{rel}").build()); // when final String first = curies.expand("http://example.com/rels/foo"); final String second = curies.expand("item"); // then assertThat(first, is("http://example.com/rels/foo")); assertThat(second, is("item")); } @Test(expected = IllegalArgumentException.class) public void shouldFailToRegisterNonCuriLink() {
emptyCuries().register(link("foo", "http://example.com/foo"));
otto-de/edison-hal
src/main/java/de/otto/edison/hal/HalRepresentation.java
// Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies emptyCuries() { // return new Curies(); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Builder copyOf(final Embedded embedded) { // final Builder builder = new Builder(); // if (embedded != null && embedded.items != null) { // builder._embedded.putAll(embedded.items); // } // return builder; // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded emptyEmbedded() { // return new Embedded(null); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder copyOf(final Links prototype) { // return new Builder().with(prototype); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // }
import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.JsonNode; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; import static de.otto.edison.hal.Curies.emptyCuries; import static de.otto.edison.hal.Embedded.Builder.copyOf; import static de.otto.edison.hal.Embedded.emptyEmbedded; import static de.otto.edison.hal.Links.copyOf; import static de.otto.edison.hal.Links.emptyLinks; import static java.util.Collections.reverse;
package de.otto.edison.hal; /** * Representation used to parse and create HAL+JSON documents from Java classes. * * @see <a href="http://stateless.co/hal_specification.html">hal_specification.html</a> * @see <a href="https://tools.ietf.org/html/draft-kelly-json-hal-08">draft-kelly-json-hal-08</a> * * @since 0.1.0 */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonPropertyOrder(alphabetic = false) public class HalRepresentation { @JsonProperty(value = "_links") @JsonInclude(NON_NULL) private volatile Links links; @JsonProperty(value = "_embedded") @JsonInclude(NON_NULL) private volatile Embedded embedded; @JsonAnySetter private Map<String,JsonNode> attributes = new LinkedHashMap<>(); @JsonIgnore private volatile Curies curies; /** * * @since 0.1.0 */ public HalRepresentation() {
// Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies emptyCuries() { // return new Curies(); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Builder copyOf(final Embedded embedded) { // final Builder builder = new Builder(); // if (embedded != null && embedded.items != null) { // builder._embedded.putAll(embedded.items); // } // return builder; // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded emptyEmbedded() { // return new Embedded(null); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder copyOf(final Links prototype) { // return new Builder().with(prototype); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // } // Path: src/main/java/de/otto/edison/hal/HalRepresentation.java import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.JsonNode; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; import static de.otto.edison.hal.Curies.emptyCuries; import static de.otto.edison.hal.Embedded.Builder.copyOf; import static de.otto.edison.hal.Embedded.emptyEmbedded; import static de.otto.edison.hal.Links.copyOf; import static de.otto.edison.hal.Links.emptyLinks; import static java.util.Collections.reverse; package de.otto.edison.hal; /** * Representation used to parse and create HAL+JSON documents from Java classes. * * @see <a href="http://stateless.co/hal_specification.html">hal_specification.html</a> * @see <a href="https://tools.ietf.org/html/draft-kelly-json-hal-08">draft-kelly-json-hal-08</a> * * @since 0.1.0 */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonPropertyOrder(alphabetic = false) public class HalRepresentation { @JsonProperty(value = "_links") @JsonInclude(NON_NULL) private volatile Links links; @JsonProperty(value = "_embedded") @JsonInclude(NON_NULL) private volatile Embedded embedded; @JsonAnySetter private Map<String,JsonNode> attributes = new LinkedHashMap<>(); @JsonIgnore private volatile Curies curies; /** * * @since 0.1.0 */ public HalRepresentation() {
this(null, null, emptyCuries());
otto-de/edison-hal
src/main/java/de/otto/edison/hal/HalRepresentation.java
// Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies emptyCuries() { // return new Curies(); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Builder copyOf(final Embedded embedded) { // final Builder builder = new Builder(); // if (embedded != null && embedded.items != null) { // builder._embedded.putAll(embedded.items); // } // return builder; // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded emptyEmbedded() { // return new Embedded(null); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder copyOf(final Links prototype) { // return new Builder().with(prototype); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // }
import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.JsonNode; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; import static de.otto.edison.hal.Curies.emptyCuries; import static de.otto.edison.hal.Embedded.Builder.copyOf; import static de.otto.edison.hal.Embedded.emptyEmbedded; import static de.otto.edison.hal.Links.copyOf; import static de.otto.edison.hal.Links.emptyLinks; import static java.util.Collections.reverse;
*/ @Deprecated public HalRepresentation(final Links links, final Embedded embedded, final Curies curies) { this.curies = curies; this.links = links == null || links.isEmpty() ? null : links.using(this.curies); this.embedded = embedded == null || embedded.isEmpty() ? null : embedded.using(this.curies); } /** * * @return the Curies used by this HalRepresentation. */ Curies getCuries() { return curies; } /** * Returns the Links of the HalRepresentation. * * @return Links * @since 0.1.0 */ @JsonIgnore public Links getLinks() {
// Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies emptyCuries() { // return new Curies(); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Builder copyOf(final Embedded embedded) { // final Builder builder = new Builder(); // if (embedded != null && embedded.items != null) { // builder._embedded.putAll(embedded.items); // } // return builder; // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded emptyEmbedded() { // return new Embedded(null); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder copyOf(final Links prototype) { // return new Builder().with(prototype); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // } // Path: src/main/java/de/otto/edison/hal/HalRepresentation.java import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.JsonNode; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; import static de.otto.edison.hal.Curies.emptyCuries; import static de.otto.edison.hal.Embedded.Builder.copyOf; import static de.otto.edison.hal.Embedded.emptyEmbedded; import static de.otto.edison.hal.Links.copyOf; import static de.otto.edison.hal.Links.emptyLinks; import static java.util.Collections.reverse; */ @Deprecated public HalRepresentation(final Links links, final Embedded embedded, final Curies curies) { this.curies = curies; this.links = links == null || links.isEmpty() ? null : links.using(this.curies); this.embedded = embedded == null || embedded.isEmpty() ? null : embedded.using(this.curies); } /** * * @return the Curies used by this HalRepresentation. */ Curies getCuries() { return curies; } /** * Returns the Links of the HalRepresentation. * * @return Links * @since 0.1.0 */ @JsonIgnore public Links getLinks() {
return links != null ? links : emptyLinks();
otto-de/edison-hal
src/main/java/de/otto/edison/hal/HalRepresentation.java
// Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies emptyCuries() { // return new Curies(); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Builder copyOf(final Embedded embedded) { // final Builder builder = new Builder(); // if (embedded != null && embedded.items != null) { // builder._embedded.putAll(embedded.items); // } // return builder; // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded emptyEmbedded() { // return new Embedded(null); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder copyOf(final Links prototype) { // return new Builder().with(prototype); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // }
import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.JsonNode; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; import static de.otto.edison.hal.Curies.emptyCuries; import static de.otto.edison.hal.Embedded.Builder.copyOf; import static de.otto.edison.hal.Embedded.emptyEmbedded; import static de.otto.edison.hal.Links.copyOf; import static de.otto.edison.hal.Links.emptyLinks; import static java.util.Collections.reverse;
/** * * @return the Curies used by this HalRepresentation. */ Curies getCuries() { return curies; } /** * Returns the Links of the HalRepresentation. * * @return Links * @since 0.1.0 */ @JsonIgnore public Links getLinks() { return links != null ? links : emptyLinks(); } /** * Add links to the HalRepresentation. * <p> * Links are only added if they are not {@link Link#isEquivalentTo(Link) equivalent} * to already existing links. * </p> * @param links links that are added to this HalRepresentation * @return this */ protected HalRepresentation add(final Links links) { this.links = this.links != null
// Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies emptyCuries() { // return new Curies(); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Builder copyOf(final Embedded embedded) { // final Builder builder = new Builder(); // if (embedded != null && embedded.items != null) { // builder._embedded.putAll(embedded.items); // } // return builder; // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded emptyEmbedded() { // return new Embedded(null); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder copyOf(final Links prototype) { // return new Builder().with(prototype); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // } // Path: src/main/java/de/otto/edison/hal/HalRepresentation.java import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.JsonNode; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; import static de.otto.edison.hal.Curies.emptyCuries; import static de.otto.edison.hal.Embedded.Builder.copyOf; import static de.otto.edison.hal.Embedded.emptyEmbedded; import static de.otto.edison.hal.Links.copyOf; import static de.otto.edison.hal.Links.emptyLinks; import static java.util.Collections.reverse; /** * * @return the Curies used by this HalRepresentation. */ Curies getCuries() { return curies; } /** * Returns the Links of the HalRepresentation. * * @return Links * @since 0.1.0 */ @JsonIgnore public Links getLinks() { return links != null ? links : emptyLinks(); } /** * Add links to the HalRepresentation. * <p> * Links are only added if they are not {@link Link#isEquivalentTo(Link) equivalent} * to already existing links. * </p> * @param links links that are added to this HalRepresentation * @return this */ protected HalRepresentation add(final Links links) { this.links = this.links != null
? copyOf(this.links).with(links).build()
otto-de/edison-hal
src/main/java/de/otto/edison/hal/HalRepresentation.java
// Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies emptyCuries() { // return new Curies(); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Builder copyOf(final Embedded embedded) { // final Builder builder = new Builder(); // if (embedded != null && embedded.items != null) { // builder._embedded.putAll(embedded.items); // } // return builder; // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded emptyEmbedded() { // return new Embedded(null); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder copyOf(final Links prototype) { // return new Builder().with(prototype); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // }
import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.JsonNode; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; import static de.otto.edison.hal.Curies.emptyCuries; import static de.otto.edison.hal.Embedded.Builder.copyOf; import static de.otto.edison.hal.Embedded.emptyEmbedded; import static de.otto.edison.hal.Links.copyOf; import static de.otto.edison.hal.Links.emptyLinks; import static java.util.Collections.reverse;
public Links getLinks() { return links != null ? links : emptyLinks(); } /** * Add links to the HalRepresentation. * <p> * Links are only added if they are not {@link Link#isEquivalentTo(Link) equivalent} * to already existing links. * </p> * @param links links that are added to this HalRepresentation * @return this */ protected HalRepresentation add(final Links links) { this.links = this.links != null ? copyOf(this.links).with(links).build() : links.using(this.curies); if (embedded != null) { embedded = embedded.using(this.curies); } return this; } /** * Returns the Embedded objects of the HalRepresentation. * * @return Embedded, possibly beeing {@link Embedded#isEmpty() empty} */ @JsonIgnore public Embedded getEmbedded() {
// Path: src/main/java/de/otto/edison/hal/Curies.java // public static Curies emptyCuries() { // return new Curies(); // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Builder copyOf(final Embedded embedded) { // final Builder builder = new Builder(); // if (embedded != null && embedded.items != null) { // builder._embedded.putAll(embedded.items); // } // return builder; // } // // Path: src/main/java/de/otto/edison/hal/Embedded.java // public static Embedded emptyEmbedded() { // return new Embedded(null); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Builder copyOf(final Links prototype) { // return new Builder().with(prototype); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // } // Path: src/main/java/de/otto/edison/hal/HalRepresentation.java import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.JsonNode; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; import static de.otto.edison.hal.Curies.emptyCuries; import static de.otto.edison.hal.Embedded.Builder.copyOf; import static de.otto.edison.hal.Embedded.emptyEmbedded; import static de.otto.edison.hal.Links.copyOf; import static de.otto.edison.hal.Links.emptyLinks; import static java.util.Collections.reverse; public Links getLinks() { return links != null ? links : emptyLinks(); } /** * Add links to the HalRepresentation. * <p> * Links are only added if they are not {@link Link#isEquivalentTo(Link) equivalent} * to already existing links. * </p> * @param links links that are added to this HalRepresentation * @return this */ protected HalRepresentation add(final Links links) { this.links = this.links != null ? copyOf(this.links).with(links).build() : links.using(this.curies); if (embedded != null) { embedded = embedded.using(this.curies); } return this; } /** * Returns the Embedded objects of the HalRepresentation. * * @return Embedded, possibly beeing {@link Embedded#isEmpty() empty} */ @JsonIgnore public Embedded getEmbedded() {
return embedded != null ? embedded : emptyEmbedded();
otto-de/edison-hal
src/test/java/de/otto/edison/hal/HalParserTest.java
// Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/HalParser.java // public static HalParser parse(final String json) { // return new HalParser(json, DEFAULT_JSON_MAPPER); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.IOException; import java.util.List; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.HalParser.parse; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.Links.emptyLinks; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*;
package de.otto.edison.hal; public class HalParserTest { @Test public void shouldParseEmptyHalDocument() throws IOException { // given final String json = "{}"; // when
// Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/HalParser.java // public static HalParser parse(final String json) { // return new HalParser(json, DEFAULT_JSON_MAPPER); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // } // Path: src/test/java/de/otto/edison/hal/HalParserTest.java import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.IOException; import java.util.List; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.HalParser.parse; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.Links.emptyLinks; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; package de.otto.edison.hal; public class HalParserTest { @Test public void shouldParseEmptyHalDocument() throws IOException { // given final String json = "{}"; // when
final HalRepresentation result = parse(json).as(HalRepresentation.class);
otto-de/edison-hal
src/test/java/de/otto/edison/hal/HalParserTest.java
// Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/HalParser.java // public static HalParser parse(final String json) { // return new HalParser(json, DEFAULT_JSON_MAPPER); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.IOException; import java.util.List; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.HalParser.parse; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.Links.emptyLinks; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*;
package de.otto.edison.hal; public class HalParserTest { @Test public void shouldParseEmptyHalDocument() throws IOException { // given final String json = "{}"; // when final HalRepresentation result = parse(json).as(HalRepresentation.class); // then final Links links = result.getLinks();
// Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/HalParser.java // public static HalParser parse(final String json) { // return new HalParser(json, DEFAULT_JSON_MAPPER); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // } // Path: src/test/java/de/otto/edison/hal/HalParserTest.java import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.IOException; import java.util.List; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.HalParser.parse; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.Links.emptyLinks; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; package de.otto.edison.hal; public class HalParserTest { @Test public void shouldParseEmptyHalDocument() throws IOException { // given final String json = "{}"; // when final HalRepresentation result = parse(json).as(HalRepresentation.class); // then final Links links = result.getLinks();
assertThat(links, is(emptyLinks()));
otto-de/edison-hal
src/test/java/de/otto/edison/hal/HalParserTest.java
// Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/HalParser.java // public static HalParser parse(final String json) { // return new HalParser(json, DEFAULT_JSON_MAPPER); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.IOException; import java.util.List; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.HalParser.parse; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.Links.emptyLinks; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*;
package de.otto.edison.hal; public class HalParserTest { @Test public void shouldParseEmptyHalDocument() throws IOException { // given final String json = "{}"; // when final HalRepresentation result = parse(json).as(HalRepresentation.class); // then final Links links = result.getLinks(); assertThat(links, is(emptyLinks())); } @Test public void shouldParseSimpleHalDocumentsWithoutEmbeddedItems() throws IOException { // given final String json = "{" + "\"ignored\":\"some value\"," +
// Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/HalParser.java // public static HalParser parse(final String json) { // return new HalParser(json, DEFAULT_JSON_MAPPER); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // } // Path: src/test/java/de/otto/edison/hal/HalParserTest.java import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.IOException; import java.util.List; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.HalParser.parse; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.Links.emptyLinks; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; package de.otto.edison.hal; public class HalParserTest { @Test public void shouldParseEmptyHalDocument() throws IOException { // given final String json = "{}"; // when final HalRepresentation result = parse(json).as(HalRepresentation.class); // then final Links links = result.getLinks(); assertThat(links, is(emptyLinks())); } @Test public void shouldParseSimpleHalDocumentsWithoutEmbeddedItems() throws IOException { // given final String json = "{" + "\"ignored\":\"some value\"," +
"\"_links\":{\"self\":{\"href\":\"http://example.org/test/foo\"}}" +
otto-de/edison-hal
src/test/java/de/otto/edison/hal/HalParserTest.java
// Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/HalParser.java // public static HalParser parse(final String json) { // return new HalParser(json, DEFAULT_JSON_MAPPER); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.IOException; import java.util.List; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.HalParser.parse; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.Links.emptyLinks; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*;
" }" + "]}" + "}"; // when final SimpleHalRepresentation result = parse(json).as(SimpleHalRepresentation.class); // then assertThat(result.first, is("1")); assertThat(result.second, is("2")); final Links links = result.getLinks(); assertThat(links.getLinkBy("self").get(), is(self("http://example.org/test/foo"))); } @Test public void shouldParseEmbeddedItemsAsPlainHalRepresentation() throws IOException { // given final String json = "{" + " \"_embedded\":{\"bar\":[" + " {" + " \"value\":\"3\"," + " \"_links\":{\"self\":[{\"href\":\"http://example.org/test/bar/01\"}]}" + " }" + " ]}" + "}"; // when final SimpleHalRepresentation result = parse(json).as(SimpleHalRepresentation.class); // then final List<HalRepresentation> embeddedItems = result.getEmbedded().getItemsBy("bar"); assertThat(embeddedItems, hasSize(1)); assertThat(embeddedItems.get(0).getClass(), equalTo(HalRepresentation.class));
// Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/HalParser.java // public static HalParser parse(final String json) { // return new HalParser(json, DEFAULT_JSON_MAPPER); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // } // Path: src/test/java/de/otto/edison/hal/HalParserTest.java import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.IOException; import java.util.List; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.HalParser.parse; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.Links.emptyLinks; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; " }" + "]}" + "}"; // when final SimpleHalRepresentation result = parse(json).as(SimpleHalRepresentation.class); // then assertThat(result.first, is("1")); assertThat(result.second, is("2")); final Links links = result.getLinks(); assertThat(links.getLinkBy("self").get(), is(self("http://example.org/test/foo"))); } @Test public void shouldParseEmbeddedItemsAsPlainHalRepresentation() throws IOException { // given final String json = "{" + " \"_embedded\":{\"bar\":[" + " {" + " \"value\":\"3\"," + " \"_links\":{\"self\":[{\"href\":\"http://example.org/test/bar/01\"}]}" + " }" + " ]}" + "}"; // when final SimpleHalRepresentation result = parse(json).as(SimpleHalRepresentation.class); // then final List<HalRepresentation> embeddedItems = result.getEmbedded().getItemsBy("bar"); assertThat(embeddedItems, hasSize(1)); assertThat(embeddedItems.get(0).getClass(), equalTo(HalRepresentation.class));
assertThat(embeddedItems.get(0).getLinks().getLinkBy("self").get(), is(link("self", "http://example.org/test/bar/01")));
otto-de/edison-hal
src/test/java/de/otto/edison/hal/HalParserTest.java
// Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/HalParser.java // public static HalParser parse(final String json) { // return new HalParser(json, DEFAULT_JSON_MAPPER); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.IOException; import java.util.List; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.HalParser.parse; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.Links.emptyLinks; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*;
final String json = "{" + " \"_embedded\":{\"bar\":[" + " {" + " \"value\":\"3\"," + " \"_links\":{\"self\":[{\"href\":\"http://example.org/test/bar/01\"}]}" + " }" + " ]}" + "}"; // when final SimpleHalRepresentation result = parse(json, new ObjectMapper()).as(SimpleHalRepresentation.class); final SimpleHalRepresentation expectedResult = parse(json).as(SimpleHalRepresentation.class); // then assertThat(result, is(expectedResult)); } @Test public void shouldParseEmbeddedItemsWithSpecificType() throws IOException { // given final String json = "{" + "\"_embedded\":{\"bar\":[" + " {" + " \"value\":\"3\"," + " \"_links\":{\"self\":[{\"href\":\"http://example.org/test/bar/01\"}]}" + " }" + "]}" + "}"; // when final SimpleHalRepresentation result = parse(json)
// Path: src/main/java/de/otto/edison/hal/EmbeddedTypeInfo.java // public static EmbeddedTypeInfo withEmbedded(final String rel, // final Class<? extends HalRepresentation> embeddedType, // final EmbeddedTypeInfo... nestedTypeInfo) { // if (nestedTypeInfo == null || nestedTypeInfo.length == 0) { // return new EmbeddedTypeInfo(rel, embeddedType, emptyList()); // } else { // return new EmbeddedTypeInfo(rel, embeddedType, asList(nestedTypeInfo)); // } // } // // Path: src/main/java/de/otto/edison/hal/HalParser.java // public static HalParser parse(final String json) { // return new HalParser(json, DEFAULT_JSON_MAPPER); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link link(final String rel, final String href) { // return new Link(rel, href); // } // // Path: src/main/java/de/otto/edison/hal/Link.java // public static Link self(final String href) { // return new Link("self", href); // } // // Path: src/main/java/de/otto/edison/hal/Links.java // public static Links emptyLinks() { // return new Links(); // } // Path: src/test/java/de/otto/edison/hal/HalParserTest.java import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import java.io.IOException; import java.util.List; import static de.otto.edison.hal.EmbeddedTypeInfo.withEmbedded; import static de.otto.edison.hal.HalParser.parse; import static de.otto.edison.hal.Link.link; import static de.otto.edison.hal.Link.self; import static de.otto.edison.hal.Links.emptyLinks; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; final String json = "{" + " \"_embedded\":{\"bar\":[" + " {" + " \"value\":\"3\"," + " \"_links\":{\"self\":[{\"href\":\"http://example.org/test/bar/01\"}]}" + " }" + " ]}" + "}"; // when final SimpleHalRepresentation result = parse(json, new ObjectMapper()).as(SimpleHalRepresentation.class); final SimpleHalRepresentation expectedResult = parse(json).as(SimpleHalRepresentation.class); // then assertThat(result, is(expectedResult)); } @Test public void shouldParseEmbeddedItemsWithSpecificType() throws IOException { // given final String json = "{" + "\"_embedded\":{\"bar\":[" + " {" + " \"value\":\"3\"," + " \"_links\":{\"self\":[{\"href\":\"http://example.org/test/bar/01\"}]}" + " }" + "]}" + "}"; // when final SimpleHalRepresentation result = parse(json)
.as(SimpleHalRepresentation.class, withEmbedded("bar", EmbeddedHalRepresentation.class));
fusesource/hawtjms
hawtjms-core/src/main/java/io/hawtjms/provider/AbstractAsyncProvider.java
// Path: hawtjms-core/src/main/java/io/hawtjms/jms/meta/JmsConsumerId.java // public final class JmsConsumerId extends JmsAbstractResourceId implements Comparable<JmsConsumerId> { // // private String connectionId; // private long sessionId; // private long value; // // private transient String key; // private transient JmsSessionId parentId; // // public JmsConsumerId(String connectionId, long sessionId, long consumerId) { // this.connectionId = connectionId; // this.sessionId = sessionId; // this.value = consumerId; // } // // public JmsConsumerId(JmsSessionId sessionId, long consumerId) { // this.connectionId = sessionId.getConnectionId(); // this.sessionId = sessionId.getValue(); // this.value = consumerId; // this.parentId = sessionId; // } // // public JmsConsumerId(JmsConsumerId id) { // this.connectionId = id.getConnectionId(); // this.sessionId = id.getSessionId(); // this.value = id.getValue(); // this.parentId = id.getParentId(); // } // // public JmsConsumerId(String consumerKey) throws IllegalArgumentException { // // Parse off the consumer Id value // int p = consumerKey.lastIndexOf(":"); // if (p >= 0) { // value = Long.parseLong(consumerKey.substring(p + 1)); // consumerKey = consumerKey.substring(0, p); // } // setConsumerSessionKey(consumerKey); // } // // public JmsSessionId getParentId() { // if (parentId == null) { // parentId = new JmsSessionId(this); // } // return parentId; // } // // public String getConnectionId() { // return connectionId; // } // // public long getSessionId() { // return sessionId; // } // // public long getValue() { // return value; // } // // @Override // public int hashCode() { // if (hashCode == 0) { // hashCode = connectionId.hashCode() ^ (int) sessionId ^ (int) value; // } // return hashCode; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || o.getClass() != JmsConsumerId.class) { // return false; // } // JmsConsumerId id = (JmsConsumerId) o; // return sessionId == id.sessionId && value == id.value && connectionId.equals(id.connectionId); // } // // @Override // public String toString() { // if (key == null) { // key = connectionId + ":" + sessionId + ":" + value; // } // return key; // } // // @Override // public int compareTo(JmsConsumerId other) { // return toString().compareTo(other.toString()); // } // // private void setConsumerSessionKey(String sessionKey) { // // Parse off the value of the session Id // int p = sessionKey.lastIndexOf(":"); // if (p >= 0) { // sessionId = Long.parseLong(sessionKey.substring(p + 1)); // sessionKey = sessionKey.substring(0, p); // } // // // The rest is the value of the connection Id. // connectionId = sessionKey; // } // }
import io.hawtjms.jms.meta.JmsConsumerId; import io.hawtjms.jms.meta.JmsSessionId; import io.hawtjms.util.IOExceptionSupport; import java.io.IOException; import java.net.URI; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicBoolean; import javax.jms.JMSException;
return serial; } }); } @Override public void start() throws IOException, IllegalStateException { checkClosed(); if (listener == null) { throw new IllegalStateException("No ProviderListener registered."); } } @Override public void commit(JmsSessionId sessionId, AsyncResult<Void> request) throws IOException, JMSException, UnsupportedOperationException { throw new UnsupportedOperationException("Provider does not support Transactions"); } @Override public void rollback(JmsSessionId sessionId, AsyncResult<Void> request) throws IOException, JMSException, UnsupportedOperationException { throw new UnsupportedOperationException("Provider does not support Transactions"); } @Override public void unsubscribe(String subscription, AsyncResult<Void> request) throws IOException, JMSException, UnsupportedOperationException { throw new UnsupportedOperationException("Provider does not support unsubscribe operations"); } @Override
// Path: hawtjms-core/src/main/java/io/hawtjms/jms/meta/JmsConsumerId.java // public final class JmsConsumerId extends JmsAbstractResourceId implements Comparable<JmsConsumerId> { // // private String connectionId; // private long sessionId; // private long value; // // private transient String key; // private transient JmsSessionId parentId; // // public JmsConsumerId(String connectionId, long sessionId, long consumerId) { // this.connectionId = connectionId; // this.sessionId = sessionId; // this.value = consumerId; // } // // public JmsConsumerId(JmsSessionId sessionId, long consumerId) { // this.connectionId = sessionId.getConnectionId(); // this.sessionId = sessionId.getValue(); // this.value = consumerId; // this.parentId = sessionId; // } // // public JmsConsumerId(JmsConsumerId id) { // this.connectionId = id.getConnectionId(); // this.sessionId = id.getSessionId(); // this.value = id.getValue(); // this.parentId = id.getParentId(); // } // // public JmsConsumerId(String consumerKey) throws IllegalArgumentException { // // Parse off the consumer Id value // int p = consumerKey.lastIndexOf(":"); // if (p >= 0) { // value = Long.parseLong(consumerKey.substring(p + 1)); // consumerKey = consumerKey.substring(0, p); // } // setConsumerSessionKey(consumerKey); // } // // public JmsSessionId getParentId() { // if (parentId == null) { // parentId = new JmsSessionId(this); // } // return parentId; // } // // public String getConnectionId() { // return connectionId; // } // // public long getSessionId() { // return sessionId; // } // // public long getValue() { // return value; // } // // @Override // public int hashCode() { // if (hashCode == 0) { // hashCode = connectionId.hashCode() ^ (int) sessionId ^ (int) value; // } // return hashCode; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || o.getClass() != JmsConsumerId.class) { // return false; // } // JmsConsumerId id = (JmsConsumerId) o; // return sessionId == id.sessionId && value == id.value && connectionId.equals(id.connectionId); // } // // @Override // public String toString() { // if (key == null) { // key = connectionId + ":" + sessionId + ":" + value; // } // return key; // } // // @Override // public int compareTo(JmsConsumerId other) { // return toString().compareTo(other.toString()); // } // // private void setConsumerSessionKey(String sessionKey) { // // Parse off the value of the session Id // int p = sessionKey.lastIndexOf(":"); // if (p >= 0) { // sessionId = Long.parseLong(sessionKey.substring(p + 1)); // sessionKey = sessionKey.substring(0, p); // } // // // The rest is the value of the connection Id. // connectionId = sessionKey; // } // } // Path: hawtjms-core/src/main/java/io/hawtjms/provider/AbstractAsyncProvider.java import io.hawtjms.jms.meta.JmsConsumerId; import io.hawtjms.jms.meta.JmsSessionId; import io.hawtjms.util.IOExceptionSupport; import java.io.IOException; import java.net.URI; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicBoolean; import javax.jms.JMSException; return serial; } }); } @Override public void start() throws IOException, IllegalStateException { checkClosed(); if (listener == null) { throw new IllegalStateException("No ProviderListener registered."); } } @Override public void commit(JmsSessionId sessionId, AsyncResult<Void> request) throws IOException, JMSException, UnsupportedOperationException { throw new UnsupportedOperationException("Provider does not support Transactions"); } @Override public void rollback(JmsSessionId sessionId, AsyncResult<Void> request) throws IOException, JMSException, UnsupportedOperationException { throw new UnsupportedOperationException("Provider does not support Transactions"); } @Override public void unsubscribe(String subscription, AsyncResult<Void> request) throws IOException, JMSException, UnsupportedOperationException { throw new UnsupportedOperationException("Provider does not support unsubscribe operations"); } @Override
public void pull(JmsConsumerId consumerId, long timeout, AsyncResult<Void> request) throws IOException, UnsupportedOperationException {
fusesource/hawtjms
hawtjms-core/src/test/java/io/hawtjms/jms/message/JmsMessageTest.java
// Path: hawtjms-core/src/main/java/io/hawtjms/jms/JmsDestination.java // public abstract class JmsDestination extends JNDIStorable implements JmsResource, Externalizable, javax.jms.Destination, Comparable<JmsDestination> { // // protected transient String name; // protected transient boolean topic; // protected transient boolean temporary; // protected transient int hashValue; // protected transient JmsConnection connection; // // protected JmsDestination(String name, boolean topic, boolean temporary) { // this.name = name; // this.topic = topic; // this.temporary = temporary; // } // // public abstract JmsDestination copy(); // // @Override // public String toString() { // return name; // } // // /** // * @return name of destination // */ // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // /** // * @return the topic // */ // public boolean isTopic() { // return this.topic; // } // // /** // * @return the temporary // */ // public boolean isTemporary() { // return this.temporary; // } // // /** // * @return true if a Topic // */ // public boolean isQueue() { // return !this.topic; // } // // /** // * @param props // */ // @Override // protected void buildFromProperties(Map<String, String> props) { // setName(getProperty(props, "name", "")); // Boolean bool = Boolean.valueOf(getProperty(props, "topic", Boolean.TRUE.toString())); // this.topic = bool.booleanValue(); // bool = Boolean.valueOf(getProperty(props, "temporary", Boolean.FALSE.toString())); // this.temporary = bool.booleanValue(); // } // // /** // * @param props // */ // @Override // protected void populateProperties(Map<String, String> props) { // props.put("name", getName()); // props.put("topic", Boolean.toString(isTopic())); // props.put("temporary", Boolean.toString(isTemporary())); // } // // /** // * @param other // * the Object to be compared. // * @return a negative integer, zero, or a positive integer as this object is // * less than, equal to, or greater than the specified object. // * @see java.lang.Comparable#compareTo(java.lang.Object) // */ // @Override // public int compareTo(JmsDestination other) { // if (other != null) { // if (this == other) { // return 0; // } // if (isTemporary() == other.isTemporary()) { // return getName().compareTo(other.getName()); // } // return -1; // } // return -1; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // // JmsDestination d = (JmsDestination) o; // return getName().equals(d.getName()); // } // // @Override // public int hashCode() { // if (hashValue == 0) { // hashValue = getName().hashCode(); // } // return hashValue; // } // // @Override // public void writeExternal(ObjectOutput out) throws IOException { // out.writeUTF(getName()); // out.writeBoolean(isTopic()); // out.writeBoolean(isTemporary()); // } // // @Override // public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { // setName(in.readUTF()); // this.topic = in.readBoolean(); // this.temporary = in.readBoolean(); // } // // void setConnection(JmsConnection connection) { // this.connection = connection; // } // // JmsConnection getConnection() { // return this.connection; // } // // /** // * Attempts to delete the destination if there is an assigned Connection object. // * // * @throws JMSException if an error occurs or the provider doesn't support // * delete of destinations from the client. // */ // protected void tryDelete() throws JMSException { // if (connection != null) { // connection.deleteDestination(this); // } // } // // @Override // public void visit(JmsResourceVistor visitor) throws Exception { // visitor.processDestination(this); // } // }
import javax.jms.MessageFormatException; import javax.jms.MessageNotWriteableException; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import io.hawtjms.jms.JmsDestination; import io.hawtjms.jms.JmsTopic; import java.util.Enumeration; import java.util.Map; import javax.jms.JMSException; import javax.jms.Message;
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 io.hawtjms.jms.message; public class JmsMessageTest { private static final Logger LOG = LoggerFactory.getLogger(JmsMessageTest.class); private final JmsMessageFactory factory = new JmsDefaultMessageFactory(); protected boolean readOnlyMessage; private String jmsMessageID; private String jmsCorrelationID;
// Path: hawtjms-core/src/main/java/io/hawtjms/jms/JmsDestination.java // public abstract class JmsDestination extends JNDIStorable implements JmsResource, Externalizable, javax.jms.Destination, Comparable<JmsDestination> { // // protected transient String name; // protected transient boolean topic; // protected transient boolean temporary; // protected transient int hashValue; // protected transient JmsConnection connection; // // protected JmsDestination(String name, boolean topic, boolean temporary) { // this.name = name; // this.topic = topic; // this.temporary = temporary; // } // // public abstract JmsDestination copy(); // // @Override // public String toString() { // return name; // } // // /** // * @return name of destination // */ // public String getName() { // return this.name; // } // // public void setName(String name) { // this.name = name; // } // // /** // * @return the topic // */ // public boolean isTopic() { // return this.topic; // } // // /** // * @return the temporary // */ // public boolean isTemporary() { // return this.temporary; // } // // /** // * @return true if a Topic // */ // public boolean isQueue() { // return !this.topic; // } // // /** // * @param props // */ // @Override // protected void buildFromProperties(Map<String, String> props) { // setName(getProperty(props, "name", "")); // Boolean bool = Boolean.valueOf(getProperty(props, "topic", Boolean.TRUE.toString())); // this.topic = bool.booleanValue(); // bool = Boolean.valueOf(getProperty(props, "temporary", Boolean.FALSE.toString())); // this.temporary = bool.booleanValue(); // } // // /** // * @param props // */ // @Override // protected void populateProperties(Map<String, String> props) { // props.put("name", getName()); // props.put("topic", Boolean.toString(isTopic())); // props.put("temporary", Boolean.toString(isTemporary())); // } // // /** // * @param other // * the Object to be compared. // * @return a negative integer, zero, or a positive integer as this object is // * less than, equal to, or greater than the specified object. // * @see java.lang.Comparable#compareTo(java.lang.Object) // */ // @Override // public int compareTo(JmsDestination other) { // if (other != null) { // if (this == other) { // return 0; // } // if (isTemporary() == other.isTemporary()) { // return getName().compareTo(other.getName()); // } // return -1; // } // return -1; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // // JmsDestination d = (JmsDestination) o; // return getName().equals(d.getName()); // } // // @Override // public int hashCode() { // if (hashValue == 0) { // hashValue = getName().hashCode(); // } // return hashValue; // } // // @Override // public void writeExternal(ObjectOutput out) throws IOException { // out.writeUTF(getName()); // out.writeBoolean(isTopic()); // out.writeBoolean(isTemporary()); // } // // @Override // public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { // setName(in.readUTF()); // this.topic = in.readBoolean(); // this.temporary = in.readBoolean(); // } // // void setConnection(JmsConnection connection) { // this.connection = connection; // } // // JmsConnection getConnection() { // return this.connection; // } // // /** // * Attempts to delete the destination if there is an assigned Connection object. // * // * @throws JMSException if an error occurs or the provider doesn't support // * delete of destinations from the client. // */ // protected void tryDelete() throws JMSException { // if (connection != null) { // connection.deleteDestination(this); // } // } // // @Override // public void visit(JmsResourceVistor visitor) throws Exception { // visitor.processDestination(this); // } // } // Path: hawtjms-core/src/test/java/io/hawtjms/jms/message/JmsMessageTest.java import javax.jms.MessageFormatException; import javax.jms.MessageNotWriteableException; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import io.hawtjms.jms.JmsDestination; import io.hawtjms.jms.JmsTopic; import java.util.Enumeration; import java.util.Map; import javax.jms.JMSException; import javax.jms.Message; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 io.hawtjms.jms.message; public class JmsMessageTest { private static final Logger LOG = LoggerFactory.getLogger(JmsMessageTest.class); private final JmsMessageFactory factory = new JmsDefaultMessageFactory(); protected boolean readOnlyMessage; private String jmsMessageID; private String jmsCorrelationID;
private JmsDestination jmsDestination;
fusesource/hawtjms
hawtjms-discovery/src/main/java/io/hawtjms/provider/discovery/multicast/MulticastDiscoveryAgent.java
// Path: hawtjms-discovery/src/main/java/io/hawtjms/provider/discovery/DiscoveryListener.java // public interface DiscoveryListener { // // /** // * Called when a DiscoveryAgent becomes aware of a new remote peer. // * // * @param event // * the event data which contains the peer address and optional name. // */ // void onServiceAdd(DiscoveryEvent event); // // /** // * Called when a DiscoveryAgent can no longer detect a previously known remote peer. // * // * @param event // * the event data which contains the peer address and optional name. // */ // void onServiceRemove(DiscoveryEvent event); // // }
import io.hawtjms.provider.discovery.DiscoveryAgent; import io.hawtjms.provider.discovery.DiscoveryEvent; import io.hawtjms.provider.discovery.DiscoveryListener; import io.hawtjms.provider.discovery.DiscoveryEvent.EventType; import java.io.IOException; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.MulticastSocket; import java.net.NetworkInterface; import java.net.SocketAddress; import java.net.SocketTimeoutException; import java.net.URI; import java.net.URISyntaxException; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 io.hawtjms.provider.discovery.multicast; /** * Discovery agent that listens on a multicast address for new Broker advisories. */ public class MulticastDiscoveryAgent implements DiscoveryAgent, Runnable { public static final String DEFAULT_DISCOVERY_URI_STRING = "multicast://239.255.2.3:6155"; public static final String DEFAULT_HOST_STR = "default"; public static final String DEFAULT_HOST_IP = System.getProperty("hawtjms.partition.discovery", "239.255.2.3"); public static final int DEFAULT_PORT = 6155; private static final Logger LOG = LoggerFactory.getLogger(MulticastDiscoveryAgent.class); private static final int BUFF_SIZE = 8192; private static final int DEFAULT_IDLE_TIME = 500; private static final int HEARTBEAT_MISS_BEFORE_DEATH = 10;
// Path: hawtjms-discovery/src/main/java/io/hawtjms/provider/discovery/DiscoveryListener.java // public interface DiscoveryListener { // // /** // * Called when a DiscoveryAgent becomes aware of a new remote peer. // * // * @param event // * the event data which contains the peer address and optional name. // */ // void onServiceAdd(DiscoveryEvent event); // // /** // * Called when a DiscoveryAgent can no longer detect a previously known remote peer. // * // * @param event // * the event data which contains the peer address and optional name. // */ // void onServiceRemove(DiscoveryEvent event); // // } // Path: hawtjms-discovery/src/main/java/io/hawtjms/provider/discovery/multicast/MulticastDiscoveryAgent.java import io.hawtjms.provider.discovery.DiscoveryAgent; import io.hawtjms.provider.discovery.DiscoveryEvent; import io.hawtjms.provider.discovery.DiscoveryListener; import io.hawtjms.provider.discovery.DiscoveryEvent.EventType; import java.io.IOException; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.MulticastSocket; import java.net.NetworkInterface; import java.net.SocketAddress; import java.net.SocketTimeoutException; import java.net.URI; import java.net.URISyntaxException; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 io.hawtjms.provider.discovery.multicast; /** * Discovery agent that listens on a multicast address for new Broker advisories. */ public class MulticastDiscoveryAgent implements DiscoveryAgent, Runnable { public static final String DEFAULT_DISCOVERY_URI_STRING = "multicast://239.255.2.3:6155"; public static final String DEFAULT_HOST_STR = "default"; public static final String DEFAULT_HOST_IP = System.getProperty("hawtjms.partition.discovery", "239.255.2.3"); public static final int DEFAULT_PORT = 6155; private static final Logger LOG = LoggerFactory.getLogger(MulticastDiscoveryAgent.class); private static final int BUFF_SIZE = 8192; private static final int DEFAULT_IDLE_TIME = 500; private static final int HEARTBEAT_MISS_BEFORE_DEATH = 10;
private DiscoveryListener listener;
fusesource/hawtjms
hawtjms-stomp/src/main/java/io/hawtjms/provider/stomp/StompSession.java
// Path: hawtjms-core/src/main/java/io/hawtjms/jms/meta/JmsConsumerId.java // public final class JmsConsumerId extends JmsAbstractResourceId implements Comparable<JmsConsumerId> { // // private String connectionId; // private long sessionId; // private long value; // // private transient String key; // private transient JmsSessionId parentId; // // public JmsConsumerId(String connectionId, long sessionId, long consumerId) { // this.connectionId = connectionId; // this.sessionId = sessionId; // this.value = consumerId; // } // // public JmsConsumerId(JmsSessionId sessionId, long consumerId) { // this.connectionId = sessionId.getConnectionId(); // this.sessionId = sessionId.getValue(); // this.value = consumerId; // this.parentId = sessionId; // } // // public JmsConsumerId(JmsConsumerId id) { // this.connectionId = id.getConnectionId(); // this.sessionId = id.getSessionId(); // this.value = id.getValue(); // this.parentId = id.getParentId(); // } // // public JmsConsumerId(String consumerKey) throws IllegalArgumentException { // // Parse off the consumer Id value // int p = consumerKey.lastIndexOf(":"); // if (p >= 0) { // value = Long.parseLong(consumerKey.substring(p + 1)); // consumerKey = consumerKey.substring(0, p); // } // setConsumerSessionKey(consumerKey); // } // // public JmsSessionId getParentId() { // if (parentId == null) { // parentId = new JmsSessionId(this); // } // return parentId; // } // // public String getConnectionId() { // return connectionId; // } // // public long getSessionId() { // return sessionId; // } // // public long getValue() { // return value; // } // // @Override // public int hashCode() { // if (hashCode == 0) { // hashCode = connectionId.hashCode() ^ (int) sessionId ^ (int) value; // } // return hashCode; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || o.getClass() != JmsConsumerId.class) { // return false; // } // JmsConsumerId id = (JmsConsumerId) o; // return sessionId == id.sessionId && value == id.value && connectionId.equals(id.connectionId); // } // // @Override // public String toString() { // if (key == null) { // key = connectionId + ":" + sessionId + ":" + value; // } // return key; // } // // @Override // public int compareTo(JmsConsumerId other) { // return toString().compareTo(other.toString()); // } // // private void setConsumerSessionKey(String sessionKey) { // // Parse off the value of the session Id // int p = sessionKey.lastIndexOf(":"); // if (p >= 0) { // sessionId = Long.parseLong(sessionKey.substring(p + 1)); // sessionKey = sessionKey.substring(0, p); // } // // // The rest is the value of the connection Id. // connectionId = sessionKey; // } // }
import javax.jms.JMSException; import io.hawtjms.jms.meta.JmsConsumerId; import io.hawtjms.jms.meta.JmsConsumerInfo; import io.hawtjms.jms.meta.JmsProducerId; import io.hawtjms.jms.meta.JmsProducerInfo; import io.hawtjms.jms.meta.JmsSessionId; import io.hawtjms.jms.meta.JmsSessionInfo; import io.hawtjms.provider.AsyncResult; import io.hawtjms.provider.ProviderRequest; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger;
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 io.hawtjms.provider.stomp; /** * Represents a logical Session instance for a STOMP connection. */ public class StompSession { private final StompConnection connection; private final JmsSessionInfo sessionInfo; private final Map<JmsProducerId, StompProducer> producers = new HashMap<JmsProducerId, StompProducer>();
// Path: hawtjms-core/src/main/java/io/hawtjms/jms/meta/JmsConsumerId.java // public final class JmsConsumerId extends JmsAbstractResourceId implements Comparable<JmsConsumerId> { // // private String connectionId; // private long sessionId; // private long value; // // private transient String key; // private transient JmsSessionId parentId; // // public JmsConsumerId(String connectionId, long sessionId, long consumerId) { // this.connectionId = connectionId; // this.sessionId = sessionId; // this.value = consumerId; // } // // public JmsConsumerId(JmsSessionId sessionId, long consumerId) { // this.connectionId = sessionId.getConnectionId(); // this.sessionId = sessionId.getValue(); // this.value = consumerId; // this.parentId = sessionId; // } // // public JmsConsumerId(JmsConsumerId id) { // this.connectionId = id.getConnectionId(); // this.sessionId = id.getSessionId(); // this.value = id.getValue(); // this.parentId = id.getParentId(); // } // // public JmsConsumerId(String consumerKey) throws IllegalArgumentException { // // Parse off the consumer Id value // int p = consumerKey.lastIndexOf(":"); // if (p >= 0) { // value = Long.parseLong(consumerKey.substring(p + 1)); // consumerKey = consumerKey.substring(0, p); // } // setConsumerSessionKey(consumerKey); // } // // public JmsSessionId getParentId() { // if (parentId == null) { // parentId = new JmsSessionId(this); // } // return parentId; // } // // public String getConnectionId() { // return connectionId; // } // // public long getSessionId() { // return sessionId; // } // // public long getValue() { // return value; // } // // @Override // public int hashCode() { // if (hashCode == 0) { // hashCode = connectionId.hashCode() ^ (int) sessionId ^ (int) value; // } // return hashCode; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || o.getClass() != JmsConsumerId.class) { // return false; // } // JmsConsumerId id = (JmsConsumerId) o; // return sessionId == id.sessionId && value == id.value && connectionId.equals(id.connectionId); // } // // @Override // public String toString() { // if (key == null) { // key = connectionId + ":" + sessionId + ":" + value; // } // return key; // } // // @Override // public int compareTo(JmsConsumerId other) { // return toString().compareTo(other.toString()); // } // // private void setConsumerSessionKey(String sessionKey) { // // Parse off the value of the session Id // int p = sessionKey.lastIndexOf(":"); // if (p >= 0) { // sessionId = Long.parseLong(sessionKey.substring(p + 1)); // sessionKey = sessionKey.substring(0, p); // } // // // The rest is the value of the connection Id. // connectionId = sessionKey; // } // } // Path: hawtjms-stomp/src/main/java/io/hawtjms/provider/stomp/StompSession.java import javax.jms.JMSException; import io.hawtjms.jms.meta.JmsConsumerId; import io.hawtjms.jms.meta.JmsConsumerInfo; import io.hawtjms.jms.meta.JmsProducerId; import io.hawtjms.jms.meta.JmsProducerInfo; import io.hawtjms.jms.meta.JmsSessionId; import io.hawtjms.jms.meta.JmsSessionInfo; import io.hawtjms.provider.AsyncResult; import io.hawtjms.provider.ProviderRequest; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 io.hawtjms.provider.stomp; /** * Represents a logical Session instance for a STOMP connection. */ public class StompSession { private final StompConnection connection; private final JmsSessionInfo sessionInfo; private final Map<JmsProducerId, StompProducer> producers = new HashMap<JmsProducerId, StompProducer>();
private final Map<JmsConsumerId, StompConsumer> consumers = new HashMap<JmsConsumerId, StompConsumer>();
fusesource/hawtjms
hawtjms-amqp/src/main/java/io/hawtjms/provider/amqp/AmqpSslProvider.java
// Path: hawtjms-core/src/main/java/io/hawtjms/transports/SslTransport.java // public class SslTransport extends TcpTransport { // // private final JmsSslContext context; // // /** // * Create an instance of the SSL transport // * // * @param listener // * The TransportListener that will handle events from this Transport instance. // * @param remoteLocation // * The location that is being connected to. // * @param JmsSslContext // * The JMS Framework SslContext to use for this SSL connection. // */ // public SslTransport(TransportListener listener, URI remoteLocation, JmsSslContext context) { // super(listener, remoteLocation); // // this.context = context; // } // // @Override // protected void configureNetClient(NetClient client) throws IOException { // super.configureNetClient(client); // // client.setSSL(true); // client.setKeyStorePath(context.getKeyStoreLocation()); // client.setKeyStorePassword(context.getKeyStorePassword()); // client.setTrustStorePath(context.getTrustStoreLocation()); // client.setTrustStorePassword(context.getTrustStorePassword()); // } // }
import io.hawtjms.jms.JmsSslContext; import io.hawtjms.transports.Transport; import io.hawtjms.transports.SslTransport; import java.net.URI; import java.util.Map;
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 io.hawtjms.provider.amqp; /** * AmqpProvider extension that enables SSL based transports. */ public class AmqpSslProvider extends AmqpProvider { private final JmsSslContext sslContext; public AmqpSslProvider(URI remoteURI) { super(remoteURI); this.sslContext = JmsSslContext.getCurrentSslContext(); } public AmqpSslProvider(URI remoteURI, Map<String, String> extraOptions) { super(remoteURI, extraOptions); this.sslContext = JmsSslContext.getCurrentSslContext(); } @Override protected Transport createTransport(URI remoteLocation) {
// Path: hawtjms-core/src/main/java/io/hawtjms/transports/SslTransport.java // public class SslTransport extends TcpTransport { // // private final JmsSslContext context; // // /** // * Create an instance of the SSL transport // * // * @param listener // * The TransportListener that will handle events from this Transport instance. // * @param remoteLocation // * The location that is being connected to. // * @param JmsSslContext // * The JMS Framework SslContext to use for this SSL connection. // */ // public SslTransport(TransportListener listener, URI remoteLocation, JmsSslContext context) { // super(listener, remoteLocation); // // this.context = context; // } // // @Override // protected void configureNetClient(NetClient client) throws IOException { // super.configureNetClient(client); // // client.setSSL(true); // client.setKeyStorePath(context.getKeyStoreLocation()); // client.setKeyStorePassword(context.getKeyStorePassword()); // client.setTrustStorePath(context.getTrustStoreLocation()); // client.setTrustStorePassword(context.getTrustStorePassword()); // } // } // Path: hawtjms-amqp/src/main/java/io/hawtjms/provider/amqp/AmqpSslProvider.java import io.hawtjms.jms.JmsSslContext; import io.hawtjms.transports.Transport; import io.hawtjms.transports.SslTransport; import java.net.URI; import java.util.Map; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 io.hawtjms.provider.amqp; /** * AmqpProvider extension that enables SSL based transports. */ public class AmqpSslProvider extends AmqpProvider { private final JmsSslContext sslContext; public AmqpSslProvider(URI remoteURI) { super(remoteURI); this.sslContext = JmsSslContext.getCurrentSslContext(); } public AmqpSslProvider(URI remoteURI, Map<String, String> extraOptions) { super(remoteURI, extraOptions); this.sslContext = JmsSslContext.getCurrentSslContext(); } @Override protected Transport createTransport(URI remoteLocation) {
return new SslTransport(this, remoteLocation, sslContext);
ezoerner/c-star-path-j
core/src/test/java/com/ebuddy/cassandra/structure/DefaultPathTest.java
// Path: api/src/main/java/com/ebuddy/cassandra/Path.java // public interface Path { // // /** Return a new Path consisting of this Path concatenated with another Path. */ // Path concat(Path other); // // /** Return a new Path consisting of this Path concatenated with the specified list indices as elements. */ // Path withIndices(int... indices); // // /** Return a new Path consisting of this Path concatenated with the specified elements. */ // Path withElements(String... elements); // // /** Get the encoded elements of this Path. */ // Iterable<String> getElements(); // // /** // * Returns the first element in this path, or null if this is an empty path. // */ // String head(); // // /** // * Returns the rest of the path after the head (first) element. // * If this is an empty path, throws IndexOutOfBoundsException, // * if this path has only one element, return an empty path, // * otherwise return a new path with elements starting after the head. // */ // Path tail(); // // /** // * Return a new Path consisting of the rest of the path elements of this path starting with the specified index. // * @param startIndex 0-based start index // * @return new Path // * @throws IndexOutOfBoundsException if path has insufficient size // */ // Path tail(int startIndex); // // /** // * Return true if this path starts with the specified path. // */ // boolean startsWith(Path path); // // /** Get the number of elements in this path. */ // int size(); // // /** Return true if this Path has zero elements. */ // boolean isEmpty(); // }
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; import com.ebuddy.cassandra.Path;
/* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.structure; /** * Tests for DefaultPath. * * @author Eric Zoerner <a href="mailto:ezoerner@ebuddy.com">ezoerner@ebuddy.com</a> */ public class DefaultPathTest { @Test(groups = "unit") public void convertFromPathStringWithTrailingDelimiter() throws Exception {
// Path: api/src/main/java/com/ebuddy/cassandra/Path.java // public interface Path { // // /** Return a new Path consisting of this Path concatenated with another Path. */ // Path concat(Path other); // // /** Return a new Path consisting of this Path concatenated with the specified list indices as elements. */ // Path withIndices(int... indices); // // /** Return a new Path consisting of this Path concatenated with the specified elements. */ // Path withElements(String... elements); // // /** Get the encoded elements of this Path. */ // Iterable<String> getElements(); // // /** // * Returns the first element in this path, or null if this is an empty path. // */ // String head(); // // /** // * Returns the rest of the path after the head (first) element. // * If this is an empty path, throws IndexOutOfBoundsException, // * if this path has only one element, return an empty path, // * otherwise return a new path with elements starting after the head. // */ // Path tail(); // // /** // * Return a new Path consisting of the rest of the path elements of this path starting with the specified index. // * @param startIndex 0-based start index // * @return new Path // * @throws IndexOutOfBoundsException if path has insufficient size // */ // Path tail(int startIndex); // // /** // * Return true if this path starts with the specified path. // */ // boolean startsWith(Path path); // // /** Get the number of elements in this path. */ // int size(); // // /** Return true if this Path has zero elements. */ // boolean isEmpty(); // } // Path: core/src/test/java/com/ebuddy/cassandra/structure/DefaultPathTest.java import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import org.testng.annotations.Test; import com.ebuddy.cassandra.Path; /* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.structure; /** * Tests for DefaultPath. * * @author Eric Zoerner <a href="mailto:ezoerner@ebuddy.com">ezoerner@ebuddy.com</a> */ public class DefaultPathTest { @Test(groups = "unit") public void convertFromPathStringWithTrailingDelimiter() throws Exception {
Path path = DefaultPath.fromEncodedPathString("x/y/");
ezoerner/c-star-path-j
thrift/src/test/java/com/ebuddy/cassandra/dao/SuperColumnFamilyTemplateSystemTest.java
// Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/SuperColumnFamilyRowMapper.java // public interface SuperColumnFamilyRowMapper<T,K,SN,N,V> { // T mapRow(K rowKey, List<HSuperColumn<SN,N,V>> superColumns); // }
import me.prettyprint.cassandra.serializers.StringSerializer; import me.prettyprint.hector.api.Cluster; import me.prettyprint.hector.api.Keyspace; import me.prettyprint.hector.api.beans.HSuperColumn; import me.prettyprint.hector.api.factory.HFactory; import static org.testng.Assert.assertEquals; import java.util.Arrays; import java.util.List; import org.cassandraunit.DataLoader; import org.cassandraunit.dataset.yaml.ClassPathYamlDataSet; import org.cassandraunit.utils.EmbeddedCassandraServerHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.ebuddy.cassandra.dao.mapper.SuperColumnFamilyRowMapper;
/* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.dao; /** * @author Aliaksandr Kazlou */ public class SuperColumnFamilyTemplateSystemTest { private static final Logger LOG = LoggerFactory.getLogger(SuperColumnFamilyTemplateSystemTest.class); private static final String CLUSTER_NAME = "Test Cluster"; private static final String HOST = "localhost:9171"; private static final String ALEX_ROW_KEY = "27e988f7-6d60-4410-ada5-fb3ebf884c68"; private static final String MIKE_ROW_KEY = "9081707c-82cb-4d32-948d-25c4733453fc"; private static final String SUPER_COLUMN_FAMILY = "SuperCF1"; private static final String KEYSPACE_NAME = "SuperColumnFamilyTemplateSystemTest"; @BeforeMethod(alwaysRun = true) public void setUp() throws Exception { // It starts only once. If this method has been already called, nothing will happen, Cassandra still be started // We can also if necessary clean the whole database and/or stop during the tests ;) // For advanced usage: see https://github.com/jsevellec/cassandra-unit/wiki/How-to-use-it-in-your-code EmbeddedCassandraServerHelper.startEmbeddedCassandra(); DataLoader dataLoader = new DataLoader(CLUSTER_NAME, HOST); ClassPathYamlDataSet dataSet = new ClassPathYamlDataSet("super-column-family-template-it-data.yaml"); dataLoader.load(dataSet); } @Test(groups = "system") public void shouldMultiGetAllSuperColumns() throws Exception { Keyspace keyspace = getKeyspace(); SuperColumnFamilyTemplate<String,String,String,String> template = new SuperColumnFamilyTemplate<String,String,String,String>( keyspace, SUPER_COLUMN_FAMILY, StringSerializer.get(), StringSerializer.get(), StringSerializer.get(), StringSerializer.get()); template.multiGetAllSuperColumns(Arrays.asList(ALEX_ROW_KEY, MIKE_ROW_KEY),
// Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/SuperColumnFamilyRowMapper.java // public interface SuperColumnFamilyRowMapper<T,K,SN,N,V> { // T mapRow(K rowKey, List<HSuperColumn<SN,N,V>> superColumns); // } // Path: thrift/src/test/java/com/ebuddy/cassandra/dao/SuperColumnFamilyTemplateSystemTest.java import me.prettyprint.cassandra.serializers.StringSerializer; import me.prettyprint.hector.api.Cluster; import me.prettyprint.hector.api.Keyspace; import me.prettyprint.hector.api.beans.HSuperColumn; import me.prettyprint.hector.api.factory.HFactory; import static org.testng.Assert.assertEquals; import java.util.Arrays; import java.util.List; import org.cassandraunit.DataLoader; import org.cassandraunit.dataset.yaml.ClassPathYamlDataSet; import org.cassandraunit.utils.EmbeddedCassandraServerHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.ebuddy.cassandra.dao.mapper.SuperColumnFamilyRowMapper; /* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.dao; /** * @author Aliaksandr Kazlou */ public class SuperColumnFamilyTemplateSystemTest { private static final Logger LOG = LoggerFactory.getLogger(SuperColumnFamilyTemplateSystemTest.class); private static final String CLUSTER_NAME = "Test Cluster"; private static final String HOST = "localhost:9171"; private static final String ALEX_ROW_KEY = "27e988f7-6d60-4410-ada5-fb3ebf884c68"; private static final String MIKE_ROW_KEY = "9081707c-82cb-4d32-948d-25c4733453fc"; private static final String SUPER_COLUMN_FAMILY = "SuperCF1"; private static final String KEYSPACE_NAME = "SuperColumnFamilyTemplateSystemTest"; @BeforeMethod(alwaysRun = true) public void setUp() throws Exception { // It starts only once. If this method has been already called, nothing will happen, Cassandra still be started // We can also if necessary clean the whole database and/or stop during the tests ;) // For advanced usage: see https://github.com/jsevellec/cassandra-unit/wiki/How-to-use-it-in-your-code EmbeddedCassandraServerHelper.startEmbeddedCassandra(); DataLoader dataLoader = new DataLoader(CLUSTER_NAME, HOST); ClassPathYamlDataSet dataSet = new ClassPathYamlDataSet("super-column-family-template-it-data.yaml"); dataLoader.load(dataSet); } @Test(groups = "system") public void shouldMultiGetAllSuperColumns() throws Exception { Keyspace keyspace = getKeyspace(); SuperColumnFamilyTemplate<String,String,String,String> template = new SuperColumnFamilyTemplate<String,String,String,String>( keyspace, SUPER_COLUMN_FAMILY, StringSerializer.get(), StringSerializer.get(), StringSerializer.get(), StringSerializer.get()); template.multiGetAllSuperColumns(Arrays.asList(ALEX_ROW_KEY, MIKE_ROW_KEY),
new SuperColumnFamilyRowMapper<Object,String,String,String,String>() {
ezoerner/c-star-path-j
core/src/main/java/com/ebuddy/cassandra/structure/Decomposer.java
// Path: api/src/main/java/com/ebuddy/cassandra/Path.java // public interface Path { // // /** Return a new Path consisting of this Path concatenated with another Path. */ // Path concat(Path other); // // /** Return a new Path consisting of this Path concatenated with the specified list indices as elements. */ // Path withIndices(int... indices); // // /** Return a new Path consisting of this Path concatenated with the specified elements. */ // Path withElements(String... elements); // // /** Get the encoded elements of this Path. */ // Iterable<String> getElements(); // // /** // * Returns the first element in this path, or null if this is an empty path. // */ // String head(); // // /** // * Returns the rest of the path after the head (first) element. // * If this is an empty path, throws IndexOutOfBoundsException, // * if this path has only one element, return an empty path, // * otherwise return a new path with elements starting after the head. // */ // Path tail(); // // /** // * Return a new Path consisting of the rest of the path elements of this path starting with the specified index. // * @param startIndex 0-based start index // * @return new Path // * @throws IndexOutOfBoundsException if path has insufficient size // */ // Path tail(int startIndex); // // /** // * Return true if this path starts with the specified path. // */ // boolean startsWith(Path path); // // /** Get the number of elements in this path. */ // int size(); // // /** Return true if this Path has zero elements. */ // boolean isEmpty(); // }
import static org.apache.commons.lang3.ObjectUtils.NULL; import java.util.HashMap; import java.util.List; import java.util.Map; import com.ebuddy.cassandra.Path;
/* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.structure; /** * Support for decomposing complex objects into paths to simple objects. * Only the basic JSON structures are currently supported, i.e. Maps, Lists, Strings, Numbers, Booleans, and null. * * @author Eric Zoerner <a href="mailto:ezoerner@ebuddy.com">ezoerner@ebuddy.com</a> */ public class Decomposer { private static final Decomposer INSTANCE = new Decomposer(); private Decomposer() { } public static Decomposer get() { return INSTANCE; } /** * Decompose a map of arbitrarily complex structured objects into a map of * simple objects keyed by paths. * * @param structures the input map of paths to objects * @return a map of simple object keyed by paths * @throws IllegalArgumentException if there is an object of unsupported type in structures * or if structures is null */
// Path: api/src/main/java/com/ebuddy/cassandra/Path.java // public interface Path { // // /** Return a new Path consisting of this Path concatenated with another Path. */ // Path concat(Path other); // // /** Return a new Path consisting of this Path concatenated with the specified list indices as elements. */ // Path withIndices(int... indices); // // /** Return a new Path consisting of this Path concatenated with the specified elements. */ // Path withElements(String... elements); // // /** Get the encoded elements of this Path. */ // Iterable<String> getElements(); // // /** // * Returns the first element in this path, or null if this is an empty path. // */ // String head(); // // /** // * Returns the rest of the path after the head (first) element. // * If this is an empty path, throws IndexOutOfBoundsException, // * if this path has only one element, return an empty path, // * otherwise return a new path with elements starting after the head. // */ // Path tail(); // // /** // * Return a new Path consisting of the rest of the path elements of this path starting with the specified index. // * @param startIndex 0-based start index // * @return new Path // * @throws IndexOutOfBoundsException if path has insufficient size // */ // Path tail(int startIndex); // // /** // * Return true if this path starts with the specified path. // */ // boolean startsWith(Path path); // // /** Get the number of elements in this path. */ // int size(); // // /** Return true if this Path has zero elements. */ // boolean isEmpty(); // } // Path: core/src/main/java/com/ebuddy/cassandra/structure/Decomposer.java import static org.apache.commons.lang3.ObjectUtils.NULL; import java.util.HashMap; import java.util.List; import java.util.Map; import com.ebuddy.cassandra.Path; /* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.structure; /** * Support for decomposing complex objects into paths to simple objects. * Only the basic JSON structures are currently supported, i.e. Maps, Lists, Strings, Numbers, Booleans, and null. * * @author Eric Zoerner <a href="mailto:ezoerner@ebuddy.com">ezoerner@ebuddy.com</a> */ public class Decomposer { private static final Decomposer INSTANCE = new Decomposer(); private Decomposer() { } public static Decomposer get() { return INSTANCE; } /** * Decompose a map of arbitrarily complex structured objects into a map of * simple objects keyed by paths. * * @param structures the input map of paths to objects * @return a map of simple object keyed by paths * @throws IllegalArgumentException if there is an object of unsupported type in structures * or if structures is null */
public Map<Path,Object> decompose(Map<Path,Object> structures) {
ezoerner/c-star-path-j
thrift/src/main/java/com/ebuddy/cassandra/dao/ColumnFamilyOperations.java
// Path: api/src/main/java/com/ebuddy/cassandra/BatchContext.java // public interface BatchContext { } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnFamilyRowMapper.java // public interface ColumnFamilyRowMapper<T,K,N,V> { // // T mapRow(K rowKey, List<HColumn<N,V>> columns); // // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnMapper.java // public interface ColumnMapper<T,N,V> { // // T mapColumn(N columnName, V columnValue); // // }
import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.annotation.Nonnull; import com.ebuddy.cassandra.BatchContext; import com.ebuddy.cassandra.dao.mapper.ColumnFamilyRowMapper; import com.ebuddy.cassandra.dao.mapper.ColumnMapper;
/* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.dao; /** * Core Column Family operations. * @author Eric Zoerner <a href="mailto:ezoerner@ebuddy.com">ezoerner@ebuddy.com</a> */ public interface ColumnFamilyOperations<K,N,V> { /** * Create a BatchContext for use with this keyspace. * * @return the BatchContext */ BatchContext begin(); /** * Execute a batch of mutations using a mutator. * * @param batchContext the BatchContext */ void commit(@Nonnull BatchContext batchContext); V readColumnValue(K rowKey, N columnName); Map<N,V> readColumnsAsMap(K rowKey); Map<N,V> readColumnsAsMap(K rowKey, N start, N finish, int count, boolean reversed);
// Path: api/src/main/java/com/ebuddy/cassandra/BatchContext.java // public interface BatchContext { } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnFamilyRowMapper.java // public interface ColumnFamilyRowMapper<T,K,N,V> { // // T mapRow(K rowKey, List<HColumn<N,V>> columns); // // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnMapper.java // public interface ColumnMapper<T,N,V> { // // T mapColumn(N columnName, V columnValue); // // } // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/ColumnFamilyOperations.java import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.annotation.Nonnull; import com.ebuddy.cassandra.BatchContext; import com.ebuddy.cassandra.dao.mapper.ColumnFamilyRowMapper; import com.ebuddy.cassandra.dao.mapper.ColumnMapper; /* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.dao; /** * Core Column Family operations. * @author Eric Zoerner <a href="mailto:ezoerner@ebuddy.com">ezoerner@ebuddy.com</a> */ public interface ColumnFamilyOperations<K,N,V> { /** * Create a BatchContext for use with this keyspace. * * @return the BatchContext */ BatchContext begin(); /** * Execute a batch of mutations using a mutator. * * @param batchContext the BatchContext */ void commit(@Nonnull BatchContext batchContext); V readColumnValue(K rowKey, N columnName); Map<N,V> readColumnsAsMap(K rowKey); Map<N,V> readColumnsAsMap(K rowKey, N start, N finish, int count, boolean reversed);
<T> List<T> readColumns(K rowKey, ColumnMapper<T,N,V> columnMapper);
ezoerner/c-star-path-j
thrift/src/main/java/com/ebuddy/cassandra/dao/ColumnFamilyOperations.java
// Path: api/src/main/java/com/ebuddy/cassandra/BatchContext.java // public interface BatchContext { } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnFamilyRowMapper.java // public interface ColumnFamilyRowMapper<T,K,N,V> { // // T mapRow(K rowKey, List<HColumn<N,V>> columns); // // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnMapper.java // public interface ColumnMapper<T,N,V> { // // T mapColumn(N columnName, V columnValue); // // }
import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.annotation.Nonnull; import com.ebuddy.cassandra.BatchContext; import com.ebuddy.cassandra.dao.mapper.ColumnFamilyRowMapper; import com.ebuddy.cassandra.dao.mapper.ColumnMapper;
/* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.dao; /** * Core Column Family operations. * @author Eric Zoerner <a href="mailto:ezoerner@ebuddy.com">ezoerner@ebuddy.com</a> */ public interface ColumnFamilyOperations<K,N,V> { /** * Create a BatchContext for use with this keyspace. * * @return the BatchContext */ BatchContext begin(); /** * Execute a batch of mutations using a mutator. * * @param batchContext the BatchContext */ void commit(@Nonnull BatchContext batchContext); V readColumnValue(K rowKey, N columnName); Map<N,V> readColumnsAsMap(K rowKey); Map<N,V> readColumnsAsMap(K rowKey, N start, N finish, int count, boolean reversed); <T> List<T> readColumns(K rowKey, ColumnMapper<T,N,V> columnMapper); <T> List<T> readColumns(K rowKey, N start, N finish, int count, boolean reversed, ColumnMapper<T,N,V> columnMapper); Map<K,Map<N,V>> multiGetAsMap(Iterable<K> rowKeys); Map<K,Map<N,V>> multiGetColumnsAsMap(Iterable<K> rowKeys, N... columnNames); Map<K,Map<N,V>> readRowsAsMap();
// Path: api/src/main/java/com/ebuddy/cassandra/BatchContext.java // public interface BatchContext { } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnFamilyRowMapper.java // public interface ColumnFamilyRowMapper<T,K,N,V> { // // T mapRow(K rowKey, List<HColumn<N,V>> columns); // // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnMapper.java // public interface ColumnMapper<T,N,V> { // // T mapColumn(N columnName, V columnValue); // // } // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/ColumnFamilyOperations.java import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.annotation.Nonnull; import com.ebuddy.cassandra.BatchContext; import com.ebuddy.cassandra.dao.mapper.ColumnFamilyRowMapper; import com.ebuddy.cassandra.dao.mapper.ColumnMapper; /* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.dao; /** * Core Column Family operations. * @author Eric Zoerner <a href="mailto:ezoerner@ebuddy.com">ezoerner@ebuddy.com</a> */ public interface ColumnFamilyOperations<K,N,V> { /** * Create a BatchContext for use with this keyspace. * * @return the BatchContext */ BatchContext begin(); /** * Execute a batch of mutations using a mutator. * * @param batchContext the BatchContext */ void commit(@Nonnull BatchContext batchContext); V readColumnValue(K rowKey, N columnName); Map<N,V> readColumnsAsMap(K rowKey); Map<N,V> readColumnsAsMap(K rowKey, N start, N finish, int count, boolean reversed); <T> List<T> readColumns(K rowKey, ColumnMapper<T,N,V> columnMapper); <T> List<T> readColumns(K rowKey, N start, N finish, int count, boolean reversed, ColumnMapper<T,N,V> columnMapper); Map<K,Map<N,V>> multiGetAsMap(Iterable<K> rowKeys); Map<K,Map<N,V>> multiGetColumnsAsMap(Iterable<K> rowKeys, N... columnNames); Map<K,Map<N,V>> readRowsAsMap();
<T> List<T> multiGet(Iterable<K> rowKeys, ColumnFamilyRowMapper<T,K,N,V> rowMapper);
ezoerner/c-star-path-j
thrift/src/main/java/com/ebuddy/cassandra/dao/KeyspaceTemplate.java
// Path: api/src/main/java/com/ebuddy/cassandra/BatchContext.java // public interface BatchContext { }
import javax.annotation.Nonnull; import org.apache.commons.lang3.Validate; import com.ebuddy.cassandra.BatchContext; import me.prettyprint.hector.api.Keyspace; import me.prettyprint.hector.api.Serializer; import me.prettyprint.hector.api.factory.HFactory; import me.prettyprint.hector.api.mutation.Mutator;
/* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.dao; /** * Template for a keyspace. Implements methods that operate on a Keyspace. * @author Eric Zoerner <a href="mailto:ezoerner@ebuddy.com">ezoerner@ebuddy.com</a> */ // See comment in AbstractColumnFamilyTemplate. public class KeyspaceTemplate<K> implements KeyspaceOperations { /** * The keyspace for operations. */ private final Keyspace keyspace; /** * The serializer for row keys. */ private final Serializer<K> keySerializer; public KeyspaceTemplate(Keyspace keyspace, Serializer<K> keySerializer) { if (keySerializer == null) { throw new IllegalArgumentException("keySerializer is null"); } if (keyspace == null) { throw new IllegalArgumentException("keyspace is null"); } this.keyspace = keyspace; this.keySerializer = keySerializer; } /** * Create a BatchContext for use with batch operations. */ @Override
// Path: api/src/main/java/com/ebuddy/cassandra/BatchContext.java // public interface BatchContext { } // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/KeyspaceTemplate.java import javax.annotation.Nonnull; import org.apache.commons.lang3.Validate; import com.ebuddy.cassandra.BatchContext; import me.prettyprint.hector.api.Keyspace; import me.prettyprint.hector.api.Serializer; import me.prettyprint.hector.api.factory.HFactory; import me.prettyprint.hector.api.mutation.Mutator; /* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.dao; /** * Template for a keyspace. Implements methods that operate on a Keyspace. * @author Eric Zoerner <a href="mailto:ezoerner@ebuddy.com">ezoerner@ebuddy.com</a> */ // See comment in AbstractColumnFamilyTemplate. public class KeyspaceTemplate<K> implements KeyspaceOperations { /** * The keyspace for operations. */ private final Keyspace keyspace; /** * The serializer for row keys. */ private final Serializer<K> keySerializer; public KeyspaceTemplate(Keyspace keyspace, Serializer<K> keySerializer) { if (keySerializer == null) { throw new IllegalArgumentException("keySerializer is null"); } if (keyspace == null) { throw new IllegalArgumentException("keyspace is null"); } this.keyspace = keyspace; this.keySerializer = keySerializer; } /** * Create a BatchContext for use with batch operations. */ @Override
public final BatchContext begin() {
ezoerner/c-star-path-j
thrift/src/test/java/com/ebuddy/cassandra/dao/ThriftStructuredDataSupportTest.java
// Path: api/src/main/java/com/ebuddy/cassandra/Path.java // public interface Path { // // /** Return a new Path consisting of this Path concatenated with another Path. */ // Path concat(Path other); // // /** Return a new Path consisting of this Path concatenated with the specified list indices as elements. */ // Path withIndices(int... indices); // // /** Return a new Path consisting of this Path concatenated with the specified elements. */ // Path withElements(String... elements); // // /** Get the encoded elements of this Path. */ // Iterable<String> getElements(); // // /** // * Returns the first element in this path, or null if this is an empty path. // */ // String head(); // // /** // * Returns the rest of the path after the head (first) element. // * If this is an empty path, throws IndexOutOfBoundsException, // * if this path has only one element, return an empty path, // * otherwise return a new path with elements starting after the head. // */ // Path tail(); // // /** // * Return a new Path consisting of the rest of the path elements of this path starting with the specified index. // * @param startIndex 0-based start index // * @return new Path // * @throws IndexOutOfBoundsException if path has insufficient size // */ // Path tail(int startIndex); // // /** // * Return true if this path starts with the specified path. // */ // boolean startsWith(Path path); // // /** Get the number of elements in this path. */ // int size(); // // /** Return true if this Path has zero elements. */ // boolean isEmpty(); // } // // Path: api/src/main/java/com/ebuddy/cassandra/TypeReference.java // public abstract class TypeReference<T> // implements Comparable<TypeReference<T>> // { // protected final Type type; // // protected TypeReference() // { // Type superClass = getClass().getGenericSuperclass(); // if (superClass instanceof Class<?>) { // sanity check, should never happen // throw new IllegalArgumentException("Internal error: TypeReference constructed without actual type information"); // } // /* 22-Dec-2008, tatu: Not sure if this case is safe -- I suspect // * it is possible to make it fail? // * But let's deal with specific // * case when we know an actual use case, and thereby suitable // * workarounds for valid case(s) and/or error to throw // * on invalid one(s). // */ // type = ((ParameterizedType) superClass).getActualTypeArguments()[0]; // } // // public Type getType() { return type; } // // /** // * The only reason we define this method (and require implementation // * of {@code Comparable}) is to prevent constructing a // * reference without type information. // */ // @Override // public int compareTo(TypeReference<T> o) { // // just need an implementation, not a good one... hence: // return 0; // } // }
import org.testng.annotations.Test; import com.ebuddy.cassandra.Path; import com.ebuddy.cassandra.TypeReference; import static org.apache.commons.lang3.ObjectUtils.NULL; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.annotations.BeforeMethod;
/* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.dao; /** * Unit tests for ThriftStructuredDataSupport. * * @author Eric Zoerner <a href="mailto:ezoerner@ebuddy.com">ezoerner@ebuddy.com</a> */ public class ThriftStructuredDataSupportTest { private static final int MAX_CODE_POINT = 0x10FFFF; @Mock private ColumnFamilyOperations<String,String,Object> operations; private ThriftStructuredDataSupport<String> dao ; private final String rowKey = "rowKey";
// Path: api/src/main/java/com/ebuddy/cassandra/Path.java // public interface Path { // // /** Return a new Path consisting of this Path concatenated with another Path. */ // Path concat(Path other); // // /** Return a new Path consisting of this Path concatenated with the specified list indices as elements. */ // Path withIndices(int... indices); // // /** Return a new Path consisting of this Path concatenated with the specified elements. */ // Path withElements(String... elements); // // /** Get the encoded elements of this Path. */ // Iterable<String> getElements(); // // /** // * Returns the first element in this path, or null if this is an empty path. // */ // String head(); // // /** // * Returns the rest of the path after the head (first) element. // * If this is an empty path, throws IndexOutOfBoundsException, // * if this path has only one element, return an empty path, // * otherwise return a new path with elements starting after the head. // */ // Path tail(); // // /** // * Return a new Path consisting of the rest of the path elements of this path starting with the specified index. // * @param startIndex 0-based start index // * @return new Path // * @throws IndexOutOfBoundsException if path has insufficient size // */ // Path tail(int startIndex); // // /** // * Return true if this path starts with the specified path. // */ // boolean startsWith(Path path); // // /** Get the number of elements in this path. */ // int size(); // // /** Return true if this Path has zero elements. */ // boolean isEmpty(); // } // // Path: api/src/main/java/com/ebuddy/cassandra/TypeReference.java // public abstract class TypeReference<T> // implements Comparable<TypeReference<T>> // { // protected final Type type; // // protected TypeReference() // { // Type superClass = getClass().getGenericSuperclass(); // if (superClass instanceof Class<?>) { // sanity check, should never happen // throw new IllegalArgumentException("Internal error: TypeReference constructed without actual type information"); // } // /* 22-Dec-2008, tatu: Not sure if this case is safe -- I suspect // * it is possible to make it fail? // * But let's deal with specific // * case when we know an actual use case, and thereby suitable // * workarounds for valid case(s) and/or error to throw // * on invalid one(s). // */ // type = ((ParameterizedType) superClass).getActualTypeArguments()[0]; // } // // public Type getType() { return type; } // // /** // * The only reason we define this method (and require implementation // * of {@code Comparable}) is to prevent constructing a // * reference without type information. // */ // @Override // public int compareTo(TypeReference<T> o) { // // just need an implementation, not a good one... hence: // return 0; // } // } // Path: thrift/src/test/java/com/ebuddy/cassandra/dao/ThriftStructuredDataSupportTest.java import org.testng.annotations.Test; import com.ebuddy.cassandra.Path; import com.ebuddy.cassandra.TypeReference; import static org.apache.commons.lang3.ObjectUtils.NULL; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.annotations.BeforeMethod; /* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.dao; /** * Unit tests for ThriftStructuredDataSupport. * * @author Eric Zoerner <a href="mailto:ezoerner@ebuddy.com">ezoerner@ebuddy.com</a> */ public class ThriftStructuredDataSupportTest { private static final int MAX_CODE_POINT = 0x10FFFF; @Mock private ColumnFamilyOperations<String,String,Object> operations; private ThriftStructuredDataSupport<String> dao ; private final String rowKey = "rowKey";
private final TypeReference<TestPojo> typeReference = new TypeReference<TestPojo>() { };
ezoerner/c-star-path-j
thrift/src/test/java/com/ebuddy/cassandra/dao/ThriftStructuredDataSupportTest.java
// Path: api/src/main/java/com/ebuddy/cassandra/Path.java // public interface Path { // // /** Return a new Path consisting of this Path concatenated with another Path. */ // Path concat(Path other); // // /** Return a new Path consisting of this Path concatenated with the specified list indices as elements. */ // Path withIndices(int... indices); // // /** Return a new Path consisting of this Path concatenated with the specified elements. */ // Path withElements(String... elements); // // /** Get the encoded elements of this Path. */ // Iterable<String> getElements(); // // /** // * Returns the first element in this path, or null if this is an empty path. // */ // String head(); // // /** // * Returns the rest of the path after the head (first) element. // * If this is an empty path, throws IndexOutOfBoundsException, // * if this path has only one element, return an empty path, // * otherwise return a new path with elements starting after the head. // */ // Path tail(); // // /** // * Return a new Path consisting of the rest of the path elements of this path starting with the specified index. // * @param startIndex 0-based start index // * @return new Path // * @throws IndexOutOfBoundsException if path has insufficient size // */ // Path tail(int startIndex); // // /** // * Return true if this path starts with the specified path. // */ // boolean startsWith(Path path); // // /** Get the number of elements in this path. */ // int size(); // // /** Return true if this Path has zero elements. */ // boolean isEmpty(); // } // // Path: api/src/main/java/com/ebuddy/cassandra/TypeReference.java // public abstract class TypeReference<T> // implements Comparable<TypeReference<T>> // { // protected final Type type; // // protected TypeReference() // { // Type superClass = getClass().getGenericSuperclass(); // if (superClass instanceof Class<?>) { // sanity check, should never happen // throw new IllegalArgumentException("Internal error: TypeReference constructed without actual type information"); // } // /* 22-Dec-2008, tatu: Not sure if this case is safe -- I suspect // * it is possible to make it fail? // * But let's deal with specific // * case when we know an actual use case, and thereby suitable // * workarounds for valid case(s) and/or error to throw // * on invalid one(s). // */ // type = ((ParameterizedType) superClass).getActualTypeArguments()[0]; // } // // public Type getType() { return type; } // // /** // * The only reason we define this method (and require implementation // * of {@code Comparable}) is to prevent constructing a // * reference without type information. // */ // @Override // public int compareTo(TypeReference<T> o) { // // just need an implementation, not a good one... hence: // return 0; // } // }
import org.testng.annotations.Test; import com.ebuddy.cassandra.Path; import com.ebuddy.cassandra.TypeReference; import static org.apache.commons.lang3.ObjectUtils.NULL; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.annotations.BeforeMethod;
/* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.dao; /** * Unit tests for ThriftStructuredDataSupport. * * @author Eric Zoerner <a href="mailto:ezoerner@ebuddy.com">ezoerner@ebuddy.com</a> */ public class ThriftStructuredDataSupportTest { private static final int MAX_CODE_POINT = 0x10FFFF; @Mock private ColumnFamilyOperations<String,String,Object> operations; private ThriftStructuredDataSupport<String> dao ; private final String rowKey = "rowKey"; private final TypeReference<TestPojo> typeReference = new TypeReference<TestPojo>() { };
// Path: api/src/main/java/com/ebuddy/cassandra/Path.java // public interface Path { // // /** Return a new Path consisting of this Path concatenated with another Path. */ // Path concat(Path other); // // /** Return a new Path consisting of this Path concatenated with the specified list indices as elements. */ // Path withIndices(int... indices); // // /** Return a new Path consisting of this Path concatenated with the specified elements. */ // Path withElements(String... elements); // // /** Get the encoded elements of this Path. */ // Iterable<String> getElements(); // // /** // * Returns the first element in this path, or null if this is an empty path. // */ // String head(); // // /** // * Returns the rest of the path after the head (first) element. // * If this is an empty path, throws IndexOutOfBoundsException, // * if this path has only one element, return an empty path, // * otherwise return a new path with elements starting after the head. // */ // Path tail(); // // /** // * Return a new Path consisting of the rest of the path elements of this path starting with the specified index. // * @param startIndex 0-based start index // * @return new Path // * @throws IndexOutOfBoundsException if path has insufficient size // */ // Path tail(int startIndex); // // /** // * Return true if this path starts with the specified path. // */ // boolean startsWith(Path path); // // /** Get the number of elements in this path. */ // int size(); // // /** Return true if this Path has zero elements. */ // boolean isEmpty(); // } // // Path: api/src/main/java/com/ebuddy/cassandra/TypeReference.java // public abstract class TypeReference<T> // implements Comparable<TypeReference<T>> // { // protected final Type type; // // protected TypeReference() // { // Type superClass = getClass().getGenericSuperclass(); // if (superClass instanceof Class<?>) { // sanity check, should never happen // throw new IllegalArgumentException("Internal error: TypeReference constructed without actual type information"); // } // /* 22-Dec-2008, tatu: Not sure if this case is safe -- I suspect // * it is possible to make it fail? // * But let's deal with specific // * case when we know an actual use case, and thereby suitable // * workarounds for valid case(s) and/or error to throw // * on invalid one(s). // */ // type = ((ParameterizedType) superClass).getActualTypeArguments()[0]; // } // // public Type getType() { return type; } // // /** // * The only reason we define this method (and require implementation // * of {@code Comparable}) is to prevent constructing a // * reference without type information. // */ // @Override // public int compareTo(TypeReference<T> o) { // // just need an implementation, not a good one... hence: // return 0; // } // } // Path: thrift/src/test/java/com/ebuddy/cassandra/dao/ThriftStructuredDataSupportTest.java import org.testng.annotations.Test; import com.ebuddy.cassandra.Path; import com.ebuddy.cassandra.TypeReference; import static org.apache.commons.lang3.ObjectUtils.NULL; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.annotations.BeforeMethod; /* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.dao; /** * Unit tests for ThriftStructuredDataSupport. * * @author Eric Zoerner <a href="mailto:ezoerner@ebuddy.com">ezoerner@ebuddy.com</a> */ public class ThriftStructuredDataSupportTest { private static final int MAX_CODE_POINT = 0x10FFFF; @Mock private ColumnFamilyOperations<String,String,Object> operations; private ThriftStructuredDataSupport<String> dao ; private final String rowKey = "rowKey"; private final TypeReference<TestPojo> typeReference = new TypeReference<TestPojo>() { };
private Path path;
ezoerner/c-star-path-j
thrift/src/test/java/com/ebuddy/cassandra/dao/SuperColumnFamilyTemplateTest.java
// Path: thrift/src/main/java/com/ebuddy/cassandra/dao/AbstractColumnFamilyTemplate.java // protected static final int ALL = Integer.MAX_VALUE; // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/visitor/ColumnVisitor.java // public interface ColumnVisitor<N, V> { // // /** // * Visit easy column and evaluates a logic. // * @param columnName the name of the column // * @param columnValue the value of the column // * @param timestamp the cassandra timestamp when the column was written // * @param ttl the time to live for that column value // */ // void visit(N columnName, V columnValue, long timestamp, int ttl); // // }
import static com.ebuddy.cassandra.dao.AbstractColumnFamilyTemplate.ALL; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.lang3.ObjectUtils; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.ebuddy.cassandra.dao.visitor.ColumnVisitor; import me.prettyprint.cassandra.model.ExecutingKeyspace; import me.prettyprint.cassandra.model.ExecutionResult; import me.prettyprint.cassandra.model.KeyspaceOperationCallback; import me.prettyprint.cassandra.serializers.StringSerializer; import me.prettyprint.hector.api.Serializer; import me.prettyprint.hector.api.beans.ColumnSlice; import me.prettyprint.hector.api.beans.HColumn; import me.prettyprint.hector.api.beans.HSuperColumn; import me.prettyprint.hector.api.beans.Row; import me.prettyprint.hector.api.beans.Rows; import me.prettyprint.hector.api.beans.SuperSlice; import me.prettyprint.hector.api.exceptions.HectorTransportException; import me.prettyprint.hector.api.factory.HFactory; import me.prettyprint.hector.api.mutation.Mutator;
/* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.dao; /** * Test for SuperColumnFamilyTemplate. * @author Eric Zoerner <a href="mailto:ezoerner@ebuddy.com">ezoerner@ebuddy.com</a> */ @SuppressWarnings({"unchecked", "rawtypes"}) public class SuperColumnFamilyTemplateTest { private final String columnFamily = "TestColumnFamily"; private final String rowKey = "testKey"; private final String superColumnName = "testSuperColumnName"; private final String columnName = "testColumnName"; private final List<String> columnNames = Arrays.asList("columnName1", "columnName2"); private final String columnValue = "testColumnValue"; private final List<String> columnValues = Arrays.asList("columnValue1", "columnValue2"); private final List<String> superColumnNames = Arrays.asList("superColumnName1", "superColumnName2"); private final List<String> rowKeys = Arrays.asList("rowKey1", "rowKey2"); @Mock private ExecutionResult executionResult; @Mock private KeyspaceTemplate.HectorBatchContext txnContext; @Mock private Mutator<String> mutator; private SuperColumnFamilyOperations<String,String,String,String> superColumnFamilyTestDao; @Mock
// Path: thrift/src/main/java/com/ebuddy/cassandra/dao/AbstractColumnFamilyTemplate.java // protected static final int ALL = Integer.MAX_VALUE; // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/visitor/ColumnVisitor.java // public interface ColumnVisitor<N, V> { // // /** // * Visit easy column and evaluates a logic. // * @param columnName the name of the column // * @param columnValue the value of the column // * @param timestamp the cassandra timestamp when the column was written // * @param ttl the time to live for that column value // */ // void visit(N columnName, V columnValue, long timestamp, int ttl); // // } // Path: thrift/src/test/java/com/ebuddy/cassandra/dao/SuperColumnFamilyTemplateTest.java import static com.ebuddy.cassandra.dao.AbstractColumnFamilyTemplate.ALL; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.lang3.ObjectUtils; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.ebuddy.cassandra.dao.visitor.ColumnVisitor; import me.prettyprint.cassandra.model.ExecutingKeyspace; import me.prettyprint.cassandra.model.ExecutionResult; import me.prettyprint.cassandra.model.KeyspaceOperationCallback; import me.prettyprint.cassandra.serializers.StringSerializer; import me.prettyprint.hector.api.Serializer; import me.prettyprint.hector.api.beans.ColumnSlice; import me.prettyprint.hector.api.beans.HColumn; import me.prettyprint.hector.api.beans.HSuperColumn; import me.prettyprint.hector.api.beans.Row; import me.prettyprint.hector.api.beans.Rows; import me.prettyprint.hector.api.beans.SuperSlice; import me.prettyprint.hector.api.exceptions.HectorTransportException; import me.prettyprint.hector.api.factory.HFactory; import me.prettyprint.hector.api.mutation.Mutator; /* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.dao; /** * Test for SuperColumnFamilyTemplate. * @author Eric Zoerner <a href="mailto:ezoerner@ebuddy.com">ezoerner@ebuddy.com</a> */ @SuppressWarnings({"unchecked", "rawtypes"}) public class SuperColumnFamilyTemplateTest { private final String columnFamily = "TestColumnFamily"; private final String rowKey = "testKey"; private final String superColumnName = "testSuperColumnName"; private final String columnName = "testColumnName"; private final List<String> columnNames = Arrays.asList("columnName1", "columnName2"); private final String columnValue = "testColumnValue"; private final List<String> columnValues = Arrays.asList("columnValue1", "columnValue2"); private final List<String> superColumnNames = Arrays.asList("superColumnName1", "superColumnName2"); private final List<String> rowKeys = Arrays.asList("rowKey1", "rowKey2"); @Mock private ExecutionResult executionResult; @Mock private KeyspaceTemplate.HectorBatchContext txnContext; @Mock private Mutator<String> mutator; private SuperColumnFamilyOperations<String,String,String,String> superColumnFamilyTestDao; @Mock
ColumnVisitor<String, String> columnVisitor;
ezoerner/c-star-path-j
thrift/src/test/java/com/ebuddy/cassandra/dao/SuperColumnFamilyTemplateTest.java
// Path: thrift/src/main/java/com/ebuddy/cassandra/dao/AbstractColumnFamilyTemplate.java // protected static final int ALL = Integer.MAX_VALUE; // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/visitor/ColumnVisitor.java // public interface ColumnVisitor<N, V> { // // /** // * Visit easy column and evaluates a logic. // * @param columnName the name of the column // * @param columnValue the value of the column // * @param timestamp the cassandra timestamp when the column was written // * @param ttl the time to live for that column value // */ // void visit(N columnName, V columnValue, long timestamp, int ttl); // // }
import static com.ebuddy.cassandra.dao.AbstractColumnFamilyTemplate.ALL; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.lang3.ObjectUtils; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.ebuddy.cassandra.dao.visitor.ColumnVisitor; import me.prettyprint.cassandra.model.ExecutingKeyspace; import me.prettyprint.cassandra.model.ExecutionResult; import me.prettyprint.cassandra.model.KeyspaceOperationCallback; import me.prettyprint.cassandra.serializers.StringSerializer; import me.prettyprint.hector.api.Serializer; import me.prettyprint.hector.api.beans.ColumnSlice; import me.prettyprint.hector.api.beans.HColumn; import me.prettyprint.hector.api.beans.HSuperColumn; import me.prettyprint.hector.api.beans.Row; import me.prettyprint.hector.api.beans.Rows; import me.prettyprint.hector.api.beans.SuperSlice; import me.prettyprint.hector.api.exceptions.HectorTransportException; import me.prettyprint.hector.api.factory.HFactory; import me.prettyprint.hector.api.mutation.Mutator;
@Test(groups={"unit"}, expectedExceptions = HectorTransportException.class) public void testDeleteColumnsTranslateHectorException() { when(mutator.addSubDelete(anyString(), anyString(), anyString(), anyString(), any(Serializer.class), any(Serializer.class))). thenThrow(new HectorTransportException("test hector exception")); //========================= superColumnFamilyTestDao.deleteColumns(rowKey, superColumnName, columnNames, txnContext); //========================= } @Test(groups = {"unit"}) public void testVisitColumn() { ColumnSlice columnSlice = mock(ColumnSlice.class); HColumn column1 = mock(HColumn.class); HColumn column2 = mock(HColumn.class); String propertyValue1 = setupHColumn(column1, "testPropKey1", "testPropValue1"); String propertyValue2 = setupHColumn(column2, "testPropKey2", "testPropValue1"); when(columnSlice.getColumns()).thenReturn(Arrays.asList(column1, column2)); when(executionResult.get()).thenReturn(columnSlice); //========================= //Map actualResult = superColumnFamilyTestDao.readColumnsAsMap(rowKey, superColumnName);
// Path: thrift/src/main/java/com/ebuddy/cassandra/dao/AbstractColumnFamilyTemplate.java // protected static final int ALL = Integer.MAX_VALUE; // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/visitor/ColumnVisitor.java // public interface ColumnVisitor<N, V> { // // /** // * Visit easy column and evaluates a logic. // * @param columnName the name of the column // * @param columnValue the value of the column // * @param timestamp the cassandra timestamp when the column was written // * @param ttl the time to live for that column value // */ // void visit(N columnName, V columnValue, long timestamp, int ttl); // // } // Path: thrift/src/test/java/com/ebuddy/cassandra/dao/SuperColumnFamilyTemplateTest.java import static com.ebuddy.cassandra.dao.AbstractColumnFamilyTemplate.ALL; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.lang3.ObjectUtils; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.ebuddy.cassandra.dao.visitor.ColumnVisitor; import me.prettyprint.cassandra.model.ExecutingKeyspace; import me.prettyprint.cassandra.model.ExecutionResult; import me.prettyprint.cassandra.model.KeyspaceOperationCallback; import me.prettyprint.cassandra.serializers.StringSerializer; import me.prettyprint.hector.api.Serializer; import me.prettyprint.hector.api.beans.ColumnSlice; import me.prettyprint.hector.api.beans.HColumn; import me.prettyprint.hector.api.beans.HSuperColumn; import me.prettyprint.hector.api.beans.Row; import me.prettyprint.hector.api.beans.Rows; import me.prettyprint.hector.api.beans.SuperSlice; import me.prettyprint.hector.api.exceptions.HectorTransportException; import me.prettyprint.hector.api.factory.HFactory; import me.prettyprint.hector.api.mutation.Mutator; @Test(groups={"unit"}, expectedExceptions = HectorTransportException.class) public void testDeleteColumnsTranslateHectorException() { when(mutator.addSubDelete(anyString(), anyString(), anyString(), anyString(), any(Serializer.class), any(Serializer.class))). thenThrow(new HectorTransportException("test hector exception")); //========================= superColumnFamilyTestDao.deleteColumns(rowKey, superColumnName, columnNames, txnContext); //========================= } @Test(groups = {"unit"}) public void testVisitColumn() { ColumnSlice columnSlice = mock(ColumnSlice.class); HColumn column1 = mock(HColumn.class); HColumn column2 = mock(HColumn.class); String propertyValue1 = setupHColumn(column1, "testPropKey1", "testPropValue1"); String propertyValue2 = setupHColumn(column2, "testPropKey2", "testPropValue1"); when(columnSlice.getColumns()).thenReturn(Arrays.asList(column1, column2)); when(executionResult.get()).thenReturn(columnSlice); //========================= //Map actualResult = superColumnFamilyTestDao.readColumnsAsMap(rowKey, superColumnName);
superColumnFamilyTestDao.visitColumns(rowKey, superColumnName, null, null, ALL, false, columnVisitor);
ezoerner/c-star-path-j
core/src/test/java/com/ebuddy/cassandra/structure/DecomposerTest.java
// Path: api/src/main/java/com/ebuddy/cassandra/Path.java // public interface Path { // // /** Return a new Path consisting of this Path concatenated with another Path. */ // Path concat(Path other); // // /** Return a new Path consisting of this Path concatenated with the specified list indices as elements. */ // Path withIndices(int... indices); // // /** Return a new Path consisting of this Path concatenated with the specified elements. */ // Path withElements(String... elements); // // /** Get the encoded elements of this Path. */ // Iterable<String> getElements(); // // /** // * Returns the first element in this path, or null if this is an empty path. // */ // String head(); // // /** // * Returns the rest of the path after the head (first) element. // * If this is an empty path, throws IndexOutOfBoundsException, // * if this path has only one element, return an empty path, // * otherwise return a new path with elements starting after the head. // */ // Path tail(); // // /** // * Return a new Path consisting of the rest of the path elements of this path starting with the specified index. // * @param startIndex 0-based start index // * @return new Path // * @throws IndexOutOfBoundsException if path has insufficient size // */ // Path tail(int startIndex); // // /** // * Return true if this path starts with the specified path. // */ // boolean startsWith(Path path); // // /** Get the number of elements in this path. */ // int size(); // // /** Return true if this Path has zero elements. */ // boolean isEmpty(); // }
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotSame; import static org.testng.Assert.assertTrue; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.ObjectUtils; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.ebuddy.cassandra.Path;
/* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.structure; /** * Tests for Decomposer. * * @author Eric Zoerner <a href="mailto:ezoerner@ebuddy.com">ezoerner@ebuddy.com</a> */ public class DecomposerTest { private Decomposer decomposer; @BeforeMethod(alwaysRun = true) public void setUp() throws Exception { decomposer = Decomposer.get(); } @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class) public void decomposeNull() throws Exception { decomposer.decompose(null); } @Test(groups = "unit") public void decomposeEmpty() throws Exception {
// Path: api/src/main/java/com/ebuddy/cassandra/Path.java // public interface Path { // // /** Return a new Path consisting of this Path concatenated with another Path. */ // Path concat(Path other); // // /** Return a new Path consisting of this Path concatenated with the specified list indices as elements. */ // Path withIndices(int... indices); // // /** Return a new Path consisting of this Path concatenated with the specified elements. */ // Path withElements(String... elements); // // /** Get the encoded elements of this Path. */ // Iterable<String> getElements(); // // /** // * Returns the first element in this path, or null if this is an empty path. // */ // String head(); // // /** // * Returns the rest of the path after the head (first) element. // * If this is an empty path, throws IndexOutOfBoundsException, // * if this path has only one element, return an empty path, // * otherwise return a new path with elements starting after the head. // */ // Path tail(); // // /** // * Return a new Path consisting of the rest of the path elements of this path starting with the specified index. // * @param startIndex 0-based start index // * @return new Path // * @throws IndexOutOfBoundsException if path has insufficient size // */ // Path tail(int startIndex); // // /** // * Return true if this path starts with the specified path. // */ // boolean startsWith(Path path); // // /** Get the number of elements in this path. */ // int size(); // // /** Return true if this Path has zero elements. */ // boolean isEmpty(); // } // Path: core/src/test/java/com/ebuddy/cassandra/structure/DecomposerTest.java import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotSame; import static org.testng.Assert.assertTrue; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.ObjectUtils; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.ebuddy.cassandra.Path; /* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.structure; /** * Tests for Decomposer. * * @author Eric Zoerner <a href="mailto:ezoerner@ebuddy.com">ezoerner@ebuddy.com</a> */ public class DecomposerTest { private Decomposer decomposer; @BeforeMethod(alwaysRun = true) public void setUp() throws Exception { decomposer = Decomposer.get(); } @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class) public void decomposeNull() throws Exception { decomposer.decompose(null); } @Test(groups = "unit") public void decomposeEmpty() throws Exception {
Map<Path,Object> result = decomposer.decompose(new HashMap<Path,Object>());
ezoerner/c-star-path-j
thrift/src/test/java/com/ebuddy/cassandra/dao/ColumnFamilyTemplateTest.java
// Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnMapper.java // public interface ColumnMapper<T,N,V> { // // T mapColumn(N columnName, V columnValue); // // }
import static org.mockito.Mockito.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.collections.KeyValue; import org.apache.commons.collections.keyvalue.DefaultKeyValue; import org.apache.commons.lang3.ObjectUtils; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.ebuddy.cassandra.dao.mapper.ColumnMapper; import me.prettyprint.cassandra.model.ExecutingKeyspace; import me.prettyprint.cassandra.model.ExecutionResult; import me.prettyprint.cassandra.model.KeyspaceOperationCallback; import me.prettyprint.cassandra.serializers.StringSerializer; import me.prettyprint.hector.api.beans.ColumnSlice; import me.prettyprint.hector.api.beans.HColumn; import me.prettyprint.hector.api.beans.Row; import me.prettyprint.hector.api.beans.Rows; import me.prettyprint.hector.api.exceptions.HectorTransportException; import me.prettyprint.hector.api.factory.HFactory; import me.prettyprint.hector.api.mutation.Mutator;
/* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.dao; /** * Test for ColumnFamilyDaoTemplate. * @author Eric Zoerner <a href="mailto:ezoerner@ebuddy.com">ezoerner@ebuddy.com</a> */ @SuppressWarnings({"unchecked", "rawtypes"}) public class ColumnFamilyTemplateTest { private final String columnFamily = "TestColumnFamily"; private final String rowKey = "testKey"; private final String columnName = "testColumnName"; private final List<String> columnNames = Arrays.asList("columnName1", "columnName2"); private final String columnValue = "testColumnValue"; private final List<String> columnValues = Arrays.asList("columnValue1", "columnValue2"); @Mock private ExecutionResult executionResult; @Mock private KeyspaceTemplate.HectorBatchContext txnContext; @Mock private Mutator<String> mutator; @Captor
// Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnMapper.java // public interface ColumnMapper<T,N,V> { // // T mapColumn(N columnName, V columnValue); // // } // Path: thrift/src/test/java/com/ebuddy/cassandra/dao/ColumnFamilyTemplateTest.java import static org.mockito.Mockito.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.collections.KeyValue; import org.apache.commons.collections.keyvalue.DefaultKeyValue; import org.apache.commons.lang3.ObjectUtils; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.ebuddy.cassandra.dao.mapper.ColumnMapper; import me.prettyprint.cassandra.model.ExecutingKeyspace; import me.prettyprint.cassandra.model.ExecutionResult; import me.prettyprint.cassandra.model.KeyspaceOperationCallback; import me.prettyprint.cassandra.serializers.StringSerializer; import me.prettyprint.hector.api.beans.ColumnSlice; import me.prettyprint.hector.api.beans.HColumn; import me.prettyprint.hector.api.beans.Row; import me.prettyprint.hector.api.beans.Rows; import me.prettyprint.hector.api.exceptions.HectorTransportException; import me.prettyprint.hector.api.factory.HFactory; import me.prettyprint.hector.api.mutation.Mutator; /* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.dao; /** * Test for ColumnFamilyDaoTemplate. * @author Eric Zoerner <a href="mailto:ezoerner@ebuddy.com">ezoerner@ebuddy.com</a> */ @SuppressWarnings({"unchecked", "rawtypes"}) public class ColumnFamilyTemplateTest { private final String columnFamily = "TestColumnFamily"; private final String rowKey = "testKey"; private final String columnName = "testColumnName"; private final List<String> columnNames = Arrays.asList("columnName1", "columnName2"); private final String columnValue = "testColumnValue"; private final List<String> columnValues = Arrays.asList("columnValue1", "columnValue2"); @Mock private ExecutionResult executionResult; @Mock private KeyspaceTemplate.HectorBatchContext txnContext; @Mock private Mutator<String> mutator; @Captor
private ArgumentCaptor<ColumnMapper<String,String,String>> mapperCaptor;
ezoerner/c-star-path-j
thrift/src/main/java/com/ebuddy/cassandra/dao/AbstractColumnFamilyTemplate.java
// Path: api/src/main/java/com/ebuddy/cassandra/BatchContext.java // public interface BatchContext { }
import javax.annotation.Nullable; import com.ebuddy.cassandra.BatchContext; import me.prettyprint.hector.api.Keyspace; import me.prettyprint.hector.api.Serializer; import me.prettyprint.hector.api.factory.HFactory; import me.prettyprint.hector.api.mutation.Mutator;
/* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.dao; /** * Abstract superclass for Cassandra Data Access templates. * * @param <K> the type of row key * @param <N> the type of top column name (super column name for Super Column Families); * use Void if this is not specific to a column family * @param <V> the type of column value; * use Void if this is not specific to a column family * @author Eric Zoerner <a href="mailto:ezoerner@ebuddy.com">ezoerner@ebuddy.com</a> */ // Extends KeyspaceTemplate as an implementation convenience to inherit the implementations of begin and commit // If in the future we add more operations to KeyspaceOperations, then we will need to split keyspace template // so this class doesn't inherit methods only appropriate for a keyspace. public abstract class AbstractColumnFamilyTemplate<K,N,V> extends KeyspaceTemplate<K> { /** * Used for queries where we just ask for all columns. */ protected static final int ALL = Integer.MAX_VALUE; /** * The serializer used for column values, or null if not specific to one column family.. */ @Nullable private final Serializer<V> valueSerializer; /** * The serializer for a standard column name or a super-column name, or null if not specific to one column family. */ @Nullable private final Serializer<N> topSerializer; /** * The default column family for this DAO, or null if not specific to a single column family. */ @Nullable private final String columnFamily; /** * Constructor. * * @param keyspace the Keyspace * @param columnFamily the name of the column family or null if this is not specific to a column family. * @param keySerializer the serializer for row keys * @param topSerializer the serializer for the top columns (columns for a Column Family, * superColumns for a Super Column Family). * If null, then this instance is not specific to one Column Family. */ protected AbstractColumnFamilyTemplate(Keyspace keyspace, @Nullable String columnFamily, Serializer<K> keySerializer, @Nullable Serializer<N> topSerializer, @Nullable Serializer<V> valueSerializer) { super(keyspace, keySerializer); this.topSerializer = topSerializer; this.columnFamily = columnFamily; this.valueSerializer = valueSerializer; } /** * Remove the entire row. * @param rowKey the row key */ @SuppressWarnings("UnusedDeclaration") public final void removeRow(K rowKey) { removeRow(rowKey, null); } /** * Remove the entire row in the default column family. * @param rowKey the row key * @param batchContext optional BatchContext */ public final void removeRow(K rowKey,
// Path: api/src/main/java/com/ebuddy/cassandra/BatchContext.java // public interface BatchContext { } // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/AbstractColumnFamilyTemplate.java import javax.annotation.Nullable; import com.ebuddy.cassandra.BatchContext; import me.prettyprint.hector.api.Keyspace; import me.prettyprint.hector.api.Serializer; import me.prettyprint.hector.api.factory.HFactory; import me.prettyprint.hector.api.mutation.Mutator; /* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.dao; /** * Abstract superclass for Cassandra Data Access templates. * * @param <K> the type of row key * @param <N> the type of top column name (super column name for Super Column Families); * use Void if this is not specific to a column family * @param <V> the type of column value; * use Void if this is not specific to a column family * @author Eric Zoerner <a href="mailto:ezoerner@ebuddy.com">ezoerner@ebuddy.com</a> */ // Extends KeyspaceTemplate as an implementation convenience to inherit the implementations of begin and commit // If in the future we add more operations to KeyspaceOperations, then we will need to split keyspace template // so this class doesn't inherit methods only appropriate for a keyspace. public abstract class AbstractColumnFamilyTemplate<K,N,V> extends KeyspaceTemplate<K> { /** * Used for queries where we just ask for all columns. */ protected static final int ALL = Integer.MAX_VALUE; /** * The serializer used for column values, or null if not specific to one column family.. */ @Nullable private final Serializer<V> valueSerializer; /** * The serializer for a standard column name or a super-column name, or null if not specific to one column family. */ @Nullable private final Serializer<N> topSerializer; /** * The default column family for this DAO, or null if not specific to a single column family. */ @Nullable private final String columnFamily; /** * Constructor. * * @param keyspace the Keyspace * @param columnFamily the name of the column family or null if this is not specific to a column family. * @param keySerializer the serializer for row keys * @param topSerializer the serializer for the top columns (columns for a Column Family, * superColumns for a Super Column Family). * If null, then this instance is not specific to one Column Family. */ protected AbstractColumnFamilyTemplate(Keyspace keyspace, @Nullable String columnFamily, Serializer<K> keySerializer, @Nullable Serializer<N> topSerializer, @Nullable Serializer<V> valueSerializer) { super(keyspace, keySerializer); this.topSerializer = topSerializer; this.columnFamily = columnFamily; this.valueSerializer = valueSerializer; } /** * Remove the entire row. * @param rowKey the row key */ @SuppressWarnings("UnusedDeclaration") public final void removeRow(K rowKey) { removeRow(rowKey, null); } /** * Remove the entire row in the default column family. * @param rowKey the row key * @param batchContext optional BatchContext */ public final void removeRow(K rowKey,
@Nullable BatchContext batchContext) {
ezoerner/c-star-path-j
core/src/test/java/com/ebuddy/cassandra/structure/ComposerTest.java
// Path: api/src/main/java/com/ebuddy/cassandra/Path.java // public interface Path { // // /** Return a new Path consisting of this Path concatenated with another Path. */ // Path concat(Path other); // // /** Return a new Path consisting of this Path concatenated with the specified list indices as elements. */ // Path withIndices(int... indices); // // /** Return a new Path consisting of this Path concatenated with the specified elements. */ // Path withElements(String... elements); // // /** Get the encoded elements of this Path. */ // Iterable<String> getElements(); // // /** // * Returns the first element in this path, or null if this is an empty path. // */ // String head(); // // /** // * Returns the rest of the path after the head (first) element. // * If this is an empty path, throws IndexOutOfBoundsException, // * if this path has only one element, return an empty path, // * otherwise return a new path with elements starting after the head. // */ // Path tail(); // // /** // * Return a new Path consisting of the rest of the path elements of this path starting with the specified index. // * @param startIndex 0-based start index // * @return new Path // * @throws IndexOutOfBoundsException if path has insufficient size // */ // Path tail(int startIndex); // // /** // * Return true if this path starts with the specified path. // */ // boolean startsWith(Path path); // // /** Get the number of elements in this path. */ // int size(); // // /** Return true if this Path has zero elements. */ // boolean isEmpty(); // }
import static org.testng.Assert.assertEquals; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.ebuddy.cassandra.Path; import com.google.common.collect.ImmutableMap;
/* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.structure; /** * Tests for Composer. * * @author Eric Zoerner <a href="mailto:ezoerner@ebuddy.com">ezoerner@ebuddy.com</a> */ @SuppressWarnings({"MagicNumber", "CloneableClassWithoutClone"}) public class ComposerTest { private Composer composer; @BeforeMethod(alwaysRun = true) public void setUp() throws Exception { composer = Composer.get(); } @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class) public void composeNull() throws Exception { composer.compose(null); } @Test(groups = "unit") public void composeEmpty() throws Exception {
// Path: api/src/main/java/com/ebuddy/cassandra/Path.java // public interface Path { // // /** Return a new Path consisting of this Path concatenated with another Path. */ // Path concat(Path other); // // /** Return a new Path consisting of this Path concatenated with the specified list indices as elements. */ // Path withIndices(int... indices); // // /** Return a new Path consisting of this Path concatenated with the specified elements. */ // Path withElements(String... elements); // // /** Get the encoded elements of this Path. */ // Iterable<String> getElements(); // // /** // * Returns the first element in this path, or null if this is an empty path. // */ // String head(); // // /** // * Returns the rest of the path after the head (first) element. // * If this is an empty path, throws IndexOutOfBoundsException, // * if this path has only one element, return an empty path, // * otherwise return a new path with elements starting after the head. // */ // Path tail(); // // /** // * Return a new Path consisting of the rest of the path elements of this path starting with the specified index. // * @param startIndex 0-based start index // * @return new Path // * @throws IndexOutOfBoundsException if path has insufficient size // */ // Path tail(int startIndex); // // /** // * Return true if this path starts with the specified path. // */ // boolean startsWith(Path path); // // /** Get the number of elements in this path. */ // int size(); // // /** Return true if this Path has zero elements. */ // boolean isEmpty(); // } // Path: core/src/test/java/com/ebuddy/cassandra/structure/ComposerTest.java import static org.testng.Assert.assertEquals; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.ebuddy.cassandra.Path; import com.google.common.collect.ImmutableMap; /* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.structure; /** * Tests for Composer. * * @author Eric Zoerner <a href="mailto:ezoerner@ebuddy.com">ezoerner@ebuddy.com</a> */ @SuppressWarnings({"MagicNumber", "CloneableClassWithoutClone"}) public class ComposerTest { private Composer composer; @BeforeMethod(alwaysRun = true) public void setUp() throws Exception { composer = Composer.get(); } @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class) public void composeNull() throws Exception { composer.compose(null); } @Test(groups = "unit") public void composeEmpty() throws Exception {
Object result = composer.compose(new HashMap<Path,Object>());
ezoerner/c-star-path-j
core/src/main/java/com/ebuddy/cassandra/structure/Composer.java
// Path: api/src/main/java/com/ebuddy/cassandra/Path.java // public interface Path { // // /** Return a new Path consisting of this Path concatenated with another Path. */ // Path concat(Path other); // // /** Return a new Path consisting of this Path concatenated with the specified list indices as elements. */ // Path withIndices(int... indices); // // /** Return a new Path consisting of this Path concatenated with the specified elements. */ // Path withElements(String... elements); // // /** Get the encoded elements of this Path. */ // Iterable<String> getElements(); // // /** // * Returns the first element in this path, or null if this is an empty path. // */ // String head(); // // /** // * Returns the rest of the path after the head (first) element. // * If this is an empty path, throws IndexOutOfBoundsException, // * if this path has only one element, return an empty path, // * otherwise return a new path with elements starting after the head. // */ // Path tail(); // // /** // * Return a new Path consisting of the rest of the path elements of this path starting with the specified index. // * @param startIndex 0-based start index // * @return new Path // * @throws IndexOutOfBoundsException if path has insufficient size // */ // Path tail(int startIndex); // // /** // * Return true if this path starts with the specified path. // */ // boolean startsWith(Path path); // // /** Get the number of elements in this path. */ // int size(); // // /** Return true if this Path has zero elements. */ // boolean isEmpty(); // }
import org.slf4j.LoggerFactory; import com.ebuddy.cassandra.Path; import static java.util.AbstractMap.SimpleEntry; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import org.slf4j.Logger;
/* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.structure; /** * Support for composing paths back to complex objects. * Only the basic JSON structures are supported, i.e. Maps, Lists, Strings, Numbers, Booleans, and null. * * It is possible to write data that will cause inconsistencies in an object structure * when it is reconstructed. This implementation will resolve inconsistencies as follows: * * If data objects are found at a particular path as well as longer paths, the data object * is returned in a map structure with the special key "@ROOT". This may cause an error * if the data is later attempted to be deserialized into a POJO. * * If list elements are found at the same level as longer paths or a data object, then * the list elements are returned in a map with the index as keys in the map, e.g. "@0", "@1", * etc. * * If inconsistencies such as these are preventing data from being deserialized into a * particular POJO, the data can always be retrieved using an instance of (a subclass of) TypeReference<Object>, * which will return the basic JSON to Java mappings, i.e. Maps, Lists and Strings, etc. * * @author Eric Zoerner <a href="mailto:ezoerner@ebuddy.com">ezoerner@ebuddy.com</a> */ public class Composer { private static final Logger log = LoggerFactory.getLogger(Composer.class); private static final String INCONSISTENT_ROOT = "@ROOT"; private static final Composer INSTANCE = new Composer(); private Composer() { } public static Composer get() { return INSTANCE; } /** * Compose a map of simple objects keyed by paths into a single complex object, e.g. a map or list * * @param simpleObjects input map of decomposed objects, paths mapped to simple values (i.e. strings, numbers, or booleans) * @return a complex object such as a map or list decoded from the paths in decomposedObjects * @throws IllegalArgumentException if there are unsupported objects types in simpleObjects, or * if there is a key that is an empty path */
// Path: api/src/main/java/com/ebuddy/cassandra/Path.java // public interface Path { // // /** Return a new Path consisting of this Path concatenated with another Path. */ // Path concat(Path other); // // /** Return a new Path consisting of this Path concatenated with the specified list indices as elements. */ // Path withIndices(int... indices); // // /** Return a new Path consisting of this Path concatenated with the specified elements. */ // Path withElements(String... elements); // // /** Get the encoded elements of this Path. */ // Iterable<String> getElements(); // // /** // * Returns the first element in this path, or null if this is an empty path. // */ // String head(); // // /** // * Returns the rest of the path after the head (first) element. // * If this is an empty path, throws IndexOutOfBoundsException, // * if this path has only one element, return an empty path, // * otherwise return a new path with elements starting after the head. // */ // Path tail(); // // /** // * Return a new Path consisting of the rest of the path elements of this path starting with the specified index. // * @param startIndex 0-based start index // * @return new Path // * @throws IndexOutOfBoundsException if path has insufficient size // */ // Path tail(int startIndex); // // /** // * Return true if this path starts with the specified path. // */ // boolean startsWith(Path path); // // /** Get the number of elements in this path. */ // int size(); // // /** Return true if this Path has zero elements. */ // boolean isEmpty(); // } // Path: core/src/main/java/com/ebuddy/cassandra/structure/Composer.java import org.slf4j.LoggerFactory; import com.ebuddy.cassandra.Path; import static java.util.AbstractMap.SimpleEntry; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import org.slf4j.Logger; /* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.structure; /** * Support for composing paths back to complex objects. * Only the basic JSON structures are supported, i.e. Maps, Lists, Strings, Numbers, Booleans, and null. * * It is possible to write data that will cause inconsistencies in an object structure * when it is reconstructed. This implementation will resolve inconsistencies as follows: * * If data objects are found at a particular path as well as longer paths, the data object * is returned in a map structure with the special key "@ROOT". This may cause an error * if the data is later attempted to be deserialized into a POJO. * * If list elements are found at the same level as longer paths or a data object, then * the list elements are returned in a map with the index as keys in the map, e.g. "@0", "@1", * etc. * * If inconsistencies such as these are preventing data from being deserialized into a * particular POJO, the data can always be retrieved using an instance of (a subclass of) TypeReference<Object>, * which will return the basic JSON to Java mappings, i.e. Maps, Lists and Strings, etc. * * @author Eric Zoerner <a href="mailto:ezoerner@ebuddy.com">ezoerner@ebuddy.com</a> */ public class Composer { private static final Logger log = LoggerFactory.getLogger(Composer.class); private static final String INCONSISTENT_ROOT = "@ROOT"; private static final Composer INSTANCE = new Composer(); private Composer() { } public static Composer get() { return INSTANCE; } /** * Compose a map of simple objects keyed by paths into a single complex object, e.g. a map or list * * @param simpleObjects input map of decomposed objects, paths mapped to simple values (i.e. strings, numbers, or booleans) * @return a complex object such as a map or list decoded from the paths in decomposedObjects * @throws IllegalArgumentException if there are unsupported objects types in simpleObjects, or * if there is a key that is an empty path */
public Object compose(Map<Path,Object> simpleObjects) {
ezoerner/c-star-path-j
thrift/src/main/java/com/ebuddy/cassandra/dao/SuperColumnFamilyTemplate.java
// Path: api/src/main/java/com/ebuddy/cassandra/BatchContext.java // public interface BatchContext { } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnMapper.java // public interface ColumnMapper<T,N,V> { // // T mapColumn(N columnName, V columnValue); // // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnMapperWithTimestamps.java // public interface ColumnMapperWithTimestamps<T,N,V> { // // T mapColumn(N columnName, V columnValue, long timestamp); // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/SuperColumnFamilyRowMapper.java // public interface SuperColumnFamilyRowMapper<T,K,SN,N,V> { // T mapRow(K rowKey, List<HSuperColumn<SN,N,V>> superColumns); // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/SuperColumnMapper.java // public interface SuperColumnMapper<T,K,SN,N,V> { // // T mapSuperColumn(K rowKey, SN superColumnName, List<HColumn<N,V>> columns); // // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/visitor/ColumnVisitor.java // public interface ColumnVisitor<N, V> { // // /** // * Visit easy column and evaluates a logic. // * @param columnName the name of the column // * @param columnValue the value of the column // * @param timestamp the cassandra timestamp when the column was written // * @param ttl the time to live for that column value // */ // void visit(N columnName, V columnValue, long timestamp, int ttl); // // }
import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.commons.lang3.Validate; import com.ebuddy.cassandra.BatchContext; import com.ebuddy.cassandra.dao.mapper.ColumnMapper; import com.ebuddy.cassandra.dao.mapper.ColumnMapperWithTimestamps; import com.ebuddy.cassandra.dao.mapper.SuperColumnFamilyRowMapper; import com.ebuddy.cassandra.dao.mapper.SuperColumnMapper; import com.ebuddy.cassandra.dao.visitor.ColumnVisitor; import com.google.common.collect.Lists; import me.prettyprint.hector.api.Keyspace; import me.prettyprint.hector.api.Serializer; import me.prettyprint.hector.api.beans.ColumnSlice; import me.prettyprint.hector.api.beans.HColumn; import me.prettyprint.hector.api.beans.HSuperColumn; import me.prettyprint.hector.api.beans.Row; import me.prettyprint.hector.api.beans.Rows; import me.prettyprint.hector.api.beans.SuperRow; import me.prettyprint.hector.api.beans.SuperRows; import me.prettyprint.hector.api.beans.SuperSlice; import me.prettyprint.hector.api.factory.HFactory; import me.prettyprint.hector.api.mutation.Mutator; import me.prettyprint.hector.api.query.MultigetSubSliceQuery; import me.prettyprint.hector.api.query.MultigetSuperSliceQuery; import me.prettyprint.hector.api.query.QueryResult; import me.prettyprint.hector.api.query.SubColumnQuery; import me.prettyprint.hector.api.query.SubSliceQuery; import me.prettyprint.hector.api.query.SuperSliceQuery;
/* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.dao; /** * Data access template for Cassandra Super column families. * * @param <K> the Row Key type. * @param <SN> The supercolumn name type. * @param <N> The subcolumn name type. * @param <V> The column value type. * * @author Eric Zoerner <a href="mailto:ezoerner@ebuddy.com">ezoerner@ebuddy.com</a> */ public final class SuperColumnFamilyTemplate<K,SN,N,V> extends AbstractColumnFamilyTemplate<K,SN,V> implements SuperColumnFamilyOperations<K,SN,N,V> { /** * The serializer for subcolumn names. */ private final Serializer<N> subSerializer;
// Path: api/src/main/java/com/ebuddy/cassandra/BatchContext.java // public interface BatchContext { } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnMapper.java // public interface ColumnMapper<T,N,V> { // // T mapColumn(N columnName, V columnValue); // // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnMapperWithTimestamps.java // public interface ColumnMapperWithTimestamps<T,N,V> { // // T mapColumn(N columnName, V columnValue, long timestamp); // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/SuperColumnFamilyRowMapper.java // public interface SuperColumnFamilyRowMapper<T,K,SN,N,V> { // T mapRow(K rowKey, List<HSuperColumn<SN,N,V>> superColumns); // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/SuperColumnMapper.java // public interface SuperColumnMapper<T,K,SN,N,V> { // // T mapSuperColumn(K rowKey, SN superColumnName, List<HColumn<N,V>> columns); // // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/visitor/ColumnVisitor.java // public interface ColumnVisitor<N, V> { // // /** // * Visit easy column and evaluates a logic. // * @param columnName the name of the column // * @param columnValue the value of the column // * @param timestamp the cassandra timestamp when the column was written // * @param ttl the time to live for that column value // */ // void visit(N columnName, V columnValue, long timestamp, int ttl); // // } // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/SuperColumnFamilyTemplate.java import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.commons.lang3.Validate; import com.ebuddy.cassandra.BatchContext; import com.ebuddy.cassandra.dao.mapper.ColumnMapper; import com.ebuddy.cassandra.dao.mapper.ColumnMapperWithTimestamps; import com.ebuddy.cassandra.dao.mapper.SuperColumnFamilyRowMapper; import com.ebuddy.cassandra.dao.mapper.SuperColumnMapper; import com.ebuddy.cassandra.dao.visitor.ColumnVisitor; import com.google.common.collect.Lists; import me.prettyprint.hector.api.Keyspace; import me.prettyprint.hector.api.Serializer; import me.prettyprint.hector.api.beans.ColumnSlice; import me.prettyprint.hector.api.beans.HColumn; import me.prettyprint.hector.api.beans.HSuperColumn; import me.prettyprint.hector.api.beans.Row; import me.prettyprint.hector.api.beans.Rows; import me.prettyprint.hector.api.beans.SuperRow; import me.prettyprint.hector.api.beans.SuperRows; import me.prettyprint.hector.api.beans.SuperSlice; import me.prettyprint.hector.api.factory.HFactory; import me.prettyprint.hector.api.mutation.Mutator; import me.prettyprint.hector.api.query.MultigetSubSliceQuery; import me.prettyprint.hector.api.query.MultigetSuperSliceQuery; import me.prettyprint.hector.api.query.QueryResult; import me.prettyprint.hector.api.query.SubColumnQuery; import me.prettyprint.hector.api.query.SubSliceQuery; import me.prettyprint.hector.api.query.SuperSliceQuery; /* * Copyright 2013 eBuddy B.V. * * 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.ebuddy.cassandra.dao; /** * Data access template for Cassandra Super column families. * * @param <K> the Row Key type. * @param <SN> The supercolumn name type. * @param <N> The subcolumn name type. * @param <V> The column value type. * * @author Eric Zoerner <a href="mailto:ezoerner@ebuddy.com">ezoerner@ebuddy.com</a> */ public final class SuperColumnFamilyTemplate<K,SN,N,V> extends AbstractColumnFamilyTemplate<K,SN,V> implements SuperColumnFamilyOperations<K,SN,N,V> { /** * The serializer for subcolumn names. */ private final Serializer<N> subSerializer;
private final ColumnMapper<N,N,V> columnMapperToGetColumnNames = new ColumnMapper<N,N,V>() {
ezoerner/c-star-path-j
thrift/src/main/java/com/ebuddy/cassandra/dao/SuperColumnFamilyTemplate.java
// Path: api/src/main/java/com/ebuddy/cassandra/BatchContext.java // public interface BatchContext { } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnMapper.java // public interface ColumnMapper<T,N,V> { // // T mapColumn(N columnName, V columnValue); // // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnMapperWithTimestamps.java // public interface ColumnMapperWithTimestamps<T,N,V> { // // T mapColumn(N columnName, V columnValue, long timestamp); // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/SuperColumnFamilyRowMapper.java // public interface SuperColumnFamilyRowMapper<T,K,SN,N,V> { // T mapRow(K rowKey, List<HSuperColumn<SN,N,V>> superColumns); // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/SuperColumnMapper.java // public interface SuperColumnMapper<T,K,SN,N,V> { // // T mapSuperColumn(K rowKey, SN superColumnName, List<HColumn<N,V>> columns); // // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/visitor/ColumnVisitor.java // public interface ColumnVisitor<N, V> { // // /** // * Visit easy column and evaluates a logic. // * @param columnName the name of the column // * @param columnValue the value of the column // * @param timestamp the cassandra timestamp when the column was written // * @param ttl the time to live for that column value // */ // void visit(N columnName, V columnValue, long timestamp, int ttl); // // }
import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.commons.lang3.Validate; import com.ebuddy.cassandra.BatchContext; import com.ebuddy.cassandra.dao.mapper.ColumnMapper; import com.ebuddy.cassandra.dao.mapper.ColumnMapperWithTimestamps; import com.ebuddy.cassandra.dao.mapper.SuperColumnFamilyRowMapper; import com.ebuddy.cassandra.dao.mapper.SuperColumnMapper; import com.ebuddy.cassandra.dao.visitor.ColumnVisitor; import com.google.common.collect.Lists; import me.prettyprint.hector.api.Keyspace; import me.prettyprint.hector.api.Serializer; import me.prettyprint.hector.api.beans.ColumnSlice; import me.prettyprint.hector.api.beans.HColumn; import me.prettyprint.hector.api.beans.HSuperColumn; import me.prettyprint.hector.api.beans.Row; import me.prettyprint.hector.api.beans.Rows; import me.prettyprint.hector.api.beans.SuperRow; import me.prettyprint.hector.api.beans.SuperRows; import me.prettyprint.hector.api.beans.SuperSlice; import me.prettyprint.hector.api.factory.HFactory; import me.prettyprint.hector.api.mutation.Mutator; import me.prettyprint.hector.api.query.MultigetSubSliceQuery; import me.prettyprint.hector.api.query.MultigetSuperSliceQuery; import me.prettyprint.hector.api.query.QueryResult; import me.prettyprint.hector.api.query.SubColumnQuery; import me.prettyprint.hector.api.query.SubSliceQuery; import me.prettyprint.hector.api.query.SuperSliceQuery;
@Override public <T> List<T> readColumns(K rowKey, SN superColumnName, ColumnMapper<T,N,V> columnMapper) { return readColumns(rowKey, superColumnName, null, null, ALL, false, columnMapper); } @Override public <T> List<T> readColumns(K rowKey, SN superColumnName, N start, N finish, int count, boolean reversed, ColumnMapper<T,N,V> columnMapper) { return readColumnsWithTimestamps(rowKey, superColumnName, start, finish, count, reversed, new ColumnMapperWrapper<T,N,V>(columnMapper)); } @Override public <T> List<T> readColumnsWithTimestamps(K rowKey, SN superColumnName, N start, N finish, int count, boolean reversed,
// Path: api/src/main/java/com/ebuddy/cassandra/BatchContext.java // public interface BatchContext { } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnMapper.java // public interface ColumnMapper<T,N,V> { // // T mapColumn(N columnName, V columnValue); // // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnMapperWithTimestamps.java // public interface ColumnMapperWithTimestamps<T,N,V> { // // T mapColumn(N columnName, V columnValue, long timestamp); // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/SuperColumnFamilyRowMapper.java // public interface SuperColumnFamilyRowMapper<T,K,SN,N,V> { // T mapRow(K rowKey, List<HSuperColumn<SN,N,V>> superColumns); // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/SuperColumnMapper.java // public interface SuperColumnMapper<T,K,SN,N,V> { // // T mapSuperColumn(K rowKey, SN superColumnName, List<HColumn<N,V>> columns); // // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/visitor/ColumnVisitor.java // public interface ColumnVisitor<N, V> { // // /** // * Visit easy column and evaluates a logic. // * @param columnName the name of the column // * @param columnValue the value of the column // * @param timestamp the cassandra timestamp when the column was written // * @param ttl the time to live for that column value // */ // void visit(N columnName, V columnValue, long timestamp, int ttl); // // } // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/SuperColumnFamilyTemplate.java import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.commons.lang3.Validate; import com.ebuddy.cassandra.BatchContext; import com.ebuddy.cassandra.dao.mapper.ColumnMapper; import com.ebuddy.cassandra.dao.mapper.ColumnMapperWithTimestamps; import com.ebuddy.cassandra.dao.mapper.SuperColumnFamilyRowMapper; import com.ebuddy.cassandra.dao.mapper.SuperColumnMapper; import com.ebuddy.cassandra.dao.visitor.ColumnVisitor; import com.google.common.collect.Lists; import me.prettyprint.hector.api.Keyspace; import me.prettyprint.hector.api.Serializer; import me.prettyprint.hector.api.beans.ColumnSlice; import me.prettyprint.hector.api.beans.HColumn; import me.prettyprint.hector.api.beans.HSuperColumn; import me.prettyprint.hector.api.beans.Row; import me.prettyprint.hector.api.beans.Rows; import me.prettyprint.hector.api.beans.SuperRow; import me.prettyprint.hector.api.beans.SuperRows; import me.prettyprint.hector.api.beans.SuperSlice; import me.prettyprint.hector.api.factory.HFactory; import me.prettyprint.hector.api.mutation.Mutator; import me.prettyprint.hector.api.query.MultigetSubSliceQuery; import me.prettyprint.hector.api.query.MultigetSuperSliceQuery; import me.prettyprint.hector.api.query.QueryResult; import me.prettyprint.hector.api.query.SubColumnQuery; import me.prettyprint.hector.api.query.SubSliceQuery; import me.prettyprint.hector.api.query.SuperSliceQuery; @Override public <T> List<T> readColumns(K rowKey, SN superColumnName, ColumnMapper<T,N,V> columnMapper) { return readColumns(rowKey, superColumnName, null, null, ALL, false, columnMapper); } @Override public <T> List<T> readColumns(K rowKey, SN superColumnName, N start, N finish, int count, boolean reversed, ColumnMapper<T,N,V> columnMapper) { return readColumnsWithTimestamps(rowKey, superColumnName, start, finish, count, reversed, new ColumnMapperWrapper<T,N,V>(columnMapper)); } @Override public <T> List<T> readColumnsWithTimestamps(K rowKey, SN superColumnName, N start, N finish, int count, boolean reversed,
ColumnMapperWithTimestamps<T,N,V> columnMapper) {
ezoerner/c-star-path-j
thrift/src/main/java/com/ebuddy/cassandra/dao/SuperColumnFamilyTemplate.java
// Path: api/src/main/java/com/ebuddy/cassandra/BatchContext.java // public interface BatchContext { } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnMapper.java // public interface ColumnMapper<T,N,V> { // // T mapColumn(N columnName, V columnValue); // // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnMapperWithTimestamps.java // public interface ColumnMapperWithTimestamps<T,N,V> { // // T mapColumn(N columnName, V columnValue, long timestamp); // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/SuperColumnFamilyRowMapper.java // public interface SuperColumnFamilyRowMapper<T,K,SN,N,V> { // T mapRow(K rowKey, List<HSuperColumn<SN,N,V>> superColumns); // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/SuperColumnMapper.java // public interface SuperColumnMapper<T,K,SN,N,V> { // // T mapSuperColumn(K rowKey, SN superColumnName, List<HColumn<N,V>> columns); // // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/visitor/ColumnVisitor.java // public interface ColumnVisitor<N, V> { // // /** // * Visit easy column and evaluates a logic. // * @param columnName the name of the column // * @param columnValue the value of the column // * @param timestamp the cassandra timestamp when the column was written // * @param ttl the time to live for that column value // */ // void visit(N columnName, V columnValue, long timestamp, int ttl); // // }
import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.commons.lang3.Validate; import com.ebuddy.cassandra.BatchContext; import com.ebuddy.cassandra.dao.mapper.ColumnMapper; import com.ebuddy.cassandra.dao.mapper.ColumnMapperWithTimestamps; import com.ebuddy.cassandra.dao.mapper.SuperColumnFamilyRowMapper; import com.ebuddy.cassandra.dao.mapper.SuperColumnMapper; import com.ebuddy.cassandra.dao.visitor.ColumnVisitor; import com.google.common.collect.Lists; import me.prettyprint.hector.api.Keyspace; import me.prettyprint.hector.api.Serializer; import me.prettyprint.hector.api.beans.ColumnSlice; import me.prettyprint.hector.api.beans.HColumn; import me.prettyprint.hector.api.beans.HSuperColumn; import me.prettyprint.hector.api.beans.Row; import me.prettyprint.hector.api.beans.Rows; import me.prettyprint.hector.api.beans.SuperRow; import me.prettyprint.hector.api.beans.SuperRows; import me.prettyprint.hector.api.beans.SuperSlice; import me.prettyprint.hector.api.factory.HFactory; import me.prettyprint.hector.api.mutation.Mutator; import me.prettyprint.hector.api.query.MultigetSubSliceQuery; import me.prettyprint.hector.api.query.MultigetSuperSliceQuery; import me.prettyprint.hector.api.query.QueryResult; import me.prettyprint.hector.api.query.SubColumnQuery; import me.prettyprint.hector.api.query.SubSliceQuery; import me.prettyprint.hector.api.query.SuperSliceQuery;
setSuperColumn(superColumnName). setRange(start, finish, reversed, count); QueryResult<ColumnSlice<N,V>> result = query.execute(); ColumnSlice<N,V> slice = result.get(); for (HColumn<N,V> column : slice.getColumns()) { resultList.add(columnMapper.mapColumn(column.getName(), column.getValue(), column.getClock())); } return resultList; } /** * Get a column from a super column based on the {@link ColumnVisitor) implementation passed. The Visitor will go through all the columns and perform some internal operation based on the column data * * @param rowKey the row key * @param superColumnName restricts query to this supercolumn. * @param start the start column name to read * @param finish the last column name to read * @param count the number of columns to read * @param reverse order in which the columns should be read * @param columnVisitor a provided visitor to visit all the columns and retrieve the needed one. */ @Override public void visitColumns(K rowKey, SN superColumnName, N start, N finish, int count, boolean reversed,
// Path: api/src/main/java/com/ebuddy/cassandra/BatchContext.java // public interface BatchContext { } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnMapper.java // public interface ColumnMapper<T,N,V> { // // T mapColumn(N columnName, V columnValue); // // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnMapperWithTimestamps.java // public interface ColumnMapperWithTimestamps<T,N,V> { // // T mapColumn(N columnName, V columnValue, long timestamp); // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/SuperColumnFamilyRowMapper.java // public interface SuperColumnFamilyRowMapper<T,K,SN,N,V> { // T mapRow(K rowKey, List<HSuperColumn<SN,N,V>> superColumns); // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/SuperColumnMapper.java // public interface SuperColumnMapper<T,K,SN,N,V> { // // T mapSuperColumn(K rowKey, SN superColumnName, List<HColumn<N,V>> columns); // // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/visitor/ColumnVisitor.java // public interface ColumnVisitor<N, V> { // // /** // * Visit easy column and evaluates a logic. // * @param columnName the name of the column // * @param columnValue the value of the column // * @param timestamp the cassandra timestamp when the column was written // * @param ttl the time to live for that column value // */ // void visit(N columnName, V columnValue, long timestamp, int ttl); // // } // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/SuperColumnFamilyTemplate.java import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.commons.lang3.Validate; import com.ebuddy.cassandra.BatchContext; import com.ebuddy.cassandra.dao.mapper.ColumnMapper; import com.ebuddy.cassandra.dao.mapper.ColumnMapperWithTimestamps; import com.ebuddy.cassandra.dao.mapper.SuperColumnFamilyRowMapper; import com.ebuddy.cassandra.dao.mapper.SuperColumnMapper; import com.ebuddy.cassandra.dao.visitor.ColumnVisitor; import com.google.common.collect.Lists; import me.prettyprint.hector.api.Keyspace; import me.prettyprint.hector.api.Serializer; import me.prettyprint.hector.api.beans.ColumnSlice; import me.prettyprint.hector.api.beans.HColumn; import me.prettyprint.hector.api.beans.HSuperColumn; import me.prettyprint.hector.api.beans.Row; import me.prettyprint.hector.api.beans.Rows; import me.prettyprint.hector.api.beans.SuperRow; import me.prettyprint.hector.api.beans.SuperRows; import me.prettyprint.hector.api.beans.SuperSlice; import me.prettyprint.hector.api.factory.HFactory; import me.prettyprint.hector.api.mutation.Mutator; import me.prettyprint.hector.api.query.MultigetSubSliceQuery; import me.prettyprint.hector.api.query.MultigetSuperSliceQuery; import me.prettyprint.hector.api.query.QueryResult; import me.prettyprint.hector.api.query.SubColumnQuery; import me.prettyprint.hector.api.query.SubSliceQuery; import me.prettyprint.hector.api.query.SuperSliceQuery; setSuperColumn(superColumnName). setRange(start, finish, reversed, count); QueryResult<ColumnSlice<N,V>> result = query.execute(); ColumnSlice<N,V> slice = result.get(); for (HColumn<N,V> column : slice.getColumns()) { resultList.add(columnMapper.mapColumn(column.getName(), column.getValue(), column.getClock())); } return resultList; } /** * Get a column from a super column based on the {@link ColumnVisitor) implementation passed. The Visitor will go through all the columns and perform some internal operation based on the column data * * @param rowKey the row key * @param superColumnName restricts query to this supercolumn. * @param start the start column name to read * @param finish the last column name to read * @param count the number of columns to read * @param reverse order in which the columns should be read * @param columnVisitor a provided visitor to visit all the columns and retrieve the needed one. */ @Override public void visitColumns(K rowKey, SN superColumnName, N start, N finish, int count, boolean reversed,
ColumnVisitor<N, V> columnVisitor) {
ezoerner/c-star-path-j
thrift/src/main/java/com/ebuddy/cassandra/dao/SuperColumnFamilyTemplate.java
// Path: api/src/main/java/com/ebuddy/cassandra/BatchContext.java // public interface BatchContext { } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnMapper.java // public interface ColumnMapper<T,N,V> { // // T mapColumn(N columnName, V columnValue); // // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnMapperWithTimestamps.java // public interface ColumnMapperWithTimestamps<T,N,V> { // // T mapColumn(N columnName, V columnValue, long timestamp); // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/SuperColumnFamilyRowMapper.java // public interface SuperColumnFamilyRowMapper<T,K,SN,N,V> { // T mapRow(K rowKey, List<HSuperColumn<SN,N,V>> superColumns); // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/SuperColumnMapper.java // public interface SuperColumnMapper<T,K,SN,N,V> { // // T mapSuperColumn(K rowKey, SN superColumnName, List<HColumn<N,V>> columns); // // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/visitor/ColumnVisitor.java // public interface ColumnVisitor<N, V> { // // /** // * Visit easy column and evaluates a logic. // * @param columnName the name of the column // * @param columnValue the value of the column // * @param timestamp the cassandra timestamp when the column was written // * @param ttl the time to live for that column value // */ // void visit(N columnName, V columnValue, long timestamp, int ttl); // // }
import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.commons.lang3.Validate; import com.ebuddy.cassandra.BatchContext; import com.ebuddy.cassandra.dao.mapper.ColumnMapper; import com.ebuddy.cassandra.dao.mapper.ColumnMapperWithTimestamps; import com.ebuddy.cassandra.dao.mapper.SuperColumnFamilyRowMapper; import com.ebuddy.cassandra.dao.mapper.SuperColumnMapper; import com.ebuddy.cassandra.dao.visitor.ColumnVisitor; import com.google.common.collect.Lists; import me.prettyprint.hector.api.Keyspace; import me.prettyprint.hector.api.Serializer; import me.prettyprint.hector.api.beans.ColumnSlice; import me.prettyprint.hector.api.beans.HColumn; import me.prettyprint.hector.api.beans.HSuperColumn; import me.prettyprint.hector.api.beans.Row; import me.prettyprint.hector.api.beans.Rows; import me.prettyprint.hector.api.beans.SuperRow; import me.prettyprint.hector.api.beans.SuperRows; import me.prettyprint.hector.api.beans.SuperSlice; import me.prettyprint.hector.api.factory.HFactory; import me.prettyprint.hector.api.mutation.Mutator; import me.prettyprint.hector.api.query.MultigetSubSliceQuery; import me.prettyprint.hector.api.query.MultigetSuperSliceQuery; import me.prettyprint.hector.api.query.QueryResult; import me.prettyprint.hector.api.query.SubColumnQuery; import me.prettyprint.hector.api.query.SubSliceQuery; import me.prettyprint.hector.api.query.SuperSliceQuery;
query.setKeys(Lists.newArrayList(rowKeys)). setSuperColumn(supercolumnName). setColumnFamily(getColumnFamily()). setRange(start, finish, reversed, count); QueryResult<Rows<K,N,V>> result = query.execute(); for (Row<K,N,V> row : result.get()) { List<T> resultList = new ArrayList<T>(); K key = row.getKey(); ColumnSlice<N,V> slice = row.getColumnSlice(); for (HColumn<N,V> column : slice.getColumns()) { resultList.add(columnMapper.mapColumn(column.getName(), column.getValue())); } resultMap.put(key, resultList); } return resultMap; } /** * Read all columns from multiple rows from a single super column in each row, * returning a list of mapped super columns. * * @param rowKeys - Keys to search * @param superColumnName - superColumn involved in the query * @return List of mapped super columns. The order is only meaningful if rows are ordered in the database. */ @Override public <T> List<T> multiGetSuperColumn(Collection<K> rowKeys, SN superColumnName,
// Path: api/src/main/java/com/ebuddy/cassandra/BatchContext.java // public interface BatchContext { } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnMapper.java // public interface ColumnMapper<T,N,V> { // // T mapColumn(N columnName, V columnValue); // // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnMapperWithTimestamps.java // public interface ColumnMapperWithTimestamps<T,N,V> { // // T mapColumn(N columnName, V columnValue, long timestamp); // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/SuperColumnFamilyRowMapper.java // public interface SuperColumnFamilyRowMapper<T,K,SN,N,V> { // T mapRow(K rowKey, List<HSuperColumn<SN,N,V>> superColumns); // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/SuperColumnMapper.java // public interface SuperColumnMapper<T,K,SN,N,V> { // // T mapSuperColumn(K rowKey, SN superColumnName, List<HColumn<N,V>> columns); // // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/visitor/ColumnVisitor.java // public interface ColumnVisitor<N, V> { // // /** // * Visit easy column and evaluates a logic. // * @param columnName the name of the column // * @param columnValue the value of the column // * @param timestamp the cassandra timestamp when the column was written // * @param ttl the time to live for that column value // */ // void visit(N columnName, V columnValue, long timestamp, int ttl); // // } // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/SuperColumnFamilyTemplate.java import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.commons.lang3.Validate; import com.ebuddy.cassandra.BatchContext; import com.ebuddy.cassandra.dao.mapper.ColumnMapper; import com.ebuddy.cassandra.dao.mapper.ColumnMapperWithTimestamps; import com.ebuddy.cassandra.dao.mapper.SuperColumnFamilyRowMapper; import com.ebuddy.cassandra.dao.mapper.SuperColumnMapper; import com.ebuddy.cassandra.dao.visitor.ColumnVisitor; import com.google.common.collect.Lists; import me.prettyprint.hector.api.Keyspace; import me.prettyprint.hector.api.Serializer; import me.prettyprint.hector.api.beans.ColumnSlice; import me.prettyprint.hector.api.beans.HColumn; import me.prettyprint.hector.api.beans.HSuperColumn; import me.prettyprint.hector.api.beans.Row; import me.prettyprint.hector.api.beans.Rows; import me.prettyprint.hector.api.beans.SuperRow; import me.prettyprint.hector.api.beans.SuperRows; import me.prettyprint.hector.api.beans.SuperSlice; import me.prettyprint.hector.api.factory.HFactory; import me.prettyprint.hector.api.mutation.Mutator; import me.prettyprint.hector.api.query.MultigetSubSliceQuery; import me.prettyprint.hector.api.query.MultigetSuperSliceQuery; import me.prettyprint.hector.api.query.QueryResult; import me.prettyprint.hector.api.query.SubColumnQuery; import me.prettyprint.hector.api.query.SubSliceQuery; import me.prettyprint.hector.api.query.SuperSliceQuery; query.setKeys(Lists.newArrayList(rowKeys)). setSuperColumn(supercolumnName). setColumnFamily(getColumnFamily()). setRange(start, finish, reversed, count); QueryResult<Rows<K,N,V>> result = query.execute(); for (Row<K,N,V> row : result.get()) { List<T> resultList = new ArrayList<T>(); K key = row.getKey(); ColumnSlice<N,V> slice = row.getColumnSlice(); for (HColumn<N,V> column : slice.getColumns()) { resultList.add(columnMapper.mapColumn(column.getName(), column.getValue())); } resultMap.put(key, resultList); } return resultMap; } /** * Read all columns from multiple rows from a single super column in each row, * returning a list of mapped super columns. * * @param rowKeys - Keys to search * @param superColumnName - superColumn involved in the query * @return List of mapped super columns. The order is only meaningful if rows are ordered in the database. */ @Override public <T> List<T> multiGetSuperColumn(Collection<K> rowKeys, SN superColumnName,
SuperColumnMapper<T,K,SN,N,V> superColumnMapper) {
ezoerner/c-star-path-j
thrift/src/main/java/com/ebuddy/cassandra/dao/SuperColumnFamilyTemplate.java
// Path: api/src/main/java/com/ebuddy/cassandra/BatchContext.java // public interface BatchContext { } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnMapper.java // public interface ColumnMapper<T,N,V> { // // T mapColumn(N columnName, V columnValue); // // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnMapperWithTimestamps.java // public interface ColumnMapperWithTimestamps<T,N,V> { // // T mapColumn(N columnName, V columnValue, long timestamp); // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/SuperColumnFamilyRowMapper.java // public interface SuperColumnFamilyRowMapper<T,K,SN,N,V> { // T mapRow(K rowKey, List<HSuperColumn<SN,N,V>> superColumns); // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/SuperColumnMapper.java // public interface SuperColumnMapper<T,K,SN,N,V> { // // T mapSuperColumn(K rowKey, SN superColumnName, List<HColumn<N,V>> columns); // // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/visitor/ColumnVisitor.java // public interface ColumnVisitor<N, V> { // // /** // * Visit easy column and evaluates a logic. // * @param columnName the name of the column // * @param columnValue the value of the column // * @param timestamp the cassandra timestamp when the column was written // * @param ttl the time to live for that column value // */ // void visit(N columnName, V columnValue, long timestamp, int ttl); // // }
import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.commons.lang3.Validate; import com.ebuddy.cassandra.BatchContext; import com.ebuddy.cassandra.dao.mapper.ColumnMapper; import com.ebuddy.cassandra.dao.mapper.ColumnMapperWithTimestamps; import com.ebuddy.cassandra.dao.mapper.SuperColumnFamilyRowMapper; import com.ebuddy.cassandra.dao.mapper.SuperColumnMapper; import com.ebuddy.cassandra.dao.visitor.ColumnVisitor; import com.google.common.collect.Lists; import me.prettyprint.hector.api.Keyspace; import me.prettyprint.hector.api.Serializer; import me.prettyprint.hector.api.beans.ColumnSlice; import me.prettyprint.hector.api.beans.HColumn; import me.prettyprint.hector.api.beans.HSuperColumn; import me.prettyprint.hector.api.beans.Row; import me.prettyprint.hector.api.beans.Rows; import me.prettyprint.hector.api.beans.SuperRow; import me.prettyprint.hector.api.beans.SuperRows; import me.prettyprint.hector.api.beans.SuperSlice; import me.prettyprint.hector.api.factory.HFactory; import me.prettyprint.hector.api.mutation.Mutator; import me.prettyprint.hector.api.query.MultigetSubSliceQuery; import me.prettyprint.hector.api.query.MultigetSuperSliceQuery; import me.prettyprint.hector.api.query.QueryResult; import me.prettyprint.hector.api.query.SubColumnQuery; import me.prettyprint.hector.api.query.SubSliceQuery; import me.prettyprint.hector.api.query.SuperSliceQuery;
for (Row<K,N,V> row : result.get()) { List<T> resultList = new ArrayList<T>(); K key = row.getKey(); ColumnSlice<N,V> slice = row.getColumnSlice(); for (HColumn<N,V> column : slice.getColumns()) { resultList.add(columnMapper.mapColumn(column.getName(), column.getValue())); } resultMap.put(key, resultList); } return resultMap; } /** * Read all columns from multiple rows from a single super column in each row, * returning a list of mapped super columns. * * @param rowKeys - Keys to search * @param superColumnName - superColumn involved in the query * @return List of mapped super columns. The order is only meaningful if rows are ordered in the database. */ @Override public <T> List<T> multiGetSuperColumn(Collection<K> rowKeys, SN superColumnName, SuperColumnMapper<T,K,SN,N,V> superColumnMapper) { return basicMultiGetSubSlice(rowKeys, superColumnName, superColumnMapper, null); } @Override
// Path: api/src/main/java/com/ebuddy/cassandra/BatchContext.java // public interface BatchContext { } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnMapper.java // public interface ColumnMapper<T,N,V> { // // T mapColumn(N columnName, V columnValue); // // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/ColumnMapperWithTimestamps.java // public interface ColumnMapperWithTimestamps<T,N,V> { // // T mapColumn(N columnName, V columnValue, long timestamp); // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/SuperColumnFamilyRowMapper.java // public interface SuperColumnFamilyRowMapper<T,K,SN,N,V> { // T mapRow(K rowKey, List<HSuperColumn<SN,N,V>> superColumns); // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/mapper/SuperColumnMapper.java // public interface SuperColumnMapper<T,K,SN,N,V> { // // T mapSuperColumn(K rowKey, SN superColumnName, List<HColumn<N,V>> columns); // // } // // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/visitor/ColumnVisitor.java // public interface ColumnVisitor<N, V> { // // /** // * Visit easy column and evaluates a logic. // * @param columnName the name of the column // * @param columnValue the value of the column // * @param timestamp the cassandra timestamp when the column was written // * @param ttl the time to live for that column value // */ // void visit(N columnName, V columnValue, long timestamp, int ttl); // // } // Path: thrift/src/main/java/com/ebuddy/cassandra/dao/SuperColumnFamilyTemplate.java import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.commons.lang3.Validate; import com.ebuddy.cassandra.BatchContext; import com.ebuddy.cassandra.dao.mapper.ColumnMapper; import com.ebuddy.cassandra.dao.mapper.ColumnMapperWithTimestamps; import com.ebuddy.cassandra.dao.mapper.SuperColumnFamilyRowMapper; import com.ebuddy.cassandra.dao.mapper.SuperColumnMapper; import com.ebuddy.cassandra.dao.visitor.ColumnVisitor; import com.google.common.collect.Lists; import me.prettyprint.hector.api.Keyspace; import me.prettyprint.hector.api.Serializer; import me.prettyprint.hector.api.beans.ColumnSlice; import me.prettyprint.hector.api.beans.HColumn; import me.prettyprint.hector.api.beans.HSuperColumn; import me.prettyprint.hector.api.beans.Row; import me.prettyprint.hector.api.beans.Rows; import me.prettyprint.hector.api.beans.SuperRow; import me.prettyprint.hector.api.beans.SuperRows; import me.prettyprint.hector.api.beans.SuperSlice; import me.prettyprint.hector.api.factory.HFactory; import me.prettyprint.hector.api.mutation.Mutator; import me.prettyprint.hector.api.query.MultigetSubSliceQuery; import me.prettyprint.hector.api.query.MultigetSuperSliceQuery; import me.prettyprint.hector.api.query.QueryResult; import me.prettyprint.hector.api.query.SubColumnQuery; import me.prettyprint.hector.api.query.SubSliceQuery; import me.prettyprint.hector.api.query.SuperSliceQuery; for (Row<K,N,V> row : result.get()) { List<T> resultList = new ArrayList<T>(); K key = row.getKey(); ColumnSlice<N,V> slice = row.getColumnSlice(); for (HColumn<N,V> column : slice.getColumns()) { resultList.add(columnMapper.mapColumn(column.getName(), column.getValue())); } resultMap.put(key, resultList); } return resultMap; } /** * Read all columns from multiple rows from a single super column in each row, * returning a list of mapped super columns. * * @param rowKeys - Keys to search * @param superColumnName - superColumn involved in the query * @return List of mapped super columns. The order is only meaningful if rows are ordered in the database. */ @Override public <T> List<T> multiGetSuperColumn(Collection<K> rowKeys, SN superColumnName, SuperColumnMapper<T,K,SN,N,V> superColumnMapper) { return basicMultiGetSubSlice(rowKeys, superColumnName, superColumnMapper, null); } @Override
public <T> List<T> multiGetAllSuperColumns(Collection<K> rowKeys, SuperColumnFamilyRowMapper<T,K,SN,N,V>