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
psiegman/ehcachetag
ehcachetag/src/test/java/nl/siegmann/ehcachetag/CacheTagTest.java
// Path: ehcachetag/src/main/java/nl/siegmann/ehcachetag/CacheTag.java // static final class ModifierNotFoundException extends Exception { // // private static final long serialVersionUID = 4535024464306691589L; // // public ModifierNotFoundException(String message) { // super(message); // } // } // // Path: ehcachetag/src/main/java/nl/siegmann/ehcachetag/cachetagmodifier/CacheTagModifier.java // public interface CacheTagModifier { // // /** // * CacheTagInterceptor that does not do anything. // * // */ // CacheTagModifier NULL_CACHETAG_MODIFIER = new CacheTagModifier() { // // @Override // public void init(ServletContext servletContext) { // } // // @Override // public void beforeLookup(CacheTag cacheTag, JspContext jspContext) { // } // // @Override // public String afterRetrieval(CacheTag cacheTag, JspContext jspContext, // String content) { // return content; // } // // @Override // public void destroy() { // } // // @Override // public String beforeUpdate(CacheTag cacheTag, JspContext jspContext, // String content) { // return content; // } // // }; // // /** // * Called once on Application startup. // * // * @param properties // */ // void init(ServletContext servletContext); // // /** // * Called before Cache lookup. // * // * Will be called by different threads concurrently. // */ // void beforeLookup(CacheTag cacheTag, JspContext jspContext); // // /** // * Called before updating the cache with the given content. // * // * @param cacheTag // * @param jspContext // * @param content the content that will be stored in the cache // * @return the content to store in the cache. // */ // String beforeUpdate(CacheTag cacheTag, JspContext jspContext, String content); // // // /** // * Called after retrieving content from the cache but before it's written to the output. // * // * @param cacheTag // * @param jspContext // * @param content the content that will be sent back to the client // * @return The content to send back to the client // */ // String afterRetrieval(CacheTag cacheTag, JspContext jspContext, String content); // // /** // * Called on Application shutdown. // */ // void destroy(); // } // // Path: ehcachetag/src/main/java/nl/siegmann/ehcachetag/cachetagmodifier/CacheTagModifierFactory.java // public interface CacheTagModifierFactory { // // /** // * Called once after application is initialized. // * // * @param servletContext // */ // void init(ServletContext servletContext); // // /** // * The names of the available cacheTagModifiers // * // * @return The names of the available cacheTagModifiers // */ // Collection<String> getCacheTagModifierNames(); // // /** // * Gets the cacheTagModifier with the given name, null if not found. // * // * @param cacheTagModifierName name of the CacheTagModifier we're looking for. // * // * @return the CacheTagModifier with the given name, null if not found. // */ // CacheTagModifier getCacheTagModifier(String cacheTagModifierName); // // /** // * Called once on application destroy. // * // */ // void destroy(); // }
import java.io.IOException; import javax.servlet.ServletContext; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspContext; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.BodyContent; import javax.servlet.jsp.tagext.BodyTagSupport; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Ehcache; import net.sf.ehcache.Element; import nl.siegmann.ehcachetag.CacheTag.ModifierNotFoundException; import nl.siegmann.ehcachetag.cachetagmodifier.CacheTagModifier; import nl.siegmann.ehcachetag.cachetagmodifier.CacheTagModifierFactory; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations;
// TODO Auto-generated method stub return null; } @Override public void beforeLookup(CacheTag cacheTag, JspContext jspContext) { cacheTag.setKey(cacheTag.getKey().toString() + "B"); } @Override public String afterRetrieval(CacheTag cacheTag, JspContext jspContext, String content) { // TODO Auto-generated method stub return null; } }; Mockito.when(cacheTagModifierFactory.getCacheTagModifier("modifierB")).thenReturn(modifierB); testSubject.setModifiers("modifierB"); Mockito.when(pageContext.findAttribute(EHCacheTagConstants.MODIFIER_FACTORY_ATTRIBUTE)).thenReturn(cacheTagModifierFactory); // when testSubject.setKey("A"); testSubject.doBeforeLookup(); Assert.assertEquals("AB", testSubject.getKey()); }
// Path: ehcachetag/src/main/java/nl/siegmann/ehcachetag/CacheTag.java // static final class ModifierNotFoundException extends Exception { // // private static final long serialVersionUID = 4535024464306691589L; // // public ModifierNotFoundException(String message) { // super(message); // } // } // // Path: ehcachetag/src/main/java/nl/siegmann/ehcachetag/cachetagmodifier/CacheTagModifier.java // public interface CacheTagModifier { // // /** // * CacheTagInterceptor that does not do anything. // * // */ // CacheTagModifier NULL_CACHETAG_MODIFIER = new CacheTagModifier() { // // @Override // public void init(ServletContext servletContext) { // } // // @Override // public void beforeLookup(CacheTag cacheTag, JspContext jspContext) { // } // // @Override // public String afterRetrieval(CacheTag cacheTag, JspContext jspContext, // String content) { // return content; // } // // @Override // public void destroy() { // } // // @Override // public String beforeUpdate(CacheTag cacheTag, JspContext jspContext, // String content) { // return content; // } // // }; // // /** // * Called once on Application startup. // * // * @param properties // */ // void init(ServletContext servletContext); // // /** // * Called before Cache lookup. // * // * Will be called by different threads concurrently. // */ // void beforeLookup(CacheTag cacheTag, JspContext jspContext); // // /** // * Called before updating the cache with the given content. // * // * @param cacheTag // * @param jspContext // * @param content the content that will be stored in the cache // * @return the content to store in the cache. // */ // String beforeUpdate(CacheTag cacheTag, JspContext jspContext, String content); // // // /** // * Called after retrieving content from the cache but before it's written to the output. // * // * @param cacheTag // * @param jspContext // * @param content the content that will be sent back to the client // * @return The content to send back to the client // */ // String afterRetrieval(CacheTag cacheTag, JspContext jspContext, String content); // // /** // * Called on Application shutdown. // */ // void destroy(); // } // // Path: ehcachetag/src/main/java/nl/siegmann/ehcachetag/cachetagmodifier/CacheTagModifierFactory.java // public interface CacheTagModifierFactory { // // /** // * Called once after application is initialized. // * // * @param servletContext // */ // void init(ServletContext servletContext); // // /** // * The names of the available cacheTagModifiers // * // * @return The names of the available cacheTagModifiers // */ // Collection<String> getCacheTagModifierNames(); // // /** // * Gets the cacheTagModifier with the given name, null if not found. // * // * @param cacheTagModifierName name of the CacheTagModifier we're looking for. // * // * @return the CacheTagModifier with the given name, null if not found. // */ // CacheTagModifier getCacheTagModifier(String cacheTagModifierName); // // /** // * Called once on application destroy. // * // */ // void destroy(); // } // Path: ehcachetag/src/test/java/nl/siegmann/ehcachetag/CacheTagTest.java import java.io.IOException; import javax.servlet.ServletContext; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspContext; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.BodyContent; import javax.servlet.jsp.tagext.BodyTagSupport; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Ehcache; import net.sf.ehcache.Element; import nl.siegmann.ehcachetag.CacheTag.ModifierNotFoundException; import nl.siegmann.ehcachetag.cachetagmodifier.CacheTagModifier; import nl.siegmann.ehcachetag.cachetagmodifier.CacheTagModifierFactory; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; // TODO Auto-generated method stub return null; } @Override public void beforeLookup(CacheTag cacheTag, JspContext jspContext) { cacheTag.setKey(cacheTag.getKey().toString() + "B"); } @Override public String afterRetrieval(CacheTag cacheTag, JspContext jspContext, String content) { // TODO Auto-generated method stub return null; } }; Mockito.when(cacheTagModifierFactory.getCacheTagModifier("modifierB")).thenReturn(modifierB); testSubject.setModifiers("modifierB"); Mockito.when(pageContext.findAttribute(EHCacheTagConstants.MODIFIER_FACTORY_ATTRIBUTE)).thenReturn(cacheTagModifierFactory); // when testSubject.setKey("A"); testSubject.doBeforeLookup(); Assert.assertEquals("AB", testSubject.getKey()); }
@Test(expected = ModifierNotFoundException.class)
psiegman/ehcachetag
ehcachetag/src/main/java/nl/siegmann/ehcachetag/EHCacheTagServletContextListener.java
// Path: ehcachetag/src/main/java/nl/siegmann/ehcachetag/cachetagmodifier/CacheTagModifierFactory.java // public interface CacheTagModifierFactory { // // /** // * Called once after application is initialized. // * // * @param servletContext // */ // void init(ServletContext servletContext); // // /** // * The names of the available cacheTagModifiers // * // * @return The names of the available cacheTagModifiers // */ // Collection<String> getCacheTagModifierNames(); // // /** // * Gets the cacheTagModifier with the given name, null if not found. // * // * @param cacheTagModifierName name of the CacheTagModifier we're looking for. // * // * @return the CacheTagModifier with the given name, null if not found. // */ // CacheTagModifier getCacheTagModifier(String cacheTagModifierName); // // /** // * Called once on application destroy. // * // */ // void destroy(); // } // // Path: ehcachetag/src/main/java/nl/siegmann/ehcachetag/cachetagmodifier/DefaultCacheTagModifierFactory.java // public class DefaultCacheTagModifierFactory implements CacheTagModifierFactory { // // public static final String DEFAULT_CACHETAG_MODIFIER_NAME = "default"; // // private static final Logger LOG = LoggerFactory.getLogger(DefaultCacheTagModifierFactory.class); // private Map<String, CacheTagModifier> cacheTagModifiers = new HashMap<String, CacheTagModifier>(); // private CacheTagModifier defaultCacheTagModifier; // // public void init(ServletContext servletContext) { // // // get the configuration of the cacheKeyMetaFactory // String propertiesString = servletContext.getInitParameter(EHCacheTagConstants.MODIFIER_FACTORY_CONFIG_PARAM); // // Map<String, Object> createBeansFromProperties = BeanFactory.createBeansFromProperties(propertiesString); // // for (Map.Entry<String, Object> mapEntry: createBeansFromProperties.entrySet()) { // if (! (mapEntry.getValue() instanceof CacheTagModifier)) { // LOG.error("cacheTagPreProcessor \'" + mapEntry.getKey() + "\' must be an instance of " + CacheTagModifier.class.getName() + " but is of unexpected type " + mapEntry.getValue().getClass().getName()); // continue; // } // CacheTagModifier cacheTagPreProcessor = (CacheTagModifier) mapEntry.getValue(); // cacheTagPreProcessor.init(servletContext); // // String name = mapEntry.getKey(); // if (DEFAULT_CACHETAG_MODIFIER_NAME.equalsIgnoreCase(name)) { // defaultCacheTagModifier = cacheTagPreProcessor; // } // cacheTagModifiers.put(mapEntry.getKey(), cacheTagPreProcessor); // } // if (defaultCacheTagModifier == null) { // defaultCacheTagModifier = CacheTagModifier.NULL_CACHETAG_MODIFIER; // } // } // // @Override // public CacheTagModifier getCacheTagModifier(String cacheTagModifierName) { // if (StringUtils.isBlank(cacheTagModifierName) || DEFAULT_CACHETAG_MODIFIER_NAME.equals(cacheTagModifierName)) { // return defaultCacheTagModifier; // } // // return cacheTagModifiers.get(cacheTagModifierName); // } // // @Override // public Collection<String> getCacheTagModifierNames() { // return cacheTagModifiers.keySet(); // } // // @Override // public void destroy() { // for (CacheTagModifier cacheTagPreProcessor: cacheTagModifiers.values()) { // try { // cacheTagPreProcessor.destroy(); // } catch(Exception e) { // LOG.error(e.toString()); // } // } // } // }
import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import net.sf.ehcache.CacheManager; import nl.siegmann.ehcachetag.cachetagmodifier.CacheTagModifierFactory; import nl.siegmann.ehcachetag.cachetagmodifier.DefaultCacheTagModifierFactory; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package nl.siegmann.ehcachetag; public class EHCacheTagServletContextListener implements ServletContextListener { private static final Logger LOG = LoggerFactory.getLogger(EHCacheTagServletContextListener.class); @Override public void contextInitialized(ServletContextEvent servletContextEvent) { ServletContext servletContext = servletContextEvent.getServletContext(); // get the class name of the cacheKeyMetaFactory String metaFactoryClassName = servletContext.getInitParameter(EHCacheTagConstants.MODIFIER_FACTORY_CLASS_PARAM); // create the metaFactory
// Path: ehcachetag/src/main/java/nl/siegmann/ehcachetag/cachetagmodifier/CacheTagModifierFactory.java // public interface CacheTagModifierFactory { // // /** // * Called once after application is initialized. // * // * @param servletContext // */ // void init(ServletContext servletContext); // // /** // * The names of the available cacheTagModifiers // * // * @return The names of the available cacheTagModifiers // */ // Collection<String> getCacheTagModifierNames(); // // /** // * Gets the cacheTagModifier with the given name, null if not found. // * // * @param cacheTagModifierName name of the CacheTagModifier we're looking for. // * // * @return the CacheTagModifier with the given name, null if not found. // */ // CacheTagModifier getCacheTagModifier(String cacheTagModifierName); // // /** // * Called once on application destroy. // * // */ // void destroy(); // } // // Path: ehcachetag/src/main/java/nl/siegmann/ehcachetag/cachetagmodifier/DefaultCacheTagModifierFactory.java // public class DefaultCacheTagModifierFactory implements CacheTagModifierFactory { // // public static final String DEFAULT_CACHETAG_MODIFIER_NAME = "default"; // // private static final Logger LOG = LoggerFactory.getLogger(DefaultCacheTagModifierFactory.class); // private Map<String, CacheTagModifier> cacheTagModifiers = new HashMap<String, CacheTagModifier>(); // private CacheTagModifier defaultCacheTagModifier; // // public void init(ServletContext servletContext) { // // // get the configuration of the cacheKeyMetaFactory // String propertiesString = servletContext.getInitParameter(EHCacheTagConstants.MODIFIER_FACTORY_CONFIG_PARAM); // // Map<String, Object> createBeansFromProperties = BeanFactory.createBeansFromProperties(propertiesString); // // for (Map.Entry<String, Object> mapEntry: createBeansFromProperties.entrySet()) { // if (! (mapEntry.getValue() instanceof CacheTagModifier)) { // LOG.error("cacheTagPreProcessor \'" + mapEntry.getKey() + "\' must be an instance of " + CacheTagModifier.class.getName() + " but is of unexpected type " + mapEntry.getValue().getClass().getName()); // continue; // } // CacheTagModifier cacheTagPreProcessor = (CacheTagModifier) mapEntry.getValue(); // cacheTagPreProcessor.init(servletContext); // // String name = mapEntry.getKey(); // if (DEFAULT_CACHETAG_MODIFIER_NAME.equalsIgnoreCase(name)) { // defaultCacheTagModifier = cacheTagPreProcessor; // } // cacheTagModifiers.put(mapEntry.getKey(), cacheTagPreProcessor); // } // if (defaultCacheTagModifier == null) { // defaultCacheTagModifier = CacheTagModifier.NULL_CACHETAG_MODIFIER; // } // } // // @Override // public CacheTagModifier getCacheTagModifier(String cacheTagModifierName) { // if (StringUtils.isBlank(cacheTagModifierName) || DEFAULT_CACHETAG_MODIFIER_NAME.equals(cacheTagModifierName)) { // return defaultCacheTagModifier; // } // // return cacheTagModifiers.get(cacheTagModifierName); // } // // @Override // public Collection<String> getCacheTagModifierNames() { // return cacheTagModifiers.keySet(); // } // // @Override // public void destroy() { // for (CacheTagModifier cacheTagPreProcessor: cacheTagModifiers.values()) { // try { // cacheTagPreProcessor.destroy(); // } catch(Exception e) { // LOG.error(e.toString()); // } // } // } // } // Path: ehcachetag/src/main/java/nl/siegmann/ehcachetag/EHCacheTagServletContextListener.java import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import net.sf.ehcache.CacheManager; import nl.siegmann.ehcachetag.cachetagmodifier.CacheTagModifierFactory; import nl.siegmann.ehcachetag.cachetagmodifier.DefaultCacheTagModifierFactory; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package nl.siegmann.ehcachetag; public class EHCacheTagServletContextListener implements ServletContextListener { private static final Logger LOG = LoggerFactory.getLogger(EHCacheTagServletContextListener.class); @Override public void contextInitialized(ServletContextEvent servletContextEvent) { ServletContext servletContext = servletContextEvent.getServletContext(); // get the class name of the cacheKeyMetaFactory String metaFactoryClassName = servletContext.getInitParameter(EHCacheTagConstants.MODIFIER_FACTORY_CLASS_PARAM); // create the metaFactory
CacheTagModifierFactory cacheKeyMetaFactory;
psiegman/ehcachetag
ehcachetag/src/main/java/nl/siegmann/ehcachetag/EHCacheTagServletContextListener.java
// Path: ehcachetag/src/main/java/nl/siegmann/ehcachetag/cachetagmodifier/CacheTagModifierFactory.java // public interface CacheTagModifierFactory { // // /** // * Called once after application is initialized. // * // * @param servletContext // */ // void init(ServletContext servletContext); // // /** // * The names of the available cacheTagModifiers // * // * @return The names of the available cacheTagModifiers // */ // Collection<String> getCacheTagModifierNames(); // // /** // * Gets the cacheTagModifier with the given name, null if not found. // * // * @param cacheTagModifierName name of the CacheTagModifier we're looking for. // * // * @return the CacheTagModifier with the given name, null if not found. // */ // CacheTagModifier getCacheTagModifier(String cacheTagModifierName); // // /** // * Called once on application destroy. // * // */ // void destroy(); // } // // Path: ehcachetag/src/main/java/nl/siegmann/ehcachetag/cachetagmodifier/DefaultCacheTagModifierFactory.java // public class DefaultCacheTagModifierFactory implements CacheTagModifierFactory { // // public static final String DEFAULT_CACHETAG_MODIFIER_NAME = "default"; // // private static final Logger LOG = LoggerFactory.getLogger(DefaultCacheTagModifierFactory.class); // private Map<String, CacheTagModifier> cacheTagModifiers = new HashMap<String, CacheTagModifier>(); // private CacheTagModifier defaultCacheTagModifier; // // public void init(ServletContext servletContext) { // // // get the configuration of the cacheKeyMetaFactory // String propertiesString = servletContext.getInitParameter(EHCacheTagConstants.MODIFIER_FACTORY_CONFIG_PARAM); // // Map<String, Object> createBeansFromProperties = BeanFactory.createBeansFromProperties(propertiesString); // // for (Map.Entry<String, Object> mapEntry: createBeansFromProperties.entrySet()) { // if (! (mapEntry.getValue() instanceof CacheTagModifier)) { // LOG.error("cacheTagPreProcessor \'" + mapEntry.getKey() + "\' must be an instance of " + CacheTagModifier.class.getName() + " but is of unexpected type " + mapEntry.getValue().getClass().getName()); // continue; // } // CacheTagModifier cacheTagPreProcessor = (CacheTagModifier) mapEntry.getValue(); // cacheTagPreProcessor.init(servletContext); // // String name = mapEntry.getKey(); // if (DEFAULT_CACHETAG_MODIFIER_NAME.equalsIgnoreCase(name)) { // defaultCacheTagModifier = cacheTagPreProcessor; // } // cacheTagModifiers.put(mapEntry.getKey(), cacheTagPreProcessor); // } // if (defaultCacheTagModifier == null) { // defaultCacheTagModifier = CacheTagModifier.NULL_CACHETAG_MODIFIER; // } // } // // @Override // public CacheTagModifier getCacheTagModifier(String cacheTagModifierName) { // if (StringUtils.isBlank(cacheTagModifierName) || DEFAULT_CACHETAG_MODIFIER_NAME.equals(cacheTagModifierName)) { // return defaultCacheTagModifier; // } // // return cacheTagModifiers.get(cacheTagModifierName); // } // // @Override // public Collection<String> getCacheTagModifierNames() { // return cacheTagModifiers.keySet(); // } // // @Override // public void destroy() { // for (CacheTagModifier cacheTagPreProcessor: cacheTagModifiers.values()) { // try { // cacheTagPreProcessor.destroy(); // } catch(Exception e) { // LOG.error(e.toString()); // } // } // } // }
import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import net.sf.ehcache.CacheManager; import nl.siegmann.ehcachetag.cachetagmodifier.CacheTagModifierFactory; import nl.siegmann.ehcachetag.cachetagmodifier.DefaultCacheTagModifierFactory; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package nl.siegmann.ehcachetag; public class EHCacheTagServletContextListener implements ServletContextListener { private static final Logger LOG = LoggerFactory.getLogger(EHCacheTagServletContextListener.class); @Override public void contextInitialized(ServletContextEvent servletContextEvent) { ServletContext servletContext = servletContextEvent.getServletContext(); // get the class name of the cacheKeyMetaFactory String metaFactoryClassName = servletContext.getInitParameter(EHCacheTagConstants.MODIFIER_FACTORY_CLASS_PARAM); // create the metaFactory CacheTagModifierFactory cacheKeyMetaFactory; if (StringUtils.isBlank(metaFactoryClassName)) { // create Default CacheKeyMetaFactory
// Path: ehcachetag/src/main/java/nl/siegmann/ehcachetag/cachetagmodifier/CacheTagModifierFactory.java // public interface CacheTagModifierFactory { // // /** // * Called once after application is initialized. // * // * @param servletContext // */ // void init(ServletContext servletContext); // // /** // * The names of the available cacheTagModifiers // * // * @return The names of the available cacheTagModifiers // */ // Collection<String> getCacheTagModifierNames(); // // /** // * Gets the cacheTagModifier with the given name, null if not found. // * // * @param cacheTagModifierName name of the CacheTagModifier we're looking for. // * // * @return the CacheTagModifier with the given name, null if not found. // */ // CacheTagModifier getCacheTagModifier(String cacheTagModifierName); // // /** // * Called once on application destroy. // * // */ // void destroy(); // } // // Path: ehcachetag/src/main/java/nl/siegmann/ehcachetag/cachetagmodifier/DefaultCacheTagModifierFactory.java // public class DefaultCacheTagModifierFactory implements CacheTagModifierFactory { // // public static final String DEFAULT_CACHETAG_MODIFIER_NAME = "default"; // // private static final Logger LOG = LoggerFactory.getLogger(DefaultCacheTagModifierFactory.class); // private Map<String, CacheTagModifier> cacheTagModifiers = new HashMap<String, CacheTagModifier>(); // private CacheTagModifier defaultCacheTagModifier; // // public void init(ServletContext servletContext) { // // // get the configuration of the cacheKeyMetaFactory // String propertiesString = servletContext.getInitParameter(EHCacheTagConstants.MODIFIER_FACTORY_CONFIG_PARAM); // // Map<String, Object> createBeansFromProperties = BeanFactory.createBeansFromProperties(propertiesString); // // for (Map.Entry<String, Object> mapEntry: createBeansFromProperties.entrySet()) { // if (! (mapEntry.getValue() instanceof CacheTagModifier)) { // LOG.error("cacheTagPreProcessor \'" + mapEntry.getKey() + "\' must be an instance of " + CacheTagModifier.class.getName() + " but is of unexpected type " + mapEntry.getValue().getClass().getName()); // continue; // } // CacheTagModifier cacheTagPreProcessor = (CacheTagModifier) mapEntry.getValue(); // cacheTagPreProcessor.init(servletContext); // // String name = mapEntry.getKey(); // if (DEFAULT_CACHETAG_MODIFIER_NAME.equalsIgnoreCase(name)) { // defaultCacheTagModifier = cacheTagPreProcessor; // } // cacheTagModifiers.put(mapEntry.getKey(), cacheTagPreProcessor); // } // if (defaultCacheTagModifier == null) { // defaultCacheTagModifier = CacheTagModifier.NULL_CACHETAG_MODIFIER; // } // } // // @Override // public CacheTagModifier getCacheTagModifier(String cacheTagModifierName) { // if (StringUtils.isBlank(cacheTagModifierName) || DEFAULT_CACHETAG_MODIFIER_NAME.equals(cacheTagModifierName)) { // return defaultCacheTagModifier; // } // // return cacheTagModifiers.get(cacheTagModifierName); // } // // @Override // public Collection<String> getCacheTagModifierNames() { // return cacheTagModifiers.keySet(); // } // // @Override // public void destroy() { // for (CacheTagModifier cacheTagPreProcessor: cacheTagModifiers.values()) { // try { // cacheTagPreProcessor.destroy(); // } catch(Exception e) { // LOG.error(e.toString()); // } // } // } // } // Path: ehcachetag/src/main/java/nl/siegmann/ehcachetag/EHCacheTagServletContextListener.java import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import net.sf.ehcache.CacheManager; import nl.siegmann.ehcachetag.cachetagmodifier.CacheTagModifierFactory; import nl.siegmann.ehcachetag.cachetagmodifier.DefaultCacheTagModifierFactory; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package nl.siegmann.ehcachetag; public class EHCacheTagServletContextListener implements ServletContextListener { private static final Logger LOG = LoggerFactory.getLogger(EHCacheTagServletContextListener.class); @Override public void contextInitialized(ServletContextEvent servletContextEvent) { ServletContext servletContext = servletContextEvent.getServletContext(); // get the class name of the cacheKeyMetaFactory String metaFactoryClassName = servletContext.getInitParameter(EHCacheTagConstants.MODIFIER_FACTORY_CLASS_PARAM); // create the metaFactory CacheTagModifierFactory cacheKeyMetaFactory; if (StringUtils.isBlank(metaFactoryClassName)) { // create Default CacheKeyMetaFactory
cacheKeyMetaFactory = new DefaultCacheTagModifierFactory();
psiegman/ehcachetag
ehcachetag/src/test/java/nl/siegmann/ehcachetag/cachetagmodifier/CompositeCacheKeyTest.java
// Path: ehcachetag/src/main/java/nl/siegmann/ehcachetag/cachetagmodifier/CompositeCacheKey.java // public class CompositeCacheKey { // // private Object[] keyComponents; // // public CompositeCacheKey(Object... keyComponents) { // this.keyComponents = keyComponents; // } // // public boolean equals(Object other) { // return ArrayUtils.isEquals(keyComponents, ((CompositeCacheKey) other).keyComponents); // } // // public int hashCode() { // return ArrayUtils.hashCode(keyComponents); // } // // public String toString() { // return new ToStringBuilder(this).append("keyComponents", keyComponents).toString(); // } // }
import junit.framework.Assert; import nl.siegmann.ehcachetag.cachetagmodifier.CompositeCacheKey; import org.junit.Test;
package nl.siegmann.ehcachetag.cachetagmodifier; public class CompositeCacheKeyTest { @Test public void test1() {
// Path: ehcachetag/src/main/java/nl/siegmann/ehcachetag/cachetagmodifier/CompositeCacheKey.java // public class CompositeCacheKey { // // private Object[] keyComponents; // // public CompositeCacheKey(Object... keyComponents) { // this.keyComponents = keyComponents; // } // // public boolean equals(Object other) { // return ArrayUtils.isEquals(keyComponents, ((CompositeCacheKey) other).keyComponents); // } // // public int hashCode() { // return ArrayUtils.hashCode(keyComponents); // } // // public String toString() { // return new ToStringBuilder(this).append("keyComponents", keyComponents).toString(); // } // } // Path: ehcachetag/src/test/java/nl/siegmann/ehcachetag/cachetagmodifier/CompositeCacheKeyTest.java import junit.framework.Assert; import nl.siegmann.ehcachetag.cachetagmodifier.CompositeCacheKey; import org.junit.Test; package nl.siegmann.ehcachetag.cachetagmodifier; public class CompositeCacheKeyTest { @Test public void test1() {
CompositeCacheKey cacheKey1 = new CompositeCacheKey("foo");
psiegman/ehcachetag
ehcachetag/src/test/java/nl/siegmann/ehcachetag/util/BeanFactoryTest.java
// Path: ehcachetag/src/main/java/nl/siegmann/ehcachetag/util/BeanFactory.java // public class BeanFactory { // // public static final String QUERY_STRING_CHARACTER_ENCODING = "UTF-8"; // // private static final Logger LOG = LoggerFactory.getLogger(BeanFactory.class); // private static final PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean(); // // public static Map<String, Object> createBeansFromProperties(String propertiesString) { // Map<String, Object> result = new HashMap<String, Object>(); // Properties properties = parseProperties(propertiesString); // for ( String beanName: properties.stringPropertyNames()) { // Object bean = BeanFactory.createBean(properties.getProperty(beanName)); // if (bean != null) { // result.put(beanName, bean); // } // } // return result; // } // // // private static Properties parseProperties(String propertiesString) { // // Properties result = new Properties(); // if (StringUtils.isBlank(propertiesString)) { // return result; // } // try { // result.load(new StringReader(propertiesString)); // } catch (IOException e) { // LOG.error(e.toString()); // } // return result; // } // // public static <T> T createBean(String beanCreateRequest) { // // // create bean // String classNameString = StringUtils.substringBefore(beanCreateRequest, "?"); // T result = createBeanInstance(classNameString); // if (result == null) { // return result; // } // // // initialize bean // String queryString = StringUtils.substringAfterLast(beanCreateRequest, "?"); // if (StringUtils.isNotBlank(queryString)) { // result = initializeBean(result, queryString); // } // // return result; // } // // /** // * Sets all the bean properties, returning null if anything goes wrong. // * // * @param bean // * @param queryString // * @return the given bean with all the bean properties set, null if anything went wrong. // */ // private static <T> T initializeBean(T bean, // String queryString) { // // T result = null; // Map<String, String> splitQuery; // try { // splitQuery = parseQueryString(queryString); // for (Map.Entry<String, String> keyValue: splitQuery.entrySet()) { // setProperty(bean, keyValue.getKey(), keyValue.getValue()); // } // result = bean; // } catch (UnsupportedEncodingException e) { // LOG.error(e.toString()); // } catch (SecurityException e) { // LOG.error(e.toString()); // } catch (IllegalAccessException e) { // LOG.error(e.toString()); // } catch (IllegalArgumentException e) { // LOG.error(e.toString()); // } catch (InvocationTargetException e) { // LOG.error(e.toString()); // } catch (NoSuchMethodException e) { // LOG.error(e.toString()); // } // return result; // } // // private static void setProperty(Object bean, String propertyName, String propertyValue) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { // // // apache commons BeanUtilsBean silently ignores missing properties, so we do the work ourselves // PropertyDescriptor propertyDescriptor = propertyUtilsBean.getPropertyDescriptor(bean, propertyName); // // if (propertyDescriptor == null) { // throw new IllegalArgumentException("Property " + propertyName + " not found on class " + bean.getClass().getName()); // } // ConvertUtilsBean convertUtilsBean = new ConvertUtilsBean(); // convertUtilsBean.register(true, true, 0); // // Object value = convertUtilsBean.convert(propertyValue, propertyDescriptor.getPropertyType()); // // propertyUtilsBean.setProperty(bean, propertyName, value); // } // // @SuppressWarnings("unchecked") // private static <T> T createBeanInstance(String beanClassName) { // T result = null; // try { // result = (T) Class.forName(beanClassName).newInstance(); // } catch (InstantiationException e) { // LOG.error(e.toString()); // } catch (IllegalAccessException e) { // LOG.error(e.toString()); // } catch (ClassNotFoundException e) { // LOG.error(e.toString()); // } // return result; // } // // private static Map<String, String> parseQueryString(String queryString) throws UnsupportedEncodingException { // Map<String, String> result = new HashMap<String, String>(); // String[] pairs = queryString.split("&"); // for (String pair : pairs) { // int equalsPos = pair.indexOf("="); // String key = urlDecode(pair.substring(0, equalsPos)); // String value = urlDecode(pair.substring(equalsPos + 1)); // result.put(key, value); // } // return result; // } // // private static String urlDecode(String input) throws UnsupportedEncodingException { // return URLDecoder.decode(input, QUERY_STRING_CHARACTER_ENCODING); // } // }
import org.junit.Test; import java.util.Map; import junit.framework.Assert; import nl.siegmann.ehcachetag.util.BeanFactory;
package nl.siegmann.ehcachetag.util; public class BeanFactoryTest { @Test public void testCreateBeansFromProperties_simple() { // given String input = "messageBean=" + TestBean.class.getName() + "?message=hi&name=jerry\n" + "secondBean=" + SecondTestBean.class.getName() + "?color=red&size=large"; // when
// Path: ehcachetag/src/main/java/nl/siegmann/ehcachetag/util/BeanFactory.java // public class BeanFactory { // // public static final String QUERY_STRING_CHARACTER_ENCODING = "UTF-8"; // // private static final Logger LOG = LoggerFactory.getLogger(BeanFactory.class); // private static final PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean(); // // public static Map<String, Object> createBeansFromProperties(String propertiesString) { // Map<String, Object> result = new HashMap<String, Object>(); // Properties properties = parseProperties(propertiesString); // for ( String beanName: properties.stringPropertyNames()) { // Object bean = BeanFactory.createBean(properties.getProperty(beanName)); // if (bean != null) { // result.put(beanName, bean); // } // } // return result; // } // // // private static Properties parseProperties(String propertiesString) { // // Properties result = new Properties(); // if (StringUtils.isBlank(propertiesString)) { // return result; // } // try { // result.load(new StringReader(propertiesString)); // } catch (IOException e) { // LOG.error(e.toString()); // } // return result; // } // // public static <T> T createBean(String beanCreateRequest) { // // // create bean // String classNameString = StringUtils.substringBefore(beanCreateRequest, "?"); // T result = createBeanInstance(classNameString); // if (result == null) { // return result; // } // // // initialize bean // String queryString = StringUtils.substringAfterLast(beanCreateRequest, "?"); // if (StringUtils.isNotBlank(queryString)) { // result = initializeBean(result, queryString); // } // // return result; // } // // /** // * Sets all the bean properties, returning null if anything goes wrong. // * // * @param bean // * @param queryString // * @return the given bean with all the bean properties set, null if anything went wrong. // */ // private static <T> T initializeBean(T bean, // String queryString) { // // T result = null; // Map<String, String> splitQuery; // try { // splitQuery = parseQueryString(queryString); // for (Map.Entry<String, String> keyValue: splitQuery.entrySet()) { // setProperty(bean, keyValue.getKey(), keyValue.getValue()); // } // result = bean; // } catch (UnsupportedEncodingException e) { // LOG.error(e.toString()); // } catch (SecurityException e) { // LOG.error(e.toString()); // } catch (IllegalAccessException e) { // LOG.error(e.toString()); // } catch (IllegalArgumentException e) { // LOG.error(e.toString()); // } catch (InvocationTargetException e) { // LOG.error(e.toString()); // } catch (NoSuchMethodException e) { // LOG.error(e.toString()); // } // return result; // } // // private static void setProperty(Object bean, String propertyName, String propertyValue) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { // // // apache commons BeanUtilsBean silently ignores missing properties, so we do the work ourselves // PropertyDescriptor propertyDescriptor = propertyUtilsBean.getPropertyDescriptor(bean, propertyName); // // if (propertyDescriptor == null) { // throw new IllegalArgumentException("Property " + propertyName + " not found on class " + bean.getClass().getName()); // } // ConvertUtilsBean convertUtilsBean = new ConvertUtilsBean(); // convertUtilsBean.register(true, true, 0); // // Object value = convertUtilsBean.convert(propertyValue, propertyDescriptor.getPropertyType()); // // propertyUtilsBean.setProperty(bean, propertyName, value); // } // // @SuppressWarnings("unchecked") // private static <T> T createBeanInstance(String beanClassName) { // T result = null; // try { // result = (T) Class.forName(beanClassName).newInstance(); // } catch (InstantiationException e) { // LOG.error(e.toString()); // } catch (IllegalAccessException e) { // LOG.error(e.toString()); // } catch (ClassNotFoundException e) { // LOG.error(e.toString()); // } // return result; // } // // private static Map<String, String> parseQueryString(String queryString) throws UnsupportedEncodingException { // Map<String, String> result = new HashMap<String, String>(); // String[] pairs = queryString.split("&"); // for (String pair : pairs) { // int equalsPos = pair.indexOf("="); // String key = urlDecode(pair.substring(0, equalsPos)); // String value = urlDecode(pair.substring(equalsPos + 1)); // result.put(key, value); // } // return result; // } // // private static String urlDecode(String input) throws UnsupportedEncodingException { // return URLDecoder.decode(input, QUERY_STRING_CHARACTER_ENCODING); // } // } // Path: ehcachetag/src/test/java/nl/siegmann/ehcachetag/util/BeanFactoryTest.java import org.junit.Test; import java.util.Map; import junit.framework.Assert; import nl.siegmann.ehcachetag.util.BeanFactory; package nl.siegmann.ehcachetag.util; public class BeanFactoryTest { @Test public void testCreateBeansFromProperties_simple() { // given String input = "messageBean=" + TestBean.class.getName() + "?message=hi&name=jerry\n" + "secondBean=" + SecondTestBean.class.getName() + "?color=red&size=large"; // when
Map<String, Object> actualResult = BeanFactory.createBeansFromProperties(input);
szhem/camel-osgi
component/src/test/java/org/apache/camel/osgi/service/OsgiRoundRobinEndpointTest.java
// Path: component/src/main/java/org/apache/camel/osgi/service/util/BundleDelegatingClassLoader.java // public class BundleDelegatingClassLoader extends ClassLoader { // private final Bundle bundle; // private final ClassLoader classLoader; // // public BundleDelegatingClassLoader(Bundle bundle) { // this(bundle, null); // } // // public BundleDelegatingClassLoader(Bundle bundle, ClassLoader classLoader) { // if (bundle == null) { // throw new IllegalArgumentException("bundle: null"); // } // this.bundle = bundle; // this.classLoader = classLoader; // } // // protected Class<?> findClass(String name) throws ClassNotFoundException { // return bundle.loadClass(name); // } // // protected URL findResource(String name) { // URL resource = bundle.getResource(name); // if (classLoader != null && resource == null) { // resource = classLoader.getResource(name); // } // return resource; // } // // @SuppressWarnings("unchecked") // protected Enumeration findResources(String name) throws IOException { // Enumeration resources = bundle.getResources(name); // if (classLoader != null && (resources == null || !resources.hasMoreElements())) { // resources = classLoader.getResources(name); // } // return resources; // } // // protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { // Class<?> clazz; // try { // clazz = findClass(name); // } catch (ClassNotFoundException cnfe) { // if (classLoader != null) { // try { // clazz = classLoader.loadClass(name); // } catch (ClassNotFoundException e) { // throw new ClassNotFoundException(String.format("[%s] from bundle [%s] (%s)", // name, bundle.getBundleId(), bundle.getSymbolicName())); // } // } else { // throw new ClassNotFoundException(String.format("[%s] from bundle [%s] (%s)", // name, bundle.getBundleId(), bundle.getSymbolicName())); // } // } // if (resolve) { // resolveClass(clazz); // } // return clazz; // } // // public Bundle getBundle() { // return bundle; // } // // @Override // public String toString() { // return String.format("BundleDelegatingClassLoader(%s)", bundle); // } // }
import org.apache.camel.CamelContext; import org.apache.camel.Component; import org.apache.camel.Processor; import org.apache.camel.osgi.service.util.BundleDelegatingClassLoader; import org.junit.Test; import org.osgi.framework.Bundle; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service; public class OsgiRoundRobinEndpointTest { @Test(expected = UnsupportedOperationException.class) public void testCreateConsumer() throws Exception { OsgiRoundRobinEndpoint endpoint = createEndpoint(); Processor processor = mock(Processor.class); endpoint.createConsumer(processor); } @Test public void testCreateProducer() throws Exception { OsgiRoundRobinEndpoint endpoint = createEndpoint(); assertThat(endpoint.createProducer(), instanceOf(OsgiRoundRobinProducer.class)); } private OsgiRoundRobinEndpoint createEndpoint() throws Exception { Bundle bundle = mock(Bundle.class);
// Path: component/src/main/java/org/apache/camel/osgi/service/util/BundleDelegatingClassLoader.java // public class BundleDelegatingClassLoader extends ClassLoader { // private final Bundle bundle; // private final ClassLoader classLoader; // // public BundleDelegatingClassLoader(Bundle bundle) { // this(bundle, null); // } // // public BundleDelegatingClassLoader(Bundle bundle, ClassLoader classLoader) { // if (bundle == null) { // throw new IllegalArgumentException("bundle: null"); // } // this.bundle = bundle; // this.classLoader = classLoader; // } // // protected Class<?> findClass(String name) throws ClassNotFoundException { // return bundle.loadClass(name); // } // // protected URL findResource(String name) { // URL resource = bundle.getResource(name); // if (classLoader != null && resource == null) { // resource = classLoader.getResource(name); // } // return resource; // } // // @SuppressWarnings("unchecked") // protected Enumeration findResources(String name) throws IOException { // Enumeration resources = bundle.getResources(name); // if (classLoader != null && (resources == null || !resources.hasMoreElements())) { // resources = classLoader.getResources(name); // } // return resources; // } // // protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { // Class<?> clazz; // try { // clazz = findClass(name); // } catch (ClassNotFoundException cnfe) { // if (classLoader != null) { // try { // clazz = classLoader.loadClass(name); // } catch (ClassNotFoundException e) { // throw new ClassNotFoundException(String.format("[%s] from bundle [%s] (%s)", // name, bundle.getBundleId(), bundle.getSymbolicName())); // } // } else { // throw new ClassNotFoundException(String.format("[%s] from bundle [%s] (%s)", // name, bundle.getBundleId(), bundle.getSymbolicName())); // } // } // if (resolve) { // resolveClass(clazz); // } // return clazz; // } // // public Bundle getBundle() { // return bundle; // } // // @Override // public String toString() { // return String.format("BundleDelegatingClassLoader(%s)", bundle); // } // } // Path: component/src/test/java/org/apache/camel/osgi/service/OsgiRoundRobinEndpointTest.java import org.apache.camel.CamelContext; import org.apache.camel.Component; import org.apache.camel.Processor; import org.apache.camel.osgi.service.util.BundleDelegatingClassLoader; import org.junit.Test; import org.osgi.framework.Bundle; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service; public class OsgiRoundRobinEndpointTest { @Test(expected = UnsupportedOperationException.class) public void testCreateConsumer() throws Exception { OsgiRoundRobinEndpoint endpoint = createEndpoint(); Processor processor = mock(Processor.class); endpoint.createConsumer(processor); } @Test public void testCreateProducer() throws Exception { OsgiRoundRobinEndpoint endpoint = createEndpoint(); assertThat(endpoint.createProducer(), instanceOf(OsgiRoundRobinProducer.class)); } private OsgiRoundRobinEndpoint createEndpoint() throws Exception { Bundle bundle = mock(Bundle.class);
ClassLoader classLoader = new BundleDelegatingClassLoader(bundle, getClass().getClassLoader());
szhem/camel-osgi
component/src/test/java/org/apache/camel/osgi/service/OsgiMulticastEndpointTest.java
// Path: component/src/main/java/org/apache/camel/osgi/service/util/BundleDelegatingClassLoader.java // public class BundleDelegatingClassLoader extends ClassLoader { // private final Bundle bundle; // private final ClassLoader classLoader; // // public BundleDelegatingClassLoader(Bundle bundle) { // this(bundle, null); // } // // public BundleDelegatingClassLoader(Bundle bundle, ClassLoader classLoader) { // if (bundle == null) { // throw new IllegalArgumentException("bundle: null"); // } // this.bundle = bundle; // this.classLoader = classLoader; // } // // protected Class<?> findClass(String name) throws ClassNotFoundException { // return bundle.loadClass(name); // } // // protected URL findResource(String name) { // URL resource = bundle.getResource(name); // if (classLoader != null && resource == null) { // resource = classLoader.getResource(name); // } // return resource; // } // // @SuppressWarnings("unchecked") // protected Enumeration findResources(String name) throws IOException { // Enumeration resources = bundle.getResources(name); // if (classLoader != null && (resources == null || !resources.hasMoreElements())) { // resources = classLoader.getResources(name); // } // return resources; // } // // protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { // Class<?> clazz; // try { // clazz = findClass(name); // } catch (ClassNotFoundException cnfe) { // if (classLoader != null) { // try { // clazz = classLoader.loadClass(name); // } catch (ClassNotFoundException e) { // throw new ClassNotFoundException(String.format("[%s] from bundle [%s] (%s)", // name, bundle.getBundleId(), bundle.getSymbolicName())); // } // } else { // throw new ClassNotFoundException(String.format("[%s] from bundle [%s] (%s)", // name, bundle.getBundleId(), bundle.getSymbolicName())); // } // } // if (resolve) { // resolveClass(clazz); // } // return clazz; // } // // public Bundle getBundle() { // return bundle; // } // // @Override // public String toString() { // return String.format("BundleDelegatingClassLoader(%s)", bundle); // } // }
import org.apache.camel.CamelContext; import org.apache.camel.Component; import org.apache.camel.Processor; import org.apache.camel.osgi.service.util.BundleDelegatingClassLoader; import org.junit.Test; import org.osgi.framework.Bundle; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service; public class OsgiMulticastEndpointTest { @Test(expected = UnsupportedOperationException.class) public void testCreateConsumer() throws Exception { OsgiMulticastEndpoint endpoint = createEndpoint(); Processor processor = mock(Processor.class); endpoint.createConsumer(processor); } @Test public void testCreateProducer() throws Exception { OsgiMulticastEndpoint endpoint = createEndpoint(); assertThat(endpoint.createProducer(), instanceOf(OsgiMulticastProducer.class)); } private OsgiMulticastEndpoint createEndpoint() { Bundle bundle = mock(Bundle.class);
// Path: component/src/main/java/org/apache/camel/osgi/service/util/BundleDelegatingClassLoader.java // public class BundleDelegatingClassLoader extends ClassLoader { // private final Bundle bundle; // private final ClassLoader classLoader; // // public BundleDelegatingClassLoader(Bundle bundle) { // this(bundle, null); // } // // public BundleDelegatingClassLoader(Bundle bundle, ClassLoader classLoader) { // if (bundle == null) { // throw new IllegalArgumentException("bundle: null"); // } // this.bundle = bundle; // this.classLoader = classLoader; // } // // protected Class<?> findClass(String name) throws ClassNotFoundException { // return bundle.loadClass(name); // } // // protected URL findResource(String name) { // URL resource = bundle.getResource(name); // if (classLoader != null && resource == null) { // resource = classLoader.getResource(name); // } // return resource; // } // // @SuppressWarnings("unchecked") // protected Enumeration findResources(String name) throws IOException { // Enumeration resources = bundle.getResources(name); // if (classLoader != null && (resources == null || !resources.hasMoreElements())) { // resources = classLoader.getResources(name); // } // return resources; // } // // protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { // Class<?> clazz; // try { // clazz = findClass(name); // } catch (ClassNotFoundException cnfe) { // if (classLoader != null) { // try { // clazz = classLoader.loadClass(name); // } catch (ClassNotFoundException e) { // throw new ClassNotFoundException(String.format("[%s] from bundle [%s] (%s)", // name, bundle.getBundleId(), bundle.getSymbolicName())); // } // } else { // throw new ClassNotFoundException(String.format("[%s] from bundle [%s] (%s)", // name, bundle.getBundleId(), bundle.getSymbolicName())); // } // } // if (resolve) { // resolveClass(clazz); // } // return clazz; // } // // public Bundle getBundle() { // return bundle; // } // // @Override // public String toString() { // return String.format("BundleDelegatingClassLoader(%s)", bundle); // } // } // Path: component/src/test/java/org/apache/camel/osgi/service/OsgiMulticastEndpointTest.java import org.apache.camel.CamelContext; import org.apache.camel.Component; import org.apache.camel.Processor; import org.apache.camel.osgi.service.util.BundleDelegatingClassLoader; import org.junit.Test; import org.osgi.framework.Bundle; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service; public class OsgiMulticastEndpointTest { @Test(expected = UnsupportedOperationException.class) public void testCreateConsumer() throws Exception { OsgiMulticastEndpoint endpoint = createEndpoint(); Processor processor = mock(Processor.class); endpoint.createConsumer(processor); } @Test public void testCreateProducer() throws Exception { OsgiMulticastEndpoint endpoint = createEndpoint(); assertThat(endpoint.createProducer(), instanceOf(OsgiMulticastProducer.class)); } private OsgiMulticastEndpoint createEndpoint() { Bundle bundle = mock(Bundle.class);
ClassLoader classLoader = new BundleDelegatingClassLoader(bundle, getClass().getClassLoader());
szhem/camel-osgi
component/src/test/java/org/apache/camel/osgi/service/OsgiComponentTest.java
// Path: component/src/main/java/org/apache/camel/osgi/service/util/BundleDelegatingClassLoader.java // public class BundleDelegatingClassLoader extends ClassLoader { // private final Bundle bundle; // private final ClassLoader classLoader; // // public BundleDelegatingClassLoader(Bundle bundle) { // this(bundle, null); // } // // public BundleDelegatingClassLoader(Bundle bundle, ClassLoader classLoader) { // if (bundle == null) { // throw new IllegalArgumentException("bundle: null"); // } // this.bundle = bundle; // this.classLoader = classLoader; // } // // protected Class<?> findClass(String name) throws ClassNotFoundException { // return bundle.loadClass(name); // } // // protected URL findResource(String name) { // URL resource = bundle.getResource(name); // if (classLoader != null && resource == null) { // resource = classLoader.getResource(name); // } // return resource; // } // // @SuppressWarnings("unchecked") // protected Enumeration findResources(String name) throws IOException { // Enumeration resources = bundle.getResources(name); // if (classLoader != null && (resources == null || !resources.hasMoreElements())) { // resources = classLoader.getResources(name); // } // return resources; // } // // protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { // Class<?> clazz; // try { // clazz = findClass(name); // } catch (ClassNotFoundException cnfe) { // if (classLoader != null) { // try { // clazz = classLoader.loadClass(name); // } catch (ClassNotFoundException e) { // throw new ClassNotFoundException(String.format("[%s] from bundle [%s] (%s)", // name, bundle.getBundleId(), bundle.getSymbolicName())); // } // } else { // throw new ClassNotFoundException(String.format("[%s] from bundle [%s] (%s)", // name, bundle.getBundleId(), bundle.getSymbolicName())); // } // } // if (resolve) { // resolveClass(clazz); // } // return clazz; // } // // public Bundle getBundle() { // return bundle; // } // // @Override // public String toString() { // return String.format("BundleDelegatingClassLoader(%s)", bundle); // } // }
import static org.mockito.Matchers.same; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.apache.camel.CamelContext; import org.apache.camel.TypeConverter; import org.apache.camel.osgi.service.util.BundleDelegatingClassLoader; import org.apache.camel.processor.aggregate.AggregationStrategy; import org.apache.camel.spi.Registry; import org.junit.Test; import org.osgi.framework.Bundle; import org.osgi.framework.Constants; import java.util.HashMap; import java.util.Map; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.eq;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service; public class OsgiComponentTest { @Test public void testCreateEndpoint() throws Exception { Bundle bundle = mock(Bundle.class);
// Path: component/src/main/java/org/apache/camel/osgi/service/util/BundleDelegatingClassLoader.java // public class BundleDelegatingClassLoader extends ClassLoader { // private final Bundle bundle; // private final ClassLoader classLoader; // // public BundleDelegatingClassLoader(Bundle bundle) { // this(bundle, null); // } // // public BundleDelegatingClassLoader(Bundle bundle, ClassLoader classLoader) { // if (bundle == null) { // throw new IllegalArgumentException("bundle: null"); // } // this.bundle = bundle; // this.classLoader = classLoader; // } // // protected Class<?> findClass(String name) throws ClassNotFoundException { // return bundle.loadClass(name); // } // // protected URL findResource(String name) { // URL resource = bundle.getResource(name); // if (classLoader != null && resource == null) { // resource = classLoader.getResource(name); // } // return resource; // } // // @SuppressWarnings("unchecked") // protected Enumeration findResources(String name) throws IOException { // Enumeration resources = bundle.getResources(name); // if (classLoader != null && (resources == null || !resources.hasMoreElements())) { // resources = classLoader.getResources(name); // } // return resources; // } // // protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { // Class<?> clazz; // try { // clazz = findClass(name); // } catch (ClassNotFoundException cnfe) { // if (classLoader != null) { // try { // clazz = classLoader.loadClass(name); // } catch (ClassNotFoundException e) { // throw new ClassNotFoundException(String.format("[%s] from bundle [%s] (%s)", // name, bundle.getBundleId(), bundle.getSymbolicName())); // } // } else { // throw new ClassNotFoundException(String.format("[%s] from bundle [%s] (%s)", // name, bundle.getBundleId(), bundle.getSymbolicName())); // } // } // if (resolve) { // resolveClass(clazz); // } // return clazz; // } // // public Bundle getBundle() { // return bundle; // } // // @Override // public String toString() { // return String.format("BundleDelegatingClassLoader(%s)", bundle); // } // } // Path: component/src/test/java/org/apache/camel/osgi/service/OsgiComponentTest.java import static org.mockito.Matchers.same; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.apache.camel.CamelContext; import org.apache.camel.TypeConverter; import org.apache.camel.osgi.service.util.BundleDelegatingClassLoader; import org.apache.camel.processor.aggregate.AggregationStrategy; import org.apache.camel.spi.Registry; import org.junit.Test; import org.osgi.framework.Bundle; import org.osgi.framework.Constants; import java.util.HashMap; import java.util.Map; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.eq; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service; public class OsgiComponentTest { @Test public void testCreateEndpoint() throws Exception { Bundle bundle = mock(Bundle.class);
BundleDelegatingClassLoader classLoader = new BundleDelegatingClassLoader(bundle, getClass().getClassLoader());
szhem/camel-osgi
component/src/test/java/org/apache/camel/osgi/service/OsgiDefaultEndpointTest.java
// Path: component/src/main/java/org/apache/camel/osgi/service/util/BundleDelegatingClassLoader.java // public class BundleDelegatingClassLoader extends ClassLoader { // private final Bundle bundle; // private final ClassLoader classLoader; // // public BundleDelegatingClassLoader(Bundle bundle) { // this(bundle, null); // } // // public BundleDelegatingClassLoader(Bundle bundle, ClassLoader classLoader) { // if (bundle == null) { // throw new IllegalArgumentException("bundle: null"); // } // this.bundle = bundle; // this.classLoader = classLoader; // } // // protected Class<?> findClass(String name) throws ClassNotFoundException { // return bundle.loadClass(name); // } // // protected URL findResource(String name) { // URL resource = bundle.getResource(name); // if (classLoader != null && resource == null) { // resource = classLoader.getResource(name); // } // return resource; // } // // @SuppressWarnings("unchecked") // protected Enumeration findResources(String name) throws IOException { // Enumeration resources = bundle.getResources(name); // if (classLoader != null && (resources == null || !resources.hasMoreElements())) { // resources = classLoader.getResources(name); // } // return resources; // } // // protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { // Class<?> clazz; // try { // clazz = findClass(name); // } catch (ClassNotFoundException cnfe) { // if (classLoader != null) { // try { // clazz = classLoader.loadClass(name); // } catch (ClassNotFoundException e) { // throw new ClassNotFoundException(String.format("[%s] from bundle [%s] (%s)", // name, bundle.getBundleId(), bundle.getSymbolicName())); // } // } else { // throw new ClassNotFoundException(String.format("[%s] from bundle [%s] (%s)", // name, bundle.getBundleId(), bundle.getSymbolicName())); // } // } // if (resolve) { // resolveClass(clazz); // } // return clazz; // } // // public Bundle getBundle() { // return bundle; // } // // @Override // public String toString() { // return String.format("BundleDelegatingClassLoader(%s)", bundle); // } // }
import org.apache.camel.CamelContext; import org.apache.camel.Component; import org.apache.camel.Processor; import org.apache.camel.osgi.service.util.BundleDelegatingClassLoader; import org.junit.Test; import org.osgi.framework.Bundle; import org.osgi.framework.BundleReference; import java.util.Collections; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service; public class OsgiDefaultEndpointTest { @Test public void testCreateClassLoaderHasGetBundle() throws Exception { Bundle bundle = mock(Bundle.class);
// Path: component/src/main/java/org/apache/camel/osgi/service/util/BundleDelegatingClassLoader.java // public class BundleDelegatingClassLoader extends ClassLoader { // private final Bundle bundle; // private final ClassLoader classLoader; // // public BundleDelegatingClassLoader(Bundle bundle) { // this(bundle, null); // } // // public BundleDelegatingClassLoader(Bundle bundle, ClassLoader classLoader) { // if (bundle == null) { // throw new IllegalArgumentException("bundle: null"); // } // this.bundle = bundle; // this.classLoader = classLoader; // } // // protected Class<?> findClass(String name) throws ClassNotFoundException { // return bundle.loadClass(name); // } // // protected URL findResource(String name) { // URL resource = bundle.getResource(name); // if (classLoader != null && resource == null) { // resource = classLoader.getResource(name); // } // return resource; // } // // @SuppressWarnings("unchecked") // protected Enumeration findResources(String name) throws IOException { // Enumeration resources = bundle.getResources(name); // if (classLoader != null && (resources == null || !resources.hasMoreElements())) { // resources = classLoader.getResources(name); // } // return resources; // } // // protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { // Class<?> clazz; // try { // clazz = findClass(name); // } catch (ClassNotFoundException cnfe) { // if (classLoader != null) { // try { // clazz = classLoader.loadClass(name); // } catch (ClassNotFoundException e) { // throw new ClassNotFoundException(String.format("[%s] from bundle [%s] (%s)", // name, bundle.getBundleId(), bundle.getSymbolicName())); // } // } else { // throw new ClassNotFoundException(String.format("[%s] from bundle [%s] (%s)", // name, bundle.getBundleId(), bundle.getSymbolicName())); // } // } // if (resolve) { // resolveClass(clazz); // } // return clazz; // } // // public Bundle getBundle() { // return bundle; // } // // @Override // public String toString() { // return String.format("BundleDelegatingClassLoader(%s)", bundle); // } // } // Path: component/src/test/java/org/apache/camel/osgi/service/OsgiDefaultEndpointTest.java import org.apache.camel.CamelContext; import org.apache.camel.Component; import org.apache.camel.Processor; import org.apache.camel.osgi.service.util.BundleDelegatingClassLoader; import org.junit.Test; import org.osgi.framework.Bundle; import org.osgi.framework.BundleReference; import java.util.Collections; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service; public class OsgiDefaultEndpointTest { @Test public void testCreateClassLoaderHasGetBundle() throws Exception { Bundle bundle = mock(Bundle.class);
ClassLoader classLoader = new BundleDelegatingClassLoader(bundle, getClass().getClassLoader());
szhem/camel-osgi
component/src/test/java/org/apache/camel/osgi/service/OsgiDefaultProducerTest.java
// Path: component/src/main/java/org/apache/camel/osgi/service/util/OsgiServiceList.java // public class OsgiServiceList<E> extends OsgiServiceCollection<E> implements List<E>, RandomAccess { // // public OsgiServiceList(BundleContext context, String filter, ClassLoader classLoader, // OsgiProxyCreator proxyCreator) { // // super(context, filter, classLoader, proxyCreator, new DynamicList<E>()); // } // // @Override // @SuppressWarnings("unchecked") // public E get(int index) { // return services.get(index); // } // // @Override // public int indexOf(Object o) { // return ((DynamicList<E>) services).indexOf(o); // } // // @Override // public int lastIndexOf(Object o) { // return ((DynamicList<E>) services).lastIndexOf(o); // } // // @Override // public ListIterator<E> listIterator() { // return listIterator(0); // } // // @Override // public ListIterator<E> listIterator(final int index) { // return new OsgiServiceListIterator(index); // } // // // TODO: implement me (sublist must be backed by this list) // @Override // public List<E> subList(int fromIndex, int toIndex) { // throw new UnsupportedOperationException(); // } // // // mutators are forbidden // // @Override // public E remove(int index) { // throw new UnsupportedOperationException(); // } // // @Override // public E set(int index, Object o) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(int index, Object o) { // throw new UnsupportedOperationException(); // } // // @Override // public boolean addAll(int index, Collection c) { // throw new UnsupportedOperationException(); // } // // protected class OsgiServiceListIterator implements ListIterator<E> { // private final ListIterator<E> iter; // // @SuppressWarnings("unchecked") // public OsgiServiceListIterator(int index) { // iter = services.iterator(index); // } // // @Override // public E next() { // return iter.next(); // } // // @Override // public E previous() { // return iter.previous(); // } // // @Override // public boolean hasNext() { // return iter.hasNext(); // } // // @Override // public boolean hasPrevious() { // return iter.hasPrevious(); // } // // @Override // public int nextIndex() { // return iter.nextIndex(); // } // // @Override // public int previousIndex() { // return iter.previousIndex(); // } // // // mutators are forbidden // // @Override // public void add(Object o) { // throw new UnsupportedOperationException(); // } // // @Override // public void remove() { // throw new UnsupportedOperationException(); // } // // @Override // public void set(Object o) { // throw new UnsupportedOperationException(); // } // // } // // }
import static org.mockito.Matchers.same; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.osgi.service.util.OsgiServiceList; import org.apache.camel.processor.loadbalancer.LoadBalancer; import org.apache.camel.util.ServiceHelper; import org.junit.Test; import org.mockito.Matchers; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceListener; import java.util.Collections; import java.util.Map; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.eq;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service; public class OsgiDefaultProducerTest { @Test public void testProcess() throws Exception { Processor processor = mock(Processor.class); OsgiDefaultProducer producer = createProducer(Collections.<String, Object>emptyMap()); producer.processor = processor; Exchange exchange = mock(Exchange.class); producer.process(exchange); verify(processor).process(same(exchange)); } @Test public void testCreateProcessor() throws Exception { OsgiDefaultProducer producer = createProducer(Collections.<String, Object>emptyMap()); Processor processor = producer.createProcessor(); assertThat(processor, instanceOf(OsgiDefaultLoadBalancer.class));
// Path: component/src/main/java/org/apache/camel/osgi/service/util/OsgiServiceList.java // public class OsgiServiceList<E> extends OsgiServiceCollection<E> implements List<E>, RandomAccess { // // public OsgiServiceList(BundleContext context, String filter, ClassLoader classLoader, // OsgiProxyCreator proxyCreator) { // // super(context, filter, classLoader, proxyCreator, new DynamicList<E>()); // } // // @Override // @SuppressWarnings("unchecked") // public E get(int index) { // return services.get(index); // } // // @Override // public int indexOf(Object o) { // return ((DynamicList<E>) services).indexOf(o); // } // // @Override // public int lastIndexOf(Object o) { // return ((DynamicList<E>) services).lastIndexOf(o); // } // // @Override // public ListIterator<E> listIterator() { // return listIterator(0); // } // // @Override // public ListIterator<E> listIterator(final int index) { // return new OsgiServiceListIterator(index); // } // // // TODO: implement me (sublist must be backed by this list) // @Override // public List<E> subList(int fromIndex, int toIndex) { // throw new UnsupportedOperationException(); // } // // // mutators are forbidden // // @Override // public E remove(int index) { // throw new UnsupportedOperationException(); // } // // @Override // public E set(int index, Object o) { // throw new UnsupportedOperationException(); // } // // @Override // public void add(int index, Object o) { // throw new UnsupportedOperationException(); // } // // @Override // public boolean addAll(int index, Collection c) { // throw new UnsupportedOperationException(); // } // // protected class OsgiServiceListIterator implements ListIterator<E> { // private final ListIterator<E> iter; // // @SuppressWarnings("unchecked") // public OsgiServiceListIterator(int index) { // iter = services.iterator(index); // } // // @Override // public E next() { // return iter.next(); // } // // @Override // public E previous() { // return iter.previous(); // } // // @Override // public boolean hasNext() { // return iter.hasNext(); // } // // @Override // public boolean hasPrevious() { // return iter.hasPrevious(); // } // // @Override // public int nextIndex() { // return iter.nextIndex(); // } // // @Override // public int previousIndex() { // return iter.previousIndex(); // } // // // mutators are forbidden // // @Override // public void add(Object o) { // throw new UnsupportedOperationException(); // } // // @Override // public void remove() { // throw new UnsupportedOperationException(); // } // // @Override // public void set(Object o) { // throw new UnsupportedOperationException(); // } // // } // // } // Path: component/src/test/java/org/apache/camel/osgi/service/OsgiDefaultProducerTest.java import static org.mockito.Matchers.same; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.osgi.service.util.OsgiServiceList; import org.apache.camel.processor.loadbalancer.LoadBalancer; import org.apache.camel.util.ServiceHelper; import org.junit.Test; import org.mockito.Matchers; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceListener; import java.util.Collections; import java.util.Map; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.eq; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service; public class OsgiDefaultProducerTest { @Test public void testProcess() throws Exception { Processor processor = mock(Processor.class); OsgiDefaultProducer producer = createProducer(Collections.<String, Object>emptyMap()); producer.processor = processor; Exchange exchange = mock(Exchange.class); producer.process(exchange); verify(processor).process(same(exchange)); } @Test public void testCreateProcessor() throws Exception { OsgiDefaultProducer producer = createProducer(Collections.<String, Object>emptyMap()); Processor processor = producer.createProcessor(); assertThat(processor, instanceOf(OsgiDefaultLoadBalancer.class));
assertThat(((LoadBalancer) processor).getProcessors(), instanceOf(OsgiServiceList.class));
szhem/camel-osgi
component/src/test/java/org/apache/camel/osgi/service/OsgiEndpointTypeTest.java
// Path: component/src/main/java/org/apache/camel/osgi/service/util/BundleDelegatingClassLoader.java // public class BundleDelegatingClassLoader extends ClassLoader { // private final Bundle bundle; // private final ClassLoader classLoader; // // public BundleDelegatingClassLoader(Bundle bundle) { // this(bundle, null); // } // // public BundleDelegatingClassLoader(Bundle bundle, ClassLoader classLoader) { // if (bundle == null) { // throw new IllegalArgumentException("bundle: null"); // } // this.bundle = bundle; // this.classLoader = classLoader; // } // // protected Class<?> findClass(String name) throws ClassNotFoundException { // return bundle.loadClass(name); // } // // protected URL findResource(String name) { // URL resource = bundle.getResource(name); // if (classLoader != null && resource == null) { // resource = classLoader.getResource(name); // } // return resource; // } // // @SuppressWarnings("unchecked") // protected Enumeration findResources(String name) throws IOException { // Enumeration resources = bundle.getResources(name); // if (classLoader != null && (resources == null || !resources.hasMoreElements())) { // resources = classLoader.getResources(name); // } // return resources; // } // // protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { // Class<?> clazz; // try { // clazz = findClass(name); // } catch (ClassNotFoundException cnfe) { // if (classLoader != null) { // try { // clazz = classLoader.loadClass(name); // } catch (ClassNotFoundException e) { // throw new ClassNotFoundException(String.format("[%s] from bundle [%s] (%s)", // name, bundle.getBundleId(), bundle.getSymbolicName())); // } // } else { // throw new ClassNotFoundException(String.format("[%s] from bundle [%s] (%s)", // name, bundle.getBundleId(), bundle.getSymbolicName())); // } // } // if (resolve) { // resolveClass(clazz); // } // return clazz; // } // // public Bundle getBundle() { // return bundle; // } // // @Override // public String toString() { // return String.format("BundleDelegatingClassLoader(%s)", bundle); // } // }
import org.apache.camel.CamelContext; import org.apache.camel.osgi.service.util.BundleDelegatingClassLoader; import org.junit.Test; import org.osgi.framework.Bundle; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service; public class OsgiEndpointTypeTest { @Test public void testGetType() throws Exception { OsgiEndpointType endpointType = OsgiEndpointType.fromPath(""); assertThat(endpointType, sameInstance(OsgiEndpointType.DEFAULT)); endpointType = OsgiEndpointType.fromPath("default:test"); assertThat(endpointType, sameInstance(OsgiEndpointType.DEFAULT)); endpointType = OsgiEndpointType.fromPath("unknown:test"); assertThat(endpointType, sameInstance(OsgiEndpointType.DEFAULT)); endpointType = OsgiEndpointType.fromPath("multicast:test"); assertThat(endpointType, sameInstance(OsgiEndpointType.MULTICAST)); endpointType = OsgiEndpointType.fromPath("roundrobin:test"); assertThat(endpointType, sameInstance(OsgiEndpointType.ROUNDROBIN)); endpointType = OsgiEndpointType.fromPath("random:test"); assertThat(endpointType, sameInstance(OsgiEndpointType.RANDOM)); } @Test public void testGetName() throws Exception { assertThat(OsgiEndpointType.DEFAULT.getName("test"), equalTo("test")); assertThat(OsgiEndpointType.DEFAULT.getName("default:test"), equalTo("test")); assertThat(OsgiEndpointType.MULTICAST.getName("multicast:test"), equalTo("test")); assertThat(OsgiEndpointType.ROUNDROBIN.getName("roundrobin:test"), equalTo("test")); assertThat(OsgiEndpointType.RANDOM.getName("random:test"), equalTo("test")); } @Test public void testCreateEndpoint() throws Exception { Bundle bundle = mock(Bundle.class);
// Path: component/src/main/java/org/apache/camel/osgi/service/util/BundleDelegatingClassLoader.java // public class BundleDelegatingClassLoader extends ClassLoader { // private final Bundle bundle; // private final ClassLoader classLoader; // // public BundleDelegatingClassLoader(Bundle bundle) { // this(bundle, null); // } // // public BundleDelegatingClassLoader(Bundle bundle, ClassLoader classLoader) { // if (bundle == null) { // throw new IllegalArgumentException("bundle: null"); // } // this.bundle = bundle; // this.classLoader = classLoader; // } // // protected Class<?> findClass(String name) throws ClassNotFoundException { // return bundle.loadClass(name); // } // // protected URL findResource(String name) { // URL resource = bundle.getResource(name); // if (classLoader != null && resource == null) { // resource = classLoader.getResource(name); // } // return resource; // } // // @SuppressWarnings("unchecked") // protected Enumeration findResources(String name) throws IOException { // Enumeration resources = bundle.getResources(name); // if (classLoader != null && (resources == null || !resources.hasMoreElements())) { // resources = classLoader.getResources(name); // } // return resources; // } // // protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { // Class<?> clazz; // try { // clazz = findClass(name); // } catch (ClassNotFoundException cnfe) { // if (classLoader != null) { // try { // clazz = classLoader.loadClass(name); // } catch (ClassNotFoundException e) { // throw new ClassNotFoundException(String.format("[%s] from bundle [%s] (%s)", // name, bundle.getBundleId(), bundle.getSymbolicName())); // } // } else { // throw new ClassNotFoundException(String.format("[%s] from bundle [%s] (%s)", // name, bundle.getBundleId(), bundle.getSymbolicName())); // } // } // if (resolve) { // resolveClass(clazz); // } // return clazz; // } // // public Bundle getBundle() { // return bundle; // } // // @Override // public String toString() { // return String.format("BundleDelegatingClassLoader(%s)", bundle); // } // } // Path: component/src/test/java/org/apache/camel/osgi/service/OsgiEndpointTypeTest.java import org.apache.camel.CamelContext; import org.apache.camel.osgi.service.util.BundleDelegatingClassLoader; import org.junit.Test; import org.osgi.framework.Bundle; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service; public class OsgiEndpointTypeTest { @Test public void testGetType() throws Exception { OsgiEndpointType endpointType = OsgiEndpointType.fromPath(""); assertThat(endpointType, sameInstance(OsgiEndpointType.DEFAULT)); endpointType = OsgiEndpointType.fromPath("default:test"); assertThat(endpointType, sameInstance(OsgiEndpointType.DEFAULT)); endpointType = OsgiEndpointType.fromPath("unknown:test"); assertThat(endpointType, sameInstance(OsgiEndpointType.DEFAULT)); endpointType = OsgiEndpointType.fromPath("multicast:test"); assertThat(endpointType, sameInstance(OsgiEndpointType.MULTICAST)); endpointType = OsgiEndpointType.fromPath("roundrobin:test"); assertThat(endpointType, sameInstance(OsgiEndpointType.ROUNDROBIN)); endpointType = OsgiEndpointType.fromPath("random:test"); assertThat(endpointType, sameInstance(OsgiEndpointType.RANDOM)); } @Test public void testGetName() throws Exception { assertThat(OsgiEndpointType.DEFAULT.getName("test"), equalTo("test")); assertThat(OsgiEndpointType.DEFAULT.getName("default:test"), equalTo("test")); assertThat(OsgiEndpointType.MULTICAST.getName("multicast:test"), equalTo("test")); assertThat(OsgiEndpointType.ROUNDROBIN.getName("roundrobin:test"), equalTo("test")); assertThat(OsgiEndpointType.RANDOM.getName("random:test"), equalTo("test")); } @Test public void testCreateEndpoint() throws Exception { Bundle bundle = mock(Bundle.class);
BundleDelegatingClassLoader classLoader = new BundleDelegatingClassLoader(bundle, getClass().getClassLoader());
szhem/camel-osgi
component/src/test/java/org/apache/camel/osgi/service/OsgiRandomEndpointTest.java
// Path: component/src/main/java/org/apache/camel/osgi/service/util/BundleDelegatingClassLoader.java // public class BundleDelegatingClassLoader extends ClassLoader { // private final Bundle bundle; // private final ClassLoader classLoader; // // public BundleDelegatingClassLoader(Bundle bundle) { // this(bundle, null); // } // // public BundleDelegatingClassLoader(Bundle bundle, ClassLoader classLoader) { // if (bundle == null) { // throw new IllegalArgumentException("bundle: null"); // } // this.bundle = bundle; // this.classLoader = classLoader; // } // // protected Class<?> findClass(String name) throws ClassNotFoundException { // return bundle.loadClass(name); // } // // protected URL findResource(String name) { // URL resource = bundle.getResource(name); // if (classLoader != null && resource == null) { // resource = classLoader.getResource(name); // } // return resource; // } // // @SuppressWarnings("unchecked") // protected Enumeration findResources(String name) throws IOException { // Enumeration resources = bundle.getResources(name); // if (classLoader != null && (resources == null || !resources.hasMoreElements())) { // resources = classLoader.getResources(name); // } // return resources; // } // // protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { // Class<?> clazz; // try { // clazz = findClass(name); // } catch (ClassNotFoundException cnfe) { // if (classLoader != null) { // try { // clazz = classLoader.loadClass(name); // } catch (ClassNotFoundException e) { // throw new ClassNotFoundException(String.format("[%s] from bundle [%s] (%s)", // name, bundle.getBundleId(), bundle.getSymbolicName())); // } // } else { // throw new ClassNotFoundException(String.format("[%s] from bundle [%s] (%s)", // name, bundle.getBundleId(), bundle.getSymbolicName())); // } // } // if (resolve) { // resolveClass(clazz); // } // return clazz; // } // // public Bundle getBundle() { // return bundle; // } // // @Override // public String toString() { // return String.format("BundleDelegatingClassLoader(%s)", bundle); // } // }
import org.apache.camel.CamelContext; import org.apache.camel.Component; import org.apache.camel.Processor; import org.apache.camel.osgi.service.util.BundleDelegatingClassLoader; import org.junit.Test; import org.osgi.framework.Bundle; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service; public class OsgiRandomEndpointTest { @Test(expected = UnsupportedOperationException.class) public void testCreateConsumer() throws Exception { OsgiRandomEndpoint endpoint = createEndpoint(); Processor processor = mock(Processor.class); endpoint.createConsumer(processor); } @Test public void testCreateProducer() throws Exception { OsgiRandomEndpoint endpoint = createEndpoint(); assertThat(endpoint.createProducer(), instanceOf(OsgiRandomProducer.class)); } private OsgiRandomEndpoint createEndpoint() throws Exception { Bundle bundle = mock(Bundle.class);
// Path: component/src/main/java/org/apache/camel/osgi/service/util/BundleDelegatingClassLoader.java // public class BundleDelegatingClassLoader extends ClassLoader { // private final Bundle bundle; // private final ClassLoader classLoader; // // public BundleDelegatingClassLoader(Bundle bundle) { // this(bundle, null); // } // // public BundleDelegatingClassLoader(Bundle bundle, ClassLoader classLoader) { // if (bundle == null) { // throw new IllegalArgumentException("bundle: null"); // } // this.bundle = bundle; // this.classLoader = classLoader; // } // // protected Class<?> findClass(String name) throws ClassNotFoundException { // return bundle.loadClass(name); // } // // protected URL findResource(String name) { // URL resource = bundle.getResource(name); // if (classLoader != null && resource == null) { // resource = classLoader.getResource(name); // } // return resource; // } // // @SuppressWarnings("unchecked") // protected Enumeration findResources(String name) throws IOException { // Enumeration resources = bundle.getResources(name); // if (classLoader != null && (resources == null || !resources.hasMoreElements())) { // resources = classLoader.getResources(name); // } // return resources; // } // // protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { // Class<?> clazz; // try { // clazz = findClass(name); // } catch (ClassNotFoundException cnfe) { // if (classLoader != null) { // try { // clazz = classLoader.loadClass(name); // } catch (ClassNotFoundException e) { // throw new ClassNotFoundException(String.format("[%s] from bundle [%s] (%s)", // name, bundle.getBundleId(), bundle.getSymbolicName())); // } // } else { // throw new ClassNotFoundException(String.format("[%s] from bundle [%s] (%s)", // name, bundle.getBundleId(), bundle.getSymbolicName())); // } // } // if (resolve) { // resolveClass(clazz); // } // return clazz; // } // // public Bundle getBundle() { // return bundle; // } // // @Override // public String toString() { // return String.format("BundleDelegatingClassLoader(%s)", bundle); // } // } // Path: component/src/test/java/org/apache/camel/osgi/service/OsgiRandomEndpointTest.java import org.apache.camel.CamelContext; import org.apache.camel.Component; import org.apache.camel.Processor; import org.apache.camel.osgi.service.util.BundleDelegatingClassLoader; import org.junit.Test; import org.osgi.framework.Bundle; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service; public class OsgiRandomEndpointTest { @Test(expected = UnsupportedOperationException.class) public void testCreateConsumer() throws Exception { OsgiRandomEndpoint endpoint = createEndpoint(); Processor processor = mock(Processor.class); endpoint.createConsumer(processor); } @Test public void testCreateProducer() throws Exception { OsgiRandomEndpoint endpoint = createEndpoint(); assertThat(endpoint.createProducer(), instanceOf(OsgiRandomProducer.class)); } private OsgiRandomEndpoint createEndpoint() throws Exception { Bundle bundle = mock(Bundle.class);
ClassLoader classLoader = new BundleDelegatingClassLoader(bundle, getClass().getClassLoader());
szhem/camel-osgi
component/src/test/java/org/apache/camel/osgi/service/filter/FiltersTest.java
// Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion allEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return and(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion and(Collection<? extends Criterion> f) { // return new AndCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion anyEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return or(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion approx(String attr, Object val) { // return new ApproxCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion eq(String attr, Object val) { // return new EqCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion le(String attr, Object val) { // return new LeCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion like(String attr, Object val, LikeCriterion.MatchMode mode) { // return new LikeCriterion(attr, val, mode); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion ne(String attr, Object val) { // return not(eq(attr, val)); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion not(Criterion f) { // return new NotCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion raw(String f) { // return new RawCriterion(f); // }
import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import org.junit.Test; import java.util.LinkedHashMap; import java.util.Map; import static org.apache.camel.osgi.service.filter.Filters.allEq; import static org.apache.camel.osgi.service.filter.Filters.and; import static org.apache.camel.osgi.service.filter.Filters.anyEq; import static org.apache.camel.osgi.service.filter.Filters.approx; import static org.apache.camel.osgi.service.filter.Filters.eq; import static org.apache.camel.osgi.service.filter.Filters.le; import static org.apache.camel.osgi.service.filter.Filters.like; import static org.apache.camel.osgi.service.filter.Filters.ne; import static org.apache.camel.osgi.service.filter.Filters.not; import static org.apache.camel.osgi.service.filter.Filters.raw; import static org.hamcrest.CoreMatchers.equalTo;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service.filter; public class FiltersTest { @Test public void testAllEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d");
// Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion allEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return and(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion and(Collection<? extends Criterion> f) { // return new AndCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion anyEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return or(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion approx(String attr, Object val) { // return new ApproxCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion eq(String attr, Object val) { // return new EqCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion le(String attr, Object val) { // return new LeCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion like(String attr, Object val, LikeCriterion.MatchMode mode) { // return new LikeCriterion(attr, val, mode); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion ne(String attr, Object val) { // return not(eq(attr, val)); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion not(Criterion f) { // return new NotCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion raw(String f) { // return new RawCriterion(f); // } // Path: component/src/test/java/org/apache/camel/osgi/service/filter/FiltersTest.java import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import org.junit.Test; import java.util.LinkedHashMap; import java.util.Map; import static org.apache.camel.osgi.service.filter.Filters.allEq; import static org.apache.camel.osgi.service.filter.Filters.and; import static org.apache.camel.osgi.service.filter.Filters.anyEq; import static org.apache.camel.osgi.service.filter.Filters.approx; import static org.apache.camel.osgi.service.filter.Filters.eq; import static org.apache.camel.osgi.service.filter.Filters.le; import static org.apache.camel.osgi.service.filter.Filters.like; import static org.apache.camel.osgi.service.filter.Filters.ne; import static org.apache.camel.osgi.service.filter.Filters.not; import static org.apache.camel.osgi.service.filter.Filters.raw; import static org.hamcrest.CoreMatchers.equalTo; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service.filter; public class FiltersTest { @Test public void testAllEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d");
Criterion criterion = allEq(attrs);
szhem/camel-osgi
component/src/test/java/org/apache/camel/osgi/service/filter/FiltersTest.java
// Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion allEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return and(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion and(Collection<? extends Criterion> f) { // return new AndCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion anyEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return or(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion approx(String attr, Object val) { // return new ApproxCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion eq(String attr, Object val) { // return new EqCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion le(String attr, Object val) { // return new LeCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion like(String attr, Object val, LikeCriterion.MatchMode mode) { // return new LikeCriterion(attr, val, mode); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion ne(String attr, Object val) { // return not(eq(attr, val)); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion not(Criterion f) { // return new NotCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion raw(String f) { // return new RawCriterion(f); // }
import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import org.junit.Test; import java.util.LinkedHashMap; import java.util.Map; import static org.apache.camel.osgi.service.filter.Filters.allEq; import static org.apache.camel.osgi.service.filter.Filters.and; import static org.apache.camel.osgi.service.filter.Filters.anyEq; import static org.apache.camel.osgi.service.filter.Filters.approx; import static org.apache.camel.osgi.service.filter.Filters.eq; import static org.apache.camel.osgi.service.filter.Filters.le; import static org.apache.camel.osgi.service.filter.Filters.like; import static org.apache.camel.osgi.service.filter.Filters.ne; import static org.apache.camel.osgi.service.filter.Filters.not; import static org.apache.camel.osgi.service.filter.Filters.raw; import static org.hamcrest.CoreMatchers.equalTo;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service.filter; public class FiltersTest { @Test public void testAllEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = allEq(attrs); assertThat(criterion.value(), equalTo("(&(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testAnyEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d");
// Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion allEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return and(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion and(Collection<? extends Criterion> f) { // return new AndCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion anyEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return or(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion approx(String attr, Object val) { // return new ApproxCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion eq(String attr, Object val) { // return new EqCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion le(String attr, Object val) { // return new LeCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion like(String attr, Object val, LikeCriterion.MatchMode mode) { // return new LikeCriterion(attr, val, mode); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion ne(String attr, Object val) { // return not(eq(attr, val)); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion not(Criterion f) { // return new NotCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion raw(String f) { // return new RawCriterion(f); // } // Path: component/src/test/java/org/apache/camel/osgi/service/filter/FiltersTest.java import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import org.junit.Test; import java.util.LinkedHashMap; import java.util.Map; import static org.apache.camel.osgi.service.filter.Filters.allEq; import static org.apache.camel.osgi.service.filter.Filters.and; import static org.apache.camel.osgi.service.filter.Filters.anyEq; import static org.apache.camel.osgi.service.filter.Filters.approx; import static org.apache.camel.osgi.service.filter.Filters.eq; import static org.apache.camel.osgi.service.filter.Filters.le; import static org.apache.camel.osgi.service.filter.Filters.like; import static org.apache.camel.osgi.service.filter.Filters.ne; import static org.apache.camel.osgi.service.filter.Filters.not; import static org.apache.camel.osgi.service.filter.Filters.raw; import static org.hamcrest.CoreMatchers.equalTo; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service.filter; public class FiltersTest { @Test public void testAllEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = allEq(attrs); assertThat(criterion.value(), equalTo("(&(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testAnyEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d");
Criterion criterion = anyEq(attrs);
szhem/camel-osgi
component/src/test/java/org/apache/camel/osgi/service/filter/FiltersTest.java
// Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion allEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return and(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion and(Collection<? extends Criterion> f) { // return new AndCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion anyEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return or(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion approx(String attr, Object val) { // return new ApproxCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion eq(String attr, Object val) { // return new EqCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion le(String attr, Object val) { // return new LeCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion like(String attr, Object val, LikeCriterion.MatchMode mode) { // return new LikeCriterion(attr, val, mode); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion ne(String attr, Object val) { // return not(eq(attr, val)); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion not(Criterion f) { // return new NotCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion raw(String f) { // return new RawCriterion(f); // }
import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import org.junit.Test; import java.util.LinkedHashMap; import java.util.Map; import static org.apache.camel.osgi.service.filter.Filters.allEq; import static org.apache.camel.osgi.service.filter.Filters.and; import static org.apache.camel.osgi.service.filter.Filters.anyEq; import static org.apache.camel.osgi.service.filter.Filters.approx; import static org.apache.camel.osgi.service.filter.Filters.eq; import static org.apache.camel.osgi.service.filter.Filters.le; import static org.apache.camel.osgi.service.filter.Filters.like; import static org.apache.camel.osgi.service.filter.Filters.ne; import static org.apache.camel.osgi.service.filter.Filters.not; import static org.apache.camel.osgi.service.filter.Filters.raw; import static org.hamcrest.CoreMatchers.equalTo;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service.filter; public class FiltersTest { @Test public void testAllEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = allEq(attrs); assertThat(criterion.value(), equalTo("(&(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testAnyEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = anyEq(attrs); assertThat(criterion.value(), equalTo("(|(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testComplex() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d");
// Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion allEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return and(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion and(Collection<? extends Criterion> f) { // return new AndCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion anyEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return or(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion approx(String attr, Object val) { // return new ApproxCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion eq(String attr, Object val) { // return new EqCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion le(String attr, Object val) { // return new LeCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion like(String attr, Object val, LikeCriterion.MatchMode mode) { // return new LikeCriterion(attr, val, mode); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion ne(String attr, Object val) { // return not(eq(attr, val)); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion not(Criterion f) { // return new NotCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion raw(String f) { // return new RawCriterion(f); // } // Path: component/src/test/java/org/apache/camel/osgi/service/filter/FiltersTest.java import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import org.junit.Test; import java.util.LinkedHashMap; import java.util.Map; import static org.apache.camel.osgi.service.filter.Filters.allEq; import static org.apache.camel.osgi.service.filter.Filters.and; import static org.apache.camel.osgi.service.filter.Filters.anyEq; import static org.apache.camel.osgi.service.filter.Filters.approx; import static org.apache.camel.osgi.service.filter.Filters.eq; import static org.apache.camel.osgi.service.filter.Filters.le; import static org.apache.camel.osgi.service.filter.Filters.like; import static org.apache.camel.osgi.service.filter.Filters.ne; import static org.apache.camel.osgi.service.filter.Filters.not; import static org.apache.camel.osgi.service.filter.Filters.raw; import static org.hamcrest.CoreMatchers.equalTo; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service.filter; public class FiltersTest { @Test public void testAllEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = allEq(attrs); assertThat(criterion.value(), equalTo("(&(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testAnyEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = anyEq(attrs); assertThat(criterion.value(), equalTo("(|(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testComplex() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d");
Criterion criterion = and(
szhem/camel-osgi
component/src/test/java/org/apache/camel/osgi/service/filter/FiltersTest.java
// Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion allEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return and(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion and(Collection<? extends Criterion> f) { // return new AndCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion anyEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return or(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion approx(String attr, Object val) { // return new ApproxCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion eq(String attr, Object val) { // return new EqCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion le(String attr, Object val) { // return new LeCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion like(String attr, Object val, LikeCriterion.MatchMode mode) { // return new LikeCriterion(attr, val, mode); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion ne(String attr, Object val) { // return not(eq(attr, val)); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion not(Criterion f) { // return new NotCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion raw(String f) { // return new RawCriterion(f); // }
import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import org.junit.Test; import java.util.LinkedHashMap; import java.util.Map; import static org.apache.camel.osgi.service.filter.Filters.allEq; import static org.apache.camel.osgi.service.filter.Filters.and; import static org.apache.camel.osgi.service.filter.Filters.anyEq; import static org.apache.camel.osgi.service.filter.Filters.approx; import static org.apache.camel.osgi.service.filter.Filters.eq; import static org.apache.camel.osgi.service.filter.Filters.le; import static org.apache.camel.osgi.service.filter.Filters.like; import static org.apache.camel.osgi.service.filter.Filters.ne; import static org.apache.camel.osgi.service.filter.Filters.not; import static org.apache.camel.osgi.service.filter.Filters.raw; import static org.hamcrest.CoreMatchers.equalTo;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service.filter; public class FiltersTest { @Test public void testAllEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = allEq(attrs); assertThat(criterion.value(), equalTo("(&(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testAnyEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = anyEq(attrs); assertThat(criterion.value(), equalTo("(|(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testComplex() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = and(
// Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion allEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return and(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion and(Collection<? extends Criterion> f) { // return new AndCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion anyEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return or(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion approx(String attr, Object val) { // return new ApproxCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion eq(String attr, Object val) { // return new EqCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion le(String attr, Object val) { // return new LeCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion like(String attr, Object val, LikeCriterion.MatchMode mode) { // return new LikeCriterion(attr, val, mode); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion ne(String attr, Object val) { // return not(eq(attr, val)); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion not(Criterion f) { // return new NotCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion raw(String f) { // return new RawCriterion(f); // } // Path: component/src/test/java/org/apache/camel/osgi/service/filter/FiltersTest.java import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import org.junit.Test; import java.util.LinkedHashMap; import java.util.Map; import static org.apache.camel.osgi.service.filter.Filters.allEq; import static org.apache.camel.osgi.service.filter.Filters.and; import static org.apache.camel.osgi.service.filter.Filters.anyEq; import static org.apache.camel.osgi.service.filter.Filters.approx; import static org.apache.camel.osgi.service.filter.Filters.eq; import static org.apache.camel.osgi.service.filter.Filters.le; import static org.apache.camel.osgi.service.filter.Filters.like; import static org.apache.camel.osgi.service.filter.Filters.ne; import static org.apache.camel.osgi.service.filter.Filters.not; import static org.apache.camel.osgi.service.filter.Filters.raw; import static org.hamcrest.CoreMatchers.equalTo; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service.filter; public class FiltersTest { @Test public void testAllEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = allEq(attrs); assertThat(criterion.value(), equalTo("(&(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testAnyEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = anyEq(attrs); assertThat(criterion.value(), equalTo("(|(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testComplex() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = and(
eq("a", "b"),
szhem/camel-osgi
component/src/test/java/org/apache/camel/osgi/service/filter/FiltersTest.java
// Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion allEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return and(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion and(Collection<? extends Criterion> f) { // return new AndCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion anyEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return or(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion approx(String attr, Object val) { // return new ApproxCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion eq(String attr, Object val) { // return new EqCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion le(String attr, Object val) { // return new LeCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion like(String attr, Object val, LikeCriterion.MatchMode mode) { // return new LikeCriterion(attr, val, mode); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion ne(String attr, Object val) { // return not(eq(attr, val)); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion not(Criterion f) { // return new NotCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion raw(String f) { // return new RawCriterion(f); // }
import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import org.junit.Test; import java.util.LinkedHashMap; import java.util.Map; import static org.apache.camel.osgi.service.filter.Filters.allEq; import static org.apache.camel.osgi.service.filter.Filters.and; import static org.apache.camel.osgi.service.filter.Filters.anyEq; import static org.apache.camel.osgi.service.filter.Filters.approx; import static org.apache.camel.osgi.service.filter.Filters.eq; import static org.apache.camel.osgi.service.filter.Filters.le; import static org.apache.camel.osgi.service.filter.Filters.like; import static org.apache.camel.osgi.service.filter.Filters.ne; import static org.apache.camel.osgi.service.filter.Filters.not; import static org.apache.camel.osgi.service.filter.Filters.raw; import static org.hamcrest.CoreMatchers.equalTo;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service.filter; public class FiltersTest { @Test public void testAllEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = allEq(attrs); assertThat(criterion.value(), equalTo("(&(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testAnyEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = anyEq(attrs); assertThat(criterion.value(), equalTo("(|(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testComplex() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = and( eq("a", "b"),
// Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion allEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return and(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion and(Collection<? extends Criterion> f) { // return new AndCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion anyEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return or(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion approx(String attr, Object val) { // return new ApproxCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion eq(String attr, Object val) { // return new EqCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion le(String attr, Object val) { // return new LeCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion like(String attr, Object val, LikeCriterion.MatchMode mode) { // return new LikeCriterion(attr, val, mode); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion ne(String attr, Object val) { // return not(eq(attr, val)); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion not(Criterion f) { // return new NotCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion raw(String f) { // return new RawCriterion(f); // } // Path: component/src/test/java/org/apache/camel/osgi/service/filter/FiltersTest.java import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import org.junit.Test; import java.util.LinkedHashMap; import java.util.Map; import static org.apache.camel.osgi.service.filter.Filters.allEq; import static org.apache.camel.osgi.service.filter.Filters.and; import static org.apache.camel.osgi.service.filter.Filters.anyEq; import static org.apache.camel.osgi.service.filter.Filters.approx; import static org.apache.camel.osgi.service.filter.Filters.eq; import static org.apache.camel.osgi.service.filter.Filters.le; import static org.apache.camel.osgi.service.filter.Filters.like; import static org.apache.camel.osgi.service.filter.Filters.ne; import static org.apache.camel.osgi.service.filter.Filters.not; import static org.apache.camel.osgi.service.filter.Filters.raw; import static org.hamcrest.CoreMatchers.equalTo; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service.filter; public class FiltersTest { @Test public void testAllEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = allEq(attrs); assertThat(criterion.value(), equalTo("(&(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testAnyEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = anyEq(attrs); assertThat(criterion.value(), equalTo("(|(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testComplex() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = and( eq("a", "b"),
ne("b", "d"),
szhem/camel-osgi
component/src/test/java/org/apache/camel/osgi/service/filter/FiltersTest.java
// Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion allEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return and(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion and(Collection<? extends Criterion> f) { // return new AndCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion anyEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return or(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion approx(String attr, Object val) { // return new ApproxCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion eq(String attr, Object val) { // return new EqCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion le(String attr, Object val) { // return new LeCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion like(String attr, Object val, LikeCriterion.MatchMode mode) { // return new LikeCriterion(attr, val, mode); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion ne(String attr, Object val) { // return not(eq(attr, val)); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion not(Criterion f) { // return new NotCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion raw(String f) { // return new RawCriterion(f); // }
import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import org.junit.Test; import java.util.LinkedHashMap; import java.util.Map; import static org.apache.camel.osgi.service.filter.Filters.allEq; import static org.apache.camel.osgi.service.filter.Filters.and; import static org.apache.camel.osgi.service.filter.Filters.anyEq; import static org.apache.camel.osgi.service.filter.Filters.approx; import static org.apache.camel.osgi.service.filter.Filters.eq; import static org.apache.camel.osgi.service.filter.Filters.le; import static org.apache.camel.osgi.service.filter.Filters.like; import static org.apache.camel.osgi.service.filter.Filters.ne; import static org.apache.camel.osgi.service.filter.Filters.not; import static org.apache.camel.osgi.service.filter.Filters.raw; import static org.hamcrest.CoreMatchers.equalTo;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service.filter; public class FiltersTest { @Test public void testAllEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = allEq(attrs); assertThat(criterion.value(), equalTo("(&(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testAnyEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = anyEq(attrs); assertThat(criterion.value(), equalTo("(|(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testComplex() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = and( eq("a", "b"), ne("b", "d"),
// Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion allEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return and(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion and(Collection<? extends Criterion> f) { // return new AndCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion anyEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return or(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion approx(String attr, Object val) { // return new ApproxCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion eq(String attr, Object val) { // return new EqCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion le(String attr, Object val) { // return new LeCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion like(String attr, Object val, LikeCriterion.MatchMode mode) { // return new LikeCriterion(attr, val, mode); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion ne(String attr, Object val) { // return not(eq(attr, val)); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion not(Criterion f) { // return new NotCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion raw(String f) { // return new RawCriterion(f); // } // Path: component/src/test/java/org/apache/camel/osgi/service/filter/FiltersTest.java import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import org.junit.Test; import java.util.LinkedHashMap; import java.util.Map; import static org.apache.camel.osgi.service.filter.Filters.allEq; import static org.apache.camel.osgi.service.filter.Filters.and; import static org.apache.camel.osgi.service.filter.Filters.anyEq; import static org.apache.camel.osgi.service.filter.Filters.approx; import static org.apache.camel.osgi.service.filter.Filters.eq; import static org.apache.camel.osgi.service.filter.Filters.le; import static org.apache.camel.osgi.service.filter.Filters.like; import static org.apache.camel.osgi.service.filter.Filters.ne; import static org.apache.camel.osgi.service.filter.Filters.not; import static org.apache.camel.osgi.service.filter.Filters.raw; import static org.hamcrest.CoreMatchers.equalTo; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service.filter; public class FiltersTest { @Test public void testAllEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = allEq(attrs); assertThat(criterion.value(), equalTo("(&(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testAnyEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = anyEq(attrs); assertThat(criterion.value(), equalTo("(|(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testComplex() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = and( eq("a", "b"), ne("b", "d"),
approx("g", "s"),
szhem/camel-osgi
component/src/test/java/org/apache/camel/osgi/service/filter/FiltersTest.java
// Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion allEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return and(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion and(Collection<? extends Criterion> f) { // return new AndCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion anyEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return or(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion approx(String attr, Object val) { // return new ApproxCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion eq(String attr, Object val) { // return new EqCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion le(String attr, Object val) { // return new LeCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion like(String attr, Object val, LikeCriterion.MatchMode mode) { // return new LikeCriterion(attr, val, mode); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion ne(String attr, Object val) { // return not(eq(attr, val)); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion not(Criterion f) { // return new NotCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion raw(String f) { // return new RawCriterion(f); // }
import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import org.junit.Test; import java.util.LinkedHashMap; import java.util.Map; import static org.apache.camel.osgi.service.filter.Filters.allEq; import static org.apache.camel.osgi.service.filter.Filters.and; import static org.apache.camel.osgi.service.filter.Filters.anyEq; import static org.apache.camel.osgi.service.filter.Filters.approx; import static org.apache.camel.osgi.service.filter.Filters.eq; import static org.apache.camel.osgi.service.filter.Filters.le; import static org.apache.camel.osgi.service.filter.Filters.like; import static org.apache.camel.osgi.service.filter.Filters.ne; import static org.apache.camel.osgi.service.filter.Filters.not; import static org.apache.camel.osgi.service.filter.Filters.raw; import static org.hamcrest.CoreMatchers.equalTo;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service.filter; public class FiltersTest { @Test public void testAllEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = allEq(attrs); assertThat(criterion.value(), equalTo("(&(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testAnyEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = anyEq(attrs); assertThat(criterion.value(), equalTo("(|(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testComplex() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = and( eq("a", "b"), ne("b", "d"), approx("g", "s"),
// Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion allEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return and(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion and(Collection<? extends Criterion> f) { // return new AndCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion anyEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return or(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion approx(String attr, Object val) { // return new ApproxCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion eq(String attr, Object val) { // return new EqCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion le(String attr, Object val) { // return new LeCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion like(String attr, Object val, LikeCriterion.MatchMode mode) { // return new LikeCriterion(attr, val, mode); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion ne(String attr, Object val) { // return not(eq(attr, val)); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion not(Criterion f) { // return new NotCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion raw(String f) { // return new RawCriterion(f); // } // Path: component/src/test/java/org/apache/camel/osgi/service/filter/FiltersTest.java import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import org.junit.Test; import java.util.LinkedHashMap; import java.util.Map; import static org.apache.camel.osgi.service.filter.Filters.allEq; import static org.apache.camel.osgi.service.filter.Filters.and; import static org.apache.camel.osgi.service.filter.Filters.anyEq; import static org.apache.camel.osgi.service.filter.Filters.approx; import static org.apache.camel.osgi.service.filter.Filters.eq; import static org.apache.camel.osgi.service.filter.Filters.le; import static org.apache.camel.osgi.service.filter.Filters.like; import static org.apache.camel.osgi.service.filter.Filters.ne; import static org.apache.camel.osgi.service.filter.Filters.not; import static org.apache.camel.osgi.service.filter.Filters.raw; import static org.hamcrest.CoreMatchers.equalTo; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service.filter; public class FiltersTest { @Test public void testAllEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = allEq(attrs); assertThat(criterion.value(), equalTo("(&(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testAnyEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = anyEq(attrs); assertThat(criterion.value(), equalTo("(|(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testComplex() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = and( eq("a", "b"), ne("b", "d"), approx("g", "s"),
le("y", "z"),
szhem/camel-osgi
component/src/test/java/org/apache/camel/osgi/service/filter/FiltersTest.java
// Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion allEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return and(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion and(Collection<? extends Criterion> f) { // return new AndCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion anyEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return or(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion approx(String attr, Object val) { // return new ApproxCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion eq(String attr, Object val) { // return new EqCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion le(String attr, Object val) { // return new LeCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion like(String attr, Object val, LikeCriterion.MatchMode mode) { // return new LikeCriterion(attr, val, mode); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion ne(String attr, Object val) { // return not(eq(attr, val)); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion not(Criterion f) { // return new NotCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion raw(String f) { // return new RawCriterion(f); // }
import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import org.junit.Test; import java.util.LinkedHashMap; import java.util.Map; import static org.apache.camel.osgi.service.filter.Filters.allEq; import static org.apache.camel.osgi.service.filter.Filters.and; import static org.apache.camel.osgi.service.filter.Filters.anyEq; import static org.apache.camel.osgi.service.filter.Filters.approx; import static org.apache.camel.osgi.service.filter.Filters.eq; import static org.apache.camel.osgi.service.filter.Filters.le; import static org.apache.camel.osgi.service.filter.Filters.like; import static org.apache.camel.osgi.service.filter.Filters.ne; import static org.apache.camel.osgi.service.filter.Filters.not; import static org.apache.camel.osgi.service.filter.Filters.raw; import static org.hamcrest.CoreMatchers.equalTo;
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service.filter; public class FiltersTest { @Test public void testAllEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = allEq(attrs); assertThat(criterion.value(), equalTo("(&(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testAnyEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = anyEq(attrs); assertThat(criterion.value(), equalTo("(|(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testComplex() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = and( eq("a", "b"), ne("b", "d"), approx("g", "s"), le("y", "z"),
// Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion allEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return and(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion and(Collection<? extends Criterion> f) { // return new AndCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion anyEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return or(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion approx(String attr, Object val) { // return new ApproxCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion eq(String attr, Object val) { // return new EqCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion le(String attr, Object val) { // return new LeCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion like(String attr, Object val, LikeCriterion.MatchMode mode) { // return new LikeCriterion(attr, val, mode); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion ne(String attr, Object val) { // return not(eq(attr, val)); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion not(Criterion f) { // return new NotCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion raw(String f) { // return new RawCriterion(f); // } // Path: component/src/test/java/org/apache/camel/osgi/service/filter/FiltersTest.java import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import org.junit.Test; import java.util.LinkedHashMap; import java.util.Map; import static org.apache.camel.osgi.service.filter.Filters.allEq; import static org.apache.camel.osgi.service.filter.Filters.and; import static org.apache.camel.osgi.service.filter.Filters.anyEq; import static org.apache.camel.osgi.service.filter.Filters.approx; import static org.apache.camel.osgi.service.filter.Filters.eq; import static org.apache.camel.osgi.service.filter.Filters.le; import static org.apache.camel.osgi.service.filter.Filters.like; import static org.apache.camel.osgi.service.filter.Filters.ne; import static org.apache.camel.osgi.service.filter.Filters.not; import static org.apache.camel.osgi.service.filter.Filters.raw; import static org.hamcrest.CoreMatchers.equalTo; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.osgi.service.filter; public class FiltersTest { @Test public void testAllEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = allEq(attrs); assertThat(criterion.value(), equalTo("(&(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testAnyEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = anyEq(attrs); assertThat(criterion.value(), equalTo("(|(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testComplex() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = and( eq("a", "b"), ne("b", "d"), approx("g", "s"), le("y", "z"),
raw("(&(g=n)(f=n))"),
szhem/camel-osgi
component/src/test/java/org/apache/camel/osgi/service/filter/FiltersTest.java
// Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion allEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return and(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion and(Collection<? extends Criterion> f) { // return new AndCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion anyEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return or(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion approx(String attr, Object val) { // return new ApproxCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion eq(String attr, Object val) { // return new EqCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion le(String attr, Object val) { // return new LeCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion like(String attr, Object val, LikeCriterion.MatchMode mode) { // return new LikeCriterion(attr, val, mode); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion ne(String attr, Object val) { // return not(eq(attr, val)); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion not(Criterion f) { // return new NotCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion raw(String f) { // return new RawCriterion(f); // }
import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import org.junit.Test; import java.util.LinkedHashMap; import java.util.Map; import static org.apache.camel.osgi.service.filter.Filters.allEq; import static org.apache.camel.osgi.service.filter.Filters.and; import static org.apache.camel.osgi.service.filter.Filters.anyEq; import static org.apache.camel.osgi.service.filter.Filters.approx; import static org.apache.camel.osgi.service.filter.Filters.eq; import static org.apache.camel.osgi.service.filter.Filters.le; import static org.apache.camel.osgi.service.filter.Filters.like; import static org.apache.camel.osgi.service.filter.Filters.ne; import static org.apache.camel.osgi.service.filter.Filters.not; import static org.apache.camel.osgi.service.filter.Filters.raw; import static org.hamcrest.CoreMatchers.equalTo;
attrs.put("c", "d"); Criterion criterion = allEq(attrs); assertThat(criterion.value(), equalTo("(&(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testAnyEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = anyEq(attrs); assertThat(criterion.value(), equalTo("(|(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testComplex() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = and( eq("a", "b"), ne("b", "d"), approx("g", "s"), le("y", "z"), raw("(&(g=n)(f=n))"),
// Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion allEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return and(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion and(Collection<? extends Criterion> f) { // return new AndCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion anyEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return or(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion approx(String attr, Object val) { // return new ApproxCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion eq(String attr, Object val) { // return new EqCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion le(String attr, Object val) { // return new LeCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion like(String attr, Object val, LikeCriterion.MatchMode mode) { // return new LikeCriterion(attr, val, mode); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion ne(String attr, Object val) { // return not(eq(attr, val)); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion not(Criterion f) { // return new NotCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion raw(String f) { // return new RawCriterion(f); // } // Path: component/src/test/java/org/apache/camel/osgi/service/filter/FiltersTest.java import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import org.junit.Test; import java.util.LinkedHashMap; import java.util.Map; import static org.apache.camel.osgi.service.filter.Filters.allEq; import static org.apache.camel.osgi.service.filter.Filters.and; import static org.apache.camel.osgi.service.filter.Filters.anyEq; import static org.apache.camel.osgi.service.filter.Filters.approx; import static org.apache.camel.osgi.service.filter.Filters.eq; import static org.apache.camel.osgi.service.filter.Filters.le; import static org.apache.camel.osgi.service.filter.Filters.like; import static org.apache.camel.osgi.service.filter.Filters.ne; import static org.apache.camel.osgi.service.filter.Filters.not; import static org.apache.camel.osgi.service.filter.Filters.raw; import static org.hamcrest.CoreMatchers.equalTo; attrs.put("c", "d"); Criterion criterion = allEq(attrs); assertThat(criterion.value(), equalTo("(&(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testAnyEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = anyEq(attrs); assertThat(criterion.value(), equalTo("(|(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testComplex() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = and( eq("a", "b"), ne("b", "d"), approx("g", "s"), le("y", "z"), raw("(&(g=n)(f=n))"),
like("f", "g", LikeCriterion.MatchMode.ANYWHERE),
szhem/camel-osgi
component/src/test/java/org/apache/camel/osgi/service/filter/FiltersTest.java
// Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion allEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return and(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion and(Collection<? extends Criterion> f) { // return new AndCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion anyEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return or(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion approx(String attr, Object val) { // return new ApproxCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion eq(String attr, Object val) { // return new EqCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion le(String attr, Object val) { // return new LeCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion like(String attr, Object val, LikeCriterion.MatchMode mode) { // return new LikeCriterion(attr, val, mode); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion ne(String attr, Object val) { // return not(eq(attr, val)); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion not(Criterion f) { // return new NotCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion raw(String f) { // return new RawCriterion(f); // }
import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import org.junit.Test; import java.util.LinkedHashMap; import java.util.Map; import static org.apache.camel.osgi.service.filter.Filters.allEq; import static org.apache.camel.osgi.service.filter.Filters.and; import static org.apache.camel.osgi.service.filter.Filters.anyEq; import static org.apache.camel.osgi.service.filter.Filters.approx; import static org.apache.camel.osgi.service.filter.Filters.eq; import static org.apache.camel.osgi.service.filter.Filters.le; import static org.apache.camel.osgi.service.filter.Filters.like; import static org.apache.camel.osgi.service.filter.Filters.ne; import static org.apache.camel.osgi.service.filter.Filters.not; import static org.apache.camel.osgi.service.filter.Filters.raw; import static org.hamcrest.CoreMatchers.equalTo;
Criterion criterion = allEq(attrs); assertThat(criterion.value(), equalTo("(&(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testAnyEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = anyEq(attrs); assertThat(criterion.value(), equalTo("(|(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testComplex() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = and( eq("a", "b"), ne("b", "d"), approx("g", "s"), le("y", "z"), raw("(&(g=n)(f=n))"), like("f", "g", LikeCriterion.MatchMode.ANYWHERE),
// Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion allEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return and(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion and(Collection<? extends Criterion> f) { // return new AndCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion anyEq(Map<String, ?> vals) { // List<Criterion> filters = new ArrayList<Criterion>(vals.size()); // for(Entry<String, ?> entry : vals.entrySet()) { // filters.add(eq(entry.getKey(), entry.getValue())); // } // return or(filters); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion approx(String attr, Object val) { // return new ApproxCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion eq(String attr, Object val) { // return new EqCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion le(String attr, Object val) { // return new LeCriterion(attr, val); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion like(String attr, Object val, LikeCriterion.MatchMode mode) { // return new LikeCriterion(attr, val, mode); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion ne(String attr, Object val) { // return not(eq(attr, val)); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion not(Criterion f) { // return new NotCriterion(f); // } // // Path: component/src/main/java/org/apache/camel/osgi/service/filter/Filters.java // public static Criterion raw(String f) { // return new RawCriterion(f); // } // Path: component/src/test/java/org/apache/camel/osgi/service/filter/FiltersTest.java import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import org.junit.Test; import java.util.LinkedHashMap; import java.util.Map; import static org.apache.camel.osgi.service.filter.Filters.allEq; import static org.apache.camel.osgi.service.filter.Filters.and; import static org.apache.camel.osgi.service.filter.Filters.anyEq; import static org.apache.camel.osgi.service.filter.Filters.approx; import static org.apache.camel.osgi.service.filter.Filters.eq; import static org.apache.camel.osgi.service.filter.Filters.le; import static org.apache.camel.osgi.service.filter.Filters.like; import static org.apache.camel.osgi.service.filter.Filters.ne; import static org.apache.camel.osgi.service.filter.Filters.not; import static org.apache.camel.osgi.service.filter.Filters.raw; import static org.hamcrest.CoreMatchers.equalTo; Criterion criterion = allEq(attrs); assertThat(criterion.value(), equalTo("(&(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testAnyEq() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = anyEq(attrs); assertThat(criterion.value(), equalTo("(|(a=b)(c=d))")); assertThat(criterion.filter(), notNullValue()); } @Test public void testComplex() throws Exception { Map<String, String> attrs = new LinkedHashMap<String, String>(); attrs.put("a", "b"); attrs.put("c", "d"); Criterion criterion = and( eq("a", "b"), ne("b", "d"), approx("g", "s"), le("y", "z"), raw("(&(g=n)(f=n))"), like("f", "g", LikeCriterion.MatchMode.ANYWHERE),
not(anyEq(attrs))
akexorcist/Example-SamsungSDK
KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/DoSomethingActivity.java
// Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/BusProvider.java // public class BusProvider { // private static Bus bus; // // public static Bus getProvider() { // if (bus == null) { // bus = new Bus(); // } // return bus; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/InsideGeofenceEvent.java // public class InsideGeofenceEvent { // int[] geofenceIdList; // // public InsideGeofenceEvent() { // } // // public InsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/LocationUnavailableEvent.java // public class LocationUnavailableEvent { // // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/OutsideGeofenceEvent.java // public class OutsideGeofenceEvent { // int[] geofenceIdList; // // public OutsideGeofenceEvent() { // } // // public OutsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // }
import android.app.enterprise.geofencing.CircularGeofence; import android.app.enterprise.geofencing.Geofence; import android.app.enterprise.geofencing.Geofencing; import android.app.enterprise.geofencing.LatLongPoint; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.akexorcist.knoxgeofencingapp.bus.BusProvider; import com.akexorcist.knoxgeofencingapp.bus.event.InsideGeofenceEvent; import com.akexorcist.knoxgeofencingapp.bus.event.LocationUnavailableEvent; import com.akexorcist.knoxgeofencingapp.bus.event.OutsideGeofenceEvent; import com.squareup.otto.Subscribe; import java.util.List;
package com.akexorcist.knoxgeofencingapp; public class DoSomethingActivity extends AppCompatActivity implements View.OnClickListener { private Button btnGeofencingStart; private Button btnGeofencingStop; private Button btnCreateGeofence; private Button btnClearGeofence; private Geofencing geofencingService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_do_something); bindView(); setupView(); setupThing(); } @Override protected void onDestroy() { super.onDestroy();
// Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/BusProvider.java // public class BusProvider { // private static Bus bus; // // public static Bus getProvider() { // if (bus == null) { // bus = new Bus(); // } // return bus; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/InsideGeofenceEvent.java // public class InsideGeofenceEvent { // int[] geofenceIdList; // // public InsideGeofenceEvent() { // } // // public InsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/LocationUnavailableEvent.java // public class LocationUnavailableEvent { // // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/OutsideGeofenceEvent.java // public class OutsideGeofenceEvent { // int[] geofenceIdList; // // public OutsideGeofenceEvent() { // } // // public OutsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // } // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/DoSomethingActivity.java import android.app.enterprise.geofencing.CircularGeofence; import android.app.enterprise.geofencing.Geofence; import android.app.enterprise.geofencing.Geofencing; import android.app.enterprise.geofencing.LatLongPoint; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.akexorcist.knoxgeofencingapp.bus.BusProvider; import com.akexorcist.knoxgeofencingapp.bus.event.InsideGeofenceEvent; import com.akexorcist.knoxgeofencingapp.bus.event.LocationUnavailableEvent; import com.akexorcist.knoxgeofencingapp.bus.event.OutsideGeofenceEvent; import com.squareup.otto.Subscribe; import java.util.List; package com.akexorcist.knoxgeofencingapp; public class DoSomethingActivity extends AppCompatActivity implements View.OnClickListener { private Button btnGeofencingStart; private Button btnGeofencingStop; private Button btnCreateGeofence; private Button btnClearGeofence; private Geofencing geofencingService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_do_something); bindView(); setupView(); setupThing(); } @Override protected void onDestroy() { super.onDestroy();
BusProvider.getProvider().unregister(this);
akexorcist/Example-SamsungSDK
KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/DoSomethingActivity.java
// Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/BusProvider.java // public class BusProvider { // private static Bus bus; // // public static Bus getProvider() { // if (bus == null) { // bus = new Bus(); // } // return bus; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/InsideGeofenceEvent.java // public class InsideGeofenceEvent { // int[] geofenceIdList; // // public InsideGeofenceEvent() { // } // // public InsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/LocationUnavailableEvent.java // public class LocationUnavailableEvent { // // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/OutsideGeofenceEvent.java // public class OutsideGeofenceEvent { // int[] geofenceIdList; // // public OutsideGeofenceEvent() { // } // // public OutsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // }
import android.app.enterprise.geofencing.CircularGeofence; import android.app.enterprise.geofencing.Geofence; import android.app.enterprise.geofencing.Geofencing; import android.app.enterprise.geofencing.LatLongPoint; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.akexorcist.knoxgeofencingapp.bus.BusProvider; import com.akexorcist.knoxgeofencingapp.bus.event.InsideGeofenceEvent; import com.akexorcist.knoxgeofencingapp.bus.event.LocationUnavailableEvent; import com.akexorcist.knoxgeofencingapp.bus.event.OutsideGeofenceEvent; import com.squareup.otto.Subscribe; import java.util.List;
private void createGeofence() { LatLongPoint center = new LatLongPoint(13.678505, 100.615474); double radius = 1000; CircularGeofence circularGeofence = new CircularGeofence(center, radius); int id = geofencingService.createGeofence(circularGeofence); if (id == -1) { Toast.makeText(this, R.string.already_exists_geofence, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, getString(R.string.geofence_was_created, id), Toast.LENGTH_SHORT).show(); } } private void clearGeofence() { List<Geofence> geofenceList = geofencingService.getGeofences(); if (geofenceList != null) { for (Geofence geofence : geofenceList) { geofencingService.destroyGeofence(geofence.id); } } } private void startGeofencing() { geofencingService.startGeofencing(); } private void stopGeofencing() { geofencingService.stopGeofencing(); } @Subscribe
// Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/BusProvider.java // public class BusProvider { // private static Bus bus; // // public static Bus getProvider() { // if (bus == null) { // bus = new Bus(); // } // return bus; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/InsideGeofenceEvent.java // public class InsideGeofenceEvent { // int[] geofenceIdList; // // public InsideGeofenceEvent() { // } // // public InsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/LocationUnavailableEvent.java // public class LocationUnavailableEvent { // // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/OutsideGeofenceEvent.java // public class OutsideGeofenceEvent { // int[] geofenceIdList; // // public OutsideGeofenceEvent() { // } // // public OutsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // } // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/DoSomethingActivity.java import android.app.enterprise.geofencing.CircularGeofence; import android.app.enterprise.geofencing.Geofence; import android.app.enterprise.geofencing.Geofencing; import android.app.enterprise.geofencing.LatLongPoint; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.akexorcist.knoxgeofencingapp.bus.BusProvider; import com.akexorcist.knoxgeofencingapp.bus.event.InsideGeofenceEvent; import com.akexorcist.knoxgeofencingapp.bus.event.LocationUnavailableEvent; import com.akexorcist.knoxgeofencingapp.bus.event.OutsideGeofenceEvent; import com.squareup.otto.Subscribe; import java.util.List; private void createGeofence() { LatLongPoint center = new LatLongPoint(13.678505, 100.615474); double radius = 1000; CircularGeofence circularGeofence = new CircularGeofence(center, radius); int id = geofencingService.createGeofence(circularGeofence); if (id == -1) { Toast.makeText(this, R.string.already_exists_geofence, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, getString(R.string.geofence_was_created, id), Toast.LENGTH_SHORT).show(); } } private void clearGeofence() { List<Geofence> geofenceList = geofencingService.getGeofences(); if (geofenceList != null) { for (Geofence geofence : geofenceList) { geofencingService.destroyGeofence(geofence.id); } } } private void startGeofencing() { geofencingService.startGeofencing(); } private void stopGeofencing() { geofencingService.stopGeofencing(); } @Subscribe
public void onInsideGeofenceEvent(InsideGeofenceEvent event) {
akexorcist/Example-SamsungSDK
KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/DoSomethingActivity.java
// Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/BusProvider.java // public class BusProvider { // private static Bus bus; // // public static Bus getProvider() { // if (bus == null) { // bus = new Bus(); // } // return bus; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/InsideGeofenceEvent.java // public class InsideGeofenceEvent { // int[] geofenceIdList; // // public InsideGeofenceEvent() { // } // // public InsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/LocationUnavailableEvent.java // public class LocationUnavailableEvent { // // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/OutsideGeofenceEvent.java // public class OutsideGeofenceEvent { // int[] geofenceIdList; // // public OutsideGeofenceEvent() { // } // // public OutsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // }
import android.app.enterprise.geofencing.CircularGeofence; import android.app.enterprise.geofencing.Geofence; import android.app.enterprise.geofencing.Geofencing; import android.app.enterprise.geofencing.LatLongPoint; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.akexorcist.knoxgeofencingapp.bus.BusProvider; import com.akexorcist.knoxgeofencingapp.bus.event.InsideGeofenceEvent; import com.akexorcist.knoxgeofencingapp.bus.event.LocationUnavailableEvent; import com.akexorcist.knoxgeofencingapp.bus.event.OutsideGeofenceEvent; import com.squareup.otto.Subscribe; import java.util.List;
if (id == -1) { Toast.makeText(this, R.string.already_exists_geofence, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, getString(R.string.geofence_was_created, id), Toast.LENGTH_SHORT).show(); } } private void clearGeofence() { List<Geofence> geofenceList = geofencingService.getGeofences(); if (geofenceList != null) { for (Geofence geofence : geofenceList) { geofencingService.destroyGeofence(geofence.id); } } } private void startGeofencing() { geofencingService.startGeofencing(); } private void stopGeofencing() { geofencingService.stopGeofencing(); } @Subscribe public void onInsideGeofenceEvent(InsideGeofenceEvent event) { // When device is inside geofence } @Subscribe
// Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/BusProvider.java // public class BusProvider { // private static Bus bus; // // public static Bus getProvider() { // if (bus == null) { // bus = new Bus(); // } // return bus; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/InsideGeofenceEvent.java // public class InsideGeofenceEvent { // int[] geofenceIdList; // // public InsideGeofenceEvent() { // } // // public InsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/LocationUnavailableEvent.java // public class LocationUnavailableEvent { // // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/OutsideGeofenceEvent.java // public class OutsideGeofenceEvent { // int[] geofenceIdList; // // public OutsideGeofenceEvent() { // } // // public OutsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // } // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/DoSomethingActivity.java import android.app.enterprise.geofencing.CircularGeofence; import android.app.enterprise.geofencing.Geofence; import android.app.enterprise.geofencing.Geofencing; import android.app.enterprise.geofencing.LatLongPoint; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.akexorcist.knoxgeofencingapp.bus.BusProvider; import com.akexorcist.knoxgeofencingapp.bus.event.InsideGeofenceEvent; import com.akexorcist.knoxgeofencingapp.bus.event.LocationUnavailableEvent; import com.akexorcist.knoxgeofencingapp.bus.event.OutsideGeofenceEvent; import com.squareup.otto.Subscribe; import java.util.List; if (id == -1) { Toast.makeText(this, R.string.already_exists_geofence, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, getString(R.string.geofence_was_created, id), Toast.LENGTH_SHORT).show(); } } private void clearGeofence() { List<Geofence> geofenceList = geofencingService.getGeofences(); if (geofenceList != null) { for (Geofence geofence : geofenceList) { geofencingService.destroyGeofence(geofence.id); } } } private void startGeofencing() { geofencingService.startGeofencing(); } private void stopGeofencing() { geofencingService.stopGeofencing(); } @Subscribe public void onInsideGeofenceEvent(InsideGeofenceEvent event) { // When device is inside geofence } @Subscribe
public void onOutsideGeofenceEvent(OutsideGeofenceEvent event) {
akexorcist/Example-SamsungSDK
KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/DoSomethingActivity.java
// Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/BusProvider.java // public class BusProvider { // private static Bus bus; // // public static Bus getProvider() { // if (bus == null) { // bus = new Bus(); // } // return bus; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/InsideGeofenceEvent.java // public class InsideGeofenceEvent { // int[] geofenceIdList; // // public InsideGeofenceEvent() { // } // // public InsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/LocationUnavailableEvent.java // public class LocationUnavailableEvent { // // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/OutsideGeofenceEvent.java // public class OutsideGeofenceEvent { // int[] geofenceIdList; // // public OutsideGeofenceEvent() { // } // // public OutsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // }
import android.app.enterprise.geofencing.CircularGeofence; import android.app.enterprise.geofencing.Geofence; import android.app.enterprise.geofencing.Geofencing; import android.app.enterprise.geofencing.LatLongPoint; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.akexorcist.knoxgeofencingapp.bus.BusProvider; import com.akexorcist.knoxgeofencingapp.bus.event.InsideGeofenceEvent; import com.akexorcist.knoxgeofencingapp.bus.event.LocationUnavailableEvent; import com.akexorcist.knoxgeofencingapp.bus.event.OutsideGeofenceEvent; import com.squareup.otto.Subscribe; import java.util.List;
} private void clearGeofence() { List<Geofence> geofenceList = geofencingService.getGeofences(); if (geofenceList != null) { for (Geofence geofence : geofenceList) { geofencingService.destroyGeofence(geofence.id); } } } private void startGeofencing() { geofencingService.startGeofencing(); } private void stopGeofencing() { geofencingService.stopGeofencing(); } @Subscribe public void onInsideGeofenceEvent(InsideGeofenceEvent event) { // When device is inside geofence } @Subscribe public void onOutsideGeofenceEvent(OutsideGeofenceEvent event) { // When device is outside geofence } @Subscribe
// Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/BusProvider.java // public class BusProvider { // private static Bus bus; // // public static Bus getProvider() { // if (bus == null) { // bus = new Bus(); // } // return bus; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/InsideGeofenceEvent.java // public class InsideGeofenceEvent { // int[] geofenceIdList; // // public InsideGeofenceEvent() { // } // // public InsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/LocationUnavailableEvent.java // public class LocationUnavailableEvent { // // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/OutsideGeofenceEvent.java // public class OutsideGeofenceEvent { // int[] geofenceIdList; // // public OutsideGeofenceEvent() { // } // // public OutsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // } // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/DoSomethingActivity.java import android.app.enterprise.geofencing.CircularGeofence; import android.app.enterprise.geofencing.Geofence; import android.app.enterprise.geofencing.Geofencing; import android.app.enterprise.geofencing.LatLongPoint; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.akexorcist.knoxgeofencingapp.bus.BusProvider; import com.akexorcist.knoxgeofencingapp.bus.event.InsideGeofenceEvent; import com.akexorcist.knoxgeofencingapp.bus.event.LocationUnavailableEvent; import com.akexorcist.knoxgeofencingapp.bus.event.OutsideGeofenceEvent; import com.squareup.otto.Subscribe; import java.util.List; } private void clearGeofence() { List<Geofence> geofenceList = geofencingService.getGeofences(); if (geofenceList != null) { for (Geofence geofence : geofenceList) { geofencingService.destroyGeofence(geofence.id); } } } private void startGeofencing() { geofencingService.startGeofencing(); } private void stopGeofencing() { geofencingService.stopGeofencing(); } @Subscribe public void onInsideGeofenceEvent(InsideGeofenceEvent event) { // When device is inside geofence } @Subscribe public void onOutsideGeofenceEvent(OutsideGeofenceEvent event) { // When device is outside geofence } @Subscribe
public void onLocationUnavailable(LocationUnavailableEvent event) {
akexorcist/Example-SamsungSDK
KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/KnoxActivationManager.java
// Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/AdminDeactivatedEvent.java // public class AdminDeactivatedEvent { } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/LicenseActivatedEvent.java // public class LicenseActivatedEvent { } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/LicenseActivationFailedEvent.java // public class LicenseActivationFailedEvent { // int errorType; // // public LicenseActivationFailedEvent(int errorType) { // this.errorType = errorType; // } // // public int getErrorType() { // return errorType; // } // } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/receiver/AdminActivationReceiver.java // public class AdminActivationReceiver extends DeviceAdminReceiver { // private static final long EVENT_LISTENER_DELAY = 500; // // @Override // public void onEnabled(Context context, Intent intent) { // } // // @Override // public CharSequence onDisableRequested(Context context, Intent intent) { // return context.getString(R.string.deactivate_device_admin_warning); // } // // @Override // public void onDisabled(Context context, Intent intent) { // new Handler().postDelayed(new Runnable() { // @Override // public void run() { // KnoxActivationBus.getInstance().getBus().post(new AdminDeactivatedEvent()); // } // }, EVENT_LISTENER_DELAY); // } // }
import android.app.Activity; import android.app.admin.DevicePolicyManager; import android.app.enterprise.EnterpriseDeviceManager; import android.app.enterprise.license.EnterpriseLicenseManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.os.Handler; import com.akexorcist.knoxactivator.event.AdminDeactivatedEvent; import com.akexorcist.knoxactivator.event.LicenseActivatedEvent; import com.akexorcist.knoxactivator.event.LicenseActivationFailedEvent; import com.akexorcist.knoxactivator.receiver.AdminActivationReceiver; import com.squareup.otto.Subscribe;
package com.akexorcist.knoxactivator; /** * Created by Akexorcist on 4/20/2016 AD. */ public class KnoxActivationManager { private static final long EVENT_LISTENER_DELAY = 500; public static final int REQUEST_CODE_KNOX = 4545; private static KnoxActivationManager knoxActivationManager; public static KnoxActivationManager getInstance() { if (knoxActivationManager == null) { knoxActivationManager = new KnoxActivationManager(); } return knoxActivationManager; } private ActivationCallback activationCallback; public void register(ActivationCallback callback) { activationCallback = callback; KnoxActivationBus.getInstance().getBus().register(this); } public void unregister() { activationCallback = null; KnoxActivationBus.getInstance().getBus().unregister(this); } public boolean isDeviceAdminActivated(Context context) { DevicePolicyManager devicePolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
// Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/AdminDeactivatedEvent.java // public class AdminDeactivatedEvent { } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/LicenseActivatedEvent.java // public class LicenseActivatedEvent { } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/LicenseActivationFailedEvent.java // public class LicenseActivationFailedEvent { // int errorType; // // public LicenseActivationFailedEvent(int errorType) { // this.errorType = errorType; // } // // public int getErrorType() { // return errorType; // } // } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/receiver/AdminActivationReceiver.java // public class AdminActivationReceiver extends DeviceAdminReceiver { // private static final long EVENT_LISTENER_DELAY = 500; // // @Override // public void onEnabled(Context context, Intent intent) { // } // // @Override // public CharSequence onDisableRequested(Context context, Intent intent) { // return context.getString(R.string.deactivate_device_admin_warning); // } // // @Override // public void onDisabled(Context context, Intent intent) { // new Handler().postDelayed(new Runnable() { // @Override // public void run() { // KnoxActivationBus.getInstance().getBus().post(new AdminDeactivatedEvent()); // } // }, EVENT_LISTENER_DELAY); // } // } // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/KnoxActivationManager.java import android.app.Activity; import android.app.admin.DevicePolicyManager; import android.app.enterprise.EnterpriseDeviceManager; import android.app.enterprise.license.EnterpriseLicenseManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.os.Handler; import com.akexorcist.knoxactivator.event.AdminDeactivatedEvent; import com.akexorcist.knoxactivator.event.LicenseActivatedEvent; import com.akexorcist.knoxactivator.event.LicenseActivationFailedEvent; import com.akexorcist.knoxactivator.receiver.AdminActivationReceiver; import com.squareup.otto.Subscribe; package com.akexorcist.knoxactivator; /** * Created by Akexorcist on 4/20/2016 AD. */ public class KnoxActivationManager { private static final long EVENT_LISTENER_DELAY = 500; public static final int REQUEST_CODE_KNOX = 4545; private static KnoxActivationManager knoxActivationManager; public static KnoxActivationManager getInstance() { if (knoxActivationManager == null) { knoxActivationManager = new KnoxActivationManager(); } return knoxActivationManager; } private ActivationCallback activationCallback; public void register(ActivationCallback callback) { activationCallback = callback; KnoxActivationBus.getInstance().getBus().register(this); } public void unregister() { activationCallback = null; KnoxActivationBus.getInstance().getBus().unregister(this); } public boolean isDeviceAdminActivated(Context context) { DevicePolicyManager devicePolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
ComponentName componentName = new ComponentName(context, AdminActivationReceiver.class);
akexorcist/Example-SamsungSDK
KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/KnoxActivationManager.java
// Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/AdminDeactivatedEvent.java // public class AdminDeactivatedEvent { } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/LicenseActivatedEvent.java // public class LicenseActivatedEvent { } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/LicenseActivationFailedEvent.java // public class LicenseActivationFailedEvent { // int errorType; // // public LicenseActivationFailedEvent(int errorType) { // this.errorType = errorType; // } // // public int getErrorType() { // return errorType; // } // } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/receiver/AdminActivationReceiver.java // public class AdminActivationReceiver extends DeviceAdminReceiver { // private static final long EVENT_LISTENER_DELAY = 500; // // @Override // public void onEnabled(Context context, Intent intent) { // } // // @Override // public CharSequence onDisableRequested(Context context, Intent intent) { // return context.getString(R.string.deactivate_device_admin_warning); // } // // @Override // public void onDisabled(Context context, Intent intent) { // new Handler().postDelayed(new Runnable() { // @Override // public void run() { // KnoxActivationBus.getInstance().getBus().post(new AdminDeactivatedEvent()); // } // }, EVENT_LISTENER_DELAY); // } // }
import android.app.Activity; import android.app.admin.DevicePolicyManager; import android.app.enterprise.EnterpriseDeviceManager; import android.app.enterprise.license.EnterpriseLicenseManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.os.Handler; import com.akexorcist.knoxactivator.event.AdminDeactivatedEvent; import com.akexorcist.knoxactivator.event.LicenseActivatedEvent; import com.akexorcist.knoxactivator.event.LicenseActivationFailedEvent; import com.akexorcist.knoxactivator.receiver.AdminActivationReceiver; import com.squareup.otto.Subscribe;
package com.akexorcist.knoxactivator; /** * Created by Akexorcist on 4/20/2016 AD. */ public class KnoxActivationManager { private static final long EVENT_LISTENER_DELAY = 500; public static final int REQUEST_CODE_KNOX = 4545; private static KnoxActivationManager knoxActivationManager; public static KnoxActivationManager getInstance() { if (knoxActivationManager == null) { knoxActivationManager = new KnoxActivationManager(); } return knoxActivationManager; } private ActivationCallback activationCallback; public void register(ActivationCallback callback) { activationCallback = callback; KnoxActivationBus.getInstance().getBus().register(this); } public void unregister() { activationCallback = null; KnoxActivationBus.getInstance().getBus().unregister(this); } public boolean isDeviceAdminActivated(Context context) { DevicePolicyManager devicePolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE); ComponentName componentName = new ComponentName(context, AdminActivationReceiver.class); return devicePolicyManager.isAdminActive(componentName); } @Subscribe
// Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/AdminDeactivatedEvent.java // public class AdminDeactivatedEvent { } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/LicenseActivatedEvent.java // public class LicenseActivatedEvent { } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/LicenseActivationFailedEvent.java // public class LicenseActivationFailedEvent { // int errorType; // // public LicenseActivationFailedEvent(int errorType) { // this.errorType = errorType; // } // // public int getErrorType() { // return errorType; // } // } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/receiver/AdminActivationReceiver.java // public class AdminActivationReceiver extends DeviceAdminReceiver { // private static final long EVENT_LISTENER_DELAY = 500; // // @Override // public void onEnabled(Context context, Intent intent) { // } // // @Override // public CharSequence onDisableRequested(Context context, Intent intent) { // return context.getString(R.string.deactivate_device_admin_warning); // } // // @Override // public void onDisabled(Context context, Intent intent) { // new Handler().postDelayed(new Runnable() { // @Override // public void run() { // KnoxActivationBus.getInstance().getBus().post(new AdminDeactivatedEvent()); // } // }, EVENT_LISTENER_DELAY); // } // } // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/KnoxActivationManager.java import android.app.Activity; import android.app.admin.DevicePolicyManager; import android.app.enterprise.EnterpriseDeviceManager; import android.app.enterprise.license.EnterpriseLicenseManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.os.Handler; import com.akexorcist.knoxactivator.event.AdminDeactivatedEvent; import com.akexorcist.knoxactivator.event.LicenseActivatedEvent; import com.akexorcist.knoxactivator.event.LicenseActivationFailedEvent; import com.akexorcist.knoxactivator.receiver.AdminActivationReceiver; import com.squareup.otto.Subscribe; package com.akexorcist.knoxactivator; /** * Created by Akexorcist on 4/20/2016 AD. */ public class KnoxActivationManager { private static final long EVENT_LISTENER_DELAY = 500; public static final int REQUEST_CODE_KNOX = 4545; private static KnoxActivationManager knoxActivationManager; public static KnoxActivationManager getInstance() { if (knoxActivationManager == null) { knoxActivationManager = new KnoxActivationManager(); } return knoxActivationManager; } private ActivationCallback activationCallback; public void register(ActivationCallback callback) { activationCallback = callback; KnoxActivationBus.getInstance().getBus().register(this); } public void unregister() { activationCallback = null; KnoxActivationBus.getInstance().getBus().unregister(this); } public boolean isDeviceAdminActivated(Context context) { DevicePolicyManager devicePolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE); ComponentName componentName = new ComponentName(context, AdminActivationReceiver.class); return devicePolicyManager.isAdminActive(componentName); } @Subscribe
public void onDeviceAdminDeactivated(AdminDeactivatedEvent event) {
akexorcist/Example-SamsungSDK
KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/KnoxActivationManager.java
// Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/AdminDeactivatedEvent.java // public class AdminDeactivatedEvent { } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/LicenseActivatedEvent.java // public class LicenseActivatedEvent { } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/LicenseActivationFailedEvent.java // public class LicenseActivationFailedEvent { // int errorType; // // public LicenseActivationFailedEvent(int errorType) { // this.errorType = errorType; // } // // public int getErrorType() { // return errorType; // } // } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/receiver/AdminActivationReceiver.java // public class AdminActivationReceiver extends DeviceAdminReceiver { // private static final long EVENT_LISTENER_DELAY = 500; // // @Override // public void onEnabled(Context context, Intent intent) { // } // // @Override // public CharSequence onDisableRequested(Context context, Intent intent) { // return context.getString(R.string.deactivate_device_admin_warning); // } // // @Override // public void onDisabled(Context context, Intent intent) { // new Handler().postDelayed(new Runnable() { // @Override // public void run() { // KnoxActivationBus.getInstance().getBus().post(new AdminDeactivatedEvent()); // } // }, EVENT_LISTENER_DELAY); // } // }
import android.app.Activity; import android.app.admin.DevicePolicyManager; import android.app.enterprise.EnterpriseDeviceManager; import android.app.enterprise.license.EnterpriseLicenseManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.os.Handler; import com.akexorcist.knoxactivator.event.AdminDeactivatedEvent; import com.akexorcist.knoxactivator.event.LicenseActivatedEvent; import com.akexorcist.knoxactivator.event.LicenseActivationFailedEvent; import com.akexorcist.knoxactivator.receiver.AdminActivationReceiver; import com.squareup.otto.Subscribe;
} return knoxActivationManager; } private ActivationCallback activationCallback; public void register(ActivationCallback callback) { activationCallback = callback; KnoxActivationBus.getInstance().getBus().register(this); } public void unregister() { activationCallback = null; KnoxActivationBus.getInstance().getBus().unregister(this); } public boolean isDeviceAdminActivated(Context context) { DevicePolicyManager devicePolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE); ComponentName componentName = new ComponentName(context, AdminActivationReceiver.class); return devicePolicyManager.isAdminActive(componentName); } @Subscribe public void onDeviceAdminDeactivated(AdminDeactivatedEvent event) { if (activationCallback != null) { activationCallback.onDeviceAdminDeactivated(); } } @Subscribe
// Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/AdminDeactivatedEvent.java // public class AdminDeactivatedEvent { } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/LicenseActivatedEvent.java // public class LicenseActivatedEvent { } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/LicenseActivationFailedEvent.java // public class LicenseActivationFailedEvent { // int errorType; // // public LicenseActivationFailedEvent(int errorType) { // this.errorType = errorType; // } // // public int getErrorType() { // return errorType; // } // } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/receiver/AdminActivationReceiver.java // public class AdminActivationReceiver extends DeviceAdminReceiver { // private static final long EVENT_LISTENER_DELAY = 500; // // @Override // public void onEnabled(Context context, Intent intent) { // } // // @Override // public CharSequence onDisableRequested(Context context, Intent intent) { // return context.getString(R.string.deactivate_device_admin_warning); // } // // @Override // public void onDisabled(Context context, Intent intent) { // new Handler().postDelayed(new Runnable() { // @Override // public void run() { // KnoxActivationBus.getInstance().getBus().post(new AdminDeactivatedEvent()); // } // }, EVENT_LISTENER_DELAY); // } // } // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/KnoxActivationManager.java import android.app.Activity; import android.app.admin.DevicePolicyManager; import android.app.enterprise.EnterpriseDeviceManager; import android.app.enterprise.license.EnterpriseLicenseManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.os.Handler; import com.akexorcist.knoxactivator.event.AdminDeactivatedEvent; import com.akexorcist.knoxactivator.event.LicenseActivatedEvent; import com.akexorcist.knoxactivator.event.LicenseActivationFailedEvent; import com.akexorcist.knoxactivator.receiver.AdminActivationReceiver; import com.squareup.otto.Subscribe; } return knoxActivationManager; } private ActivationCallback activationCallback; public void register(ActivationCallback callback) { activationCallback = callback; KnoxActivationBus.getInstance().getBus().register(this); } public void unregister() { activationCallback = null; KnoxActivationBus.getInstance().getBus().unregister(this); } public boolean isDeviceAdminActivated(Context context) { DevicePolicyManager devicePolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE); ComponentName componentName = new ComponentName(context, AdminActivationReceiver.class); return devicePolicyManager.isAdminActive(componentName); } @Subscribe public void onDeviceAdminDeactivated(AdminDeactivatedEvent event) { if (activationCallback != null) { activationCallback.onDeviceAdminDeactivated(); } } @Subscribe
public void onLicenseActivated(LicenseActivatedEvent event) {
akexorcist/Example-SamsungSDK
KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/KnoxActivationManager.java
// Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/AdminDeactivatedEvent.java // public class AdminDeactivatedEvent { } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/LicenseActivatedEvent.java // public class LicenseActivatedEvent { } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/LicenseActivationFailedEvent.java // public class LicenseActivationFailedEvent { // int errorType; // // public LicenseActivationFailedEvent(int errorType) { // this.errorType = errorType; // } // // public int getErrorType() { // return errorType; // } // } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/receiver/AdminActivationReceiver.java // public class AdminActivationReceiver extends DeviceAdminReceiver { // private static final long EVENT_LISTENER_DELAY = 500; // // @Override // public void onEnabled(Context context, Intent intent) { // } // // @Override // public CharSequence onDisableRequested(Context context, Intent intent) { // return context.getString(R.string.deactivate_device_admin_warning); // } // // @Override // public void onDisabled(Context context, Intent intent) { // new Handler().postDelayed(new Runnable() { // @Override // public void run() { // KnoxActivationBus.getInstance().getBus().post(new AdminDeactivatedEvent()); // } // }, EVENT_LISTENER_DELAY); // } // }
import android.app.Activity; import android.app.admin.DevicePolicyManager; import android.app.enterprise.EnterpriseDeviceManager; import android.app.enterprise.license.EnterpriseLicenseManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.os.Handler; import com.akexorcist.knoxactivator.event.AdminDeactivatedEvent; import com.akexorcist.knoxactivator.event.LicenseActivatedEvent; import com.akexorcist.knoxactivator.event.LicenseActivationFailedEvent; import com.akexorcist.knoxactivator.receiver.AdminActivationReceiver; import com.squareup.otto.Subscribe;
activationCallback = callback; KnoxActivationBus.getInstance().getBus().register(this); } public void unregister() { activationCallback = null; KnoxActivationBus.getInstance().getBus().unregister(this); } public boolean isDeviceAdminActivated(Context context) { DevicePolicyManager devicePolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE); ComponentName componentName = new ComponentName(context, AdminActivationReceiver.class); return devicePolicyManager.isAdminActive(componentName); } @Subscribe public void onDeviceAdminDeactivated(AdminDeactivatedEvent event) { if (activationCallback != null) { activationCallback.onDeviceAdminDeactivated(); } } @Subscribe public void onLicenseActivated(LicenseActivatedEvent event) { if (activationCallback != null) { activationCallback.onLicenseActivated(); } } @Subscribe
// Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/AdminDeactivatedEvent.java // public class AdminDeactivatedEvent { } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/LicenseActivatedEvent.java // public class LicenseActivatedEvent { } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/LicenseActivationFailedEvent.java // public class LicenseActivationFailedEvent { // int errorType; // // public LicenseActivationFailedEvent(int errorType) { // this.errorType = errorType; // } // // public int getErrorType() { // return errorType; // } // } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/receiver/AdminActivationReceiver.java // public class AdminActivationReceiver extends DeviceAdminReceiver { // private static final long EVENT_LISTENER_DELAY = 500; // // @Override // public void onEnabled(Context context, Intent intent) { // } // // @Override // public CharSequence onDisableRequested(Context context, Intent intent) { // return context.getString(R.string.deactivate_device_admin_warning); // } // // @Override // public void onDisabled(Context context, Intent intent) { // new Handler().postDelayed(new Runnable() { // @Override // public void run() { // KnoxActivationBus.getInstance().getBus().post(new AdminDeactivatedEvent()); // } // }, EVENT_LISTENER_DELAY); // } // } // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/KnoxActivationManager.java import android.app.Activity; import android.app.admin.DevicePolicyManager; import android.app.enterprise.EnterpriseDeviceManager; import android.app.enterprise.license.EnterpriseLicenseManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.os.Handler; import com.akexorcist.knoxactivator.event.AdminDeactivatedEvent; import com.akexorcist.knoxactivator.event.LicenseActivatedEvent; import com.akexorcist.knoxactivator.event.LicenseActivationFailedEvent; import com.akexorcist.knoxactivator.receiver.AdminActivationReceiver; import com.squareup.otto.Subscribe; activationCallback = callback; KnoxActivationBus.getInstance().getBus().register(this); } public void unregister() { activationCallback = null; KnoxActivationBus.getInstance().getBus().unregister(this); } public boolean isDeviceAdminActivated(Context context) { DevicePolicyManager devicePolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE); ComponentName componentName = new ComponentName(context, AdminActivationReceiver.class); return devicePolicyManager.isAdminActive(componentName); } @Subscribe public void onDeviceAdminDeactivated(AdminDeactivatedEvent event) { if (activationCallback != null) { activationCallback.onDeviceAdminDeactivated(); } } @Subscribe public void onLicenseActivated(LicenseActivatedEvent event) { if (activationCallback != null) { activationCallback.onLicenseActivated(); } } @Subscribe
public void onLicenseActivationFailed(LicenseActivationFailedEvent event) {
akexorcist/Example-SamsungSDK
KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/receiver/AdminActivationReceiver.java
// Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/KnoxActivationBus.java // public class KnoxActivationBus { // private static KnoxActivationBus knoxActivationBus; // // public static KnoxActivationBus getInstance() { // if (knoxActivationBus == null) { // knoxActivationBus = new KnoxActivationBus(); // } // return knoxActivationBus; // } // // private Bus bus; // // public Bus getBus() { // if (bus == null) { // bus = new Bus(); // } // return bus; // } // } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/AdminDeactivatedEvent.java // public class AdminDeactivatedEvent { }
import com.akexorcist.knoxactivator.event.AdminDeactivatedEvent; import android.app.admin.DeviceAdminReceiver; import android.content.Context; import android.content.Intent; import android.os.Handler; import com.akexorcist.knoxactivator.KnoxActivationBus; import com.akexorcist.knoxactivator.R;
/** * DISCLAIMER: PLEASE TAKE NOTE THAT THE SAMPLE APPLICATION AND * SOURCE CODE DESCRIBED HEREIN IS PROVIDED FOR TESTING PURPOSES ONLY. * <p/> * Samsung expressly disclaims any and all warranties of any kind, * whether express or implied, including but not limited to the implied warranties and conditions * of merchantability, fitness for a particular purpose and non-infringement. * Further, Samsung does not represent or warrant that any portion of the sample application and * source code is free of inaccuracies, errors, bugs or interruptions, or is reliable, * accurate, complete, or otherwise valid. The sample application and source code is provided * "as is" and "as available", without any warranty of any kind from Samsung. * <p/> * Your use of the sample application and source code is at its own discretion and risk, * and licensee will be solely responsible for any damage that results from the use of the sample * application and source code including, but not limited to, any damage to your computer system or * platform. For the purpose of clarity, the sample code is licensed “as is” and * licenses bears the risk of using it. * <p/> * Samsung shall not be liable for any direct, indirect or consequential damages or * costs of any type arising out of any action taken by you or others related to the sample application * and source code. */ package com.akexorcist.knoxactivator.receiver; //This BroadcastReceiver handles device admin activation and deactivation public class AdminActivationReceiver extends DeviceAdminReceiver { private static final long EVENT_LISTENER_DELAY = 500; @Override public void onEnabled(Context context, Intent intent) { } @Override public CharSequence onDisableRequested(Context context, Intent intent) { return context.getString(R.string.deactivate_device_admin_warning); } @Override public void onDisabled(Context context, Intent intent) { new Handler().postDelayed(new Runnable() { @Override public void run() {
// Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/KnoxActivationBus.java // public class KnoxActivationBus { // private static KnoxActivationBus knoxActivationBus; // // public static KnoxActivationBus getInstance() { // if (knoxActivationBus == null) { // knoxActivationBus = new KnoxActivationBus(); // } // return knoxActivationBus; // } // // private Bus bus; // // public Bus getBus() { // if (bus == null) { // bus = new Bus(); // } // return bus; // } // } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/AdminDeactivatedEvent.java // public class AdminDeactivatedEvent { } // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/receiver/AdminActivationReceiver.java import com.akexorcist.knoxactivator.event.AdminDeactivatedEvent; import android.app.admin.DeviceAdminReceiver; import android.content.Context; import android.content.Intent; import android.os.Handler; import com.akexorcist.knoxactivator.KnoxActivationBus; import com.akexorcist.knoxactivator.R; /** * DISCLAIMER: PLEASE TAKE NOTE THAT THE SAMPLE APPLICATION AND * SOURCE CODE DESCRIBED HEREIN IS PROVIDED FOR TESTING PURPOSES ONLY. * <p/> * Samsung expressly disclaims any and all warranties of any kind, * whether express or implied, including but not limited to the implied warranties and conditions * of merchantability, fitness for a particular purpose and non-infringement. * Further, Samsung does not represent or warrant that any portion of the sample application and * source code is free of inaccuracies, errors, bugs or interruptions, or is reliable, * accurate, complete, or otherwise valid. The sample application and source code is provided * "as is" and "as available", without any warranty of any kind from Samsung. * <p/> * Your use of the sample application and source code is at its own discretion and risk, * and licensee will be solely responsible for any damage that results from the use of the sample * application and source code including, but not limited to, any damage to your computer system or * platform. For the purpose of clarity, the sample code is licensed “as is” and * licenses bears the risk of using it. * <p/> * Samsung shall not be liable for any direct, indirect or consequential damages or * costs of any type arising out of any action taken by you or others related to the sample application * and source code. */ package com.akexorcist.knoxactivator.receiver; //This BroadcastReceiver handles device admin activation and deactivation public class AdminActivationReceiver extends DeviceAdminReceiver { private static final long EVENT_LISTENER_DELAY = 500; @Override public void onEnabled(Context context, Intent intent) { } @Override public CharSequence onDisableRequested(Context context, Intent intent) { return context.getString(R.string.deactivate_device_admin_warning); } @Override public void onDisabled(Context context, Intent intent) { new Handler().postDelayed(new Runnable() { @Override public void run() {
KnoxActivationBus.getInstance().getBus().post(new AdminDeactivatedEvent());
akexorcist/Example-SamsungSDK
KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/receiver/AdminActivationReceiver.java
// Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/KnoxActivationBus.java // public class KnoxActivationBus { // private static KnoxActivationBus knoxActivationBus; // // public static KnoxActivationBus getInstance() { // if (knoxActivationBus == null) { // knoxActivationBus = new KnoxActivationBus(); // } // return knoxActivationBus; // } // // private Bus bus; // // public Bus getBus() { // if (bus == null) { // bus = new Bus(); // } // return bus; // } // } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/AdminDeactivatedEvent.java // public class AdminDeactivatedEvent { }
import com.akexorcist.knoxactivator.event.AdminDeactivatedEvent; import android.app.admin.DeviceAdminReceiver; import android.content.Context; import android.content.Intent; import android.os.Handler; import com.akexorcist.knoxactivator.KnoxActivationBus; import com.akexorcist.knoxactivator.R;
/** * DISCLAIMER: PLEASE TAKE NOTE THAT THE SAMPLE APPLICATION AND * SOURCE CODE DESCRIBED HEREIN IS PROVIDED FOR TESTING PURPOSES ONLY. * <p/> * Samsung expressly disclaims any and all warranties of any kind, * whether express or implied, including but not limited to the implied warranties and conditions * of merchantability, fitness for a particular purpose and non-infringement. * Further, Samsung does not represent or warrant that any portion of the sample application and * source code is free of inaccuracies, errors, bugs or interruptions, or is reliable, * accurate, complete, or otherwise valid. The sample application and source code is provided * "as is" and "as available", without any warranty of any kind from Samsung. * <p/> * Your use of the sample application and source code is at its own discretion and risk, * and licensee will be solely responsible for any damage that results from the use of the sample * application and source code including, but not limited to, any damage to your computer system or * platform. For the purpose of clarity, the sample code is licensed “as is” and * licenses bears the risk of using it. * <p/> * Samsung shall not be liable for any direct, indirect or consequential damages or * costs of any type arising out of any action taken by you or others related to the sample application * and source code. */ package com.akexorcist.knoxactivator.receiver; //This BroadcastReceiver handles device admin activation and deactivation public class AdminActivationReceiver extends DeviceAdminReceiver { private static final long EVENT_LISTENER_DELAY = 500; @Override public void onEnabled(Context context, Intent intent) { } @Override public CharSequence onDisableRequested(Context context, Intent intent) { return context.getString(R.string.deactivate_device_admin_warning); } @Override public void onDisabled(Context context, Intent intent) { new Handler().postDelayed(new Runnable() { @Override public void run() {
// Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/KnoxActivationBus.java // public class KnoxActivationBus { // private static KnoxActivationBus knoxActivationBus; // // public static KnoxActivationBus getInstance() { // if (knoxActivationBus == null) { // knoxActivationBus = new KnoxActivationBus(); // } // return knoxActivationBus; // } // // private Bus bus; // // public Bus getBus() { // if (bus == null) { // bus = new Bus(); // } // return bus; // } // } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/AdminDeactivatedEvent.java // public class AdminDeactivatedEvent { } // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/receiver/AdminActivationReceiver.java import com.akexorcist.knoxactivator.event.AdminDeactivatedEvent; import android.app.admin.DeviceAdminReceiver; import android.content.Context; import android.content.Intent; import android.os.Handler; import com.akexorcist.knoxactivator.KnoxActivationBus; import com.akexorcist.knoxactivator.R; /** * DISCLAIMER: PLEASE TAKE NOTE THAT THE SAMPLE APPLICATION AND * SOURCE CODE DESCRIBED HEREIN IS PROVIDED FOR TESTING PURPOSES ONLY. * <p/> * Samsung expressly disclaims any and all warranties of any kind, * whether express or implied, including but not limited to the implied warranties and conditions * of merchantability, fitness for a particular purpose and non-infringement. * Further, Samsung does not represent or warrant that any portion of the sample application and * source code is free of inaccuracies, errors, bugs or interruptions, or is reliable, * accurate, complete, or otherwise valid. The sample application and source code is provided * "as is" and "as available", without any warranty of any kind from Samsung. * <p/> * Your use of the sample application and source code is at its own discretion and risk, * and licensee will be solely responsible for any damage that results from the use of the sample * application and source code including, but not limited to, any damage to your computer system or * platform. For the purpose of clarity, the sample code is licensed “as is” and * licenses bears the risk of using it. * <p/> * Samsung shall not be liable for any direct, indirect or consequential damages or * costs of any type arising out of any action taken by you or others related to the sample application * and source code. */ package com.akexorcist.knoxactivator.receiver; //This BroadcastReceiver handles device admin activation and deactivation public class AdminActivationReceiver extends DeviceAdminReceiver { private static final long EVENT_LISTENER_DELAY = 500; @Override public void onEnabled(Context context, Intent intent) { } @Override public CharSequence onDisableRequested(Context context, Intent intent) { return context.getString(R.string.deactivate_device_admin_warning); } @Override public void onDisabled(Context context, Intent intent) { new Handler().postDelayed(new Runnable() { @Override public void run() {
KnoxActivationBus.getInstance().getBus().post(new AdminDeactivatedEvent());
akexorcist/Example-SamsungSDK
KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/GeofencingReceiver.java
// Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/BusProvider.java // public class BusProvider { // private static Bus bus; // // public static Bus getProvider() { // if (bus == null) { // bus = new Bus(); // } // return bus; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/InsideGeofenceEvent.java // public class InsideGeofenceEvent { // int[] geofenceIdList; // // public InsideGeofenceEvent() { // } // // public InsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/LocationUnavailableEvent.java // public class LocationUnavailableEvent { // // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/OutsideGeofenceEvent.java // public class OutsideGeofenceEvent { // int[] geofenceIdList; // // public OutsideGeofenceEvent() { // } // // public OutsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // }
import android.app.enterprise.geofencing.Geofence; import android.app.enterprise.geofencing.Geofencing; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.akexorcist.knoxgeofencingapp.bus.BusProvider; import com.akexorcist.knoxgeofencingapp.bus.event.InsideGeofenceEvent; import com.akexorcist.knoxgeofencingapp.bus.event.LocationUnavailableEvent; import com.akexorcist.knoxgeofencingapp.bus.event.OutsideGeofenceEvent;
package com.akexorcist.knoxgeofencingapp; /** * Created by Akexorcist on 5/10/16 AD. */ public class GeofencingReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equalsIgnoreCase(Geofencing.ACTION_DEVICE_INSIDE_GEOFENCE)) { int[] geofenceIdList = intent.getIntArrayExtra(Geofencing.INTENT_EXTRA_ID);
// Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/BusProvider.java // public class BusProvider { // private static Bus bus; // // public static Bus getProvider() { // if (bus == null) { // bus = new Bus(); // } // return bus; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/InsideGeofenceEvent.java // public class InsideGeofenceEvent { // int[] geofenceIdList; // // public InsideGeofenceEvent() { // } // // public InsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/LocationUnavailableEvent.java // public class LocationUnavailableEvent { // // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/OutsideGeofenceEvent.java // public class OutsideGeofenceEvent { // int[] geofenceIdList; // // public OutsideGeofenceEvent() { // } // // public OutsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // } // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/GeofencingReceiver.java import android.app.enterprise.geofencing.Geofence; import android.app.enterprise.geofencing.Geofencing; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.akexorcist.knoxgeofencingapp.bus.BusProvider; import com.akexorcist.knoxgeofencingapp.bus.event.InsideGeofenceEvent; import com.akexorcist.knoxgeofencingapp.bus.event.LocationUnavailableEvent; import com.akexorcist.knoxgeofencingapp.bus.event.OutsideGeofenceEvent; package com.akexorcist.knoxgeofencingapp; /** * Created by Akexorcist on 5/10/16 AD. */ public class GeofencingReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equalsIgnoreCase(Geofencing.ACTION_DEVICE_INSIDE_GEOFENCE)) { int[] geofenceIdList = intent.getIntArrayExtra(Geofencing.INTENT_EXTRA_ID);
BusProvider.getProvider().post(new InsideGeofenceEvent(geofenceIdList));
akexorcist/Example-SamsungSDK
KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/GeofencingReceiver.java
// Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/BusProvider.java // public class BusProvider { // private static Bus bus; // // public static Bus getProvider() { // if (bus == null) { // bus = new Bus(); // } // return bus; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/InsideGeofenceEvent.java // public class InsideGeofenceEvent { // int[] geofenceIdList; // // public InsideGeofenceEvent() { // } // // public InsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/LocationUnavailableEvent.java // public class LocationUnavailableEvent { // // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/OutsideGeofenceEvent.java // public class OutsideGeofenceEvent { // int[] geofenceIdList; // // public OutsideGeofenceEvent() { // } // // public OutsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // }
import android.app.enterprise.geofencing.Geofence; import android.app.enterprise.geofencing.Geofencing; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.akexorcist.knoxgeofencingapp.bus.BusProvider; import com.akexorcist.knoxgeofencingapp.bus.event.InsideGeofenceEvent; import com.akexorcist.knoxgeofencingapp.bus.event.LocationUnavailableEvent; import com.akexorcist.knoxgeofencingapp.bus.event.OutsideGeofenceEvent;
package com.akexorcist.knoxgeofencingapp; /** * Created by Akexorcist on 5/10/16 AD. */ public class GeofencingReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equalsIgnoreCase(Geofencing.ACTION_DEVICE_INSIDE_GEOFENCE)) { int[] geofenceIdList = intent.getIntArrayExtra(Geofencing.INTENT_EXTRA_ID);
// Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/BusProvider.java // public class BusProvider { // private static Bus bus; // // public static Bus getProvider() { // if (bus == null) { // bus = new Bus(); // } // return bus; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/InsideGeofenceEvent.java // public class InsideGeofenceEvent { // int[] geofenceIdList; // // public InsideGeofenceEvent() { // } // // public InsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/LocationUnavailableEvent.java // public class LocationUnavailableEvent { // // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/OutsideGeofenceEvent.java // public class OutsideGeofenceEvent { // int[] geofenceIdList; // // public OutsideGeofenceEvent() { // } // // public OutsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // } // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/GeofencingReceiver.java import android.app.enterprise.geofencing.Geofence; import android.app.enterprise.geofencing.Geofencing; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.akexorcist.knoxgeofencingapp.bus.BusProvider; import com.akexorcist.knoxgeofencingapp.bus.event.InsideGeofenceEvent; import com.akexorcist.knoxgeofencingapp.bus.event.LocationUnavailableEvent; import com.akexorcist.knoxgeofencingapp.bus.event.OutsideGeofenceEvent; package com.akexorcist.knoxgeofencingapp; /** * Created by Akexorcist on 5/10/16 AD. */ public class GeofencingReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equalsIgnoreCase(Geofencing.ACTION_DEVICE_INSIDE_GEOFENCE)) { int[] geofenceIdList = intent.getIntArrayExtra(Geofencing.INTENT_EXTRA_ID);
BusProvider.getProvider().post(new InsideGeofenceEvent(geofenceIdList));
akexorcist/Example-SamsungSDK
KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/GeofencingReceiver.java
// Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/BusProvider.java // public class BusProvider { // private static Bus bus; // // public static Bus getProvider() { // if (bus == null) { // bus = new Bus(); // } // return bus; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/InsideGeofenceEvent.java // public class InsideGeofenceEvent { // int[] geofenceIdList; // // public InsideGeofenceEvent() { // } // // public InsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/LocationUnavailableEvent.java // public class LocationUnavailableEvent { // // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/OutsideGeofenceEvent.java // public class OutsideGeofenceEvent { // int[] geofenceIdList; // // public OutsideGeofenceEvent() { // } // // public OutsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // }
import android.app.enterprise.geofencing.Geofence; import android.app.enterprise.geofencing.Geofencing; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.akexorcist.knoxgeofencingapp.bus.BusProvider; import com.akexorcist.knoxgeofencingapp.bus.event.InsideGeofenceEvent; import com.akexorcist.knoxgeofencingapp.bus.event.LocationUnavailableEvent; import com.akexorcist.knoxgeofencingapp.bus.event.OutsideGeofenceEvent;
package com.akexorcist.knoxgeofencingapp; /** * Created by Akexorcist on 5/10/16 AD. */ public class GeofencingReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equalsIgnoreCase(Geofencing.ACTION_DEVICE_INSIDE_GEOFENCE)) { int[] geofenceIdList = intent.getIntArrayExtra(Geofencing.INTENT_EXTRA_ID); BusProvider.getProvider().post(new InsideGeofenceEvent(geofenceIdList)); } else if (action.equalsIgnoreCase(Geofencing.ACTION_DEVICE_OUTSIDE_GEOFENCE)) { int[] geofenceIdList = intent.getIntArrayExtra(Geofencing.INTENT_EXTRA_ID);
// Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/BusProvider.java // public class BusProvider { // private static Bus bus; // // public static Bus getProvider() { // if (bus == null) { // bus = new Bus(); // } // return bus; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/InsideGeofenceEvent.java // public class InsideGeofenceEvent { // int[] geofenceIdList; // // public InsideGeofenceEvent() { // } // // public InsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/LocationUnavailableEvent.java // public class LocationUnavailableEvent { // // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/OutsideGeofenceEvent.java // public class OutsideGeofenceEvent { // int[] geofenceIdList; // // public OutsideGeofenceEvent() { // } // // public OutsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // } // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/GeofencingReceiver.java import android.app.enterprise.geofencing.Geofence; import android.app.enterprise.geofencing.Geofencing; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.akexorcist.knoxgeofencingapp.bus.BusProvider; import com.akexorcist.knoxgeofencingapp.bus.event.InsideGeofenceEvent; import com.akexorcist.knoxgeofencingapp.bus.event.LocationUnavailableEvent; import com.akexorcist.knoxgeofencingapp.bus.event.OutsideGeofenceEvent; package com.akexorcist.knoxgeofencingapp; /** * Created by Akexorcist on 5/10/16 AD. */ public class GeofencingReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equalsIgnoreCase(Geofencing.ACTION_DEVICE_INSIDE_GEOFENCE)) { int[] geofenceIdList = intent.getIntArrayExtra(Geofencing.INTENT_EXTRA_ID); BusProvider.getProvider().post(new InsideGeofenceEvent(geofenceIdList)); } else if (action.equalsIgnoreCase(Geofencing.ACTION_DEVICE_OUTSIDE_GEOFENCE)) { int[] geofenceIdList = intent.getIntArrayExtra(Geofencing.INTENT_EXTRA_ID);
BusProvider.getProvider().post(new OutsideGeofenceEvent(geofenceIdList));
akexorcist/Example-SamsungSDK
KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/GeofencingReceiver.java
// Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/BusProvider.java // public class BusProvider { // private static Bus bus; // // public static Bus getProvider() { // if (bus == null) { // bus = new Bus(); // } // return bus; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/InsideGeofenceEvent.java // public class InsideGeofenceEvent { // int[] geofenceIdList; // // public InsideGeofenceEvent() { // } // // public InsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/LocationUnavailableEvent.java // public class LocationUnavailableEvent { // // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/OutsideGeofenceEvent.java // public class OutsideGeofenceEvent { // int[] geofenceIdList; // // public OutsideGeofenceEvent() { // } // // public OutsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // }
import android.app.enterprise.geofencing.Geofence; import android.app.enterprise.geofencing.Geofencing; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.akexorcist.knoxgeofencingapp.bus.BusProvider; import com.akexorcist.knoxgeofencingapp.bus.event.InsideGeofenceEvent; import com.akexorcist.knoxgeofencingapp.bus.event.LocationUnavailableEvent; import com.akexorcist.knoxgeofencingapp.bus.event.OutsideGeofenceEvent;
package com.akexorcist.knoxgeofencingapp; /** * Created by Akexorcist on 5/10/16 AD. */ public class GeofencingReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equalsIgnoreCase(Geofencing.ACTION_DEVICE_INSIDE_GEOFENCE)) { int[] geofenceIdList = intent.getIntArrayExtra(Geofencing.INTENT_EXTRA_ID); BusProvider.getProvider().post(new InsideGeofenceEvent(geofenceIdList)); } else if (action.equalsIgnoreCase(Geofencing.ACTION_DEVICE_OUTSIDE_GEOFENCE)) { int[] geofenceIdList = intent.getIntArrayExtra(Geofencing.INTENT_EXTRA_ID); BusProvider.getProvider().post(new OutsideGeofenceEvent(geofenceIdList)); } else if (action.equalsIgnoreCase(Geofencing.ACTION_DEVICE_LOCATION_UNAVAILABLE)) {
// Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/BusProvider.java // public class BusProvider { // private static Bus bus; // // public static Bus getProvider() { // if (bus == null) { // bus = new Bus(); // } // return bus; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/InsideGeofenceEvent.java // public class InsideGeofenceEvent { // int[] geofenceIdList; // // public InsideGeofenceEvent() { // } // // public InsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/LocationUnavailableEvent.java // public class LocationUnavailableEvent { // // } // // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/bus/event/OutsideGeofenceEvent.java // public class OutsideGeofenceEvent { // int[] geofenceIdList; // // public OutsideGeofenceEvent() { // } // // public OutsideGeofenceEvent(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // // public int[] getGeofenceIdList() { // return geofenceIdList; // } // // public void setGeofenceIdList(int[] geofenceIdList) { // this.geofenceIdList = geofenceIdList; // } // } // Path: KNOXGeofencingApp/app/src/main/java/com/akexorcist/knoxgeofencingapp/GeofencingReceiver.java import android.app.enterprise.geofencing.Geofence; import android.app.enterprise.geofencing.Geofencing; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.akexorcist.knoxgeofencingapp.bus.BusProvider; import com.akexorcist.knoxgeofencingapp.bus.event.InsideGeofenceEvent; import com.akexorcist.knoxgeofencingapp.bus.event.LocationUnavailableEvent; import com.akexorcist.knoxgeofencingapp.bus.event.OutsideGeofenceEvent; package com.akexorcist.knoxgeofencingapp; /** * Created by Akexorcist on 5/10/16 AD. */ public class GeofencingReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equalsIgnoreCase(Geofencing.ACTION_DEVICE_INSIDE_GEOFENCE)) { int[] geofenceIdList = intent.getIntArrayExtra(Geofencing.INTENT_EXTRA_ID); BusProvider.getProvider().post(new InsideGeofenceEvent(geofenceIdList)); } else if (action.equalsIgnoreCase(Geofencing.ACTION_DEVICE_OUTSIDE_GEOFENCE)) { int[] geofenceIdList = intent.getIntArrayExtra(Geofencing.INTENT_EXTRA_ID); BusProvider.getProvider().post(new OutsideGeofenceEvent(geofenceIdList)); } else if (action.equalsIgnoreCase(Geofencing.ACTION_DEVICE_LOCATION_UNAVAILABLE)) {
BusProvider.getProvider().post(new LocationUnavailableEvent());
akexorcist/Example-SamsungSDK
KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/receiver/LicenseActivationReceiver.java
// Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/KnoxActivationBus.java // public class KnoxActivationBus { // private static KnoxActivationBus knoxActivationBus; // // public static KnoxActivationBus getInstance() { // if (knoxActivationBus == null) { // knoxActivationBus = new KnoxActivationBus(); // } // return knoxActivationBus; // } // // private Bus bus; // // public Bus getBus() { // if (bus == null) { // bus = new Bus(); // } // return bus; // } // } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/LicenseActivatedEvent.java // public class LicenseActivatedEvent { } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/LicenseActivationFailedEvent.java // public class LicenseActivationFailedEvent { // int errorType; // // public LicenseActivationFailedEvent(int errorType) { // this.errorType = errorType; // } // // public int getErrorType() { // return errorType; // } // }
import com.akexorcist.knoxactivator.event.LicenseActivatedEvent; import com.akexorcist.knoxactivator.event.LicenseActivationFailedEvent; import android.app.enterprise.license.EnterpriseLicenseManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Handler; import com.akexorcist.knoxactivator.KnoxActivationBus;
/** * DISCLAIMER: PLEASE TAKE NOTE THAT THE SAMPLE APPLICATION AND * SOURCE CODE DESCRIBED HEREIN IS PROVIDED FOR TESTING PURPOSES ONLY. * <p/> * Samsung expressly disclaims any and all warranties of any kind, * whether express or implied, including but not limited to the implied warranties and conditions * of merchantability, fitness for a particular purpose and non-infringement. * Further, Samsung does not represent or warrant that any portion of the sample application and * source code is free of inaccuracies, errors, bugs or interruptions, or is reliable, * accurate, complete, or otherwise valid. The sample application and source code is provided * "as is" and "as available", without any warranty of any kind from Samsung. * <p/> * Your use of the sample application and source code is at its own discretion and risk, * and licensee will be solely responsible for any damage that results from the use of the sample * application and source code including, but not limited to, any damage to your computer system or * platform. For the purpose of clarity, the sample code is licensed “as is” and * licenses bears the risk of using it. * <p/> * Samsung shall not be liable for any direct, indirect or consequential damages or * costs of any type arising out of any action taken by you or others related to the sample application * and source code. */ package com.akexorcist.knoxactivator.receiver; public class LicenseActivationReceiver extends BroadcastReceiver { private static final long EVENT_LISTENER_DELAY = 500; public LicenseActivationReceiver() { } @Override public void onReceive(Context context, Intent intent) { if (intent != null) { String action = intent.getAction(); if (action != null && action.equals(EnterpriseLicenseManager.ACTION_LICENSE_STATUS)) { int errorCode = intent.getIntExtra(EnterpriseLicenseManager.EXTRA_LICENSE_ERROR_CODE, EnterpriseLicenseManager.ERROR_UNKNOWN); if (errorCode == EnterpriseLicenseManager.ERROR_NONE) { onLicenseActivated(); } else { onLicenseActivationFailed(errorCode); } } } } private void onLicenseActivated() { new Handler().postDelayed(new Runnable() { @Override public void run() {
// Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/KnoxActivationBus.java // public class KnoxActivationBus { // private static KnoxActivationBus knoxActivationBus; // // public static KnoxActivationBus getInstance() { // if (knoxActivationBus == null) { // knoxActivationBus = new KnoxActivationBus(); // } // return knoxActivationBus; // } // // private Bus bus; // // public Bus getBus() { // if (bus == null) { // bus = new Bus(); // } // return bus; // } // } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/LicenseActivatedEvent.java // public class LicenseActivatedEvent { } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/LicenseActivationFailedEvent.java // public class LicenseActivationFailedEvent { // int errorType; // // public LicenseActivationFailedEvent(int errorType) { // this.errorType = errorType; // } // // public int getErrorType() { // return errorType; // } // } // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/receiver/LicenseActivationReceiver.java import com.akexorcist.knoxactivator.event.LicenseActivatedEvent; import com.akexorcist.knoxactivator.event.LicenseActivationFailedEvent; import android.app.enterprise.license.EnterpriseLicenseManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Handler; import com.akexorcist.knoxactivator.KnoxActivationBus; /** * DISCLAIMER: PLEASE TAKE NOTE THAT THE SAMPLE APPLICATION AND * SOURCE CODE DESCRIBED HEREIN IS PROVIDED FOR TESTING PURPOSES ONLY. * <p/> * Samsung expressly disclaims any and all warranties of any kind, * whether express or implied, including but not limited to the implied warranties and conditions * of merchantability, fitness for a particular purpose and non-infringement. * Further, Samsung does not represent or warrant that any portion of the sample application and * source code is free of inaccuracies, errors, bugs or interruptions, or is reliable, * accurate, complete, or otherwise valid. The sample application and source code is provided * "as is" and "as available", without any warranty of any kind from Samsung. * <p/> * Your use of the sample application and source code is at its own discretion and risk, * and licensee will be solely responsible for any damage that results from the use of the sample * application and source code including, but not limited to, any damage to your computer system or * platform. For the purpose of clarity, the sample code is licensed “as is” and * licenses bears the risk of using it. * <p/> * Samsung shall not be liable for any direct, indirect or consequential damages or * costs of any type arising out of any action taken by you or others related to the sample application * and source code. */ package com.akexorcist.knoxactivator.receiver; public class LicenseActivationReceiver extends BroadcastReceiver { private static final long EVENT_LISTENER_DELAY = 500; public LicenseActivationReceiver() { } @Override public void onReceive(Context context, Intent intent) { if (intent != null) { String action = intent.getAction(); if (action != null && action.equals(EnterpriseLicenseManager.ACTION_LICENSE_STATUS)) { int errorCode = intent.getIntExtra(EnterpriseLicenseManager.EXTRA_LICENSE_ERROR_CODE, EnterpriseLicenseManager.ERROR_UNKNOWN); if (errorCode == EnterpriseLicenseManager.ERROR_NONE) { onLicenseActivated(); } else { onLicenseActivationFailed(errorCode); } } } } private void onLicenseActivated() { new Handler().postDelayed(new Runnable() { @Override public void run() {
KnoxActivationBus.getInstance().getBus().post(new LicenseActivatedEvent());
akexorcist/Example-SamsungSDK
KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/receiver/LicenseActivationReceiver.java
// Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/KnoxActivationBus.java // public class KnoxActivationBus { // private static KnoxActivationBus knoxActivationBus; // // public static KnoxActivationBus getInstance() { // if (knoxActivationBus == null) { // knoxActivationBus = new KnoxActivationBus(); // } // return knoxActivationBus; // } // // private Bus bus; // // public Bus getBus() { // if (bus == null) { // bus = new Bus(); // } // return bus; // } // } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/LicenseActivatedEvent.java // public class LicenseActivatedEvent { } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/LicenseActivationFailedEvent.java // public class LicenseActivationFailedEvent { // int errorType; // // public LicenseActivationFailedEvent(int errorType) { // this.errorType = errorType; // } // // public int getErrorType() { // return errorType; // } // }
import com.akexorcist.knoxactivator.event.LicenseActivatedEvent; import com.akexorcist.knoxactivator.event.LicenseActivationFailedEvent; import android.app.enterprise.license.EnterpriseLicenseManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Handler; import com.akexorcist.knoxactivator.KnoxActivationBus;
/** * DISCLAIMER: PLEASE TAKE NOTE THAT THE SAMPLE APPLICATION AND * SOURCE CODE DESCRIBED HEREIN IS PROVIDED FOR TESTING PURPOSES ONLY. * <p/> * Samsung expressly disclaims any and all warranties of any kind, * whether express or implied, including but not limited to the implied warranties and conditions * of merchantability, fitness for a particular purpose and non-infringement. * Further, Samsung does not represent or warrant that any portion of the sample application and * source code is free of inaccuracies, errors, bugs or interruptions, or is reliable, * accurate, complete, or otherwise valid. The sample application and source code is provided * "as is" and "as available", without any warranty of any kind from Samsung. * <p/> * Your use of the sample application and source code is at its own discretion and risk, * and licensee will be solely responsible for any damage that results from the use of the sample * application and source code including, but not limited to, any damage to your computer system or * platform. For the purpose of clarity, the sample code is licensed “as is” and * licenses bears the risk of using it. * <p/> * Samsung shall not be liable for any direct, indirect or consequential damages or * costs of any type arising out of any action taken by you or others related to the sample application * and source code. */ package com.akexorcist.knoxactivator.receiver; public class LicenseActivationReceiver extends BroadcastReceiver { private static final long EVENT_LISTENER_DELAY = 500; public LicenseActivationReceiver() { } @Override public void onReceive(Context context, Intent intent) { if (intent != null) { String action = intent.getAction(); if (action != null && action.equals(EnterpriseLicenseManager.ACTION_LICENSE_STATUS)) { int errorCode = intent.getIntExtra(EnterpriseLicenseManager.EXTRA_LICENSE_ERROR_CODE, EnterpriseLicenseManager.ERROR_UNKNOWN); if (errorCode == EnterpriseLicenseManager.ERROR_NONE) { onLicenseActivated(); } else { onLicenseActivationFailed(errorCode); } } } } private void onLicenseActivated() { new Handler().postDelayed(new Runnable() { @Override public void run() {
// Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/KnoxActivationBus.java // public class KnoxActivationBus { // private static KnoxActivationBus knoxActivationBus; // // public static KnoxActivationBus getInstance() { // if (knoxActivationBus == null) { // knoxActivationBus = new KnoxActivationBus(); // } // return knoxActivationBus; // } // // private Bus bus; // // public Bus getBus() { // if (bus == null) { // bus = new Bus(); // } // return bus; // } // } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/LicenseActivatedEvent.java // public class LicenseActivatedEvent { } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/LicenseActivationFailedEvent.java // public class LicenseActivationFailedEvent { // int errorType; // // public LicenseActivationFailedEvent(int errorType) { // this.errorType = errorType; // } // // public int getErrorType() { // return errorType; // } // } // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/receiver/LicenseActivationReceiver.java import com.akexorcist.knoxactivator.event.LicenseActivatedEvent; import com.akexorcist.knoxactivator.event.LicenseActivationFailedEvent; import android.app.enterprise.license.EnterpriseLicenseManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Handler; import com.akexorcist.knoxactivator.KnoxActivationBus; /** * DISCLAIMER: PLEASE TAKE NOTE THAT THE SAMPLE APPLICATION AND * SOURCE CODE DESCRIBED HEREIN IS PROVIDED FOR TESTING PURPOSES ONLY. * <p/> * Samsung expressly disclaims any and all warranties of any kind, * whether express or implied, including but not limited to the implied warranties and conditions * of merchantability, fitness for a particular purpose and non-infringement. * Further, Samsung does not represent or warrant that any portion of the sample application and * source code is free of inaccuracies, errors, bugs or interruptions, or is reliable, * accurate, complete, or otherwise valid. The sample application and source code is provided * "as is" and "as available", without any warranty of any kind from Samsung. * <p/> * Your use of the sample application and source code is at its own discretion and risk, * and licensee will be solely responsible for any damage that results from the use of the sample * application and source code including, but not limited to, any damage to your computer system or * platform. For the purpose of clarity, the sample code is licensed “as is” and * licenses bears the risk of using it. * <p/> * Samsung shall not be liable for any direct, indirect or consequential damages or * costs of any type arising out of any action taken by you or others related to the sample application * and source code. */ package com.akexorcist.knoxactivator.receiver; public class LicenseActivationReceiver extends BroadcastReceiver { private static final long EVENT_LISTENER_DELAY = 500; public LicenseActivationReceiver() { } @Override public void onReceive(Context context, Intent intent) { if (intent != null) { String action = intent.getAction(); if (action != null && action.equals(EnterpriseLicenseManager.ACTION_LICENSE_STATUS)) { int errorCode = intent.getIntExtra(EnterpriseLicenseManager.EXTRA_LICENSE_ERROR_CODE, EnterpriseLicenseManager.ERROR_UNKNOWN); if (errorCode == EnterpriseLicenseManager.ERROR_NONE) { onLicenseActivated(); } else { onLicenseActivationFailed(errorCode); } } } } private void onLicenseActivated() { new Handler().postDelayed(new Runnable() { @Override public void run() {
KnoxActivationBus.getInstance().getBus().post(new LicenseActivatedEvent());
akexorcist/Example-SamsungSDK
KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/receiver/LicenseActivationReceiver.java
// Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/KnoxActivationBus.java // public class KnoxActivationBus { // private static KnoxActivationBus knoxActivationBus; // // public static KnoxActivationBus getInstance() { // if (knoxActivationBus == null) { // knoxActivationBus = new KnoxActivationBus(); // } // return knoxActivationBus; // } // // private Bus bus; // // public Bus getBus() { // if (bus == null) { // bus = new Bus(); // } // return bus; // } // } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/LicenseActivatedEvent.java // public class LicenseActivatedEvent { } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/LicenseActivationFailedEvent.java // public class LicenseActivationFailedEvent { // int errorType; // // public LicenseActivationFailedEvent(int errorType) { // this.errorType = errorType; // } // // public int getErrorType() { // return errorType; // } // }
import com.akexorcist.knoxactivator.event.LicenseActivatedEvent; import com.akexorcist.knoxactivator.event.LicenseActivationFailedEvent; import android.app.enterprise.license.EnterpriseLicenseManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Handler; import com.akexorcist.knoxactivator.KnoxActivationBus;
} @Override public void onReceive(Context context, Intent intent) { if (intent != null) { String action = intent.getAction(); if (action != null && action.equals(EnterpriseLicenseManager.ACTION_LICENSE_STATUS)) { int errorCode = intent.getIntExtra(EnterpriseLicenseManager.EXTRA_LICENSE_ERROR_CODE, EnterpriseLicenseManager.ERROR_UNKNOWN); if (errorCode == EnterpriseLicenseManager.ERROR_NONE) { onLicenseActivated(); } else { onLicenseActivationFailed(errorCode); } } } } private void onLicenseActivated() { new Handler().postDelayed(new Runnable() { @Override public void run() { KnoxActivationBus.getInstance().getBus().post(new LicenseActivatedEvent()); } }, EVENT_LISTENER_DELAY); } private void onLicenseActivationFailed(final int errorCode) { new Handler().postDelayed(new Runnable() { @Override public void run() {
// Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/KnoxActivationBus.java // public class KnoxActivationBus { // private static KnoxActivationBus knoxActivationBus; // // public static KnoxActivationBus getInstance() { // if (knoxActivationBus == null) { // knoxActivationBus = new KnoxActivationBus(); // } // return knoxActivationBus; // } // // private Bus bus; // // public Bus getBus() { // if (bus == null) { // bus = new Bus(); // } // return bus; // } // } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/LicenseActivatedEvent.java // public class LicenseActivatedEvent { } // // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/event/LicenseActivationFailedEvent.java // public class LicenseActivationFailedEvent { // int errorType; // // public LicenseActivationFailedEvent(int errorType) { // this.errorType = errorType; // } // // public int getErrorType() { // return errorType; // } // } // Path: KNOXSampleApp/knoxActivator/src/main/java/com/akexorcist/knoxactivator/receiver/LicenseActivationReceiver.java import com.akexorcist.knoxactivator.event.LicenseActivatedEvent; import com.akexorcist.knoxactivator.event.LicenseActivationFailedEvent; import android.app.enterprise.license.EnterpriseLicenseManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Handler; import com.akexorcist.knoxactivator.KnoxActivationBus; } @Override public void onReceive(Context context, Intent intent) { if (intent != null) { String action = intent.getAction(); if (action != null && action.equals(EnterpriseLicenseManager.ACTION_LICENSE_STATUS)) { int errorCode = intent.getIntExtra(EnterpriseLicenseManager.EXTRA_LICENSE_ERROR_CODE, EnterpriseLicenseManager.ERROR_UNKNOWN); if (errorCode == EnterpriseLicenseManager.ERROR_NONE) { onLicenseActivated(); } else { onLicenseActivationFailed(errorCode); } } } } private void onLicenseActivated() { new Handler().postDelayed(new Runnable() { @Override public void run() { KnoxActivationBus.getInstance().getBus().post(new LicenseActivatedEvent()); } }, EVENT_LISTENER_DELAY); } private void onLicenseActivationFailed(final int errorCode) { new Handler().postDelayed(new Runnable() { @Override public void run() {
KnoxActivationBus.getInstance().getBus().post(new LicenseActivationFailedEvent(errorCode));
akexorcist/Example-SamsungSDK
KNOXLSOApp/app/src/main/java/com/akexorcist/knoxlsoapp/DoSomethingActivity.java
// Path: KNOXLSOApp/app/src/main/java/com/akexorcist/knoxlsoapp/manager/FileAssetManager.java // public class FileAssetManager { // public static void copyFileFromAssetToStorage(Context context, String assetFilePath, String filePath) { // InputStream in = null; // OutputStream out = null; // try { // in = context.getAssets().open(assetFilePath); // File outFile = new File(filePath); // out = new FileOutputStream(outFile); // copyFile(in, out); // } catch (IOException e) { // Log.e("tag", "Failed to copy asset file: " + assetFilePath, e); // } finally { // if (in != null) { // try { // in.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // if (out != null) { // try { // out.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // } // // private static void copyFile(InputStream in, OutputStream out) throws IOException { // byte[] buffer = new byte[1024]; // int read; // while ((read = in.read(buffer)) != -1) { // out.write(buffer, 0, read); // } // } // }
import android.app.enterprise.lso.LockscreenOverlay; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import com.akexorcist.knoxlsoapp.manager.FileAssetManager;
package com.akexorcist.knoxlsoapp; public class DoSomethingActivity extends AppCompatActivity implements View.OnClickListener { private String logoFileName = "akexorcist_logo.png"; private Button btnSetCustomLSO; private Button btnClearCustomLSO; private LockscreenOverlay lso; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_do_something); bindView(); setupView(); setupThing(); } private void bindView() { btnSetCustomLSO = (Button) findViewById(R.id.btn_set_custom_lso); btnClearCustomLSO = (Button) findViewById(R.id.btn_clear_custom_lso); } private void setupView() { btnSetCustomLSO.setOnClickListener(this); btnClearCustomLSO.setOnClickListener(this); } private void setupThing() {
// Path: KNOXLSOApp/app/src/main/java/com/akexorcist/knoxlsoapp/manager/FileAssetManager.java // public class FileAssetManager { // public static void copyFileFromAssetToStorage(Context context, String assetFilePath, String filePath) { // InputStream in = null; // OutputStream out = null; // try { // in = context.getAssets().open(assetFilePath); // File outFile = new File(filePath); // out = new FileOutputStream(outFile); // copyFile(in, out); // } catch (IOException e) { // Log.e("tag", "Failed to copy asset file: " + assetFilePath, e); // } finally { // if (in != null) { // try { // in.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // if (out != null) { // try { // out.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // } // // private static void copyFile(InputStream in, OutputStream out) throws IOException { // byte[] buffer = new byte[1024]; // int read; // while ((read = in.read(buffer)) != -1) { // out.write(buffer, 0, read); // } // } // } // Path: KNOXLSOApp/app/src/main/java/com/akexorcist/knoxlsoapp/DoSomethingActivity.java import android.app.enterprise.lso.LockscreenOverlay; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import com.akexorcist.knoxlsoapp.manager.FileAssetManager; package com.akexorcist.knoxlsoapp; public class DoSomethingActivity extends AppCompatActivity implements View.OnClickListener { private String logoFileName = "akexorcist_logo.png"; private Button btnSetCustomLSO; private Button btnClearCustomLSO; private LockscreenOverlay lso; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_do_something); bindView(); setupView(); setupThing(); } private void bindView() { btnSetCustomLSO = (Button) findViewById(R.id.btn_set_custom_lso); btnClearCustomLSO = (Button) findViewById(R.id.btn_clear_custom_lso); } private void setupView() { btnSetCustomLSO.setOnClickListener(this); btnClearCustomLSO.setOnClickListener(this); } private void setupThing() {
FileAssetManager.copyFileFromAssetToStorage(this, logoFileName, getFilesDir().getAbsolutePath() + logoFileName);
jferrater/Tap-And-Eat-MicroServices
AccountService/src/main/java/com/github/joffryferrater/accountservice/AccountServiceApplication.java
// Path: AccountService/src/main/java/com/github/joffryferrater/accountservice/models/Account.java // @Entity // @Table(name = "users") // @Data // @RequiredArgsConstructor // public class Account { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // @NotNull // @JsonProperty("Email") // private final String email; // @JsonProperty("First Name") // private final String firstName; // @JsonProperty("Last Name") // private final String lastName; // @JsonProperty("Country Code") // private final String countryCode; // @JsonProperty("Phone Number") // private final String phoneNumber; // // @JsonIgnore // private final String password; // // // } // // Path: AccountService/src/main/java/com/github/joffryferrater/accountservice/models/AccountRepository.java // @RepositoryRestResource(path="accounts", collectionResourceRel="accounts") // public interface AccountRepository extends CrudRepository<Account, Long>{ // // Account findByEmail(@Param("email") String email); // // Account findByFirstName(@Param("firstName") String firstName); // // Account findByLastName(@Param("lastName") String lastName); // // // }
import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import com.github.joffryferrater.accountservice.models.Account; import com.github.joffryferrater.accountservice.models.AccountRepository;
package com.github.joffryferrater.accountservice; /** * * @author Joffry Ferrater * */ @SpringBootApplication @EnableDiscoveryClient public class AccountServiceApplication { public static void main(String[] args) { SpringApplication.run(AccountServiceApplication.class, args); } @Autowired
// Path: AccountService/src/main/java/com/github/joffryferrater/accountservice/models/Account.java // @Entity // @Table(name = "users") // @Data // @RequiredArgsConstructor // public class Account { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // @NotNull // @JsonProperty("Email") // private final String email; // @JsonProperty("First Name") // private final String firstName; // @JsonProperty("Last Name") // private final String lastName; // @JsonProperty("Country Code") // private final String countryCode; // @JsonProperty("Phone Number") // private final String phoneNumber; // // @JsonIgnore // private final String password; // // // } // // Path: AccountService/src/main/java/com/github/joffryferrater/accountservice/models/AccountRepository.java // @RepositoryRestResource(path="accounts", collectionResourceRel="accounts") // public interface AccountRepository extends CrudRepository<Account, Long>{ // // Account findByEmail(@Param("email") String email); // // Account findByFirstName(@Param("firstName") String firstName); // // Account findByLastName(@Param("lastName") String lastName); // // // } // Path: AccountService/src/main/java/com/github/joffryferrater/accountservice/AccountServiceApplication.java import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import com.github.joffryferrater.accountservice.models.Account; import com.github.joffryferrater.accountservice.models.AccountRepository; package com.github.joffryferrater.accountservice; /** * * @author Joffry Ferrater * */ @SpringBootApplication @EnableDiscoveryClient public class AccountServiceApplication { public static void main(String[] args) { SpringApplication.run(AccountServiceApplication.class, args); } @Autowired
AccountRepository accountRepo;
jferrater/Tap-And-Eat-MicroServices
AccountService/src/main/java/com/github/joffryferrater/accountservice/AccountServiceApplication.java
// Path: AccountService/src/main/java/com/github/joffryferrater/accountservice/models/Account.java // @Entity // @Table(name = "users") // @Data // @RequiredArgsConstructor // public class Account { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // @NotNull // @JsonProperty("Email") // private final String email; // @JsonProperty("First Name") // private final String firstName; // @JsonProperty("Last Name") // private final String lastName; // @JsonProperty("Country Code") // private final String countryCode; // @JsonProperty("Phone Number") // private final String phoneNumber; // // @JsonIgnore // private final String password; // // // } // // Path: AccountService/src/main/java/com/github/joffryferrater/accountservice/models/AccountRepository.java // @RepositoryRestResource(path="accounts", collectionResourceRel="accounts") // public interface AccountRepository extends CrudRepository<Account, Long>{ // // Account findByEmail(@Param("email") String email); // // Account findByFirstName(@Param("firstName") String firstName); // // Account findByLastName(@Param("lastName") String lastName); // // // }
import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import com.github.joffryferrater.accountservice.models.Account; import com.github.joffryferrater.accountservice.models.AccountRepository;
package com.github.joffryferrater.accountservice; /** * * @author Joffry Ferrater * */ @SpringBootApplication @EnableDiscoveryClient public class AccountServiceApplication { public static void main(String[] args) { SpringApplication.run(AccountServiceApplication.class, args); } @Autowired AccountRepository accountRepo; @PostConstruct public void init() {
// Path: AccountService/src/main/java/com/github/joffryferrater/accountservice/models/Account.java // @Entity // @Table(name = "users") // @Data // @RequiredArgsConstructor // public class Account { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Long id; // @NotNull // @JsonProperty("Email") // private final String email; // @JsonProperty("First Name") // private final String firstName; // @JsonProperty("Last Name") // private final String lastName; // @JsonProperty("Country Code") // private final String countryCode; // @JsonProperty("Phone Number") // private final String phoneNumber; // // @JsonIgnore // private final String password; // // // } // // Path: AccountService/src/main/java/com/github/joffryferrater/accountservice/models/AccountRepository.java // @RepositoryRestResource(path="accounts", collectionResourceRel="accounts") // public interface AccountRepository extends CrudRepository<Account, Long>{ // // Account findByEmail(@Param("email") String email); // // Account findByFirstName(@Param("firstName") String firstName); // // Account findByLastName(@Param("lastName") String lastName); // // // } // Path: AccountService/src/main/java/com/github/joffryferrater/accountservice/AccountServiceApplication.java import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import com.github.joffryferrater.accountservice.models.Account; import com.github.joffryferrater.accountservice.models.AccountRepository; package com.github.joffryferrater.accountservice; /** * * @author Joffry Ferrater * */ @SpringBootApplication @EnableDiscoveryClient public class AccountServiceApplication { public static void main(String[] args) { SpringApplication.run(AccountServiceApplication.class, args); } @Autowired AccountRepository accountRepo; @PostConstruct public void init() {
Account account = new Account("joffry.ferrater@gmail.com", "Joffry", "Ferrater",
jferrater/Tap-And-Eat-MicroServices
FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/PriceServiceRepository.java
// Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/Price.java // @lombok.Getter // public class Price { // // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Price") // private String price; // // public Price(){ // super(); // } // // public Price(String itemCode, String price) { // this(); // this.itemCode = itemCode; // this.price = price; // } // // }
import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.github.joffryferrater.foodtrayservice.domain.Price;
package com.github.joffryferrater.foodtrayservice.repository; /** * * @author Joffry Ferrater * */ @FeignClient(value="PRICE-SERVICE", fallback=PriceServiceRepository.class) public interface PriceServiceRepository { @RequestMapping(method=RequestMethod.GET, value="/prices/search/findByItemCode?itemCode={itemCode}")
// Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/Price.java // @lombok.Getter // public class Price { // // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Price") // private String price; // // public Price(){ // super(); // } // // public Price(String itemCode, String price) { // this(); // this.itemCode = itemCode; // this.price = price; // } // // } // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/PriceServiceRepository.java import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.github.joffryferrater.foodtrayservice.domain.Price; package com.github.joffryferrater.foodtrayservice.repository; /** * * @author Joffry Ferrater * */ @FeignClient(value="PRICE-SERVICE", fallback=PriceServiceRepository.class) public interface PriceServiceRepository { @RequestMapping(method=RequestMethod.GET, value="/prices/search/findByItemCode?itemCode={itemCode}")
Price findByItemCode(@PathVariable("itemCode") String itemCode);
jferrater/Tap-And-Eat-MicroServices
ItemService/src/main/java/com/github/joffryferrater/itemservice/ItemServiceApplication.java
// Path: ItemService/src/main/java/com/github/joffryferrater/itemservice/models/Item.java // @Entity // @Table(name = "items") // @Data // public class Item { // // @Id // @GeneratedValue(strategy=GenerationType.AUTO) // private Long id; // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Name") // private String name; // // public Item() { // super(); // } // // public Item(String itemCode, String name) { // this(); // this.itemCode = itemCode; // this.name = name; // } // // } // // Path: ItemService/src/main/java/com/github/joffryferrater/itemservice/models/ItemRepository.java // @RepositoryRestResource(path="items", collectionResourceRel="items") // public interface ItemRepository extends CrudRepository<Item, Long>{ // // Item findByItemCode(@Param("itemCode")String itemCode); // // List<Item> findByName(@Param("name") String name); // }
import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import com.github.joffryferrater.itemservice.models.Item; import com.github.joffryferrater.itemservice.models.ItemRepository;
package com.github.joffryferrater.itemservice; /** * * @author Joffry Ferrater * */ @SpringBootApplication @EnableDiscoveryClient public class ItemServiceApplication { public static void main(String[] args) { SpringApplication.run(ItemServiceApplication.class, args); } @Autowired
// Path: ItemService/src/main/java/com/github/joffryferrater/itemservice/models/Item.java // @Entity // @Table(name = "items") // @Data // public class Item { // // @Id // @GeneratedValue(strategy=GenerationType.AUTO) // private Long id; // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Name") // private String name; // // public Item() { // super(); // } // // public Item(String itemCode, String name) { // this(); // this.itemCode = itemCode; // this.name = name; // } // // } // // Path: ItemService/src/main/java/com/github/joffryferrater/itemservice/models/ItemRepository.java // @RepositoryRestResource(path="items", collectionResourceRel="items") // public interface ItemRepository extends CrudRepository<Item, Long>{ // // Item findByItemCode(@Param("itemCode")String itemCode); // // List<Item> findByName(@Param("name") String name); // } // Path: ItemService/src/main/java/com/github/joffryferrater/itemservice/ItemServiceApplication.java import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import com.github.joffryferrater.itemservice.models.Item; import com.github.joffryferrater.itemservice.models.ItemRepository; package com.github.joffryferrater.itemservice; /** * * @author Joffry Ferrater * */ @SpringBootApplication @EnableDiscoveryClient public class ItemServiceApplication { public static void main(String[] args) { SpringApplication.run(ItemServiceApplication.class, args); } @Autowired
ItemRepository itemRepository;
jferrater/Tap-And-Eat-MicroServices
ItemService/src/main/java/com/github/joffryferrater/itemservice/ItemServiceApplication.java
// Path: ItemService/src/main/java/com/github/joffryferrater/itemservice/models/Item.java // @Entity // @Table(name = "items") // @Data // public class Item { // // @Id // @GeneratedValue(strategy=GenerationType.AUTO) // private Long id; // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Name") // private String name; // // public Item() { // super(); // } // // public Item(String itemCode, String name) { // this(); // this.itemCode = itemCode; // this.name = name; // } // // } // // Path: ItemService/src/main/java/com/github/joffryferrater/itemservice/models/ItemRepository.java // @RepositoryRestResource(path="items", collectionResourceRel="items") // public interface ItemRepository extends CrudRepository<Item, Long>{ // // Item findByItemCode(@Param("itemCode")String itemCode); // // List<Item> findByName(@Param("name") String name); // }
import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import com.github.joffryferrater.itemservice.models.Item; import com.github.joffryferrater.itemservice.models.ItemRepository;
package com.github.joffryferrater.itemservice; /** * * @author Joffry Ferrater * */ @SpringBootApplication @EnableDiscoveryClient public class ItemServiceApplication { public static void main(String[] args) { SpringApplication.run(ItemServiceApplication.class, args); } @Autowired ItemRepository itemRepository; @PostConstruct public void init() {
// Path: ItemService/src/main/java/com/github/joffryferrater/itemservice/models/Item.java // @Entity // @Table(name = "items") // @Data // public class Item { // // @Id // @GeneratedValue(strategy=GenerationType.AUTO) // private Long id; // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Name") // private String name; // // public Item() { // super(); // } // // public Item(String itemCode, String name) { // this(); // this.itemCode = itemCode; // this.name = name; // } // // } // // Path: ItemService/src/main/java/com/github/joffryferrater/itemservice/models/ItemRepository.java // @RepositoryRestResource(path="items", collectionResourceRel="items") // public interface ItemRepository extends CrudRepository<Item, Long>{ // // Item findByItemCode(@Param("itemCode")String itemCode); // // List<Item> findByName(@Param("name") String name); // } // Path: ItemService/src/main/java/com/github/joffryferrater/itemservice/ItemServiceApplication.java import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import com.github.joffryferrater.itemservice.models.Item; import com.github.joffryferrater.itemservice.models.ItemRepository; package com.github.joffryferrater.itemservice; /** * * @author Joffry Ferrater * */ @SpringBootApplication @EnableDiscoveryClient public class ItemServiceApplication { public static void main(String[] args) { SpringApplication.run(ItemServiceApplication.class, args); } @Autowired ItemRepository itemRepository; @PostConstruct public void init() {
List<Item> items = new ArrayList<Item>();
jferrater/Tap-And-Eat-MicroServices
FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/FoodTrayServiceApplication.java
// Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/ItemServiceRepository.java // @FeignClient(value="ITEM-SERVICE", fallback=ItemServiceFallback.class) // public interface ItemServiceRepository { // // @RequestMapping(method=RequestMethod.GET, value="/items/search/findByItemCode?itemCode={itemCode}") // Item findByItemCode(@PathVariable("itemCode") String itemCode); // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/PriceServiceRepository.java // @FeignClient(value="PRICE-SERVICE", fallback=PriceServiceRepository.class) // public interface PriceServiceRepository { // // @RequestMapping(method=RequestMethod.GET, value="/prices/search/findByItemCode?itemCode={itemCode}") // Price findByItemCode(@PathVariable("itemCode") String itemCode); // }
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.feign.EnableFeignClients; import org.springframework.cloud.netflix.hystrix.EnableHystrix; import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard; import org.springframework.context.annotation.ComponentScan; import com.github.joffryferrater.foodtrayservice.repository.ItemServiceRepository; import com.github.joffryferrater.foodtrayservice.repository.PriceServiceRepository;
package com.github.joffryferrater.foodtrayservice; @SpringBootApplication @EnableDiscoveryClient @EnableCircuitBreaker @EnableHystrixDashboard @EnableHystrix //@EnableFeignClients
// Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/ItemServiceRepository.java // @FeignClient(value="ITEM-SERVICE", fallback=ItemServiceFallback.class) // public interface ItemServiceRepository { // // @RequestMapping(method=RequestMethod.GET, value="/items/search/findByItemCode?itemCode={itemCode}") // Item findByItemCode(@PathVariable("itemCode") String itemCode); // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/PriceServiceRepository.java // @FeignClient(value="PRICE-SERVICE", fallback=PriceServiceRepository.class) // public interface PriceServiceRepository { // // @RequestMapping(method=RequestMethod.GET, value="/prices/search/findByItemCode?itemCode={itemCode}") // Price findByItemCode(@PathVariable("itemCode") String itemCode); // } // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/FoodTrayServiceApplication.java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.feign.EnableFeignClients; import org.springframework.cloud.netflix.hystrix.EnableHystrix; import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard; import org.springframework.context.annotation.ComponentScan; import com.github.joffryferrater.foodtrayservice.repository.ItemServiceRepository; import com.github.joffryferrater.foodtrayservice.repository.PriceServiceRepository; package com.github.joffryferrater.foodtrayservice; @SpringBootApplication @EnableDiscoveryClient @EnableCircuitBreaker @EnableHystrixDashboard @EnableHystrix //@EnableFeignClients
@EnableFeignClients(basePackageClasses = {ItemServiceRepository.class, PriceServiceRepository.class})
jferrater/Tap-And-Eat-MicroServices
FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/FoodTrayServiceApplication.java
// Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/ItemServiceRepository.java // @FeignClient(value="ITEM-SERVICE", fallback=ItemServiceFallback.class) // public interface ItemServiceRepository { // // @RequestMapping(method=RequestMethod.GET, value="/items/search/findByItemCode?itemCode={itemCode}") // Item findByItemCode(@PathVariable("itemCode") String itemCode); // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/PriceServiceRepository.java // @FeignClient(value="PRICE-SERVICE", fallback=PriceServiceRepository.class) // public interface PriceServiceRepository { // // @RequestMapping(method=RequestMethod.GET, value="/prices/search/findByItemCode?itemCode={itemCode}") // Price findByItemCode(@PathVariable("itemCode") String itemCode); // }
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.feign.EnableFeignClients; import org.springframework.cloud.netflix.hystrix.EnableHystrix; import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard; import org.springframework.context.annotation.ComponentScan; import com.github.joffryferrater.foodtrayservice.repository.ItemServiceRepository; import com.github.joffryferrater.foodtrayservice.repository.PriceServiceRepository;
package com.github.joffryferrater.foodtrayservice; @SpringBootApplication @EnableDiscoveryClient @EnableCircuitBreaker @EnableHystrixDashboard @EnableHystrix //@EnableFeignClients
// Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/ItemServiceRepository.java // @FeignClient(value="ITEM-SERVICE", fallback=ItemServiceFallback.class) // public interface ItemServiceRepository { // // @RequestMapping(method=RequestMethod.GET, value="/items/search/findByItemCode?itemCode={itemCode}") // Item findByItemCode(@PathVariable("itemCode") String itemCode); // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/PriceServiceRepository.java // @FeignClient(value="PRICE-SERVICE", fallback=PriceServiceRepository.class) // public interface PriceServiceRepository { // // @RequestMapping(method=RequestMethod.GET, value="/prices/search/findByItemCode?itemCode={itemCode}") // Price findByItemCode(@PathVariable("itemCode") String itemCode); // } // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/FoodTrayServiceApplication.java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.feign.EnableFeignClients; import org.springframework.cloud.netflix.hystrix.EnableHystrix; import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard; import org.springframework.context.annotation.ComponentScan; import com.github.joffryferrater.foodtrayservice.repository.ItemServiceRepository; import com.github.joffryferrater.foodtrayservice.repository.PriceServiceRepository; package com.github.joffryferrater.foodtrayservice; @SpringBootApplication @EnableDiscoveryClient @EnableCircuitBreaker @EnableHystrixDashboard @EnableHystrix //@EnableFeignClients
@EnableFeignClients(basePackageClasses = {ItemServiceRepository.class, PriceServiceRepository.class})
jferrater/Tap-And-Eat-MicroServices
FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/FoodTrayController.java
// Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/Item.java // @lombok.Getter // public class Item { // // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Name") // private String name; // // public Item() { // super(); // } // // public Item(String itemCode, String name) { // this.itemCode = itemCode; // this.name = name; // } // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/Price.java // @lombok.Getter // public class Price { // // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Price") // private String price; // // public Price(){ // super(); // } // // public Price(String itemCode, String price) { // this(); // this.itemCode = itemCode; // this.price = price; // } // // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/TrayItem.java // public class TrayItem { // // @JsonProperty("Name") // private String name; // @JsonProperty("Price") // private String amount; // // // public TrayItem() { // super(); // } // // public TrayItem(String name, String amount) { // this.name = name; // this.amount = amount; // } // // public String getName() { // return name; // } // // public String getAmount() { // return amount; // } // // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/ItemServiceRepository.java // @FeignClient(value="ITEM-SERVICE", fallback=ItemServiceFallback.class) // public interface ItemServiceRepository { // // @RequestMapping(method=RequestMethod.GET, value="/items/search/findByItemCode?itemCode={itemCode}") // Item findByItemCode(@PathVariable("itemCode") String itemCode); // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/PriceServiceRepository.java // @FeignClient(value="PRICE-SERVICE", fallback=PriceServiceRepository.class) // public interface PriceServiceRepository { // // @RequestMapping(method=RequestMethod.GET, value="/prices/search/findByItemCode?itemCode={itemCode}") // Price findByItemCode(@PathVariable("itemCode") String itemCode); // }
import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.github.joffryferrater.foodtrayservice.domain.Item; import com.github.joffryferrater.foodtrayservice.domain.Price; import com.github.joffryferrater.foodtrayservice.domain.TrayItem; import com.github.joffryferrater.foodtrayservice.repository.ItemServiceRepository; import com.github.joffryferrater.foodtrayservice.repository.PriceServiceRepository;
package com.github.joffryferrater.foodtrayservice; /** * * @author Joffry Ferrater * */ @RestController @RequestMapping("/foodtrays") public class FoodTrayController { @Autowired
// Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/Item.java // @lombok.Getter // public class Item { // // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Name") // private String name; // // public Item() { // super(); // } // // public Item(String itemCode, String name) { // this.itemCode = itemCode; // this.name = name; // } // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/Price.java // @lombok.Getter // public class Price { // // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Price") // private String price; // // public Price(){ // super(); // } // // public Price(String itemCode, String price) { // this(); // this.itemCode = itemCode; // this.price = price; // } // // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/TrayItem.java // public class TrayItem { // // @JsonProperty("Name") // private String name; // @JsonProperty("Price") // private String amount; // // // public TrayItem() { // super(); // } // // public TrayItem(String name, String amount) { // this.name = name; // this.amount = amount; // } // // public String getName() { // return name; // } // // public String getAmount() { // return amount; // } // // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/ItemServiceRepository.java // @FeignClient(value="ITEM-SERVICE", fallback=ItemServiceFallback.class) // public interface ItemServiceRepository { // // @RequestMapping(method=RequestMethod.GET, value="/items/search/findByItemCode?itemCode={itemCode}") // Item findByItemCode(@PathVariable("itemCode") String itemCode); // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/PriceServiceRepository.java // @FeignClient(value="PRICE-SERVICE", fallback=PriceServiceRepository.class) // public interface PriceServiceRepository { // // @RequestMapping(method=RequestMethod.GET, value="/prices/search/findByItemCode?itemCode={itemCode}") // Price findByItemCode(@PathVariable("itemCode") String itemCode); // } // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/FoodTrayController.java import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.github.joffryferrater.foodtrayservice.domain.Item; import com.github.joffryferrater.foodtrayservice.domain.Price; import com.github.joffryferrater.foodtrayservice.domain.TrayItem; import com.github.joffryferrater.foodtrayservice.repository.ItemServiceRepository; import com.github.joffryferrater.foodtrayservice.repository.PriceServiceRepository; package com.github.joffryferrater.foodtrayservice; /** * * @author Joffry Ferrater * */ @RestController @RequestMapping("/foodtrays") public class FoodTrayController { @Autowired
ItemServiceRepository itemServiceRepository;
jferrater/Tap-And-Eat-MicroServices
FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/FoodTrayController.java
// Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/Item.java // @lombok.Getter // public class Item { // // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Name") // private String name; // // public Item() { // super(); // } // // public Item(String itemCode, String name) { // this.itemCode = itemCode; // this.name = name; // } // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/Price.java // @lombok.Getter // public class Price { // // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Price") // private String price; // // public Price(){ // super(); // } // // public Price(String itemCode, String price) { // this(); // this.itemCode = itemCode; // this.price = price; // } // // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/TrayItem.java // public class TrayItem { // // @JsonProperty("Name") // private String name; // @JsonProperty("Price") // private String amount; // // // public TrayItem() { // super(); // } // // public TrayItem(String name, String amount) { // this.name = name; // this.amount = amount; // } // // public String getName() { // return name; // } // // public String getAmount() { // return amount; // } // // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/ItemServiceRepository.java // @FeignClient(value="ITEM-SERVICE", fallback=ItemServiceFallback.class) // public interface ItemServiceRepository { // // @RequestMapping(method=RequestMethod.GET, value="/items/search/findByItemCode?itemCode={itemCode}") // Item findByItemCode(@PathVariable("itemCode") String itemCode); // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/PriceServiceRepository.java // @FeignClient(value="PRICE-SERVICE", fallback=PriceServiceRepository.class) // public interface PriceServiceRepository { // // @RequestMapping(method=RequestMethod.GET, value="/prices/search/findByItemCode?itemCode={itemCode}") // Price findByItemCode(@PathVariable("itemCode") String itemCode); // }
import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.github.joffryferrater.foodtrayservice.domain.Item; import com.github.joffryferrater.foodtrayservice.domain.Price; import com.github.joffryferrater.foodtrayservice.domain.TrayItem; import com.github.joffryferrater.foodtrayservice.repository.ItemServiceRepository; import com.github.joffryferrater.foodtrayservice.repository.PriceServiceRepository;
package com.github.joffryferrater.foodtrayservice; /** * * @author Joffry Ferrater * */ @RestController @RequestMapping("/foodtrays") public class FoodTrayController { @Autowired ItemServiceRepository itemServiceRepository; @Autowired
// Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/Item.java // @lombok.Getter // public class Item { // // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Name") // private String name; // // public Item() { // super(); // } // // public Item(String itemCode, String name) { // this.itemCode = itemCode; // this.name = name; // } // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/Price.java // @lombok.Getter // public class Price { // // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Price") // private String price; // // public Price(){ // super(); // } // // public Price(String itemCode, String price) { // this(); // this.itemCode = itemCode; // this.price = price; // } // // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/TrayItem.java // public class TrayItem { // // @JsonProperty("Name") // private String name; // @JsonProperty("Price") // private String amount; // // // public TrayItem() { // super(); // } // // public TrayItem(String name, String amount) { // this.name = name; // this.amount = amount; // } // // public String getName() { // return name; // } // // public String getAmount() { // return amount; // } // // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/ItemServiceRepository.java // @FeignClient(value="ITEM-SERVICE", fallback=ItemServiceFallback.class) // public interface ItemServiceRepository { // // @RequestMapping(method=RequestMethod.GET, value="/items/search/findByItemCode?itemCode={itemCode}") // Item findByItemCode(@PathVariable("itemCode") String itemCode); // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/PriceServiceRepository.java // @FeignClient(value="PRICE-SERVICE", fallback=PriceServiceRepository.class) // public interface PriceServiceRepository { // // @RequestMapping(method=RequestMethod.GET, value="/prices/search/findByItemCode?itemCode={itemCode}") // Price findByItemCode(@PathVariable("itemCode") String itemCode); // } // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/FoodTrayController.java import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.github.joffryferrater.foodtrayservice.domain.Item; import com.github.joffryferrater.foodtrayservice.domain.Price; import com.github.joffryferrater.foodtrayservice.domain.TrayItem; import com.github.joffryferrater.foodtrayservice.repository.ItemServiceRepository; import com.github.joffryferrater.foodtrayservice.repository.PriceServiceRepository; package com.github.joffryferrater.foodtrayservice; /** * * @author Joffry Ferrater * */ @RestController @RequestMapping("/foodtrays") public class FoodTrayController { @Autowired ItemServiceRepository itemServiceRepository; @Autowired
PriceServiceRepository priceServiceRepo;
jferrater/Tap-And-Eat-MicroServices
FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/FoodTrayController.java
// Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/Item.java // @lombok.Getter // public class Item { // // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Name") // private String name; // // public Item() { // super(); // } // // public Item(String itemCode, String name) { // this.itemCode = itemCode; // this.name = name; // } // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/Price.java // @lombok.Getter // public class Price { // // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Price") // private String price; // // public Price(){ // super(); // } // // public Price(String itemCode, String price) { // this(); // this.itemCode = itemCode; // this.price = price; // } // // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/TrayItem.java // public class TrayItem { // // @JsonProperty("Name") // private String name; // @JsonProperty("Price") // private String amount; // // // public TrayItem() { // super(); // } // // public TrayItem(String name, String amount) { // this.name = name; // this.amount = amount; // } // // public String getName() { // return name; // } // // public String getAmount() { // return amount; // } // // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/ItemServiceRepository.java // @FeignClient(value="ITEM-SERVICE", fallback=ItemServiceFallback.class) // public interface ItemServiceRepository { // // @RequestMapping(method=RequestMethod.GET, value="/items/search/findByItemCode?itemCode={itemCode}") // Item findByItemCode(@PathVariable("itemCode") String itemCode); // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/PriceServiceRepository.java // @FeignClient(value="PRICE-SERVICE", fallback=PriceServiceRepository.class) // public interface PriceServiceRepository { // // @RequestMapping(method=RequestMethod.GET, value="/prices/search/findByItemCode?itemCode={itemCode}") // Price findByItemCode(@PathVariable("itemCode") String itemCode); // }
import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.github.joffryferrater.foodtrayservice.domain.Item; import com.github.joffryferrater.foodtrayservice.domain.Price; import com.github.joffryferrater.foodtrayservice.domain.TrayItem; import com.github.joffryferrater.foodtrayservice.repository.ItemServiceRepository; import com.github.joffryferrater.foodtrayservice.repository.PriceServiceRepository;
package com.github.joffryferrater.foodtrayservice; /** * * @author Joffry Ferrater * */ @RestController @RequestMapping("/foodtrays") public class FoodTrayController { @Autowired ItemServiceRepository itemServiceRepository; @Autowired PriceServiceRepository priceServiceRepo;
// Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/Item.java // @lombok.Getter // public class Item { // // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Name") // private String name; // // public Item() { // super(); // } // // public Item(String itemCode, String name) { // this.itemCode = itemCode; // this.name = name; // } // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/Price.java // @lombok.Getter // public class Price { // // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Price") // private String price; // // public Price(){ // super(); // } // // public Price(String itemCode, String price) { // this(); // this.itemCode = itemCode; // this.price = price; // } // // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/TrayItem.java // public class TrayItem { // // @JsonProperty("Name") // private String name; // @JsonProperty("Price") // private String amount; // // // public TrayItem() { // super(); // } // // public TrayItem(String name, String amount) { // this.name = name; // this.amount = amount; // } // // public String getName() { // return name; // } // // public String getAmount() { // return amount; // } // // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/ItemServiceRepository.java // @FeignClient(value="ITEM-SERVICE", fallback=ItemServiceFallback.class) // public interface ItemServiceRepository { // // @RequestMapping(method=RequestMethod.GET, value="/items/search/findByItemCode?itemCode={itemCode}") // Item findByItemCode(@PathVariable("itemCode") String itemCode); // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/PriceServiceRepository.java // @FeignClient(value="PRICE-SERVICE", fallback=PriceServiceRepository.class) // public interface PriceServiceRepository { // // @RequestMapping(method=RequestMethod.GET, value="/prices/search/findByItemCode?itemCode={itemCode}") // Price findByItemCode(@PathVariable("itemCode") String itemCode); // } // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/FoodTrayController.java import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.github.joffryferrater.foodtrayservice.domain.Item; import com.github.joffryferrater.foodtrayservice.domain.Price; import com.github.joffryferrater.foodtrayservice.domain.TrayItem; import com.github.joffryferrater.foodtrayservice.repository.ItemServiceRepository; import com.github.joffryferrater.foodtrayservice.repository.PriceServiceRepository; package com.github.joffryferrater.foodtrayservice; /** * * @author Joffry Ferrater * */ @RestController @RequestMapping("/foodtrays") public class FoodTrayController { @Autowired ItemServiceRepository itemServiceRepository; @Autowired PriceServiceRepository priceServiceRepo;
private List<TrayItem> trayItems = new ArrayList<TrayItem>();
jferrater/Tap-And-Eat-MicroServices
FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/FoodTrayController.java
// Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/Item.java // @lombok.Getter // public class Item { // // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Name") // private String name; // // public Item() { // super(); // } // // public Item(String itemCode, String name) { // this.itemCode = itemCode; // this.name = name; // } // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/Price.java // @lombok.Getter // public class Price { // // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Price") // private String price; // // public Price(){ // super(); // } // // public Price(String itemCode, String price) { // this(); // this.itemCode = itemCode; // this.price = price; // } // // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/TrayItem.java // public class TrayItem { // // @JsonProperty("Name") // private String name; // @JsonProperty("Price") // private String amount; // // // public TrayItem() { // super(); // } // // public TrayItem(String name, String amount) { // this.name = name; // this.amount = amount; // } // // public String getName() { // return name; // } // // public String getAmount() { // return amount; // } // // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/ItemServiceRepository.java // @FeignClient(value="ITEM-SERVICE", fallback=ItemServiceFallback.class) // public interface ItemServiceRepository { // // @RequestMapping(method=RequestMethod.GET, value="/items/search/findByItemCode?itemCode={itemCode}") // Item findByItemCode(@PathVariable("itemCode") String itemCode); // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/PriceServiceRepository.java // @FeignClient(value="PRICE-SERVICE", fallback=PriceServiceRepository.class) // public interface PriceServiceRepository { // // @RequestMapping(method=RequestMethod.GET, value="/prices/search/findByItemCode?itemCode={itemCode}") // Price findByItemCode(@PathVariable("itemCode") String itemCode); // }
import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.github.joffryferrater.foodtrayservice.domain.Item; import com.github.joffryferrater.foodtrayservice.domain.Price; import com.github.joffryferrater.foodtrayservice.domain.TrayItem; import com.github.joffryferrater.foodtrayservice.repository.ItemServiceRepository; import com.github.joffryferrater.foodtrayservice.repository.PriceServiceRepository;
package com.github.joffryferrater.foodtrayservice; /** * * @author Joffry Ferrater * */ @RestController @RequestMapping("/foodtrays") public class FoodTrayController { @Autowired ItemServiceRepository itemServiceRepository; @Autowired PriceServiceRepository priceServiceRepo; private List<TrayItem> trayItems = new ArrayList<TrayItem>(); @RequestMapping(value="/price/{itemCode}", method=RequestMethod.GET)
// Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/Item.java // @lombok.Getter // public class Item { // // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Name") // private String name; // // public Item() { // super(); // } // // public Item(String itemCode, String name) { // this.itemCode = itemCode; // this.name = name; // } // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/Price.java // @lombok.Getter // public class Price { // // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Price") // private String price; // // public Price(){ // super(); // } // // public Price(String itemCode, String price) { // this(); // this.itemCode = itemCode; // this.price = price; // } // // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/TrayItem.java // public class TrayItem { // // @JsonProperty("Name") // private String name; // @JsonProperty("Price") // private String amount; // // // public TrayItem() { // super(); // } // // public TrayItem(String name, String amount) { // this.name = name; // this.amount = amount; // } // // public String getName() { // return name; // } // // public String getAmount() { // return amount; // } // // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/ItemServiceRepository.java // @FeignClient(value="ITEM-SERVICE", fallback=ItemServiceFallback.class) // public interface ItemServiceRepository { // // @RequestMapping(method=RequestMethod.GET, value="/items/search/findByItemCode?itemCode={itemCode}") // Item findByItemCode(@PathVariable("itemCode") String itemCode); // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/PriceServiceRepository.java // @FeignClient(value="PRICE-SERVICE", fallback=PriceServiceRepository.class) // public interface PriceServiceRepository { // // @RequestMapping(method=RequestMethod.GET, value="/prices/search/findByItemCode?itemCode={itemCode}") // Price findByItemCode(@PathVariable("itemCode") String itemCode); // } // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/FoodTrayController.java import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.github.joffryferrater.foodtrayservice.domain.Item; import com.github.joffryferrater.foodtrayservice.domain.Price; import com.github.joffryferrater.foodtrayservice.domain.TrayItem; import com.github.joffryferrater.foodtrayservice.repository.ItemServiceRepository; import com.github.joffryferrater.foodtrayservice.repository.PriceServiceRepository; package com.github.joffryferrater.foodtrayservice; /** * * @author Joffry Ferrater * */ @RestController @RequestMapping("/foodtrays") public class FoodTrayController { @Autowired ItemServiceRepository itemServiceRepository; @Autowired PriceServiceRepository priceServiceRepo; private List<TrayItem> trayItems = new ArrayList<TrayItem>(); @RequestMapping(value="/price/{itemCode}", method=RequestMethod.GET)
public Price getPrice(@PathVariable("itemCode") String itemCode) {
jferrater/Tap-And-Eat-MicroServices
FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/FoodTrayController.java
// Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/Item.java // @lombok.Getter // public class Item { // // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Name") // private String name; // // public Item() { // super(); // } // // public Item(String itemCode, String name) { // this.itemCode = itemCode; // this.name = name; // } // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/Price.java // @lombok.Getter // public class Price { // // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Price") // private String price; // // public Price(){ // super(); // } // // public Price(String itemCode, String price) { // this(); // this.itemCode = itemCode; // this.price = price; // } // // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/TrayItem.java // public class TrayItem { // // @JsonProperty("Name") // private String name; // @JsonProperty("Price") // private String amount; // // // public TrayItem() { // super(); // } // // public TrayItem(String name, String amount) { // this.name = name; // this.amount = amount; // } // // public String getName() { // return name; // } // // public String getAmount() { // return amount; // } // // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/ItemServiceRepository.java // @FeignClient(value="ITEM-SERVICE", fallback=ItemServiceFallback.class) // public interface ItemServiceRepository { // // @RequestMapping(method=RequestMethod.GET, value="/items/search/findByItemCode?itemCode={itemCode}") // Item findByItemCode(@PathVariable("itemCode") String itemCode); // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/PriceServiceRepository.java // @FeignClient(value="PRICE-SERVICE", fallback=PriceServiceRepository.class) // public interface PriceServiceRepository { // // @RequestMapping(method=RequestMethod.GET, value="/prices/search/findByItemCode?itemCode={itemCode}") // Price findByItemCode(@PathVariable("itemCode") String itemCode); // }
import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.github.joffryferrater.foodtrayservice.domain.Item; import com.github.joffryferrater.foodtrayservice.domain.Price; import com.github.joffryferrater.foodtrayservice.domain.TrayItem; import com.github.joffryferrater.foodtrayservice.repository.ItemServiceRepository; import com.github.joffryferrater.foodtrayservice.repository.PriceServiceRepository;
package com.github.joffryferrater.foodtrayservice; /** * * @author Joffry Ferrater * */ @RestController @RequestMapping("/foodtrays") public class FoodTrayController { @Autowired ItemServiceRepository itemServiceRepository; @Autowired PriceServiceRepository priceServiceRepo; private List<TrayItem> trayItems = new ArrayList<TrayItem>(); @RequestMapping(value="/price/{itemCode}", method=RequestMethod.GET) public Price getPrice(@PathVariable("itemCode") String itemCode) { return priceServiceRepo.findByItemCode(itemCode); } @RequestMapping(value="/item/{itemCode}", method=RequestMethod.GET)
// Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/Item.java // @lombok.Getter // public class Item { // // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Name") // private String name; // // public Item() { // super(); // } // // public Item(String itemCode, String name) { // this.itemCode = itemCode; // this.name = name; // } // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/Price.java // @lombok.Getter // public class Price { // // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Price") // private String price; // // public Price(){ // super(); // } // // public Price(String itemCode, String price) { // this(); // this.itemCode = itemCode; // this.price = price; // } // // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/TrayItem.java // public class TrayItem { // // @JsonProperty("Name") // private String name; // @JsonProperty("Price") // private String amount; // // // public TrayItem() { // super(); // } // // public TrayItem(String name, String amount) { // this.name = name; // this.amount = amount; // } // // public String getName() { // return name; // } // // public String getAmount() { // return amount; // } // // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/ItemServiceRepository.java // @FeignClient(value="ITEM-SERVICE", fallback=ItemServiceFallback.class) // public interface ItemServiceRepository { // // @RequestMapping(method=RequestMethod.GET, value="/items/search/findByItemCode?itemCode={itemCode}") // Item findByItemCode(@PathVariable("itemCode") String itemCode); // } // // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/PriceServiceRepository.java // @FeignClient(value="PRICE-SERVICE", fallback=PriceServiceRepository.class) // public interface PriceServiceRepository { // // @RequestMapping(method=RequestMethod.GET, value="/prices/search/findByItemCode?itemCode={itemCode}") // Price findByItemCode(@PathVariable("itemCode") String itemCode); // } // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/FoodTrayController.java import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.github.joffryferrater.foodtrayservice.domain.Item; import com.github.joffryferrater.foodtrayservice.domain.Price; import com.github.joffryferrater.foodtrayservice.domain.TrayItem; import com.github.joffryferrater.foodtrayservice.repository.ItemServiceRepository; import com.github.joffryferrater.foodtrayservice.repository.PriceServiceRepository; package com.github.joffryferrater.foodtrayservice; /** * * @author Joffry Ferrater * */ @RestController @RequestMapping("/foodtrays") public class FoodTrayController { @Autowired ItemServiceRepository itemServiceRepository; @Autowired PriceServiceRepository priceServiceRepo; private List<TrayItem> trayItems = new ArrayList<TrayItem>(); @RequestMapping(value="/price/{itemCode}", method=RequestMethod.GET) public Price getPrice(@PathVariable("itemCode") String itemCode) { return priceServiceRepo.findByItemCode(itemCode); } @RequestMapping(value="/item/{itemCode}", method=RequestMethod.GET)
public Item getItem(@PathVariable("itemCode") String itemCode) {
jferrater/Tap-And-Eat-MicroServices
PriceService/src/main/java/com/github/joffryferrater/priceservice/PriceServiceApplication.java
// Path: PriceService/src/main/java/com/github/joffryferrater/priceservice/models/Price.java // @Entity // @Table (name="prices") // @Data // public class Price { // // @Id // @GeneratedValue (strategy = GenerationType.AUTO) // private Long id; // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Price") // private String price; // // public Price() { // super(); // } // // public Price(String itemCode, String price) { // this(); // this.itemCode = itemCode; // this.price = price; // } // } // // Path: PriceService/src/main/java/com/github/joffryferrater/priceservice/models/PriceRepository.java // @RepositoryRestResource (path="prices", collectionResourceRel= "prices") // public interface PriceRepository extends CrudRepository<Price, Long> { // // Price findByItemCode(@Param("itemCode")String itemCode); // // }
import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import com.github.joffryferrater.priceservice.models.Price; import com.github.joffryferrater.priceservice.models.PriceRepository;
package com.github.joffryferrater.priceservice; @SpringBootApplication @EnableDiscoveryClient public class PriceServiceApplication { public static void main(String[] args) { SpringApplication.run(PriceServiceApplication.class, args); } @Autowired
// Path: PriceService/src/main/java/com/github/joffryferrater/priceservice/models/Price.java // @Entity // @Table (name="prices") // @Data // public class Price { // // @Id // @GeneratedValue (strategy = GenerationType.AUTO) // private Long id; // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Price") // private String price; // // public Price() { // super(); // } // // public Price(String itemCode, String price) { // this(); // this.itemCode = itemCode; // this.price = price; // } // } // // Path: PriceService/src/main/java/com/github/joffryferrater/priceservice/models/PriceRepository.java // @RepositoryRestResource (path="prices", collectionResourceRel= "prices") // public interface PriceRepository extends CrudRepository<Price, Long> { // // Price findByItemCode(@Param("itemCode")String itemCode); // // } // Path: PriceService/src/main/java/com/github/joffryferrater/priceservice/PriceServiceApplication.java import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import com.github.joffryferrater.priceservice.models.Price; import com.github.joffryferrater.priceservice.models.PriceRepository; package com.github.joffryferrater.priceservice; @SpringBootApplication @EnableDiscoveryClient public class PriceServiceApplication { public static void main(String[] args) { SpringApplication.run(PriceServiceApplication.class, args); } @Autowired
PriceRepository priceRepo;
jferrater/Tap-And-Eat-MicroServices
PriceService/src/main/java/com/github/joffryferrater/priceservice/PriceServiceApplication.java
// Path: PriceService/src/main/java/com/github/joffryferrater/priceservice/models/Price.java // @Entity // @Table (name="prices") // @Data // public class Price { // // @Id // @GeneratedValue (strategy = GenerationType.AUTO) // private Long id; // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Price") // private String price; // // public Price() { // super(); // } // // public Price(String itemCode, String price) { // this(); // this.itemCode = itemCode; // this.price = price; // } // } // // Path: PriceService/src/main/java/com/github/joffryferrater/priceservice/models/PriceRepository.java // @RepositoryRestResource (path="prices", collectionResourceRel= "prices") // public interface PriceRepository extends CrudRepository<Price, Long> { // // Price findByItemCode(@Param("itemCode")String itemCode); // // }
import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import com.github.joffryferrater.priceservice.models.Price; import com.github.joffryferrater.priceservice.models.PriceRepository;
package com.github.joffryferrater.priceservice; @SpringBootApplication @EnableDiscoveryClient public class PriceServiceApplication { public static void main(String[] args) { SpringApplication.run(PriceServiceApplication.class, args); } @Autowired PriceRepository priceRepo; @PostConstruct public void init() {
// Path: PriceService/src/main/java/com/github/joffryferrater/priceservice/models/Price.java // @Entity // @Table (name="prices") // @Data // public class Price { // // @Id // @GeneratedValue (strategy = GenerationType.AUTO) // private Long id; // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Price") // private String price; // // public Price() { // super(); // } // // public Price(String itemCode, String price) { // this(); // this.itemCode = itemCode; // this.price = price; // } // } // // Path: PriceService/src/main/java/com/github/joffryferrater/priceservice/models/PriceRepository.java // @RepositoryRestResource (path="prices", collectionResourceRel= "prices") // public interface PriceRepository extends CrudRepository<Price, Long> { // // Price findByItemCode(@Param("itemCode")String itemCode); // // } // Path: PriceService/src/main/java/com/github/joffryferrater/priceservice/PriceServiceApplication.java import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import com.github.joffryferrater.priceservice.models.Price; import com.github.joffryferrater.priceservice.models.PriceRepository; package com.github.joffryferrater.priceservice; @SpringBootApplication @EnableDiscoveryClient public class PriceServiceApplication { public static void main(String[] args) { SpringApplication.run(PriceServiceApplication.class, args); } @Autowired PriceRepository priceRepo; @PostConstruct public void init() {
Price price = new Price("BUR01", "150");
jferrater/Tap-And-Eat-MicroServices
FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/PriceServiceFallback.java
// Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/Price.java // @lombok.Getter // public class Price { // // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Price") // private String price; // // public Price(){ // super(); // } // // public Price(String itemCode, String price) { // this(); // this.itemCode = itemCode; // this.price = price; // } // // }
import com.github.joffryferrater.foodtrayservice.domain.Price;
package com.github.joffryferrater.foodtrayservice.repository; /** * Fall back function if price service is not available. * * @author Joffry Ferrater * */ public class PriceServiceFallback implements PriceServiceRepository { @Override
// Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/Price.java // @lombok.Getter // public class Price { // // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Price") // private String price; // // public Price(){ // super(); // } // // public Price(String itemCode, String price) { // this(); // this.itemCode = itemCode; // this.price = price; // } // // } // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/PriceServiceFallback.java import com.github.joffryferrater.foodtrayservice.domain.Price; package com.github.joffryferrater.foodtrayservice.repository; /** * Fall back function if price service is not available. * * @author Joffry Ferrater * */ public class PriceServiceFallback implements PriceServiceRepository { @Override
public Price findByItemCode(String itemCode) {
jferrater/Tap-And-Eat-MicroServices
FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/ItemServiceFallback.java
// Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/Item.java // @lombok.Getter // public class Item { // // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Name") // private String name; // // public Item() { // super(); // } // // public Item(String itemCode, String name) { // this.itemCode = itemCode; // this.name = name; // } // }
import org.springframework.stereotype.Component; import com.github.joffryferrater.foodtrayservice.domain.Item;
package com.github.joffryferrater.foodtrayservice.repository; /** * Fall back function if ItemService is not available. * * @author Joffry Ferrater * */ @Component public class ItemServiceFallback implements ItemServiceRepository { @Override
// Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/Item.java // @lombok.Getter // public class Item { // // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Name") // private String name; // // public Item() { // super(); // } // // public Item(String itemCode, String name) { // this.itemCode = itemCode; // this.name = name; // } // } // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/ItemServiceFallback.java import org.springframework.stereotype.Component; import com.github.joffryferrater.foodtrayservice.domain.Item; package com.github.joffryferrater.foodtrayservice.repository; /** * Fall back function if ItemService is not available. * * @author Joffry Ferrater * */ @Component public class ItemServiceFallback implements ItemServiceRepository { @Override
public Item findByItemCode(String itemCode) {
jferrater/Tap-And-Eat-MicroServices
FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/ItemServiceRepository.java
// Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/Item.java // @lombok.Getter // public class Item { // // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Name") // private String name; // // public Item() { // super(); // } // // public Item(String itemCode, String name) { // this.itemCode = itemCode; // this.name = name; // } // }
import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.github.joffryferrater.foodtrayservice.domain.Item;
package com.github.joffryferrater.foodtrayservice.repository; /** * * @author Joffry Ferrater * */ @FeignClient(value="ITEM-SERVICE", fallback=ItemServiceFallback.class) public interface ItemServiceRepository { @RequestMapping(method=RequestMethod.GET, value="/items/search/findByItemCode?itemCode={itemCode}")
// Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/domain/Item.java // @lombok.Getter // public class Item { // // @JsonProperty("Item Code") // private String itemCode; // @JsonProperty("Name") // private String name; // // public Item() { // super(); // } // // public Item(String itemCode, String name) { // this.itemCode = itemCode; // this.name = name; // } // } // Path: FoodTrayService/src/main/java/com/github/joffryferrater/foodtrayservice/repository/ItemServiceRepository.java import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.github.joffryferrater.foodtrayservice.domain.Item; package com.github.joffryferrater.foodtrayservice.repository; /** * * @author Joffry Ferrater * */ @FeignClient(value="ITEM-SERVICE", fallback=ItemServiceFallback.class) public interface ItemServiceRepository { @RequestMapping(method=RequestMethod.GET, value="/items/search/findByItemCode?itemCode={itemCode}")
Item findByItemCode(@PathVariable("itemCode") String itemCode);
BlochsTech/BitcoinCardTerminal
src/com/blochstech/bitcoincardterminal/Model/Communication/TXSourceUtil.java
// Path: src/com/blochstech/bitcoincardterminal/Model/Communication/TXSourceId.java // class TXSourceId { // String OutIndex = null; //Len 4 (8 in hex) // String TXHash = null; //Len 32 (64 in hex) // long Satoshi = 0; // boolean Verified; // boolean Unusable; //Card did not accept due to unusual script, error or block not difficult enough. //TODO: Use and handle. // } // // Path: src/com/blochstech/bitcoincardterminal/Utils/Tags.java // public class Tags { // //Set this to false when building to Google Play app store. // public static final boolean DEBUG = false; // // public static final String APP_TAG = "BitcoinCardTerminal"; // }
import java.util.ArrayList; import java.util.Locale; import android.util.Log; import com.blochstech.bitcoincardterminal.Model.Communication.TXSourceId; import com.blochstech.bitcoincardterminal.Utils.Tags;
package com.blochstech.bitcoincardterminal.Model.Communication; public class TXSourceUtil { public static boolean containsSource(ArrayList<TXSourceId> list, String hash){ try{ if(hash == null || list == null) return false; for(int i = 0; i < list.size(); i++){ if(list.get(i).TXHash.toLowerCase(Locale.ENGLISH).equals(hash.toLowerCase(Locale.ENGLISH)) && (list.get(i).Verified || list.get(i).Unusable)) return true; } }catch(Exception e){
// Path: src/com/blochstech/bitcoincardterminal/Model/Communication/TXSourceId.java // class TXSourceId { // String OutIndex = null; //Len 4 (8 in hex) // String TXHash = null; //Len 32 (64 in hex) // long Satoshi = 0; // boolean Verified; // boolean Unusable; //Card did not accept due to unusual script, error or block not difficult enough. //TODO: Use and handle. // } // // Path: src/com/blochstech/bitcoincardterminal/Utils/Tags.java // public class Tags { // //Set this to false when building to Google Play app store. // public static final boolean DEBUG = false; // // public static final String APP_TAG = "BitcoinCardTerminal"; // } // Path: src/com/blochstech/bitcoincardterminal/Model/Communication/TXSourceUtil.java import java.util.ArrayList; import java.util.Locale; import android.util.Log; import com.blochstech.bitcoincardterminal.Model.Communication.TXSourceId; import com.blochstech.bitcoincardterminal.Utils.Tags; package com.blochstech.bitcoincardterminal.Model.Communication; public class TXSourceUtil { public static boolean containsSource(ArrayList<TXSourceId> list, String hash){ try{ if(hash == null || list == null) return false; for(int i = 0; i < list.size(); i++){ if(list.get(i).TXHash.toLowerCase(Locale.ENGLISH).equals(hash.toLowerCase(Locale.ENGLISH)) && (list.get(i).Verified || list.get(i).Unusable)) return true; } }catch(Exception e){
Log.e(Tags.APP_TAG, "ContainsSource failed: " + e.toString());
BlochsTech/BitcoinCardTerminal
src/com/blochstech/bitcoincardterminal/DataLayer/DAL.java
// Path: src/com/blochstech/bitcoincardterminal/Interfaces/IDAL.java // public interface IDAL { // //Events: // public Event<Message> MessageEventReference(); // // //Database mehtods: // public void setReceiveAddress(String address); // public String getReceiveAddress(); // // public void setFee(String fee); // public String getFee(); // // public void setCourtesyOK(boolean courtesyOK); // public boolean getCourtesyOK(); // // public void setCurrency(int currency); // public int getCurrency(); // } // // Path: src/com/blochstech/bitcoincardterminal/Interfaces/Message.java // public class Message { // public long CreatedMillis; // public String Message; // public MessageType Type; // // public Message(String message, MessageType type, long createdMillis){ // this.Type = type; // this.Message = message; // this.CreatedMillis = createdMillis; // } // public Message(String message, MessageType type){ // this.Type = type; // this.Message = message; // this.CreatedMillis = System.currentTimeMillis(); // } // public Message(String message){ // this.Type = MessageType.Info; // this.Message = message; // this.CreatedMillis = System.currentTimeMillis(); // } // // public enum MessageType{ // Info, // Warning, // Error // } // } // // Path: src/com/blochstech/bitcoincardterminal/Interfaces/Message.java // public enum MessageType{ // Info, // Warning, // Error // }
import android.util.Log; import com.blochstech.bitcoincardterminal.Interfaces.IDAL; import com.blochstech.bitcoincardterminal.Interfaces.Message; import com.blochstech.bitcoincardterminal.Interfaces.Message.MessageType; import com.blochstech.bitcoincardterminal.Utils.*;
package com.blochstech.bitcoincardterminal.DataLayer; public class DAL implements IDAL { //Singleton pattern: private static IDAL instance = null; public static IDAL Instance() { if(instance == null) { instance = new DAL(); } return instance; } private DAL() { try {
// Path: src/com/blochstech/bitcoincardterminal/Interfaces/IDAL.java // public interface IDAL { // //Events: // public Event<Message> MessageEventReference(); // // //Database mehtods: // public void setReceiveAddress(String address); // public String getReceiveAddress(); // // public void setFee(String fee); // public String getFee(); // // public void setCourtesyOK(boolean courtesyOK); // public boolean getCourtesyOK(); // // public void setCurrency(int currency); // public int getCurrency(); // } // // Path: src/com/blochstech/bitcoincardterminal/Interfaces/Message.java // public class Message { // public long CreatedMillis; // public String Message; // public MessageType Type; // // public Message(String message, MessageType type, long createdMillis){ // this.Type = type; // this.Message = message; // this.CreatedMillis = createdMillis; // } // public Message(String message, MessageType type){ // this.Type = type; // this.Message = message; // this.CreatedMillis = System.currentTimeMillis(); // } // public Message(String message){ // this.Type = MessageType.Info; // this.Message = message; // this.CreatedMillis = System.currentTimeMillis(); // } // // public enum MessageType{ // Info, // Warning, // Error // } // } // // Path: src/com/blochstech/bitcoincardterminal/Interfaces/Message.java // public enum MessageType{ // Info, // Warning, // Error // } // Path: src/com/blochstech/bitcoincardterminal/DataLayer/DAL.java import android.util.Log; import com.blochstech.bitcoincardterminal.Interfaces.IDAL; import com.blochstech.bitcoincardterminal.Interfaces.Message; import com.blochstech.bitcoincardterminal.Interfaces.Message.MessageType; import com.blochstech.bitcoincardterminal.Utils.*; package com.blochstech.bitcoincardterminal.DataLayer; public class DAL implements IDAL { //Singleton pattern: private static IDAL instance = null; public static IDAL Instance() { if(instance == null) { instance = new DAL(); } return instance; } private DAL() { try {
messageEvent = new Event<Message>(this);
BlochsTech/BitcoinCardTerminal
src/com/blochstech/bitcoincardterminal/DataLayer/DAL.java
// Path: src/com/blochstech/bitcoincardterminal/Interfaces/IDAL.java // public interface IDAL { // //Events: // public Event<Message> MessageEventReference(); // // //Database mehtods: // public void setReceiveAddress(String address); // public String getReceiveAddress(); // // public void setFee(String fee); // public String getFee(); // // public void setCourtesyOK(boolean courtesyOK); // public boolean getCourtesyOK(); // // public void setCurrency(int currency); // public int getCurrency(); // } // // Path: src/com/blochstech/bitcoincardterminal/Interfaces/Message.java // public class Message { // public long CreatedMillis; // public String Message; // public MessageType Type; // // public Message(String message, MessageType type, long createdMillis){ // this.Type = type; // this.Message = message; // this.CreatedMillis = createdMillis; // } // public Message(String message, MessageType type){ // this.Type = type; // this.Message = message; // this.CreatedMillis = System.currentTimeMillis(); // } // public Message(String message){ // this.Type = MessageType.Info; // this.Message = message; // this.CreatedMillis = System.currentTimeMillis(); // } // // public enum MessageType{ // Info, // Warning, // Error // } // } // // Path: src/com/blochstech/bitcoincardterminal/Interfaces/Message.java // public enum MessageType{ // Info, // Warning, // Error // }
import android.util.Log; import com.blochstech.bitcoincardterminal.Interfaces.IDAL; import com.blochstech.bitcoincardterminal.Interfaces.Message; import com.blochstech.bitcoincardterminal.Interfaces.Message.MessageType; import com.blochstech.bitcoincardterminal.Utils.*;
messageEvent = new Event<Message>(this); addressCache = new GenericFileCache<String>(addressCachePath, ""); feeCache = new GenericFileCache<String>(feeCachePath, "100"); courtesyOKCache = new GenericFileCache<Boolean>(courtesyOKCachePath, false); currencyCache = new GenericFileCache<Integer>(currencyCachePath, 0); } catch (Exception e) { Log.e(Tags.APP_TAG, "DAL failed to initialize. Error: " + e.toString()); } } //Singleton pattern end. private GenericFileCache<String> addressCache; private GenericFileCache<String> feeCache; private GenericFileCache<Boolean> courtesyOKCache; private GenericFileCache<Integer> currencyCache; private final String addressCachePath = "/BitcoinTerminal/Data/receiverAddress.bin"; private final String feeCachePath = "/BitcoinTerminal/Data/fee.bin"; private final String courtesyOKCachePath = "/BitcoinTerminal/Data/courtesyOK.bin"; private final String currencyCachePath = "/BitcoinTerminal/Data/currency.bin"; //TODO: Permission. public Event<Message> messageEvent; @Override public void setReceiveAddress(String address) { try { addressCache.Open(this); addressCache.set(this, address); addressCache.Close(this); } catch (Exception e) {
// Path: src/com/blochstech/bitcoincardterminal/Interfaces/IDAL.java // public interface IDAL { // //Events: // public Event<Message> MessageEventReference(); // // //Database mehtods: // public void setReceiveAddress(String address); // public String getReceiveAddress(); // // public void setFee(String fee); // public String getFee(); // // public void setCourtesyOK(boolean courtesyOK); // public boolean getCourtesyOK(); // // public void setCurrency(int currency); // public int getCurrency(); // } // // Path: src/com/blochstech/bitcoincardterminal/Interfaces/Message.java // public class Message { // public long CreatedMillis; // public String Message; // public MessageType Type; // // public Message(String message, MessageType type, long createdMillis){ // this.Type = type; // this.Message = message; // this.CreatedMillis = createdMillis; // } // public Message(String message, MessageType type){ // this.Type = type; // this.Message = message; // this.CreatedMillis = System.currentTimeMillis(); // } // public Message(String message){ // this.Type = MessageType.Info; // this.Message = message; // this.CreatedMillis = System.currentTimeMillis(); // } // // public enum MessageType{ // Info, // Warning, // Error // } // } // // Path: src/com/blochstech/bitcoincardterminal/Interfaces/Message.java // public enum MessageType{ // Info, // Warning, // Error // } // Path: src/com/blochstech/bitcoincardterminal/DataLayer/DAL.java import android.util.Log; import com.blochstech.bitcoincardterminal.Interfaces.IDAL; import com.blochstech.bitcoincardterminal.Interfaces.Message; import com.blochstech.bitcoincardterminal.Interfaces.Message.MessageType; import com.blochstech.bitcoincardterminal.Utils.*; messageEvent = new Event<Message>(this); addressCache = new GenericFileCache<String>(addressCachePath, ""); feeCache = new GenericFileCache<String>(feeCachePath, "100"); courtesyOKCache = new GenericFileCache<Boolean>(courtesyOKCachePath, false); currencyCache = new GenericFileCache<Integer>(currencyCachePath, 0); } catch (Exception e) { Log.e(Tags.APP_TAG, "DAL failed to initialize. Error: " + e.toString()); } } //Singleton pattern end. private GenericFileCache<String> addressCache; private GenericFileCache<String> feeCache; private GenericFileCache<Boolean> courtesyOKCache; private GenericFileCache<Integer> currencyCache; private final String addressCachePath = "/BitcoinTerminal/Data/receiverAddress.bin"; private final String feeCachePath = "/BitcoinTerminal/Data/fee.bin"; private final String courtesyOKCachePath = "/BitcoinTerminal/Data/courtesyOK.bin"; private final String currencyCachePath = "/BitcoinTerminal/Data/currency.bin"; //TODO: Permission. public Event<Message> messageEvent; @Override public void setReceiveAddress(String address) { try { addressCache.Open(this); addressCache.set(this, address); addressCache.Close(this); } catch (Exception e) {
messageEvent.fire(this, new Message("Error: " + e.getMessage() + e.toString(), MessageType.Error));
BlochsTech/BitcoinCardTerminal
src/com/blochstech/bitcoincardterminal/DataLayer/GenericFileCache.java
// Path: src/com/blochstech/bitcoincardterminal/Utils/ResourceHolder.java // public class ResourceHolder { // //private Object lockKey; Usually as key in hashmap or unnecessary. // private Object holder; // private Thread holdingThread; // // //public Object LockKey(){ return lockKey; } //The value or resource being locked upon. // public Object Holder(){ return holder; } //The object with access (only for extra restrictive cases). // public Thread HoldingThread(){ return holdingThread; } //The thread that has the lock, re-entry should generally be allowed. // // public ResourceHolder(Object holder, Thread holdingThread){ // //this.lockKey = lockKey; // this.holder = holder; // this.holdingThread = holdingThread; // } // public ResourceHolder(Object holder){ // //this.lockKey = lockKey; // this.holder = holder; // this.holdingThread = Thread.currentThread(); // } // } // // Path: src/com/blochstech/bitcoincardterminal/Utils/SyntacticSugar.java // public class SyntacticSugar { // @SuppressWarnings("unchecked") // public static <T> T castAs(Object castee){ // try{ // return (T) castee; // }catch(Exception ex){ // return null; // } // } // // public static boolean EqualWithinMargin(Double value1, Double value2, Double margin){ // return value1 * (1+margin) >= value2 && value2 * (1+margin) >= value1; // } // } // // Path: src/com/blochstech/bitcoincardterminal/Utils/Tags.java // public class Tags { // //Set this to false when building to Google Play app store. // public static final boolean DEBUG = false; // // public static final String APP_TAG = "BitcoinCardTerminal"; // }
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.HashMap; import android.os.Environment; import android.util.Log; import com.blochstech.bitcoincardterminal.Utils.ResourceHolder; import com.blochstech.bitcoincardterminal.Utils.SyntacticSugar; import com.blochstech.bitcoincardterminal.Utils.Tags;
} public synchronized void Open(Object holder) throws Exception{ ResourceHolder holderObj; long startTime = System.currentTimeMillis(); boolean wait = true; while(wait){ holderObj = pathsInUse.get(FileCachePath); if(holderObj == null){ pathsInUse.put(FileCachePath, new ResourceHolder(holder)); wait = false; } else if (holderObj.Holder() == holder && holderObj.HoldingThread() == Thread.currentThread()){ wait = false; } else { if(startTime + 20000 < System.currentTimeMillis()) throw new Exception("Deadlock for 20 seconds while opening generic cache. Path: " + FileCachePath); try { this.wait(); } catch (InterruptedException e) {} } } //Permit re-entry: return; } public synchronized void Close(Object holder){ //TODO: Find all usages and make sure they are called even if exception happens. if(isHolder(holder)){ pathsInUse.remove(FileCachePath); this.notifyAll(); }else{
// Path: src/com/blochstech/bitcoincardterminal/Utils/ResourceHolder.java // public class ResourceHolder { // //private Object lockKey; Usually as key in hashmap or unnecessary. // private Object holder; // private Thread holdingThread; // // //public Object LockKey(){ return lockKey; } //The value or resource being locked upon. // public Object Holder(){ return holder; } //The object with access (only for extra restrictive cases). // public Thread HoldingThread(){ return holdingThread; } //The thread that has the lock, re-entry should generally be allowed. // // public ResourceHolder(Object holder, Thread holdingThread){ // //this.lockKey = lockKey; // this.holder = holder; // this.holdingThread = holdingThread; // } // public ResourceHolder(Object holder){ // //this.lockKey = lockKey; // this.holder = holder; // this.holdingThread = Thread.currentThread(); // } // } // // Path: src/com/blochstech/bitcoincardterminal/Utils/SyntacticSugar.java // public class SyntacticSugar { // @SuppressWarnings("unchecked") // public static <T> T castAs(Object castee){ // try{ // return (T) castee; // }catch(Exception ex){ // return null; // } // } // // public static boolean EqualWithinMargin(Double value1, Double value2, Double margin){ // return value1 * (1+margin) >= value2 && value2 * (1+margin) >= value1; // } // } // // Path: src/com/blochstech/bitcoincardterminal/Utils/Tags.java // public class Tags { // //Set this to false when building to Google Play app store. // public static final boolean DEBUG = false; // // public static final String APP_TAG = "BitcoinCardTerminal"; // } // Path: src/com/blochstech/bitcoincardterminal/DataLayer/GenericFileCache.java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.HashMap; import android.os.Environment; import android.util.Log; import com.blochstech.bitcoincardterminal.Utils.ResourceHolder; import com.blochstech.bitcoincardterminal.Utils.SyntacticSugar; import com.blochstech.bitcoincardterminal.Utils.Tags; } public synchronized void Open(Object holder) throws Exception{ ResourceHolder holderObj; long startTime = System.currentTimeMillis(); boolean wait = true; while(wait){ holderObj = pathsInUse.get(FileCachePath); if(holderObj == null){ pathsInUse.put(FileCachePath, new ResourceHolder(holder)); wait = false; } else if (holderObj.Holder() == holder && holderObj.HoldingThread() == Thread.currentThread()){ wait = false; } else { if(startTime + 20000 < System.currentTimeMillis()) throw new Exception("Deadlock for 20 seconds while opening generic cache. Path: " + FileCachePath); try { this.wait(); } catch (InterruptedException e) {} } } //Permit re-entry: return; } public synchronized void Close(Object holder){ //TODO: Find all usages and make sure they are called even if exception happens. if(isHolder(holder)){ pathsInUse.remove(FileCachePath); this.notifyAll(); }else{
if(Tags.DEBUG)
BlochsTech/BitcoinCardTerminal
src/com/blochstech/bitcoincardterminal/DataLayer/GenericFileCache.java
// Path: src/com/blochstech/bitcoincardterminal/Utils/ResourceHolder.java // public class ResourceHolder { // //private Object lockKey; Usually as key in hashmap or unnecessary. // private Object holder; // private Thread holdingThread; // // //public Object LockKey(){ return lockKey; } //The value or resource being locked upon. // public Object Holder(){ return holder; } //The object with access (only for extra restrictive cases). // public Thread HoldingThread(){ return holdingThread; } //The thread that has the lock, re-entry should generally be allowed. // // public ResourceHolder(Object holder, Thread holdingThread){ // //this.lockKey = lockKey; // this.holder = holder; // this.holdingThread = holdingThread; // } // public ResourceHolder(Object holder){ // //this.lockKey = lockKey; // this.holder = holder; // this.holdingThread = Thread.currentThread(); // } // } // // Path: src/com/blochstech/bitcoincardterminal/Utils/SyntacticSugar.java // public class SyntacticSugar { // @SuppressWarnings("unchecked") // public static <T> T castAs(Object castee){ // try{ // return (T) castee; // }catch(Exception ex){ // return null; // } // } // // public static boolean EqualWithinMargin(Double value1, Double value2, Double margin){ // return value1 * (1+margin) >= value2 && value2 * (1+margin) >= value1; // } // } // // Path: src/com/blochstech/bitcoincardterminal/Utils/Tags.java // public class Tags { // //Set this to false when building to Google Play app store. // public static final boolean DEBUG = false; // // public static final String APP_TAG = "BitcoinCardTerminal"; // }
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.HashMap; import android.os.Environment; import android.util.Log; import com.blochstech.bitcoincardterminal.Utils.ResourceHolder; import com.blochstech.bitcoincardterminal.Utils.SyntacticSugar; import com.blochstech.bitcoincardterminal.Utils.Tags;
{ dir.mkdirs(); } if(!dir.exists()) throw new Exception("Getting directory failed. Path: " + FileCachePath); File file = new File(FileCachePath); if(file == null || !file.exists()) SaveFileValue(initialValue); }catch(Exception ex) { throw ex; } } private T GetFileValue() throws Exception //Use generics and Xml serilization in the future save any value { boolean fail = true; long startTry = System.currentTimeMillis(); while (fail) { fail = false; try { File file = new File(FileCachePath); FileInputStream fis = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(fis); Object readObj = ois.readObject(); ois.close(); fis.close();
// Path: src/com/blochstech/bitcoincardterminal/Utils/ResourceHolder.java // public class ResourceHolder { // //private Object lockKey; Usually as key in hashmap or unnecessary. // private Object holder; // private Thread holdingThread; // // //public Object LockKey(){ return lockKey; } //The value or resource being locked upon. // public Object Holder(){ return holder; } //The object with access (only for extra restrictive cases). // public Thread HoldingThread(){ return holdingThread; } //The thread that has the lock, re-entry should generally be allowed. // // public ResourceHolder(Object holder, Thread holdingThread){ // //this.lockKey = lockKey; // this.holder = holder; // this.holdingThread = holdingThread; // } // public ResourceHolder(Object holder){ // //this.lockKey = lockKey; // this.holder = holder; // this.holdingThread = Thread.currentThread(); // } // } // // Path: src/com/blochstech/bitcoincardterminal/Utils/SyntacticSugar.java // public class SyntacticSugar { // @SuppressWarnings("unchecked") // public static <T> T castAs(Object castee){ // try{ // return (T) castee; // }catch(Exception ex){ // return null; // } // } // // public static boolean EqualWithinMargin(Double value1, Double value2, Double margin){ // return value1 * (1+margin) >= value2 && value2 * (1+margin) >= value1; // } // } // // Path: src/com/blochstech/bitcoincardterminal/Utils/Tags.java // public class Tags { // //Set this to false when building to Google Play app store. // public static final boolean DEBUG = false; // // public static final String APP_TAG = "BitcoinCardTerminal"; // } // Path: src/com/blochstech/bitcoincardterminal/DataLayer/GenericFileCache.java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.HashMap; import android.os.Environment; import android.util.Log; import com.blochstech.bitcoincardterminal.Utils.ResourceHolder; import com.blochstech.bitcoincardterminal.Utils.SyntacticSugar; import com.blochstech.bitcoincardterminal.Utils.Tags; { dir.mkdirs(); } if(!dir.exists()) throw new Exception("Getting directory failed. Path: " + FileCachePath); File file = new File(FileCachePath); if(file == null || !file.exists()) SaveFileValue(initialValue); }catch(Exception ex) { throw ex; } } private T GetFileValue() throws Exception //Use generics and Xml serilization in the future save any value { boolean fail = true; long startTry = System.currentTimeMillis(); while (fail) { fail = false; try { File file = new File(FileCachePath); FileInputStream fis = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(fis); Object readObj = ois.readObject(); ois.close(); fis.close();
return SyntacticSugar.<T>castAs(readObj);
BlochsTech/BitcoinCardTerminal
src/com/blochstech/bitcoincardterminal/View/MainFragmentPager.java
// Path: src/com/blochstech/bitcoincardterminal/ViewModel/ViewStateManagers/MessageManager.java // public class MessageManager { // //Singleton pattern: // private static MessageManager instance = null; // public static MessageManager Instance() // { // if(instance == null) // { // instance = new MessageManager(); // } // return instance; // } // private MessageManager() // { // Model.Instance().MessageEventReference().register(modelMessageListener); // } // //Singleton pattern end. // // private Queue<String> messages = new LinkedList<String>(); // private final int maxMessages = 500; // private EventListener<Message> modelMessageListener = new ModelMessageListener(); // // public void AddMessage(String msg, boolean isError){ // AddMessage(msg, isError, false); // } // // @SuppressWarnings("unused") // public void AddMessage(String msg, boolean isError, boolean isWarning){ // //TODO: Add to list + android log... rest can wait... post log guide in this class. // if(msg != null && !msg.isEmpty() && (Tags.DEBUG || isError)){ // messages.add(msg); // if(isError){ // Log.e(Tags.APP_TAG, msg); // Toast.makeText(MainActivity.GetMainContext(), "ERR: " + msg, Toast.LENGTH_LONG).show(); // }else if(isWarning){ // Log.w(Tags.APP_TAG, msg); // }else{ // Log.i(Tags.APP_TAG, msg); // } // if(messages.size() > maxMessages) // messages.poll(); // } // } // // public void AddMessage(String msg){ // AddMessage(msg, false); // } // // private class ModelMessageListener extends EventListener<Message>{ // @Override // public void onEvent(Message event) { // AddMessage(event.Message, event.Type == MessageType.Error, event.Type == MessageType.Warning); // } // } // } // // Path: src/com/blochstech/bitcoincardterminal/ViewModel/ViewStateManagers/NavigationManager.java // public class NavigationManager { // //Singleton pattern: // private static NavigationManager instance = null; // public static NavigationManager Instance() // { // if(instance == null) // { // instance = new NavigationManager(); // } // return instance; // } // private NavigationManager() // { // UpdateEvent = new Event<Object>(this); // } // //Singleton pattern end. // // public Event<Object> UpdateEvent; // // private boolean allowRightSwipe = true, allowLeftSwipe = true; // public boolean AllowRightSwipe(){ // return allowRightSwipe; // } // public boolean AllowLeftSwipe(){ // return allowLeftSwipe; // } // public void allowSwipes(boolean right, boolean left){ // allowRightSwipe = right; // allowLeftSwipe = left; // } // // private int currentPage = 0; // public int CurrentPageNumber(){ // return currentPage; // } // private PageTags currentPageEnum = PageTags.CHARGE_PAGE; // public PageTags CurrentPage(){ // return currentPageEnum; // } // private void setPage(int page){ // if(page < 4 && page >= 0){ // currentPage = page; // } // } // // public void setPage(PageTags page){ // setPage(page, false); // } // public void setPage(PageTags page, boolean quiet){ // if(page == PageTags.CHARGE_PAGE){ // setPage(0); // allowSwipes(true, false); // } // if(page == PageTags.HISTORY_PAGE){ // setPage(1); // allowSwipes(false, true); // } // if(page == PageTags.PIN_PAGE){ // setPage(2); // allowSwipes(false, false); // } // if(page == PageTags.SETTINGS_PAGE){ // setPage(3); // allowSwipes(false, false); // } // // currentPageEnum = page; // if(!quiet) // UpdateEvent.fire(this, null); // } // }
import com.blochstech.bitcoincardterminal.ViewModel.ViewStateManagers.MessageManager; import com.blochstech.bitcoincardterminal.ViewModel.ViewStateManagers.NavigationManager; import android.content.Context; import android.support.v4.view.ViewPager; import android.util.AttributeSet;
package com.blochstech.bitcoincardterminal.View; public class MainFragmentPager extends ViewPager { public MainFragmentPager(Context context) { super(context); } public MainFragmentPager(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean onTouchEvent(android.view.MotionEvent event) {
// Path: src/com/blochstech/bitcoincardterminal/ViewModel/ViewStateManagers/MessageManager.java // public class MessageManager { // //Singleton pattern: // private static MessageManager instance = null; // public static MessageManager Instance() // { // if(instance == null) // { // instance = new MessageManager(); // } // return instance; // } // private MessageManager() // { // Model.Instance().MessageEventReference().register(modelMessageListener); // } // //Singleton pattern end. // // private Queue<String> messages = new LinkedList<String>(); // private final int maxMessages = 500; // private EventListener<Message> modelMessageListener = new ModelMessageListener(); // // public void AddMessage(String msg, boolean isError){ // AddMessage(msg, isError, false); // } // // @SuppressWarnings("unused") // public void AddMessage(String msg, boolean isError, boolean isWarning){ // //TODO: Add to list + android log... rest can wait... post log guide in this class. // if(msg != null && !msg.isEmpty() && (Tags.DEBUG || isError)){ // messages.add(msg); // if(isError){ // Log.e(Tags.APP_TAG, msg); // Toast.makeText(MainActivity.GetMainContext(), "ERR: " + msg, Toast.LENGTH_LONG).show(); // }else if(isWarning){ // Log.w(Tags.APP_TAG, msg); // }else{ // Log.i(Tags.APP_TAG, msg); // } // if(messages.size() > maxMessages) // messages.poll(); // } // } // // public void AddMessage(String msg){ // AddMessage(msg, false); // } // // private class ModelMessageListener extends EventListener<Message>{ // @Override // public void onEvent(Message event) { // AddMessage(event.Message, event.Type == MessageType.Error, event.Type == MessageType.Warning); // } // } // } // // Path: src/com/blochstech/bitcoincardterminal/ViewModel/ViewStateManagers/NavigationManager.java // public class NavigationManager { // //Singleton pattern: // private static NavigationManager instance = null; // public static NavigationManager Instance() // { // if(instance == null) // { // instance = new NavigationManager(); // } // return instance; // } // private NavigationManager() // { // UpdateEvent = new Event<Object>(this); // } // //Singleton pattern end. // // public Event<Object> UpdateEvent; // // private boolean allowRightSwipe = true, allowLeftSwipe = true; // public boolean AllowRightSwipe(){ // return allowRightSwipe; // } // public boolean AllowLeftSwipe(){ // return allowLeftSwipe; // } // public void allowSwipes(boolean right, boolean left){ // allowRightSwipe = right; // allowLeftSwipe = left; // } // // private int currentPage = 0; // public int CurrentPageNumber(){ // return currentPage; // } // private PageTags currentPageEnum = PageTags.CHARGE_PAGE; // public PageTags CurrentPage(){ // return currentPageEnum; // } // private void setPage(int page){ // if(page < 4 && page >= 0){ // currentPage = page; // } // } // // public void setPage(PageTags page){ // setPage(page, false); // } // public void setPage(PageTags page, boolean quiet){ // if(page == PageTags.CHARGE_PAGE){ // setPage(0); // allowSwipes(true, false); // } // if(page == PageTags.HISTORY_PAGE){ // setPage(1); // allowSwipes(false, true); // } // if(page == PageTags.PIN_PAGE){ // setPage(2); // allowSwipes(false, false); // } // if(page == PageTags.SETTINGS_PAGE){ // setPage(3); // allowSwipes(false, false); // } // // currentPageEnum = page; // if(!quiet) // UpdateEvent.fire(this, null); // } // } // Path: src/com/blochstech/bitcoincardterminal/View/MainFragmentPager.java import com.blochstech.bitcoincardterminal.ViewModel.ViewStateManagers.MessageManager; import com.blochstech.bitcoincardterminal.ViewModel.ViewStateManagers.NavigationManager; import android.content.Context; import android.support.v4.view.ViewPager; import android.util.AttributeSet; package com.blochstech.bitcoincardterminal.View; public class MainFragmentPager extends ViewPager { public MainFragmentPager(Context context) { super(context); } public MainFragmentPager(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean onTouchEvent(android.view.MotionEvent event) {
if(event.getActionMasked() == 2 && !NavigationManager.Instance().AllowLeftSwipe() && !NavigationManager.Instance().AllowRightSwipe())
BlochsTech/BitcoinCardTerminal
src/com/blochstech/bitcoincardterminal/View/MainFragmentPager.java
// Path: src/com/blochstech/bitcoincardterminal/ViewModel/ViewStateManagers/MessageManager.java // public class MessageManager { // //Singleton pattern: // private static MessageManager instance = null; // public static MessageManager Instance() // { // if(instance == null) // { // instance = new MessageManager(); // } // return instance; // } // private MessageManager() // { // Model.Instance().MessageEventReference().register(modelMessageListener); // } // //Singleton pattern end. // // private Queue<String> messages = new LinkedList<String>(); // private final int maxMessages = 500; // private EventListener<Message> modelMessageListener = new ModelMessageListener(); // // public void AddMessage(String msg, boolean isError){ // AddMessage(msg, isError, false); // } // // @SuppressWarnings("unused") // public void AddMessage(String msg, boolean isError, boolean isWarning){ // //TODO: Add to list + android log... rest can wait... post log guide in this class. // if(msg != null && !msg.isEmpty() && (Tags.DEBUG || isError)){ // messages.add(msg); // if(isError){ // Log.e(Tags.APP_TAG, msg); // Toast.makeText(MainActivity.GetMainContext(), "ERR: " + msg, Toast.LENGTH_LONG).show(); // }else if(isWarning){ // Log.w(Tags.APP_TAG, msg); // }else{ // Log.i(Tags.APP_TAG, msg); // } // if(messages.size() > maxMessages) // messages.poll(); // } // } // // public void AddMessage(String msg){ // AddMessage(msg, false); // } // // private class ModelMessageListener extends EventListener<Message>{ // @Override // public void onEvent(Message event) { // AddMessage(event.Message, event.Type == MessageType.Error, event.Type == MessageType.Warning); // } // } // } // // Path: src/com/blochstech/bitcoincardterminal/ViewModel/ViewStateManagers/NavigationManager.java // public class NavigationManager { // //Singleton pattern: // private static NavigationManager instance = null; // public static NavigationManager Instance() // { // if(instance == null) // { // instance = new NavigationManager(); // } // return instance; // } // private NavigationManager() // { // UpdateEvent = new Event<Object>(this); // } // //Singleton pattern end. // // public Event<Object> UpdateEvent; // // private boolean allowRightSwipe = true, allowLeftSwipe = true; // public boolean AllowRightSwipe(){ // return allowRightSwipe; // } // public boolean AllowLeftSwipe(){ // return allowLeftSwipe; // } // public void allowSwipes(boolean right, boolean left){ // allowRightSwipe = right; // allowLeftSwipe = left; // } // // private int currentPage = 0; // public int CurrentPageNumber(){ // return currentPage; // } // private PageTags currentPageEnum = PageTags.CHARGE_PAGE; // public PageTags CurrentPage(){ // return currentPageEnum; // } // private void setPage(int page){ // if(page < 4 && page >= 0){ // currentPage = page; // } // } // // public void setPage(PageTags page){ // setPage(page, false); // } // public void setPage(PageTags page, boolean quiet){ // if(page == PageTags.CHARGE_PAGE){ // setPage(0); // allowSwipes(true, false); // } // if(page == PageTags.HISTORY_PAGE){ // setPage(1); // allowSwipes(false, true); // } // if(page == PageTags.PIN_PAGE){ // setPage(2); // allowSwipes(false, false); // } // if(page == PageTags.SETTINGS_PAGE){ // setPage(3); // allowSwipes(false, false); // } // // currentPageEnum = page; // if(!quiet) // UpdateEvent.fire(this, null); // } // }
import com.blochstech.bitcoincardterminal.ViewModel.ViewStateManagers.MessageManager; import com.blochstech.bitcoincardterminal.ViewModel.ViewStateManagers.NavigationManager; import android.content.Context; import android.support.v4.view.ViewPager; import android.util.AttributeSet;
package com.blochstech.bitcoincardterminal.View; public class MainFragmentPager extends ViewPager { public MainFragmentPager(Context context) { super(context); } public MainFragmentPager(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean onTouchEvent(android.view.MotionEvent event) { if(event.getActionMasked() == 2 && !NavigationManager.Instance().AllowLeftSwipe() && !NavigationManager.Instance().AllowRightSwipe()) { return false; } return super.onTouchEvent(event); } @Override public void setCurrentItem(int i) { try{ super.setCurrentItem(i); }catch(Exception ex){
// Path: src/com/blochstech/bitcoincardterminal/ViewModel/ViewStateManagers/MessageManager.java // public class MessageManager { // //Singleton pattern: // private static MessageManager instance = null; // public static MessageManager Instance() // { // if(instance == null) // { // instance = new MessageManager(); // } // return instance; // } // private MessageManager() // { // Model.Instance().MessageEventReference().register(modelMessageListener); // } // //Singleton pattern end. // // private Queue<String> messages = new LinkedList<String>(); // private final int maxMessages = 500; // private EventListener<Message> modelMessageListener = new ModelMessageListener(); // // public void AddMessage(String msg, boolean isError){ // AddMessage(msg, isError, false); // } // // @SuppressWarnings("unused") // public void AddMessage(String msg, boolean isError, boolean isWarning){ // //TODO: Add to list + android log... rest can wait... post log guide in this class. // if(msg != null && !msg.isEmpty() && (Tags.DEBUG || isError)){ // messages.add(msg); // if(isError){ // Log.e(Tags.APP_TAG, msg); // Toast.makeText(MainActivity.GetMainContext(), "ERR: " + msg, Toast.LENGTH_LONG).show(); // }else if(isWarning){ // Log.w(Tags.APP_TAG, msg); // }else{ // Log.i(Tags.APP_TAG, msg); // } // if(messages.size() > maxMessages) // messages.poll(); // } // } // // public void AddMessage(String msg){ // AddMessage(msg, false); // } // // private class ModelMessageListener extends EventListener<Message>{ // @Override // public void onEvent(Message event) { // AddMessage(event.Message, event.Type == MessageType.Error, event.Type == MessageType.Warning); // } // } // } // // Path: src/com/blochstech/bitcoincardterminal/ViewModel/ViewStateManagers/NavigationManager.java // public class NavigationManager { // //Singleton pattern: // private static NavigationManager instance = null; // public static NavigationManager Instance() // { // if(instance == null) // { // instance = new NavigationManager(); // } // return instance; // } // private NavigationManager() // { // UpdateEvent = new Event<Object>(this); // } // //Singleton pattern end. // // public Event<Object> UpdateEvent; // // private boolean allowRightSwipe = true, allowLeftSwipe = true; // public boolean AllowRightSwipe(){ // return allowRightSwipe; // } // public boolean AllowLeftSwipe(){ // return allowLeftSwipe; // } // public void allowSwipes(boolean right, boolean left){ // allowRightSwipe = right; // allowLeftSwipe = left; // } // // private int currentPage = 0; // public int CurrentPageNumber(){ // return currentPage; // } // private PageTags currentPageEnum = PageTags.CHARGE_PAGE; // public PageTags CurrentPage(){ // return currentPageEnum; // } // private void setPage(int page){ // if(page < 4 && page >= 0){ // currentPage = page; // } // } // // public void setPage(PageTags page){ // setPage(page, false); // } // public void setPage(PageTags page, boolean quiet){ // if(page == PageTags.CHARGE_PAGE){ // setPage(0); // allowSwipes(true, false); // } // if(page == PageTags.HISTORY_PAGE){ // setPage(1); // allowSwipes(false, true); // } // if(page == PageTags.PIN_PAGE){ // setPage(2); // allowSwipes(false, false); // } // if(page == PageTags.SETTINGS_PAGE){ // setPage(3); // allowSwipes(false, false); // } // // currentPageEnum = page; // if(!quiet) // UpdateEvent.fire(this, null); // } // } // Path: src/com/blochstech/bitcoincardterminal/View/MainFragmentPager.java import com.blochstech.bitcoincardterminal.ViewModel.ViewStateManagers.MessageManager; import com.blochstech.bitcoincardterminal.ViewModel.ViewStateManagers.NavigationManager; import android.content.Context; import android.support.v4.view.ViewPager; import android.util.AttributeSet; package com.blochstech.bitcoincardterminal.View; public class MainFragmentPager extends ViewPager { public MainFragmentPager(Context context) { super(context); } public MainFragmentPager(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean onTouchEvent(android.view.MotionEvent event) { if(event.getActionMasked() == 2 && !NavigationManager.Instance().AllowLeftSwipe() && !NavigationManager.Instance().AllowRightSwipe()) { return false; } return super.onTouchEvent(event); } @Override public void setCurrentItem(int i) { try{ super.setCurrentItem(i); }catch(Exception ex){
MessageManager.Instance().AddMessage("Failed to set page to page #" + i + ". Likely the page's startup code or XML layout file is invalid."
BlochsTech/BitcoinCardTerminal
src/com/blochstech/bitcoincardterminal/Model/Communication/BitcoinCardStateObject.java
// Path: src/com/blochstech/bitcoincardterminal/Model/AppSettings.java // public class AppSettings { // public static final double DUST_LIMIT = 0.00005460; // public static final double MIN_FEE_BITCOINS = 0.0001; // } // // Path: src/com/blochstech/bitcoincardterminal/Utils/ShortNumberConverter.java // public class ShortNumberConverter { // // public static String ToShort(Double value){ // NumberFormat formatter = new DecimalFormat(); // // formatter = new DecimalFormat("0.000E00"); // String temp = formatter.format(value); // // String temp2 = temp.substring(0, 5); // temp2 = temp2.replace(",", "."); // Double temp3 = Double.parseDouble(temp2); // formatter = new DecimalFormat("0.00"); // formatter.setRoundingMode(RoundingMode.HALF_UP); // temp = formatter.format(temp3) + temp.substring(5); // // if(!temp.contains("E-")){ // temp = temp.substring(0, temp.indexOf("E")+1) + "0" + temp.substring(temp.indexOf("E")+1, temp.length()); // } // // return temp.toLowerCase(Locale.ENGLISH); // } // /*public static Double FromShort(String value){ // // }*/ // } // // Path: src/com/blochstech/bitcoincardterminal/Utils/SyntacticSugar.java // public class SyntacticSugar { // @SuppressWarnings("unchecked") // public static <T> T castAs(Object castee){ // try{ // return (T) castee; // }catch(Exception ex){ // return null; // } // } // // public static boolean EqualWithinMargin(Double value1, Double value2, Double margin){ // return value1 * (1+margin) >= value2 && value2 * (1+margin) >= value1; // } // }
import java.util.ArrayList; import java.util.LinkedList; import java.util.Locale; import com.blochstech.bitcoincardterminal.Model.AppSettings; import com.blochstech.bitcoincardterminal.Utils.ShortNumberConverter; import com.blochstech.bitcoincardterminal.Utils.SyntacticSugar;
if(go1 == true && go2 == true) break; if(go1 == false){ if(addressBytes != null && waitingAddress != null) { if(addressBytes[i] != waitingAddress[i]){ waitingAddressMatch = false; go1 = true; } }else{ waitingAddressMatch = amount <= 0.0; go1 = true; } } if(go2 == false){ if(terminalAddressBytes != null && waitingTerminalAddress != null) { if(terminalAddressBytes[i] != waitingTerminalAddress[i]){ waitingTerminalAddressMatch = false; go1 = true; } }else{ waitingAddressMatch = terminalAmount <= 0.0; go2 = true; } } } return waitingKnown && waitingAddressMatch && waitingTerminalAddressMatch
// Path: src/com/blochstech/bitcoincardterminal/Model/AppSettings.java // public class AppSettings { // public static final double DUST_LIMIT = 0.00005460; // public static final double MIN_FEE_BITCOINS = 0.0001; // } // // Path: src/com/blochstech/bitcoincardterminal/Utils/ShortNumberConverter.java // public class ShortNumberConverter { // // public static String ToShort(Double value){ // NumberFormat formatter = new DecimalFormat(); // // formatter = new DecimalFormat("0.000E00"); // String temp = formatter.format(value); // // String temp2 = temp.substring(0, 5); // temp2 = temp2.replace(",", "."); // Double temp3 = Double.parseDouble(temp2); // formatter = new DecimalFormat("0.00"); // formatter.setRoundingMode(RoundingMode.HALF_UP); // temp = formatter.format(temp3) + temp.substring(5); // // if(!temp.contains("E-")){ // temp = temp.substring(0, temp.indexOf("E")+1) + "0" + temp.substring(temp.indexOf("E")+1, temp.length()); // } // // return temp.toLowerCase(Locale.ENGLISH); // } // /*public static Double FromShort(String value){ // // }*/ // } // // Path: src/com/blochstech/bitcoincardterminal/Utils/SyntacticSugar.java // public class SyntacticSugar { // @SuppressWarnings("unchecked") // public static <T> T castAs(Object castee){ // try{ // return (T) castee; // }catch(Exception ex){ // return null; // } // } // // public static boolean EqualWithinMargin(Double value1, Double value2, Double margin){ // return value1 * (1+margin) >= value2 && value2 * (1+margin) >= value1; // } // } // Path: src/com/blochstech/bitcoincardterminal/Model/Communication/BitcoinCardStateObject.java import java.util.ArrayList; import java.util.LinkedList; import java.util.Locale; import com.blochstech.bitcoincardterminal.Model.AppSettings; import com.blochstech.bitcoincardterminal.Utils.ShortNumberConverter; import com.blochstech.bitcoincardterminal.Utils.SyntacticSugar; if(go1 == true && go2 == true) break; if(go1 == false){ if(addressBytes != null && waitingAddress != null) { if(addressBytes[i] != waitingAddress[i]){ waitingAddressMatch = false; go1 = true; } }else{ waitingAddressMatch = amount <= 0.0; go1 = true; } } if(go2 == false){ if(terminalAddressBytes != null && waitingTerminalAddress != null) { if(terminalAddressBytes[i] != waitingTerminalAddress[i]){ waitingTerminalAddressMatch = false; go1 = true; } }else{ waitingAddressMatch = terminalAmount <= 0.0; go2 = true; } } } return waitingKnown && waitingAddressMatch && waitingTerminalAddressMatch
&& SyntacticSugar.EqualWithinMargin(amount, waitingAmount, 0.001)
BlochsTech/BitcoinCardTerminal
src/com/blochstech/bitcoincardterminal/Model/Communication/BitcoinCardStateObject.java
// Path: src/com/blochstech/bitcoincardterminal/Model/AppSettings.java // public class AppSettings { // public static final double DUST_LIMIT = 0.00005460; // public static final double MIN_FEE_BITCOINS = 0.0001; // } // // Path: src/com/blochstech/bitcoincardterminal/Utils/ShortNumberConverter.java // public class ShortNumberConverter { // // public static String ToShort(Double value){ // NumberFormat formatter = new DecimalFormat(); // // formatter = new DecimalFormat("0.000E00"); // String temp = formatter.format(value); // // String temp2 = temp.substring(0, 5); // temp2 = temp2.replace(",", "."); // Double temp3 = Double.parseDouble(temp2); // formatter = new DecimalFormat("0.00"); // formatter.setRoundingMode(RoundingMode.HALF_UP); // temp = formatter.format(temp3) + temp.substring(5); // // if(!temp.contains("E-")){ // temp = temp.substring(0, temp.indexOf("E")+1) + "0" + temp.substring(temp.indexOf("E")+1, temp.length()); // } // // return temp.toLowerCase(Locale.ENGLISH); // } // /*public static Double FromShort(String value){ // // }*/ // } // // Path: src/com/blochstech/bitcoincardterminal/Utils/SyntacticSugar.java // public class SyntacticSugar { // @SuppressWarnings("unchecked") // public static <T> T castAs(Object castee){ // try{ // return (T) castee; // }catch(Exception ex){ // return null; // } // } // // public static boolean EqualWithinMargin(Double value1, Double value2, Double margin){ // return value1 * (1+margin) >= value2 && value2 * (1+margin) >= value1; // } // }
import java.util.ArrayList; import java.util.LinkedList; import java.util.Locale; import com.blochstech.bitcoincardterminal.Model.AppSettings; import com.blochstech.bitcoincardterminal.Utils.ShortNumberConverter; import com.blochstech.bitcoincardterminal.Utils.SyntacticSugar;
if(knownSources.get(i).TXHash.toLowerCase(Locale.ENGLISH).equals(txHash.toLowerCase(Locale.ENGLISH))) return knownSources.get(i).Verified; } return false; } //TODO: This is becomming too complex to understand, consider moving logic into separated self-contained "steps"... //basically what we are doing with ProcessStateChange... CONSIDER solutions void addKnownSource(TXSourceId source){ if(!knownSource(source)){ knownSources.add(source); }else{ for(int i = 0; i < knownSources.size(); i++){ if(knownSources.get(i).TXHash.toLowerCase(Locale.ENGLISH).equals(source.TXHash.toLowerCase(Locale.ENGLISH))){ source.Unusable = knownSources.get(i).Unusable || source.Unusable; knownSources.set(i, source); } } } } //This method does not handle the "Purchase complete."-message. TODO: Make sure the charge gets cleared etc. to prevent accidental auto double-charge.. String updateCardMessageFromState(){ if(!isConnected || cardNetworkType != 0 || cardProtocolType != 0) return "No card."; if (paymentComplete != 0){ return paymentComplete == 1 ? "Payment complete." : "Error"; }
// Path: src/com/blochstech/bitcoincardterminal/Model/AppSettings.java // public class AppSettings { // public static final double DUST_LIMIT = 0.00005460; // public static final double MIN_FEE_BITCOINS = 0.0001; // } // // Path: src/com/blochstech/bitcoincardterminal/Utils/ShortNumberConverter.java // public class ShortNumberConverter { // // public static String ToShort(Double value){ // NumberFormat formatter = new DecimalFormat(); // // formatter = new DecimalFormat("0.000E00"); // String temp = formatter.format(value); // // String temp2 = temp.substring(0, 5); // temp2 = temp2.replace(",", "."); // Double temp3 = Double.parseDouble(temp2); // formatter = new DecimalFormat("0.00"); // formatter.setRoundingMode(RoundingMode.HALF_UP); // temp = formatter.format(temp3) + temp.substring(5); // // if(!temp.contains("E-")){ // temp = temp.substring(0, temp.indexOf("E")+1) + "0" + temp.substring(temp.indexOf("E")+1, temp.length()); // } // // return temp.toLowerCase(Locale.ENGLISH); // } // /*public static Double FromShort(String value){ // // }*/ // } // // Path: src/com/blochstech/bitcoincardterminal/Utils/SyntacticSugar.java // public class SyntacticSugar { // @SuppressWarnings("unchecked") // public static <T> T castAs(Object castee){ // try{ // return (T) castee; // }catch(Exception ex){ // return null; // } // } // // public static boolean EqualWithinMargin(Double value1, Double value2, Double margin){ // return value1 * (1+margin) >= value2 && value2 * (1+margin) >= value1; // } // } // Path: src/com/blochstech/bitcoincardterminal/Model/Communication/BitcoinCardStateObject.java import java.util.ArrayList; import java.util.LinkedList; import java.util.Locale; import com.blochstech.bitcoincardterminal.Model.AppSettings; import com.blochstech.bitcoincardterminal.Utils.ShortNumberConverter; import com.blochstech.bitcoincardterminal.Utils.SyntacticSugar; if(knownSources.get(i).TXHash.toLowerCase(Locale.ENGLISH).equals(txHash.toLowerCase(Locale.ENGLISH))) return knownSources.get(i).Verified; } return false; } //TODO: This is becomming too complex to understand, consider moving logic into separated self-contained "steps"... //basically what we are doing with ProcessStateChange... CONSIDER solutions void addKnownSource(TXSourceId source){ if(!knownSource(source)){ knownSources.add(source); }else{ for(int i = 0; i < knownSources.size(); i++){ if(knownSources.get(i).TXHash.toLowerCase(Locale.ENGLISH).equals(source.TXHash.toLowerCase(Locale.ENGLISH))){ source.Unusable = knownSources.get(i).Unusable || source.Unusable; knownSources.set(i, source); } } } } //This method does not handle the "Purchase complete."-message. TODO: Make sure the charge gets cleared etc. to prevent accidental auto double-charge.. String updateCardMessageFromState(){ if(!isConnected || cardNetworkType != 0 || cardProtocolType != 0) return "No card."; if (paymentComplete != 0){ return paymentComplete == 1 ? "Payment complete." : "Error"; }
if(amount < AppSettings.DUST_LIMIT)
BlochsTech/BitcoinCardTerminal
src/com/blochstech/bitcoincardterminal/Model/Communication/BitcoinCardStateObject.java
// Path: src/com/blochstech/bitcoincardterminal/Model/AppSettings.java // public class AppSettings { // public static final double DUST_LIMIT = 0.00005460; // public static final double MIN_FEE_BITCOINS = 0.0001; // } // // Path: src/com/blochstech/bitcoincardterminal/Utils/ShortNumberConverter.java // public class ShortNumberConverter { // // public static String ToShort(Double value){ // NumberFormat formatter = new DecimalFormat(); // // formatter = new DecimalFormat("0.000E00"); // String temp = formatter.format(value); // // String temp2 = temp.substring(0, 5); // temp2 = temp2.replace(",", "."); // Double temp3 = Double.parseDouble(temp2); // formatter = new DecimalFormat("0.00"); // formatter.setRoundingMode(RoundingMode.HALF_UP); // temp = formatter.format(temp3) + temp.substring(5); // // if(!temp.contains("E-")){ // temp = temp.substring(0, temp.indexOf("E")+1) + "0" + temp.substring(temp.indexOf("E")+1, temp.length()); // } // // return temp.toLowerCase(Locale.ENGLISH); // } // /*public static Double FromShort(String value){ // // }*/ // } // // Path: src/com/blochstech/bitcoincardterminal/Utils/SyntacticSugar.java // public class SyntacticSugar { // @SuppressWarnings("unchecked") // public static <T> T castAs(Object castee){ // try{ // return (T) castee; // }catch(Exception ex){ // return null; // } // } // // public static boolean EqualWithinMargin(Double value1, Double value2, Double margin){ // return value1 * (1+margin) >= value2 && value2 * (1+margin) >= value1; // } // }
import java.util.ArrayList; import java.util.LinkedList; import java.util.Locale; import com.blochstech.bitcoincardterminal.Model.AppSettings; import com.blochstech.bitcoincardterminal.Utils.ShortNumberConverter; import com.blochstech.bitcoincardterminal.Utils.SyntacticSugar;
} //TODO: This is becomming too complex to understand, consider moving logic into separated self-contained "steps"... //basically what we are doing with ProcessStateChange... CONSIDER solutions void addKnownSource(TXSourceId source){ if(!knownSource(source)){ knownSources.add(source); }else{ for(int i = 0; i < knownSources.size(); i++){ if(knownSources.get(i).TXHash.toLowerCase(Locale.ENGLISH).equals(source.TXHash.toLowerCase(Locale.ENGLISH))){ source.Unusable = knownSources.get(i).Unusable || source.Unusable; knownSources.set(i, source); } } } } //This method does not handle the "Purchase complete."-message. TODO: Make sure the charge gets cleared etc. to prevent accidental auto double-charge.. String updateCardMessageFromState(){ if(!isConnected || cardNetworkType != 0 || cardProtocolType != 0) return "No card."; if (paymentComplete != 0){ return paymentComplete == 1 ? "Payment complete." : "Error"; } if(amount < AppSettings.DUST_LIMIT) return "Below dust limit."; if(maxCardCharge != null && totalChargeAsBitcoin() != null && maxCardCharge < totalChargeAsBitcoin())
// Path: src/com/blochstech/bitcoincardterminal/Model/AppSettings.java // public class AppSettings { // public static final double DUST_LIMIT = 0.00005460; // public static final double MIN_FEE_BITCOINS = 0.0001; // } // // Path: src/com/blochstech/bitcoincardterminal/Utils/ShortNumberConverter.java // public class ShortNumberConverter { // // public static String ToShort(Double value){ // NumberFormat formatter = new DecimalFormat(); // // formatter = new DecimalFormat("0.000E00"); // String temp = formatter.format(value); // // String temp2 = temp.substring(0, 5); // temp2 = temp2.replace(",", "."); // Double temp3 = Double.parseDouble(temp2); // formatter = new DecimalFormat("0.00"); // formatter.setRoundingMode(RoundingMode.HALF_UP); // temp = formatter.format(temp3) + temp.substring(5); // // if(!temp.contains("E-")){ // temp = temp.substring(0, temp.indexOf("E")+1) + "0" + temp.substring(temp.indexOf("E")+1, temp.length()); // } // // return temp.toLowerCase(Locale.ENGLISH); // } // /*public static Double FromShort(String value){ // // }*/ // } // // Path: src/com/blochstech/bitcoincardterminal/Utils/SyntacticSugar.java // public class SyntacticSugar { // @SuppressWarnings("unchecked") // public static <T> T castAs(Object castee){ // try{ // return (T) castee; // }catch(Exception ex){ // return null; // } // } // // public static boolean EqualWithinMargin(Double value1, Double value2, Double margin){ // return value1 * (1+margin) >= value2 && value2 * (1+margin) >= value1; // } // } // Path: src/com/blochstech/bitcoincardterminal/Model/Communication/BitcoinCardStateObject.java import java.util.ArrayList; import java.util.LinkedList; import java.util.Locale; import com.blochstech.bitcoincardterminal.Model.AppSettings; import com.blochstech.bitcoincardterminal.Utils.ShortNumberConverter; import com.blochstech.bitcoincardterminal.Utils.SyntacticSugar; } //TODO: This is becomming too complex to understand, consider moving logic into separated self-contained "steps"... //basically what we are doing with ProcessStateChange... CONSIDER solutions void addKnownSource(TXSourceId source){ if(!knownSource(source)){ knownSources.add(source); }else{ for(int i = 0; i < knownSources.size(); i++){ if(knownSources.get(i).TXHash.toLowerCase(Locale.ENGLISH).equals(source.TXHash.toLowerCase(Locale.ENGLISH))){ source.Unusable = knownSources.get(i).Unusable || source.Unusable; knownSources.set(i, source); } } } } //This method does not handle the "Purchase complete."-message. TODO: Make sure the charge gets cleared etc. to prevent accidental auto double-charge.. String updateCardMessageFromState(){ if(!isConnected || cardNetworkType != 0 || cardProtocolType != 0) return "No card."; if (paymentComplete != 0){ return paymentComplete == 1 ? "Payment complete." : "Error"; } if(amount < AppSettings.DUST_LIMIT) return "Below dust limit."; if(maxCardCharge != null && totalChargeAsBitcoin() != null && maxCardCharge < totalChargeAsBitcoin())
return "Over max " + ShortNumberConverter.ToShort(maxCardCharge) + ".";
BlochsTech/BitcoinCardTerminal
src/com/blochstech/bitcoincardterminal/Utils/ByteConversionUtil.java
// Path: src/com/blochstech/bitcoincardterminal/Model/Communication/MerkleBranchElement.java // public class MerkleBranchElement { // public String hash; //This is the one sent to the card. // public boolean rightNode; //True if property hash is on the right side of the pair. // public String otherHash; //In the first round this is the txHash. // // public MerkleBranchElement(String hash, boolean rightNode, String otherHash){ // this.hash = hash; // this.rightNode = rightNode; // this.otherHash = otherHash; // } // }
import java.nio.ByteBuffer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.LinkedList; import java.util.List; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import com.blochstech.bitcoincardterminal.Model.Communication.MerkleBranchElement;
public static int[] toUnsigned(byte[] bytes) { if (bytes == null) return null; int[] res = new int[bytes.length]; for(int i = 0; i < bytes.length; i++){ res[i] = (int) (bytes[i] < 0 ? bytes[i] + 256 : bytes[i]); } return res; } public static int toUnsigned(byte singleByte) { return (int) (singleByte < 0 ? singleByte + 256 : singleByte); } public static byte[] hexStringToByteArray(String s) { if(RegexUtil.isMatch(s, RegexUtil.CommonPatterns.BYTEHEX)){ int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16)); } return data; }else{ return null; } }
// Path: src/com/blochstech/bitcoincardterminal/Model/Communication/MerkleBranchElement.java // public class MerkleBranchElement { // public String hash; //This is the one sent to the card. // public boolean rightNode; //True if property hash is on the right side of the pair. // public String otherHash; //In the first round this is the txHash. // // public MerkleBranchElement(String hash, boolean rightNode, String otherHash){ // this.hash = hash; // this.rightNode = rightNode; // this.otherHash = otherHash; // } // } // Path: src/com/blochstech/bitcoincardterminal/Utils/ByteConversionUtil.java import java.nio.ByteBuffer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.LinkedList; import java.util.List; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import com.blochstech.bitcoincardterminal.Model.Communication.MerkleBranchElement; public static int[] toUnsigned(byte[] bytes) { if (bytes == null) return null; int[] res = new int[bytes.length]; for(int i = 0; i < bytes.length; i++){ res[i] = (int) (bytes[i] < 0 ? bytes[i] + 256 : bytes[i]); } return res; } public static int toUnsigned(byte singleByte) { return (int) (singleByte < 0 ? singleByte + 256 : singleByte); } public static byte[] hexStringToByteArray(String s) { if(RegexUtil.isMatch(s, RegexUtil.CommonPatterns.BYTEHEX)){ int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16)); } return data; }else{ return null; } }
public static MerkleBranchElement[] MerkleListToArray(LinkedList<MerkleBranchElement> list){
blubin/JOpt
src/main/java/edu/harvard/econcs/jopt/solver/mip/Variable.java
// Path: src/main/java/edu/harvard/econcs/jopt/solver/MIPException.java // public class MIPException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 3257289123487103030L; // // public MIPException(String msg) { // super(msg); // } // // public MIPException(String msg, Throwable arg1) { // super(msg, arg1); // } // }
import java.io.Serializable; import edu.harvard.econcs.jopt.solver.MIPException;
/* * Copyright (c) 2005-2017 Benjamin Lubin * Copyright (c) 2005-2017 The President and Fellows of Harvard College * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.harvard.econcs.jopt.solver.mip; /** * Basic MIP Variable. * * @author Benjamin Lubin Last modified by $Author: blubin $ * @version $Revision: 1.8 $ on $Date: 2013/12/03 23:52:56 $ * @since Apr 13, 2004 */ public class Variable implements Serializable, Cloneable { private static final long serialVersionUID = 45646456456l; private String name; private double lowerBound; private double upperBound; private VarType type; private boolean ignore = false; /** * @param name * @param upperBound * @param lowerBound * @param type */ public Variable(String name, VarType type, double lowerBound, double upperBound) { super(); MIP.checkMax(lowerBound); if (lowerBound > upperBound) {
// Path: src/main/java/edu/harvard/econcs/jopt/solver/MIPException.java // public class MIPException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 3257289123487103030L; // // public MIPException(String msg) { // super(msg); // } // // public MIPException(String msg, Throwable arg1) { // super(msg, arg1); // } // } // Path: src/main/java/edu/harvard/econcs/jopt/solver/mip/Variable.java import java.io.Serializable; import edu.harvard.econcs.jopt.solver.MIPException; /* * Copyright (c) 2005-2017 Benjamin Lubin * Copyright (c) 2005-2017 The President and Fellows of Harvard College * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.harvard.econcs.jopt.solver.mip; /** * Basic MIP Variable. * * @author Benjamin Lubin Last modified by $Author: blubin $ * @version $Revision: 1.8 $ on $Date: 2013/12/03 23:52:56 $ * @since Apr 13, 2004 */ public class Variable implements Serializable, Cloneable { private static final long serialVersionUID = 45646456456l; private String name; private double lowerBound; private double upperBound; private VarType type; private boolean ignore = false; /** * @param name * @param upperBound * @param lowerBound * @param type */ public Variable(String name, VarType type, double lowerBound, double upperBound) { super(); MIP.checkMax(lowerBound); if (lowerBound > upperBound) {
throw new MIPException("Lowerbound must be less than upperBound");
blubin/JOpt
src/main/java/edu/harvard/econcs/jopt/solver/mip/LinearTerm.java
// Path: src/main/java/edu/harvard/econcs/jopt/solver/MIPException.java // public class MIPException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 3257289123487103030L; // // public MIPException(String msg) { // super(msg); // } // // public MIPException(String msg, Throwable arg1) { // super(msg, arg1); // } // }
import java.io.Serializable; import edu.harvard.econcs.jopt.solver.MIPException;
/* * Copyright (c) 2005-2017 Benjamin Lubin * Copyright (c) 2005-2017 The President and Fellows of Harvard College * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.harvard.econcs.jopt.solver.mip; /** * Represents a Linear Term * * @author Benjamin Lubin; Last modified by $Author: blubin $ * @version $Revision: 1.2 $ on $Date: 2013/12/04 02:54:09 $ * @since Apr 13, 2004 **/ public class LinearTerm implements Serializable, Cloneable, Term { private static final long serialVersionUID = 8777676765l; private double coefficient; private String varName; /** * @param coefficient * @param varIndex */ private LinearTerm(double coefficient, String varName) { MIP.checkMax(coefficient); this.coefficient = coefficient; this.varName = varName; } public LinearTerm(double coefficient, Variable var) { this(coefficient, var.getName()); } /** * @return Returns the coefficient. */ public double getCoefficient() { return coefficient; } /** * @return Returns the varIndex. */ public String getVarName() { return varName; } public String toString() { //return coefficient +"*V" + varName; return coefficient +"*" + varName; } public Object clone() throws CloneNotSupportedException { LinearTerm ret = (LinearTerm)super.clone(); return ret; } public LinearTerm typedClone() { try { return (LinearTerm)clone(); } catch (CloneNotSupportedException e) {
// Path: src/main/java/edu/harvard/econcs/jopt/solver/MIPException.java // public class MIPException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 3257289123487103030L; // // public MIPException(String msg) { // super(msg); // } // // public MIPException(String msg, Throwable arg1) { // super(msg, arg1); // } // } // Path: src/main/java/edu/harvard/econcs/jopt/solver/mip/LinearTerm.java import java.io.Serializable; import edu.harvard.econcs.jopt.solver.MIPException; /* * Copyright (c) 2005-2017 Benjamin Lubin * Copyright (c) 2005-2017 The President and Fellows of Harvard College * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.harvard.econcs.jopt.solver.mip; /** * Represents a Linear Term * * @author Benjamin Lubin; Last modified by $Author: blubin $ * @version $Revision: 1.2 $ on $Date: 2013/12/04 02:54:09 $ * @since Apr 13, 2004 **/ public class LinearTerm implements Serializable, Cloneable, Term { private static final long serialVersionUID = 8777676765l; private double coefficient; private String varName; /** * @param coefficient * @param varIndex */ private LinearTerm(double coefficient, String varName) { MIP.checkMax(coefficient); this.coefficient = coefficient; this.varName = varName; } public LinearTerm(double coefficient, Variable var) { this(coefficient, var.getName()); } /** * @return Returns the coefficient. */ public double getCoefficient() { return coefficient; } /** * @return Returns the varIndex. */ public String getVarName() { return varName; } public String toString() { //return coefficient +"*V" + varName; return coefficient +"*" + varName; } public Object clone() throws CloneNotSupportedException { LinearTerm ret = (LinearTerm)super.clone(); return ret; } public LinearTerm typedClone() { try { return (LinearTerm)clone(); } catch (CloneNotSupportedException e) {
throw new MIPException("Problem in clone", e);
blubin/JOpt
src/main/java/edu/harvard/econcs/jopt/solver/mip/Constraint.java
// Path: src/main/java/edu/harvard/econcs/jopt/solver/MIPException.java // public class MIPException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 3257289123487103030L; // // public MIPException(String msg) { // super(msg); // } // // public MIPException(String msg, Throwable arg1) { // super(msg, arg1); // } // }
import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import edu.harvard.econcs.jopt.solver.MIPException;
return false; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } protected Object clone() throws CloneNotSupportedException { Constraint ret = (Constraint)super.clone(); if(linearTerms != null) { ret.linearTerms = new ArrayList(); for (LinearTerm term : getLinearTerms()) { ret.linearTerms.add(term.typedClone()); } } if(quadraticTerms != null) { ret.quadraticTerms = new ArrayList(); for (QuadraticTerm term : getQuadraticTerms()) { ret.quadraticTerms.add(term.typedClone()); } } return ret; } public Constraint typedClone() { try { return (Constraint)clone(); } catch (CloneNotSupportedException e) {
// Path: src/main/java/edu/harvard/econcs/jopt/solver/MIPException.java // public class MIPException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 3257289123487103030L; // // public MIPException(String msg) { // super(msg); // } // // public MIPException(String msg, Throwable arg1) { // super(msg, arg1); // } // } // Path: src/main/java/edu/harvard/econcs/jopt/solver/mip/Constraint.java import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import edu.harvard.econcs.jopt.solver.MIPException; return false; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } protected Object clone() throws CloneNotSupportedException { Constraint ret = (Constraint)super.clone(); if(linearTerms != null) { ret.linearTerms = new ArrayList(); for (LinearTerm term : getLinearTerms()) { ret.linearTerms.add(term.typedClone()); } } if(quadraticTerms != null) { ret.quadraticTerms = new ArrayList(); for (QuadraticTerm term : getQuadraticTerms()) { ret.quadraticTerms.add(term.typedClone()); } } return ret; } public Constraint typedClone() { try { return (Constraint)clone(); } catch (CloneNotSupportedException e) {
throw new MIPException("Problem in clone", e);
blubin/JOpt
src/main/java/edu/harvard/econcs/jopt/solver/server/SolverServer.java
// Path: src/main/java/edu/harvard/econcs/jopt/solver/IMIPSolver.java // public interface IMIPSolver { // /** Solves a MIP that you have constructed. Results for the solve are in the return value. */ // IMIPResult solve(IMIP mip) throws MIPException; // } // // Path: src/main/java/edu/harvard/econcs/jopt/solver/MIPException.java // public class MIPException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 3257289123487103030L; // // public MIPException(String msg) { // super(msg); // } // // public MIPException(String msg, Throwable arg1) { // super(msg, arg1); // } // }
import java.rmi.AccessException; import java.rmi.AlreadyBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import edu.harvard.econcs.jopt.solver.IMIPSolver; import edu.harvard.econcs.jopt.solver.MIPException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger;
/* * Copyright (c) 2005-2017 Benjamin Lubin * Copyright (c) 2005-2017 The President and Fellows of Harvard College * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.harvard.econcs.jopt.solver.server; /** * @author Benjamin Lubin; Last modified by $Author: blubin $ * @version $Revision: 1.5 $ on $Date: 2010/10/28 00:11:26 $ * @since Apr 12, 2004 **/ public class SolverServer extends UnicastRemoteObject implements ISolverServer { /** * */ private static final long serialVersionUID = 3977583593201872945L; private static final Logger log = LogManager.getLogger(SolverServer.class); private Class solverClass; protected int port; /** * Create a new Server * @param port * @param solverClass */
// Path: src/main/java/edu/harvard/econcs/jopt/solver/IMIPSolver.java // public interface IMIPSolver { // /** Solves a MIP that you have constructed. Results for the solve are in the return value. */ // IMIPResult solve(IMIP mip) throws MIPException; // } // // Path: src/main/java/edu/harvard/econcs/jopt/solver/MIPException.java // public class MIPException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 3257289123487103030L; // // public MIPException(String msg) { // super(msg); // } // // public MIPException(String msg, Throwable arg1) { // super(msg, arg1); // } // } // Path: src/main/java/edu/harvard/econcs/jopt/solver/server/SolverServer.java import java.rmi.AccessException; import java.rmi.AlreadyBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import edu.harvard.econcs.jopt.solver.IMIPSolver; import edu.harvard.econcs.jopt.solver.MIPException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /* * Copyright (c) 2005-2017 Benjamin Lubin * Copyright (c) 2005-2017 The President and Fellows of Harvard College * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.harvard.econcs.jopt.solver.server; /** * @author Benjamin Lubin; Last modified by $Author: blubin $ * @version $Revision: 1.5 $ on $Date: 2010/10/28 00:11:26 $ * @since Apr 12, 2004 **/ public class SolverServer extends UnicastRemoteObject implements ISolverServer { /** * */ private static final long serialVersionUID = 3977583593201872945L; private static final Logger log = LogManager.getLogger(SolverServer.class); private Class solverClass; protected int port; /** * Create a new Server * @param port * @param solverClass */
public static void createServer(int port, Class solverClass) throws MIPException {
blubin/JOpt
src/main/java/edu/harvard/econcs/jopt/solver/server/SolverServer.java
// Path: src/main/java/edu/harvard/econcs/jopt/solver/IMIPSolver.java // public interface IMIPSolver { // /** Solves a MIP that you have constructed. Results for the solve are in the return value. */ // IMIPResult solve(IMIP mip) throws MIPException; // } // // Path: src/main/java/edu/harvard/econcs/jopt/solver/MIPException.java // public class MIPException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 3257289123487103030L; // // public MIPException(String msg) { // super(msg); // } // // public MIPException(String msg, Throwable arg1) { // super(msg, arg1); // } // }
import java.rmi.AccessException; import java.rmi.AlreadyBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import edu.harvard.econcs.jopt.solver.IMIPSolver; import edu.harvard.econcs.jopt.solver.MIPException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger;
/* * Copyright (c) 2005-2017 Benjamin Lubin * Copyright (c) 2005-2017 The President and Fellows of Harvard College * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.harvard.econcs.jopt.solver.server; /** * @author Benjamin Lubin; Last modified by $Author: blubin $ * @version $Revision: 1.5 $ on $Date: 2010/10/28 00:11:26 $ * @since Apr 12, 2004 **/ public class SolverServer extends UnicastRemoteObject implements ISolverServer { /** * */ private static final long serialVersionUID = 3977583593201872945L; private static final Logger log = LogManager.getLogger(SolverServer.class); private Class solverClass; protected int port; /** * Create a new Server * @param port * @param solverClass */ public static void createServer(int port, Class solverClass) throws MIPException { try { log.info("Binding server to port: " + port); Registry localreg = LocateRegistry.createRegistry(port); SolverServer server = new SolverServer(port, solverClass); localreg.bind(NAME, server); } catch (AccessException e) { throw new MIPException("Access", e); } catch (AlreadyBoundException e) { throw new MIPException("AlreadyBound",e); } catch (RemoteException e) { throw new MIPException("RemoteException",e); } } /** * @param solverClass -- what class to use to create new instances * of the solver. * @throws RemoteException */ protected SolverServer(int port, Class solverClass) throws RemoteException { super(port); this.port = port; this.solverClass = solverClass; } /** * @see edu.harvard.econcs.jopt.solver.server.ISolverServer#getSolver() */ public IRemoteMIPSolver getSolver() throws RemoteException { log.info("Creating a new Solver Instance");
// Path: src/main/java/edu/harvard/econcs/jopt/solver/IMIPSolver.java // public interface IMIPSolver { // /** Solves a MIP that you have constructed. Results for the solve are in the return value. */ // IMIPResult solve(IMIP mip) throws MIPException; // } // // Path: src/main/java/edu/harvard/econcs/jopt/solver/MIPException.java // public class MIPException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 3257289123487103030L; // // public MIPException(String msg) { // super(msg); // } // // public MIPException(String msg, Throwable arg1) { // super(msg, arg1); // } // } // Path: src/main/java/edu/harvard/econcs/jopt/solver/server/SolverServer.java import java.rmi.AccessException; import java.rmi.AlreadyBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import edu.harvard.econcs.jopt.solver.IMIPSolver; import edu.harvard.econcs.jopt.solver.MIPException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /* * Copyright (c) 2005-2017 Benjamin Lubin * Copyright (c) 2005-2017 The President and Fellows of Harvard College * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.harvard.econcs.jopt.solver.server; /** * @author Benjamin Lubin; Last modified by $Author: blubin $ * @version $Revision: 1.5 $ on $Date: 2010/10/28 00:11:26 $ * @since Apr 12, 2004 **/ public class SolverServer extends UnicastRemoteObject implements ISolverServer { /** * */ private static final long serialVersionUID = 3977583593201872945L; private static final Logger log = LogManager.getLogger(SolverServer.class); private Class solverClass; protected int port; /** * Create a new Server * @param port * @param solverClass */ public static void createServer(int port, Class solverClass) throws MIPException { try { log.info("Binding server to port: " + port); Registry localreg = LocateRegistry.createRegistry(port); SolverServer server = new SolverServer(port, solverClass); localreg.bind(NAME, server); } catch (AccessException e) { throw new MIPException("Access", e); } catch (AlreadyBoundException e) { throw new MIPException("AlreadyBound",e); } catch (RemoteException e) { throw new MIPException("RemoteException",e); } } /** * @param solverClass -- what class to use to create new instances * of the solver. * @throws RemoteException */ protected SolverServer(int port, Class solverClass) throws RemoteException { super(port); this.port = port; this.solverClass = solverClass; } /** * @see edu.harvard.econcs.jopt.solver.server.ISolverServer#getSolver() */ public IRemoteMIPSolver getSolver() throws RemoteException { log.info("Creating a new Solver Instance");
IMIPSolver solver = null;
blubin/JOpt
src/main/java/edu/harvard/econcs/jopt/solver/mip/QuadraticTerm.java
// Path: src/main/java/edu/harvard/econcs/jopt/solver/MIPException.java // public class MIPException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 3257289123487103030L; // // public MIPException(String msg) { // super(msg); // } // // public MIPException(String msg, Throwable arg1) { // super(msg, arg1); // } // }
import java.io.Serializable; import edu.harvard.econcs.jopt.solver.MIPException;
/** * @return Returns the coefficient. */ public double getCoefficient() { return coefficient; } public String getVarNameA() { return varNameA; } public String getVarNameB() { return varNameB; } public String toString() { //return coefficient +"*V" + varName; return coefficient +"*" + varNameA + "*" + varNameB; } public Object clone() throws CloneNotSupportedException { QuadraticTerm ret = (QuadraticTerm)super.clone(); return ret; } public QuadraticTerm typedClone() { try { return (QuadraticTerm)clone(); } catch (CloneNotSupportedException e) {
// Path: src/main/java/edu/harvard/econcs/jopt/solver/MIPException.java // public class MIPException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 3257289123487103030L; // // public MIPException(String msg) { // super(msg); // } // // public MIPException(String msg, Throwable arg1) { // super(msg, arg1); // } // } // Path: src/main/java/edu/harvard/econcs/jopt/solver/mip/QuadraticTerm.java import java.io.Serializable; import edu.harvard.econcs.jopt.solver.MIPException; /** * @return Returns the coefficient. */ public double getCoefficient() { return coefficient; } public String getVarNameA() { return varNameA; } public String getVarNameB() { return varNameB; } public String toString() { //return coefficient +"*V" + varName; return coefficient +"*" + varNameA + "*" + varNameB; } public Object clone() throws CloneNotSupportedException { QuadraticTerm ret = (QuadraticTerm)super.clone(); return ret; } public QuadraticTerm typedClone() { try { return (QuadraticTerm)clone(); } catch (CloneNotSupportedException e) {
throw new MIPException("Problem in clone", e);
blubin/JOpt
src/main/java/edu/harvard/econcs/jopt/solver/server/cplex/InstanceManager.java
// Path: src/main/java/edu/harvard/econcs/jopt/solver/MIPException.java // public class MIPException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 3257289123487103030L; // // public MIPException(String msg) { // super(msg); // } // // public MIPException(String msg, Throwable arg1) { // super(msg, arg1); // } // }
import ilog.concert.IloException; import ilog.cplex.IloCplex; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import edu.harvard.econcs.jopt.solver.MIPException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger;
logger.error("Exception trying to close CPLEX", ex); } } inUse.clear(); } } IloCplex cplex = getCplex(); inUse.add(cplex); return cplex; } private boolean notAvailable() { return inUse.size() >= numSimultaneous; } private IloCplex getCplex() { for (int i = 0; i < 100; i++) { if (!available.isEmpty()) { IloCplex ret = available.iterator().next(); available.remove(ret); return ret; } if (available.size() + inUse.size() < numSimultaneous) { IloCplex ret = createCplex(); if (ret != null) { return ret; } } }
// Path: src/main/java/edu/harvard/econcs/jopt/solver/MIPException.java // public class MIPException extends RuntimeException { // // /** // * // */ // private static final long serialVersionUID = 3257289123487103030L; // // public MIPException(String msg) { // super(msg); // } // // public MIPException(String msg, Throwable arg1) { // super(msg, arg1); // } // } // Path: src/main/java/edu/harvard/econcs/jopt/solver/server/cplex/InstanceManager.java import ilog.concert.IloException; import ilog.cplex.IloCplex; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import edu.harvard.econcs.jopt.solver.MIPException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; logger.error("Exception trying to close CPLEX", ex); } } inUse.clear(); } } IloCplex cplex = getCplex(); inUse.add(cplex); return cplex; } private boolean notAvailable() { return inUse.size() >= numSimultaneous; } private IloCplex getCplex() { for (int i = 0; i < 100; i++) { if (!available.isEmpty()) { IloCplex ret = available.iterator().next(); available.remove(ret); return ret; } if (available.size() + inUse.size() < numSimultaneous) { IloCplex ret = createCplex(); if (ret != null) { return ret; } } }
throw new MIPException("Could not obtain cplex instance");
blubin/JOpt
src/main/java/edu/harvard/econcs/jopt/solver/server/cplex/CPlexMIPSolver.java
// Path: src/main/java/edu/harvard/econcs/jopt/solver/MIPInfeasibleException.java // public static class Cause implements Serializable { // public static Cause LOWER = new Cause(1); // public static Cause UPPER = new Cause(2); // private static final long serialVersionUID = 200504191645l; // private int type; // // public Cause(int type) { // this.type = type; // } // // public boolean equals(Object o) { // return o != null && o.getClass().equals(Cause.class) && ((Cause)o).type == type; // } // // public int hashCode() { // return type; // } // // public String toString() { // switch(type) { // case 1: // return "Lower"; // case 2: // return "Upper"; // } // return "Unknown:ERROR"; // } // // /** Make serialization work. **/ // private Object readResolve () throws ObjectStreamException // { // switch(type) { // case 1: // return LOWER; // case 2: // return UPPER; // } // throw new InvalidObjectException("Unknown type: " + type); // } // // } // // Path: src/main/java/edu/harvard/econcs/jopt/solver/server/SolverServer.java // public class SolverServer extends UnicastRemoteObject implements ISolverServer { // /** // * // */ // private static final long serialVersionUID = 3977583593201872945L; // private static final Logger log = LogManager.getLogger(SolverServer.class); // private Class solverClass; // // protected int port; // // /** // * Create a new Server // * @param port // * @param solverClass // */ // public static void createServer(int port, Class solverClass) throws MIPException { // try { // log.info("Binding server to port: " + port); // Registry localreg = LocateRegistry.createRegistry(port); // SolverServer server = new SolverServer(port, solverClass); // localreg.bind(NAME, server); // } catch (AccessException e) { // throw new MIPException("Access", e); // } catch (AlreadyBoundException e) { // throw new MIPException("AlreadyBound",e); // } catch (RemoteException e) { // throw new MIPException("RemoteException",e); // } // } // // /** // * @param solverClass -- what class to use to create new instances // * of the solver. // * @throws RemoteException // */ // protected SolverServer(int port, Class solverClass) throws RemoteException { // super(port); // this.port = port; // this.solverClass = solverClass; // } // // /** // * @see edu.harvard.econcs.jopt.solver.server.ISolverServer#getSolver() // */ // public IRemoteMIPSolver getSolver() throws RemoteException { // log.info("Creating a new Solver Instance"); // IMIPSolver solver = null; // try { // solver = (IMIPSolver)solverClass.newInstance(); // } catch (InstantiationException | IllegalAccessException e) { // throw new MIPException("Could not create solver intance", e); // } // return new RemoteMIPSolver(port, solver); // } // }
import edu.harvard.econcs.jopt.solver.*; import edu.harvard.econcs.jopt.solver.MIPInfeasibleException.Cause; import edu.harvard.econcs.jopt.solver.mip.*; import edu.harvard.econcs.jopt.solver.server.SolverServer; import ilog.concert.*; import ilog.cplex.IloCplex; import ilog.cplex.IloCplex.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.nio.file.Path; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors;
Map<IloNumVarBound, Variable> vConstToVars = new HashMap<>(vars.size()); for (String varName : vars.keySet()) { IloNumVar numVar = vars.get(varName); Variable mipVar = mip.getVar(varName); if (mipVar.getType() != VarType.BOOLEAN) { // only include non-boolean variables vConstToVars.put(cplex.lowerBound(numVar), mipVar); vConstToVars.put(cplex.upperBound(numVar), mipVar); } } Map<IloConstraint, Constraint> iloConstraintsToConstraints = new HashMap<IloConstraint, Constraint>(constraintsToIloConstraints.size()); for (Constraint constraint : constraintsToIloConstraints.keySet()) { IloConstraint iloConst = constraintsToIloConstraints.get(constraint); iloConstraintsToConstraints.put(iloConst, constraint); } // Now build the full array: ArrayList<IloConstraint> full = new ArrayList<>(vConstToVars.size() + constraintsToIloConstraints.size()); full.addAll(vConstToVars.keySet()); full.addAll(constraintsToIloConstraints.values()); IloConstraint[] arr = full.toArray(new IloConstraint[full.size()]); double prefs[] = new double[arr.length]; Arrays.fill(prefs, 1); try { if (!cplex.refineConflict(arr, prefs)) { throw new MIPInfeasibleException("Could not refine conflict"); }
// Path: src/main/java/edu/harvard/econcs/jopt/solver/MIPInfeasibleException.java // public static class Cause implements Serializable { // public static Cause LOWER = new Cause(1); // public static Cause UPPER = new Cause(2); // private static final long serialVersionUID = 200504191645l; // private int type; // // public Cause(int type) { // this.type = type; // } // // public boolean equals(Object o) { // return o != null && o.getClass().equals(Cause.class) && ((Cause)o).type == type; // } // // public int hashCode() { // return type; // } // // public String toString() { // switch(type) { // case 1: // return "Lower"; // case 2: // return "Upper"; // } // return "Unknown:ERROR"; // } // // /** Make serialization work. **/ // private Object readResolve () throws ObjectStreamException // { // switch(type) { // case 1: // return LOWER; // case 2: // return UPPER; // } // throw new InvalidObjectException("Unknown type: " + type); // } // // } // // Path: src/main/java/edu/harvard/econcs/jopt/solver/server/SolverServer.java // public class SolverServer extends UnicastRemoteObject implements ISolverServer { // /** // * // */ // private static final long serialVersionUID = 3977583593201872945L; // private static final Logger log = LogManager.getLogger(SolverServer.class); // private Class solverClass; // // protected int port; // // /** // * Create a new Server // * @param port // * @param solverClass // */ // public static void createServer(int port, Class solverClass) throws MIPException { // try { // log.info("Binding server to port: " + port); // Registry localreg = LocateRegistry.createRegistry(port); // SolverServer server = new SolverServer(port, solverClass); // localreg.bind(NAME, server); // } catch (AccessException e) { // throw new MIPException("Access", e); // } catch (AlreadyBoundException e) { // throw new MIPException("AlreadyBound",e); // } catch (RemoteException e) { // throw new MIPException("RemoteException",e); // } // } // // /** // * @param solverClass -- what class to use to create new instances // * of the solver. // * @throws RemoteException // */ // protected SolverServer(int port, Class solverClass) throws RemoteException { // super(port); // this.port = port; // this.solverClass = solverClass; // } // // /** // * @see edu.harvard.econcs.jopt.solver.server.ISolverServer#getSolver() // */ // public IRemoteMIPSolver getSolver() throws RemoteException { // log.info("Creating a new Solver Instance"); // IMIPSolver solver = null; // try { // solver = (IMIPSolver)solverClass.newInstance(); // } catch (InstantiationException | IllegalAccessException e) { // throw new MIPException("Could not create solver intance", e); // } // return new RemoteMIPSolver(port, solver); // } // } // Path: src/main/java/edu/harvard/econcs/jopt/solver/server/cplex/CPlexMIPSolver.java import edu.harvard.econcs.jopt.solver.*; import edu.harvard.econcs.jopt.solver.MIPInfeasibleException.Cause; import edu.harvard.econcs.jopt.solver.mip.*; import edu.harvard.econcs.jopt.solver.server.SolverServer; import ilog.concert.*; import ilog.cplex.IloCplex; import ilog.cplex.IloCplex.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.nio.file.Path; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; Map<IloNumVarBound, Variable> vConstToVars = new HashMap<>(vars.size()); for (String varName : vars.keySet()) { IloNumVar numVar = vars.get(varName); Variable mipVar = mip.getVar(varName); if (mipVar.getType() != VarType.BOOLEAN) { // only include non-boolean variables vConstToVars.put(cplex.lowerBound(numVar), mipVar); vConstToVars.put(cplex.upperBound(numVar), mipVar); } } Map<IloConstraint, Constraint> iloConstraintsToConstraints = new HashMap<IloConstraint, Constraint>(constraintsToIloConstraints.size()); for (Constraint constraint : constraintsToIloConstraints.keySet()) { IloConstraint iloConst = constraintsToIloConstraints.get(constraint); iloConstraintsToConstraints.put(iloConst, constraint); } // Now build the full array: ArrayList<IloConstraint> full = new ArrayList<>(vConstToVars.size() + constraintsToIloConstraints.size()); full.addAll(vConstToVars.keySet()); full.addAll(constraintsToIloConstraints.values()); IloConstraint[] arr = full.toArray(new IloConstraint[full.size()]); double prefs[] = new double[arr.length]; Arrays.fill(prefs, 1); try { if (!cplex.refineConflict(arr, prefs)) { throw new MIPInfeasibleException("Could not refine conflict"); }
Map<Variable, Cause> mipVarsToCauses = new HashMap<>();
blubin/JOpt
src/main/java/edu/harvard/econcs/jopt/solver/server/cplex/CPlexMIPSolver.java
// Path: src/main/java/edu/harvard/econcs/jopt/solver/MIPInfeasibleException.java // public static class Cause implements Serializable { // public static Cause LOWER = new Cause(1); // public static Cause UPPER = new Cause(2); // private static final long serialVersionUID = 200504191645l; // private int type; // // public Cause(int type) { // this.type = type; // } // // public boolean equals(Object o) { // return o != null && o.getClass().equals(Cause.class) && ((Cause)o).type == type; // } // // public int hashCode() { // return type; // } // // public String toString() { // switch(type) { // case 1: // return "Lower"; // case 2: // return "Upper"; // } // return "Unknown:ERROR"; // } // // /** Make serialization work. **/ // private Object readResolve () throws ObjectStreamException // { // switch(type) { // case 1: // return LOWER; // case 2: // return UPPER; // } // throw new InvalidObjectException("Unknown type: " + type); // } // // } // // Path: src/main/java/edu/harvard/econcs/jopt/solver/server/SolverServer.java // public class SolverServer extends UnicastRemoteObject implements ISolverServer { // /** // * // */ // private static final long serialVersionUID = 3977583593201872945L; // private static final Logger log = LogManager.getLogger(SolverServer.class); // private Class solverClass; // // protected int port; // // /** // * Create a new Server // * @param port // * @param solverClass // */ // public static void createServer(int port, Class solverClass) throws MIPException { // try { // log.info("Binding server to port: " + port); // Registry localreg = LocateRegistry.createRegistry(port); // SolverServer server = new SolverServer(port, solverClass); // localreg.bind(NAME, server); // } catch (AccessException e) { // throw new MIPException("Access", e); // } catch (AlreadyBoundException e) { // throw new MIPException("AlreadyBound",e); // } catch (RemoteException e) { // throw new MIPException("RemoteException",e); // } // } // // /** // * @param solverClass -- what class to use to create new instances // * of the solver. // * @throws RemoteException // */ // protected SolverServer(int port, Class solverClass) throws RemoteException { // super(port); // this.port = port; // this.solverClass = solverClass; // } // // /** // * @see edu.harvard.econcs.jopt.solver.server.ISolverServer#getSolver() // */ // public IRemoteMIPSolver getSolver() throws RemoteException { // log.info("Creating a new Solver Instance"); // IMIPSolver solver = null; // try { // solver = (IMIPSolver)solverClass.newInstance(); // } catch (InstantiationException | IllegalAccessException e) { // throw new MIPException("Could not create solver intance", e); // } // return new RemoteMIPSolver(port, solver); // } // }
import edu.harvard.econcs.jopt.solver.*; import edu.harvard.econcs.jopt.solver.MIPInfeasibleException.Cause; import edu.harvard.econcs.jopt.solver.mip.*; import edu.harvard.econcs.jopt.solver.server.SolverServer; import ilog.concert.*; import ilog.cplex.IloCplex; import ilog.cplex.IloCplex.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.nio.file.Path; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors;
private PoolSolution createSolution() { Map<String, Double> values = new HashMap<String, Double>(); for (String name : vars.keySet()) { IloNumVar var = vars.get(name); try { values.put(name, getIncumbentValue(var)); } catch (IloException e) { throw new MIPException("Couldn't get incumbent value.", e); } } try { return new PoolSolution(getIncumbentObjValue(), getBestObjValue(), values); } catch (IloException e) { throw new MIPException("Couldn't get incumbent objective value.", e); } } } public static void main(String argv[]) { if (argv.length < 1 || argv.length > 2) { logger.error("Usage: edu.harvard.econcs.jopt.solver.server.cplex.CPlexMIPSolver <port> <num simultaneous>"); System.exit(1); } int port = Integer.parseInt(argv[0]); int numSimultaneous = 10; if (argv.length >= 2) { numSimultaneous = Integer.parseInt(argv[1]); } InstanceManager.setNumSimultaneous(numSimultaneous);
// Path: src/main/java/edu/harvard/econcs/jopt/solver/MIPInfeasibleException.java // public static class Cause implements Serializable { // public static Cause LOWER = new Cause(1); // public static Cause UPPER = new Cause(2); // private static final long serialVersionUID = 200504191645l; // private int type; // // public Cause(int type) { // this.type = type; // } // // public boolean equals(Object o) { // return o != null && o.getClass().equals(Cause.class) && ((Cause)o).type == type; // } // // public int hashCode() { // return type; // } // // public String toString() { // switch(type) { // case 1: // return "Lower"; // case 2: // return "Upper"; // } // return "Unknown:ERROR"; // } // // /** Make serialization work. **/ // private Object readResolve () throws ObjectStreamException // { // switch(type) { // case 1: // return LOWER; // case 2: // return UPPER; // } // throw new InvalidObjectException("Unknown type: " + type); // } // // } // // Path: src/main/java/edu/harvard/econcs/jopt/solver/server/SolverServer.java // public class SolverServer extends UnicastRemoteObject implements ISolverServer { // /** // * // */ // private static final long serialVersionUID = 3977583593201872945L; // private static final Logger log = LogManager.getLogger(SolverServer.class); // private Class solverClass; // // protected int port; // // /** // * Create a new Server // * @param port // * @param solverClass // */ // public static void createServer(int port, Class solverClass) throws MIPException { // try { // log.info("Binding server to port: " + port); // Registry localreg = LocateRegistry.createRegistry(port); // SolverServer server = new SolverServer(port, solverClass); // localreg.bind(NAME, server); // } catch (AccessException e) { // throw new MIPException("Access", e); // } catch (AlreadyBoundException e) { // throw new MIPException("AlreadyBound",e); // } catch (RemoteException e) { // throw new MIPException("RemoteException",e); // } // } // // /** // * @param solverClass -- what class to use to create new instances // * of the solver. // * @throws RemoteException // */ // protected SolverServer(int port, Class solverClass) throws RemoteException { // super(port); // this.port = port; // this.solverClass = solverClass; // } // // /** // * @see edu.harvard.econcs.jopt.solver.server.ISolverServer#getSolver() // */ // public IRemoteMIPSolver getSolver() throws RemoteException { // log.info("Creating a new Solver Instance"); // IMIPSolver solver = null; // try { // solver = (IMIPSolver)solverClass.newInstance(); // } catch (InstantiationException | IllegalAccessException e) { // throw new MIPException("Could not create solver intance", e); // } // return new RemoteMIPSolver(port, solver); // } // } // Path: src/main/java/edu/harvard/econcs/jopt/solver/server/cplex/CPlexMIPSolver.java import edu.harvard.econcs.jopt.solver.*; import edu.harvard.econcs.jopt.solver.MIPInfeasibleException.Cause; import edu.harvard.econcs.jopt.solver.mip.*; import edu.harvard.econcs.jopt.solver.server.SolverServer; import ilog.concert.*; import ilog.cplex.IloCplex; import ilog.cplex.IloCplex.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.nio.file.Path; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; private PoolSolution createSolution() { Map<String, Double> values = new HashMap<String, Double>(); for (String name : vars.keySet()) { IloNumVar var = vars.get(name); try { values.put(name, getIncumbentValue(var)); } catch (IloException e) { throw new MIPException("Couldn't get incumbent value.", e); } } try { return new PoolSolution(getIncumbentObjValue(), getBestObjValue(), values); } catch (IloException e) { throw new MIPException("Couldn't get incumbent objective value.", e); } } } public static void main(String argv[]) { if (argv.length < 1 || argv.length > 2) { logger.error("Usage: edu.harvard.econcs.jopt.solver.server.cplex.CPlexMIPSolver <port> <num simultaneous>"); System.exit(1); } int port = Integer.parseInt(argv[0]); int numSimultaneous = 10; if (argv.length >= 2) { numSimultaneous = Integer.parseInt(argv[1]); } InstanceManager.setNumSimultaneous(numSimultaneous);
SolverServer.createServer(port, CPlexMIPSolver.class);
exquery/xpath2-parser
src/main/java/com/evolvedbinary/xpath/parser/XPathUtil.java
// Path: src/main/java/com/evolvedbinary/xpath/parser/ast/ASTNode.java // public interface ASTNode { // } // // Path: src/main/java/com/evolvedbinary/xpath/parser/ast/Expr.java // public class Expr extends AbstractASTNode { // private final List<? extends ASTNode> exprSingles; // // public Expr(final List<? extends ASTNode> exprSingles) { // this.exprSingles = exprSingles; // } // // public Expr(final ASTNode... exprSingles) { // this.exprSingles = Arrays.asList(exprSingles); // } // // @Override // protected String describe() { // final StringBuilder builder = new StringBuilder(); // for(final ASTNode exprSingle : exprSingles) { // if(builder.length() > 0) { // builder.append(", "); // } // builder.append(exprSingle.toString()); // } // // return "Expr(" + builder.toString() + ")"; // } // // @Override // public boolean equals(final Object obj) { // if(obj != null && obj instanceof Expr) { // return ((Expr)obj).exprSingles.equals(exprSingles); // } // // return false; // } // // public List<? extends ASTNode> getExprSingles() { // return exprSingles; // } // }
import static org.parboiled.errors.ErrorUtils.printParseErrors; import com.evolvedbinary.xpath.parser.ast.ASTNode; import com.evolvedbinary.xpath.parser.ast.Expr; import org.parboiled.Parboiled; import org.parboiled.parserunners.ParseRunner; import org.parboiled.parserunners.RecoveringParseRunner; import org.parboiled.support.Chars; import org.parboiled.support.ParseTreeUtils; import org.parboiled.support.ParsingResult; import java.io.PrintStream;
/** * XPath 2 Parser * A Parser for XPath 2 * Copyright (C) 2016 Evolved Binary Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.evolvedbinary.xpath.parser; /** * Simple utility class showing how to use * the XPathParser * * Created by aretter on 16/03/2016. */ public class XPathUtil { public final static void main(final String args[]) { if(args.length != 1) { System.err.println("You must provide an XPath as an argument."); System.exit(-1); } else { parseXPath(args[0], System.out, System.err); } } /** * Parses an XPath Expression and generates an AST * * @param xpath The XPath to parse * @param out Either a print stream for receiving a debug print of the NodeTree generated by the parser, or null otherwise * @param err Either a print stream for receiving errors that occurred during parsing or null otherwise * * @return An {@link Expr} which is the root of the generated AST */
// Path: src/main/java/com/evolvedbinary/xpath/parser/ast/ASTNode.java // public interface ASTNode { // } // // Path: src/main/java/com/evolvedbinary/xpath/parser/ast/Expr.java // public class Expr extends AbstractASTNode { // private final List<? extends ASTNode> exprSingles; // // public Expr(final List<? extends ASTNode> exprSingles) { // this.exprSingles = exprSingles; // } // // public Expr(final ASTNode... exprSingles) { // this.exprSingles = Arrays.asList(exprSingles); // } // // @Override // protected String describe() { // final StringBuilder builder = new StringBuilder(); // for(final ASTNode exprSingle : exprSingles) { // if(builder.length() > 0) { // builder.append(", "); // } // builder.append(exprSingle.toString()); // } // // return "Expr(" + builder.toString() + ")"; // } // // @Override // public boolean equals(final Object obj) { // if(obj != null && obj instanceof Expr) { // return ((Expr)obj).exprSingles.equals(exprSingles); // } // // return false; // } // // public List<? extends ASTNode> getExprSingles() { // return exprSingles; // } // } // Path: src/main/java/com/evolvedbinary/xpath/parser/XPathUtil.java import static org.parboiled.errors.ErrorUtils.printParseErrors; import com.evolvedbinary.xpath.parser.ast.ASTNode; import com.evolvedbinary.xpath.parser.ast.Expr; import org.parboiled.Parboiled; import org.parboiled.parserunners.ParseRunner; import org.parboiled.parserunners.RecoveringParseRunner; import org.parboiled.support.Chars; import org.parboiled.support.ParseTreeUtils; import org.parboiled.support.ParsingResult; import java.io.PrintStream; /** * XPath 2 Parser * A Parser for XPath 2 * Copyright (C) 2016 Evolved Binary Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.evolvedbinary.xpath.parser; /** * Simple utility class showing how to use * the XPathParser * * Created by aretter on 16/03/2016. */ public class XPathUtil { public final static void main(final String args[]) { if(args.length != 1) { System.err.println("You must provide an XPath as an argument."); System.exit(-1); } else { parseXPath(args[0], System.out, System.err); } } /** * Parses an XPath Expression and generates an AST * * @param xpath The XPath to parse * @param out Either a print stream for receiving a debug print of the NodeTree generated by the parser, or null otherwise * @param err Either a print stream for receiving errors that occurred during parsing or null otherwise * * @return An {@link Expr} which is the root of the generated AST */
public static Expr parseXPath(final String xpath, final PrintStream out, final PrintStream err) {
exquery/xpath2-parser
src/main/java/com/evolvedbinary/xpath/parser/XPathUtil.java
// Path: src/main/java/com/evolvedbinary/xpath/parser/ast/ASTNode.java // public interface ASTNode { // } // // Path: src/main/java/com/evolvedbinary/xpath/parser/ast/Expr.java // public class Expr extends AbstractASTNode { // private final List<? extends ASTNode> exprSingles; // // public Expr(final List<? extends ASTNode> exprSingles) { // this.exprSingles = exprSingles; // } // // public Expr(final ASTNode... exprSingles) { // this.exprSingles = Arrays.asList(exprSingles); // } // // @Override // protected String describe() { // final StringBuilder builder = new StringBuilder(); // for(final ASTNode exprSingle : exprSingles) { // if(builder.length() > 0) { // builder.append(", "); // } // builder.append(exprSingle.toString()); // } // // return "Expr(" + builder.toString() + ")"; // } // // @Override // public boolean equals(final Object obj) { // if(obj != null && obj instanceof Expr) { // return ((Expr)obj).exprSingles.equals(exprSingles); // } // // return false; // } // // public List<? extends ASTNode> getExprSingles() { // return exprSingles; // } // }
import static org.parboiled.errors.ErrorUtils.printParseErrors; import com.evolvedbinary.xpath.parser.ast.ASTNode; import com.evolvedbinary.xpath.parser.ast.Expr; import org.parboiled.Parboiled; import org.parboiled.parserunners.ParseRunner; import org.parboiled.parserunners.RecoveringParseRunner; import org.parboiled.support.Chars; import org.parboiled.support.ParseTreeUtils; import org.parboiled.support.ParsingResult; import java.io.PrintStream;
/** * XPath 2 Parser * A Parser for XPath 2 * Copyright (C) 2016 Evolved Binary Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.evolvedbinary.xpath.parser; /** * Simple utility class showing how to use * the XPathParser * * Created by aretter on 16/03/2016. */ public class XPathUtil { public final static void main(final String args[]) { if(args.length != 1) { System.err.println("You must provide an XPath as an argument."); System.exit(-1); } else { parseXPath(args[0], System.out, System.err); } } /** * Parses an XPath Expression and generates an AST * * @param xpath The XPath to parse * @param out Either a print stream for receiving a debug print of the NodeTree generated by the parser, or null otherwise * @param err Either a print stream for receiving errors that occurred during parsing or null otherwise * * @return An {@link Expr} which is the root of the generated AST */ public static Expr parseXPath(final String xpath, final PrintStream out, final PrintStream err) { final XPathParser parser = Parboiled.createParser(XPathParser.class, Boolean.TRUE);
// Path: src/main/java/com/evolvedbinary/xpath/parser/ast/ASTNode.java // public interface ASTNode { // } // // Path: src/main/java/com/evolvedbinary/xpath/parser/ast/Expr.java // public class Expr extends AbstractASTNode { // private final List<? extends ASTNode> exprSingles; // // public Expr(final List<? extends ASTNode> exprSingles) { // this.exprSingles = exprSingles; // } // // public Expr(final ASTNode... exprSingles) { // this.exprSingles = Arrays.asList(exprSingles); // } // // @Override // protected String describe() { // final StringBuilder builder = new StringBuilder(); // for(final ASTNode exprSingle : exprSingles) { // if(builder.length() > 0) { // builder.append(", "); // } // builder.append(exprSingle.toString()); // } // // return "Expr(" + builder.toString() + ")"; // } // // @Override // public boolean equals(final Object obj) { // if(obj != null && obj instanceof Expr) { // return ((Expr)obj).exprSingles.equals(exprSingles); // } // // return false; // } // // public List<? extends ASTNode> getExprSingles() { // return exprSingles; // } // } // Path: src/main/java/com/evolvedbinary/xpath/parser/XPathUtil.java import static org.parboiled.errors.ErrorUtils.printParseErrors; import com.evolvedbinary.xpath.parser.ast.ASTNode; import com.evolvedbinary.xpath.parser.ast.Expr; import org.parboiled.Parboiled; import org.parboiled.parserunners.ParseRunner; import org.parboiled.parserunners.RecoveringParseRunner; import org.parboiled.support.Chars; import org.parboiled.support.ParseTreeUtils; import org.parboiled.support.ParsingResult; import java.io.PrintStream; /** * XPath 2 Parser * A Parser for XPath 2 * Copyright (C) 2016 Evolved Binary Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.evolvedbinary.xpath.parser; /** * Simple utility class showing how to use * the XPathParser * * Created by aretter on 16/03/2016. */ public class XPathUtil { public final static void main(final String args[]) { if(args.length != 1) { System.err.println("You must provide an XPath as an argument."); System.exit(-1); } else { parseXPath(args[0], System.out, System.err); } } /** * Parses an XPath Expression and generates an AST * * @param xpath The XPath to parse * @param out Either a print stream for receiving a debug print of the NodeTree generated by the parser, or null otherwise * @param err Either a print stream for receiving errors that occurred during parsing or null otherwise * * @return An {@link Expr} which is the root of the generated AST */ public static Expr parseXPath(final String xpath, final PrintStream out, final PrintStream err) { final XPathParser parser = Parboiled.createParser(XPathParser.class, Boolean.TRUE);
final ParseRunner<ASTNode> parseRunner = new RecoveringParseRunner<ASTNode>(parser.withEOI(parser.XPath()));
exquery/xpath2-parser
src/main/java/com/evolvedbinary/xpath/parser/ast/partial/PartialElementTest.java
// Path: src/main/java/com/evolvedbinary/xpath/parser/ast/ElementTest.java // public class ElementTest extends KindTest { // @Nullable final QNameW name; // @Nullable QNameW typeName; // @Nullable boolean optionalType; // // public ElementTest() { // this(null); // } // // public ElementTest(final QNameW name) { // this(name, null); // } // // public ElementTest(final QNameW name, final QNameW typeName) { // this(name, typeName, false); // } // // public ElementTest(final QNameW name, final QNameW typeName, final Boolean optionalType) { // super(Kind.ELEMENT); // this.name = name; // this.typeName = typeName; // this.optionalType = optionalType == null ? false : optionalType; // } // // @Override // protected String describeParams() { // return (name == null ? "" : name.toString()) + // (typeName == null ? "" : ", " + typeName.toString()) + // (optionalType ? "?" : ""); // } // // @Override // public boolean equals(final Object obj) { // if(obj != null && obj instanceof ElementTest) { // final ElementTest other = (ElementTest)obj; // // return // ((this.name == null && other.name == null) || this.name.equals(other.name)) && // ((this.typeName == null && other.typeName == null) || this.typeName.equals(other.typeName)) && // this.optionalType == other.optionalType; // } // return false; // } // // @Nullable // public QNameW getName() { // return name; // } // } // // Path: src/main/java/com/evolvedbinary/xpath/parser/ast/QNameW.java // public class QNameW extends AbstractASTNode { // public final static String WILDCARD = "*"; // // @Nullable private final String prefix; // private final String localPart; // // public QNameW(final String localPart) { // this(null, localPart); // } // // public QNameW(final String prefix, final String localPart) { // this.prefix = prefix; // this.localPart = localPart; // } // // @Override // public final String describe() { // if(prefix != null) { // return "QNameW(" + prefix + ":" + localPart + ")"; // } else { // return "QNameW(" + localPart + ")"; // } // } // // @Override // public boolean equals(final Object obj) { // if(obj != null && obj instanceof QNameW) { // final QNameW other = (QNameW)obj; // // return other.localPart.equals(this.localPart) && // (other.prefix == null ? "" : other.prefix).equals(this.prefix == null ? "" : this.prefix); // } // // return false; // } // // @Nullable // public String getPrefix() { // return prefix; // } // // public String getLocalPart() { // return localPart; // } // }
import com.evolvedbinary.xpath.parser.ast.ElementTest; import com.evolvedbinary.xpath.parser.ast.QNameW; import org.jetbrains.annotations.Nullable;
/** * XPath 2 Parser * A Parser for XPath 2 * Copyright (C) 2016 Evolved Binary Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.evolvedbinary.xpath.parser.ast.partial; /** * Created by aretter on 30/01/2016. */ public class PartialElementTest extends AbstractPartialASTNode<PartialElementTest.PartialElementTest1, QNameW> { @Override public PartialElementTest1 complete(@Nullable final QNameW name) { return new PartialElementTest1(name); } @Override protected String describe() { return "ElementTest(?, ?, ?)"; } public class PartialElementTest1 extends AbstractPartialASTNode<PartialElementTest1.PartialElementTest2, QNameW> { @Nullable final QNameW name; public PartialElementTest1(final QNameW name) { this.name = name; } @Override public PartialElementTest2 complete(@Nullable final QNameW typeName){ return new PartialElementTest2(typeName); } @Override protected String describe() { return "ElementTest(" + (name == null ? "" : name) + ", ?, ?)"; }
// Path: src/main/java/com/evolvedbinary/xpath/parser/ast/ElementTest.java // public class ElementTest extends KindTest { // @Nullable final QNameW name; // @Nullable QNameW typeName; // @Nullable boolean optionalType; // // public ElementTest() { // this(null); // } // // public ElementTest(final QNameW name) { // this(name, null); // } // // public ElementTest(final QNameW name, final QNameW typeName) { // this(name, typeName, false); // } // // public ElementTest(final QNameW name, final QNameW typeName, final Boolean optionalType) { // super(Kind.ELEMENT); // this.name = name; // this.typeName = typeName; // this.optionalType = optionalType == null ? false : optionalType; // } // // @Override // protected String describeParams() { // return (name == null ? "" : name.toString()) + // (typeName == null ? "" : ", " + typeName.toString()) + // (optionalType ? "?" : ""); // } // // @Override // public boolean equals(final Object obj) { // if(obj != null && obj instanceof ElementTest) { // final ElementTest other = (ElementTest)obj; // // return // ((this.name == null && other.name == null) || this.name.equals(other.name)) && // ((this.typeName == null && other.typeName == null) || this.typeName.equals(other.typeName)) && // this.optionalType == other.optionalType; // } // return false; // } // // @Nullable // public QNameW getName() { // return name; // } // } // // Path: src/main/java/com/evolvedbinary/xpath/parser/ast/QNameW.java // public class QNameW extends AbstractASTNode { // public final static String WILDCARD = "*"; // // @Nullable private final String prefix; // private final String localPart; // // public QNameW(final String localPart) { // this(null, localPart); // } // // public QNameW(final String prefix, final String localPart) { // this.prefix = prefix; // this.localPart = localPart; // } // // @Override // public final String describe() { // if(prefix != null) { // return "QNameW(" + prefix + ":" + localPart + ")"; // } else { // return "QNameW(" + localPart + ")"; // } // } // // @Override // public boolean equals(final Object obj) { // if(obj != null && obj instanceof QNameW) { // final QNameW other = (QNameW)obj; // // return other.localPart.equals(this.localPart) && // (other.prefix == null ? "" : other.prefix).equals(this.prefix == null ? "" : this.prefix); // } // // return false; // } // // @Nullable // public String getPrefix() { // return prefix; // } // // public String getLocalPart() { // return localPart; // } // } // Path: src/main/java/com/evolvedbinary/xpath/parser/ast/partial/PartialElementTest.java import com.evolvedbinary.xpath.parser.ast.ElementTest; import com.evolvedbinary.xpath.parser.ast.QNameW; import org.jetbrains.annotations.Nullable; /** * XPath 2 Parser * A Parser for XPath 2 * Copyright (C) 2016 Evolved Binary Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.evolvedbinary.xpath.parser.ast.partial; /** * Created by aretter on 30/01/2016. */ public class PartialElementTest extends AbstractPartialASTNode<PartialElementTest.PartialElementTest1, QNameW> { @Override public PartialElementTest1 complete(@Nullable final QNameW name) { return new PartialElementTest1(name); } @Override protected String describe() { return "ElementTest(?, ?, ?)"; } public class PartialElementTest1 extends AbstractPartialASTNode<PartialElementTest1.PartialElementTest2, QNameW> { @Nullable final QNameW name; public PartialElementTest1(final QNameW name) { this.name = name; } @Override public PartialElementTest2 complete(@Nullable final QNameW typeName){ return new PartialElementTest2(typeName); } @Override protected String describe() { return "ElementTest(" + (name == null ? "" : name) + ", ?, ?)"; }
public class PartialElementTest2 extends AbstractPartialASTNode<ElementTest, Boolean> {
exquery/xpath2-parser
src/main/java/com/evolvedbinary/xpath/parser/ast/partial/PartialDoubleLiteral.java
// Path: src/main/java/com/evolvedbinary/xpath/parser/ast/DoubleLiteral.java // public class DoubleLiteral extends NumericLiteral<BigDecimal> { // public DoubleLiteral(final String value) { // super(new BigDecimal(value)); // } // // @Override // protected String describe() { // return "DoubleLiteral(" + getValue() + ")"; // } // }
import com.evolvedbinary.xpath.parser.ast.DoubleLiteral; import org.jetbrains.annotations.Nullable;
return "DoubleLiteral(" + characteristic + ".?)e??"; } @Override public PartialDoubleLiteral1 complete(@Nullable final String mantissa) { return new PartialDoubleLiteral1(mantissa); } public class PartialDoubleLiteral1 extends AbstractPartialASTNode<PartialDoubleLiteral1.PartialDoubleLiteral2, String> { @Nullable final String mantissa; public PartialDoubleLiteral1(final String mantissa) { this.mantissa = mantissa; } @Override protected String describe() { final String m = (mantissa == null ? ".0" : "." + mantissa); return "DoubleLiteral(" + characteristic + m + ")e??"; } @Override public PartialDoubleLiteral1.PartialDoubleLiteral2 complete(final String exponentSign) { if(exponentSign == null || exponentSign.isEmpty()) { return new PartialDoubleLiteral2('+'); } else { return new PartialDoubleLiteral2(exponentSign.charAt(0)); } }
// Path: src/main/java/com/evolvedbinary/xpath/parser/ast/DoubleLiteral.java // public class DoubleLiteral extends NumericLiteral<BigDecimal> { // public DoubleLiteral(final String value) { // super(new BigDecimal(value)); // } // // @Override // protected String describe() { // return "DoubleLiteral(" + getValue() + ")"; // } // } // Path: src/main/java/com/evolvedbinary/xpath/parser/ast/partial/PartialDoubleLiteral.java import com.evolvedbinary.xpath.parser.ast.DoubleLiteral; import org.jetbrains.annotations.Nullable; return "DoubleLiteral(" + characteristic + ".?)e??"; } @Override public PartialDoubleLiteral1 complete(@Nullable final String mantissa) { return new PartialDoubleLiteral1(mantissa); } public class PartialDoubleLiteral1 extends AbstractPartialASTNode<PartialDoubleLiteral1.PartialDoubleLiteral2, String> { @Nullable final String mantissa; public PartialDoubleLiteral1(final String mantissa) { this.mantissa = mantissa; } @Override protected String describe() { final String m = (mantissa == null ? ".0" : "." + mantissa); return "DoubleLiteral(" + characteristic + m + ")e??"; } @Override public PartialDoubleLiteral1.PartialDoubleLiteral2 complete(final String exponentSign) { if(exponentSign == null || exponentSign.isEmpty()) { return new PartialDoubleLiteral2('+'); } else { return new PartialDoubleLiteral2(exponentSign.charAt(0)); } }
public class PartialDoubleLiteral2 extends AbstractPartialASTNode<DoubleLiteral, String> {
exquery/xpath2-parser
src/main/java/com/evolvedbinary/xpath/parser/ast/partial/PartialComparisonExpr.java
// Path: src/main/java/com/evolvedbinary/xpath/parser/ast/AbstractOperand.java // public abstract class AbstractOperand extends AbstractASTNode { // // //TODO(AR) make generic and move constructor etc from sub-classes into here // } // // Path: src/main/java/com/evolvedbinary/xpath/parser/ast/Comparison.java // public interface Comparison extends ASTNode { // String getSyntax(); // } // // Path: src/main/java/com/evolvedbinary/xpath/parser/ast/ComparisonExpr.java // public class ComparisonExpr extends AbstractOperand { // private final AbstractOperand left; // private final Comparison comparison; // private final AbstractOperand right; // // public ComparisonExpr(final AbstractOperand left, final Comparison comparison, final AbstractOperand right) { // this.left = left; // this.comparison = comparison; // this.right = right; // } // // @Override // protected String describe() { // return "ComparisonExpr(" + left + " " + comparison + " " + right + ")"; // } // // @Override // public boolean equals(final Object obj) { // if(obj != null && obj instanceof ComparisonExpr) { // final ComparisonExpr other = (ComparisonExpr)obj; // return other.left.equals(left) // && other.comparison.equals(comparison) // && other.right.equals(right); // } // // return false; // } // }
import com.evolvedbinary.xpath.parser.ast.AbstractOperand; import com.evolvedbinary.xpath.parser.ast.Comparison; import com.evolvedbinary.xpath.parser.ast.ComparisonExpr;
/** * XPath 2 Parser * A Parser for XPath 2 * Copyright (C) 2016 Evolved Binary Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.evolvedbinary.xpath.parser.ast.partial; /** * Created by aretter on 14/02/2016. */ public class PartialComparisonExpr extends AbstractPartialASTNode<PartialComparisonExpr.PartialComparisonExpr1, Comparison> { private final AbstractOperand left; public PartialComparisonExpr(final AbstractOperand left) { this.left = left; } @Override protected String describe() { return "ComparisonExpr(" + left + ", ?, ?)"; } @Override public PartialComparisonExpr.PartialComparisonExpr1 complete(final Comparison comparison) { return new PartialComparisonExpr1(comparison); }
// Path: src/main/java/com/evolvedbinary/xpath/parser/ast/AbstractOperand.java // public abstract class AbstractOperand extends AbstractASTNode { // // //TODO(AR) make generic and move constructor etc from sub-classes into here // } // // Path: src/main/java/com/evolvedbinary/xpath/parser/ast/Comparison.java // public interface Comparison extends ASTNode { // String getSyntax(); // } // // Path: src/main/java/com/evolvedbinary/xpath/parser/ast/ComparisonExpr.java // public class ComparisonExpr extends AbstractOperand { // private final AbstractOperand left; // private final Comparison comparison; // private final AbstractOperand right; // // public ComparisonExpr(final AbstractOperand left, final Comparison comparison, final AbstractOperand right) { // this.left = left; // this.comparison = comparison; // this.right = right; // } // // @Override // protected String describe() { // return "ComparisonExpr(" + left + " " + comparison + " " + right + ")"; // } // // @Override // public boolean equals(final Object obj) { // if(obj != null && obj instanceof ComparisonExpr) { // final ComparisonExpr other = (ComparisonExpr)obj; // return other.left.equals(left) // && other.comparison.equals(comparison) // && other.right.equals(right); // } // // return false; // } // } // Path: src/main/java/com/evolvedbinary/xpath/parser/ast/partial/PartialComparisonExpr.java import com.evolvedbinary.xpath.parser.ast.AbstractOperand; import com.evolvedbinary.xpath.parser.ast.Comparison; import com.evolvedbinary.xpath.parser.ast.ComparisonExpr; /** * XPath 2 Parser * A Parser for XPath 2 * Copyright (C) 2016 Evolved Binary Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.evolvedbinary.xpath.parser.ast.partial; /** * Created by aretter on 14/02/2016. */ public class PartialComparisonExpr extends AbstractPartialASTNode<PartialComparisonExpr.PartialComparisonExpr1, Comparison> { private final AbstractOperand left; public PartialComparisonExpr(final AbstractOperand left) { this.left = left; } @Override protected String describe() { return "ComparisonExpr(" + left + ", ?, ?)"; } @Override public PartialComparisonExpr.PartialComparisonExpr1 complete(final Comparison comparison) { return new PartialComparisonExpr1(comparison); }
public class PartialComparisonExpr1 extends AbstractPartialASTNode<ComparisonExpr, AbstractOperand> {
exquery/xpath2-parser
src/main/java/com/evolvedbinary/xpath/parser/ast/partial/PartialQuantifierExpr.java
// Path: src/main/java/com/evolvedbinary/xpath/parser/ast/ASTNode.java // public interface ASTNode { // } // // Path: src/main/java/com/evolvedbinary/xpath/parser/ast/QuantifiedExpr.java // public class QuantifiedExpr extends AbstractASTNode implements ExprSingle { // // public enum Quantifier { // SOME, // EVERY; // // public final static Quantifier fromSyntax(final String syntax) { // for(final Quantifier quantifier : Quantifier.values()) { // if(quantifier.name().toLowerCase().equals(syntax)) { // return quantifier; // } // } // throw new IllegalArgumentException("No such Quantifier: '" + syntax + "'"); // } // // public String getSyntax() { // return name().toLowerCase(); // } // } // // public static class InClause { // public final QNameW varName; // public final ASTNode in; //TODO(AR) ideally should be ExprSingle... but as we simplify the AST, so we have to use ASTNode // // public InClause(final QNameW varName, final ASTNode in) { // this.varName = varName; // this.in = in; // } // // @Override // public boolean equals(final Object obj) { // if(obj != null && obj instanceof InClause) { // final InClause other = (InClause)obj; // return other.varName.equals(varName) // && other.in.equals(in); // } // // return false; // } // } // // private final Quantifier quantifier; // private final List<InClause> inClauses; // private final ASTNode satisfies; //TODO(AR) ideally should be ExprSingle... but as we simplify the AST, so we have to use ASTNode // // public QuantifiedExpr(final Quantifier quantifier, final List<InClause> inClauses, final ASTNode satisfies) { // this.quantifier = quantifier; // this.inClauses = inClauses; // this.satisfies = satisfies; // } // // @Override // protected String describe() { // final StringBuilder builder = new StringBuilder(); // for(final InClause inClause : inClauses) { // if(builder.length() > 0) { // builder.append(", "); // } // // builder // .append("$") // .append(inClause.varName.toString()) // .append(" in ") // .append(inClause.in.toString()); // } // return "QuantifiedExpr(" + quantifier.getSyntax() + " " + builder.toString() + " satisfies " + satisfies.toString() + ")"; // } // // @Override // public boolean equals(final Object obj) { // if(obj != null && obj instanceof QuantifiedExpr) { // final QuantifiedExpr other = (QuantifiedExpr)obj; // return other.quantifier == quantifier // && other.inClauses.equals(inClauses) // && other.satisfies.equals(satisfies); // } // // return false; // } // }
import java.util.List; import com.evolvedbinary.xpath.parser.ast.ASTNode; import com.evolvedbinary.xpath.parser.ast.QuantifiedExpr;
/** * XPath 2 Parser * A Parser for XPath 2 * Copyright (C) 2016 Evolved Binary Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.evolvedbinary.xpath.parser.ast.partial; /** * Created by aretter on 15/02/2016. */ public class PartialQuantifierExpr extends AbstractPartialASTNode<PartialQuantifierExpr.PartialQuantifierExpr1, List<QuantifiedExpr.InClause>> { private final QuantifiedExpr.Quantifier quantifier; public PartialQuantifierExpr(final QuantifiedExpr.Quantifier quantifier) { this.quantifier = quantifier; } @Override public PartialQuantifierExpr.PartialQuantifierExpr1 complete(final List<QuantifiedExpr.InClause> inClauses) { return new PartialQuantifierExpr1(inClauses); } @Override protected String describe() { return "QuantifiedExpr(" + quantifier.getSyntax() + " ?..., ?)"; }
// Path: src/main/java/com/evolvedbinary/xpath/parser/ast/ASTNode.java // public interface ASTNode { // } // // Path: src/main/java/com/evolvedbinary/xpath/parser/ast/QuantifiedExpr.java // public class QuantifiedExpr extends AbstractASTNode implements ExprSingle { // // public enum Quantifier { // SOME, // EVERY; // // public final static Quantifier fromSyntax(final String syntax) { // for(final Quantifier quantifier : Quantifier.values()) { // if(quantifier.name().toLowerCase().equals(syntax)) { // return quantifier; // } // } // throw new IllegalArgumentException("No such Quantifier: '" + syntax + "'"); // } // // public String getSyntax() { // return name().toLowerCase(); // } // } // // public static class InClause { // public final QNameW varName; // public final ASTNode in; //TODO(AR) ideally should be ExprSingle... but as we simplify the AST, so we have to use ASTNode // // public InClause(final QNameW varName, final ASTNode in) { // this.varName = varName; // this.in = in; // } // // @Override // public boolean equals(final Object obj) { // if(obj != null && obj instanceof InClause) { // final InClause other = (InClause)obj; // return other.varName.equals(varName) // && other.in.equals(in); // } // // return false; // } // } // // private final Quantifier quantifier; // private final List<InClause> inClauses; // private final ASTNode satisfies; //TODO(AR) ideally should be ExprSingle... but as we simplify the AST, so we have to use ASTNode // // public QuantifiedExpr(final Quantifier quantifier, final List<InClause> inClauses, final ASTNode satisfies) { // this.quantifier = quantifier; // this.inClauses = inClauses; // this.satisfies = satisfies; // } // // @Override // protected String describe() { // final StringBuilder builder = new StringBuilder(); // for(final InClause inClause : inClauses) { // if(builder.length() > 0) { // builder.append(", "); // } // // builder // .append("$") // .append(inClause.varName.toString()) // .append(" in ") // .append(inClause.in.toString()); // } // return "QuantifiedExpr(" + quantifier.getSyntax() + " " + builder.toString() + " satisfies " + satisfies.toString() + ")"; // } // // @Override // public boolean equals(final Object obj) { // if(obj != null && obj instanceof QuantifiedExpr) { // final QuantifiedExpr other = (QuantifiedExpr)obj; // return other.quantifier == quantifier // && other.inClauses.equals(inClauses) // && other.satisfies.equals(satisfies); // } // // return false; // } // } // Path: src/main/java/com/evolvedbinary/xpath/parser/ast/partial/PartialQuantifierExpr.java import java.util.List; import com.evolvedbinary.xpath.parser.ast.ASTNode; import com.evolvedbinary.xpath.parser.ast.QuantifiedExpr; /** * XPath 2 Parser * A Parser for XPath 2 * Copyright (C) 2016 Evolved Binary Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.evolvedbinary.xpath.parser.ast.partial; /** * Created by aretter on 15/02/2016. */ public class PartialQuantifierExpr extends AbstractPartialASTNode<PartialQuantifierExpr.PartialQuantifierExpr1, List<QuantifiedExpr.InClause>> { private final QuantifiedExpr.Quantifier quantifier; public PartialQuantifierExpr(final QuantifiedExpr.Quantifier quantifier) { this.quantifier = quantifier; } @Override public PartialQuantifierExpr.PartialQuantifierExpr1 complete(final List<QuantifiedExpr.InClause> inClauses) { return new PartialQuantifierExpr1(inClauses); } @Override protected String describe() { return "QuantifiedExpr(" + quantifier.getSyntax() + " ?..., ?)"; }
public class PartialQuantifierExpr1 extends AbstractPartialASTNode<QuantifiedExpr, ASTNode> {
exquery/xpath2-parser
src/main/java/com/evolvedbinary/xpath/parser/ast/partial/PartialAttributeTest.java
// Path: src/main/java/com/evolvedbinary/xpath/parser/ast/AttributeTest.java // public class AttributeTest extends KindTest { // @Nullable final QNameW name; // @Nullable QNameW typeName; // // public AttributeTest() { // this(null); // } // // public AttributeTest(final QNameW name) { // this(name, null); // } // // public AttributeTest(final QNameW name, final QNameW typeName) { // super(Kind.ATTRIBUTE); // this.name = name; // this.typeName = typeName; // } // // @Override // protected String describeParams() { // return (name == null ? "" : name.toString()) + // (typeName == null ? "" : ", " + typeName.toString()); // } // // @Override // public boolean equals(final Object obj) { // if(obj != null && obj instanceof AttributeTest) { // final AttributeTest other = (AttributeTest)obj; // // return // ((this.name == null && other.name == null) || this.name.equals(other.name)) && // ((this.typeName == null && other.typeName == null) || this.typeName.equals(other.typeName)); // } // return false; // } // // @Nullable // public QNameW getName() { // return name; // } // } // // Path: src/main/java/com/evolvedbinary/xpath/parser/ast/QNameW.java // public class QNameW extends AbstractASTNode { // public final static String WILDCARD = "*"; // // @Nullable private final String prefix; // private final String localPart; // // public QNameW(final String localPart) { // this(null, localPart); // } // // public QNameW(final String prefix, final String localPart) { // this.prefix = prefix; // this.localPart = localPart; // } // // @Override // public final String describe() { // if(prefix != null) { // return "QNameW(" + prefix + ":" + localPart + ")"; // } else { // return "QNameW(" + localPart + ")"; // } // } // // @Override // public boolean equals(final Object obj) { // if(obj != null && obj instanceof QNameW) { // final QNameW other = (QNameW)obj; // // return other.localPart.equals(this.localPart) && // (other.prefix == null ? "" : other.prefix).equals(this.prefix == null ? "" : this.prefix); // } // // return false; // } // // @Nullable // public String getPrefix() { // return prefix; // } // // public String getLocalPart() { // return localPart; // } // }
import com.evolvedbinary.xpath.parser.ast.AttributeTest; import com.evolvedbinary.xpath.parser.ast.QNameW; import org.jetbrains.annotations.Nullable;
/** * XPath 2 Parser * A Parser for XPath 2 * Copyright (C) 2016 Evolved Binary Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.evolvedbinary.xpath.parser.ast.partial; /** * Created by aretter on 30/01/2016. */ public class PartialAttributeTest extends AbstractPartialASTNode<PartialAttributeTest.PartialAttributeTest1, QNameW> { @Override public PartialAttributeTest1 complete(@Nullable final QNameW name) { return new PartialAttributeTest1(name); } @Override protected String describe() { return "AttributeTest(?, ?)"; }
// Path: src/main/java/com/evolvedbinary/xpath/parser/ast/AttributeTest.java // public class AttributeTest extends KindTest { // @Nullable final QNameW name; // @Nullable QNameW typeName; // // public AttributeTest() { // this(null); // } // // public AttributeTest(final QNameW name) { // this(name, null); // } // // public AttributeTest(final QNameW name, final QNameW typeName) { // super(Kind.ATTRIBUTE); // this.name = name; // this.typeName = typeName; // } // // @Override // protected String describeParams() { // return (name == null ? "" : name.toString()) + // (typeName == null ? "" : ", " + typeName.toString()); // } // // @Override // public boolean equals(final Object obj) { // if(obj != null && obj instanceof AttributeTest) { // final AttributeTest other = (AttributeTest)obj; // // return // ((this.name == null && other.name == null) || this.name.equals(other.name)) && // ((this.typeName == null && other.typeName == null) || this.typeName.equals(other.typeName)); // } // return false; // } // // @Nullable // public QNameW getName() { // return name; // } // } // // Path: src/main/java/com/evolvedbinary/xpath/parser/ast/QNameW.java // public class QNameW extends AbstractASTNode { // public final static String WILDCARD = "*"; // // @Nullable private final String prefix; // private final String localPart; // // public QNameW(final String localPart) { // this(null, localPart); // } // // public QNameW(final String prefix, final String localPart) { // this.prefix = prefix; // this.localPart = localPart; // } // // @Override // public final String describe() { // if(prefix != null) { // return "QNameW(" + prefix + ":" + localPart + ")"; // } else { // return "QNameW(" + localPart + ")"; // } // } // // @Override // public boolean equals(final Object obj) { // if(obj != null && obj instanceof QNameW) { // final QNameW other = (QNameW)obj; // // return other.localPart.equals(this.localPart) && // (other.prefix == null ? "" : other.prefix).equals(this.prefix == null ? "" : this.prefix); // } // // return false; // } // // @Nullable // public String getPrefix() { // return prefix; // } // // public String getLocalPart() { // return localPart; // } // } // Path: src/main/java/com/evolvedbinary/xpath/parser/ast/partial/PartialAttributeTest.java import com.evolvedbinary.xpath.parser.ast.AttributeTest; import com.evolvedbinary.xpath.parser.ast.QNameW; import org.jetbrains.annotations.Nullable; /** * XPath 2 Parser * A Parser for XPath 2 * Copyright (C) 2016 Evolved Binary Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.evolvedbinary.xpath.parser.ast.partial; /** * Created by aretter on 30/01/2016. */ public class PartialAttributeTest extends AbstractPartialASTNode<PartialAttributeTest.PartialAttributeTest1, QNameW> { @Override public PartialAttributeTest1 complete(@Nullable final QNameW name) { return new PartialAttributeTest1(name); } @Override protected String describe() { return "AttributeTest(?, ?)"; }
public class PartialAttributeTest1 extends AbstractPartialASTNode<AttributeTest, QNameW> {
exquery/xpath2-parser
src/main/java/com/evolvedbinary/xpath/parser/ast/partial/PartialIfExpr.java
// Path: src/main/java/com/evolvedbinary/xpath/parser/ast/ASTNode.java // public interface ASTNode { // } // // Path: src/main/java/com/evolvedbinary/xpath/parser/ast/Expr.java // public class Expr extends AbstractASTNode { // private final List<? extends ASTNode> exprSingles; // // public Expr(final List<? extends ASTNode> exprSingles) { // this.exprSingles = exprSingles; // } // // public Expr(final ASTNode... exprSingles) { // this.exprSingles = Arrays.asList(exprSingles); // } // // @Override // protected String describe() { // final StringBuilder builder = new StringBuilder(); // for(final ASTNode exprSingle : exprSingles) { // if(builder.length() > 0) { // builder.append(", "); // } // builder.append(exprSingle.toString()); // } // // return "Expr(" + builder.toString() + ")"; // } // // @Override // public boolean equals(final Object obj) { // if(obj != null && obj instanceof Expr) { // return ((Expr)obj).exprSingles.equals(exprSingles); // } // // return false; // } // // public List<? extends ASTNode> getExprSingles() { // return exprSingles; // } // } // // Path: src/main/java/com/evolvedbinary/xpath/parser/ast/IfExpr.java // public class IfExpr extends AbstractASTNode implements ExprSingle { // private final Expr testExpression; // private final ASTNode thenExpression; //TODO(AR) ideally should be ExprSingle... but as we simplify the AST, so we have to use ASTNode // private final ASTNode elseExpression; //TODO(AR) ideally should be ExprSingle... but as we simplify the AST, so we have to use ASTNode // // public IfExpr(final Expr testExpression, final ASTNode thenExpression, final ASTNode elseExpression) { // this.testExpression = testExpression; // this.thenExpression = thenExpression; // this.elseExpression = elseExpression; // } // // @Override // protected String describe() { // return "IfExpr(" + testExpression + " then " + thenExpression + " else " + elseExpression + ")"; // } // // @Override // public boolean equals(final Object obj) { // if(obj != null && obj instanceof IfExpr) { // final IfExpr other = (IfExpr)obj; // return other.testExpression.equals(testExpression) // && other.thenExpression.equals(thenExpression) // && other.elseExpression.equals(elseExpression); // } // // return false; // } // }
import com.evolvedbinary.xpath.parser.ast.ASTNode; import com.evolvedbinary.xpath.parser.ast.Expr; import com.evolvedbinary.xpath.parser.ast.IfExpr;
/** * XPath 2 Parser * A Parser for XPath 2 * Copyright (C) 2016 Evolved Binary Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.evolvedbinary.xpath.parser.ast.partial; /** * Created by aretter on 15/02/2016. */ public class PartialIfExpr extends AbstractPartialASTNode<PartialIfExpr.PartialIfExpr1, ASTNode> { private final Expr testExpression; public PartialIfExpr(final Expr testExpression) { this.testExpression = testExpression; } @Override protected String describe() { return "IfExpr(" + testExpression + " then ? else ?)"; } @Override public PartialIfExpr.PartialIfExpr1 complete(final ASTNode thenExpression) { return new PartialIfExpr1(thenExpression); }
// Path: src/main/java/com/evolvedbinary/xpath/parser/ast/ASTNode.java // public interface ASTNode { // } // // Path: src/main/java/com/evolvedbinary/xpath/parser/ast/Expr.java // public class Expr extends AbstractASTNode { // private final List<? extends ASTNode> exprSingles; // // public Expr(final List<? extends ASTNode> exprSingles) { // this.exprSingles = exprSingles; // } // // public Expr(final ASTNode... exprSingles) { // this.exprSingles = Arrays.asList(exprSingles); // } // // @Override // protected String describe() { // final StringBuilder builder = new StringBuilder(); // for(final ASTNode exprSingle : exprSingles) { // if(builder.length() > 0) { // builder.append(", "); // } // builder.append(exprSingle.toString()); // } // // return "Expr(" + builder.toString() + ")"; // } // // @Override // public boolean equals(final Object obj) { // if(obj != null && obj instanceof Expr) { // return ((Expr)obj).exprSingles.equals(exprSingles); // } // // return false; // } // // public List<? extends ASTNode> getExprSingles() { // return exprSingles; // } // } // // Path: src/main/java/com/evolvedbinary/xpath/parser/ast/IfExpr.java // public class IfExpr extends AbstractASTNode implements ExprSingle { // private final Expr testExpression; // private final ASTNode thenExpression; //TODO(AR) ideally should be ExprSingle... but as we simplify the AST, so we have to use ASTNode // private final ASTNode elseExpression; //TODO(AR) ideally should be ExprSingle... but as we simplify the AST, so we have to use ASTNode // // public IfExpr(final Expr testExpression, final ASTNode thenExpression, final ASTNode elseExpression) { // this.testExpression = testExpression; // this.thenExpression = thenExpression; // this.elseExpression = elseExpression; // } // // @Override // protected String describe() { // return "IfExpr(" + testExpression + " then " + thenExpression + " else " + elseExpression + ")"; // } // // @Override // public boolean equals(final Object obj) { // if(obj != null && obj instanceof IfExpr) { // final IfExpr other = (IfExpr)obj; // return other.testExpression.equals(testExpression) // && other.thenExpression.equals(thenExpression) // && other.elseExpression.equals(elseExpression); // } // // return false; // } // } // Path: src/main/java/com/evolvedbinary/xpath/parser/ast/partial/PartialIfExpr.java import com.evolvedbinary.xpath.parser.ast.ASTNode; import com.evolvedbinary.xpath.parser.ast.Expr; import com.evolvedbinary.xpath.parser.ast.IfExpr; /** * XPath 2 Parser * A Parser for XPath 2 * Copyright (C) 2016 Evolved Binary Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.evolvedbinary.xpath.parser.ast.partial; /** * Created by aretter on 15/02/2016. */ public class PartialIfExpr extends AbstractPartialASTNode<PartialIfExpr.PartialIfExpr1, ASTNode> { private final Expr testExpression; public PartialIfExpr(final Expr testExpression) { this.testExpression = testExpression; } @Override protected String describe() { return "IfExpr(" + testExpression + " then ? else ?)"; } @Override public PartialIfExpr.PartialIfExpr1 complete(final ASTNode thenExpression) { return new PartialIfExpr1(thenExpression); }
public class PartialIfExpr1 extends AbstractPartialASTNode<IfExpr, ASTNode> {
jacek99/immutizer4j
src/test/java/org/immutizer4j/test/sample/ImmutableArrayPojo.java
// Path: src/test/java/org/immutizer4j/test/sample/generics/ImmutableArray.java // @Value // public class ImmutableArray<T> { // // private T[] array; // // /** // * Constructor. Creates a copy of the source array // */ // public ImmutableArray(T[] a){ // array = Arrays.copyOf(a, a.length); // } // // public T get(int index){ // return array[index]; // } // }
import lombok.Value; import org.immutizer4j.test.sample.generics.ImmutableArray;
package org.immutizer4j.test.sample; /** * A POJO that uses ImmutableArray to wrap both mutable and immutable object types * and ensure we correctly process both */ @Value public class ImmutableArrayPojo { // this one is OK, as ImmutablePojo is obviously immutable
// Path: src/test/java/org/immutizer4j/test/sample/generics/ImmutableArray.java // @Value // public class ImmutableArray<T> { // // private T[] array; // // /** // * Constructor. Creates a copy of the source array // */ // public ImmutableArray(T[] a){ // array = Arrays.copyOf(a, a.length); // } // // public T get(int index){ // return array[index]; // } // } // Path: src/test/java/org/immutizer4j/test/sample/ImmutableArrayPojo.java import lombok.Value; import org.immutizer4j.test.sample.generics.ImmutableArray; package org.immutizer4j.test.sample; /** * A POJO that uses ImmutableArray to wrap both mutable and immutable object types * and ensure we correctly process both */ @Value public class ImmutableArrayPojo { // this one is OK, as ImmutablePojo is obviously immutable
private ImmutableArray<ImmutablePojo> immutablePojoArray;
indexiatech/antiquity
src/main/java/co/indexia/antiquity/graph/IndexableTransactionalVersionedGraphImpl.java
// Path: src/main/java/co/indexia/antiquity/graph/identifierBehavior/GraphIdentifierBehavior.java // public interface GraphIdentifierBehavior<V extends Comparable<V>> { // /** // * Get the latest(current) graph version. // * // * <p> // * Graph latest version is stored in the root historic vertex. // * <p> // * // * @see co.indexia.antiquity.graph.ActiveVersionedGraph#getRootVertex() // * // * @return The latest graph version. // */ // public V getLatestGraphVersion(); // // /** // * Get the next graph version. // * // * @param currentVersion The current version of the graph. // */ // public V getNextGraphVersion(V currentVersion); // // /** // * Get the minimum possible graph version. // * // * @return The minimum possible graph version. // */ // public V getMinPossibleGraphVersion(); // // /** // * Get the maximum possible graph version. // * // * @return The maximum possible graph version // */ // public V getMaxPossibleGraphVersion(); // // /** // * Set the {@link co.indexia.antiquity.graph.VersionedGraphBase} // * instance associated with this behavior // */ // public void setGraph(VersionedGraphBase<?, V> graph); // }
import com.tinkerpop.blueprints.Element; import com.tinkerpop.blueprints.Index; import com.tinkerpop.blueprints.IndexableGraph; import com.tinkerpop.blueprints.KeyIndexableGraph; import com.tinkerpop.blueprints.Parameter; import com.tinkerpop.blueprints.TransactionalGraph; import com.tinkerpop.blueprints.util.wrappers.id.IdGraph; import co.indexia.antiquity.graph.identifierBehavior.GraphIdentifierBehavior;
/** * Copyright (c) 2012-2014 "Indexia Technologies, ltd." * * This file is part of Antiquity. * * Antiquity is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package co.indexia.antiquity.graph; /** * TODO: This is a starting point of having a flavor of transactional graph that supports manual indexing as this * commit removed the native support for IndexableGraph since it's not supported by Titan and others * * To make it work, it still needs impl of another EventableGraph that implements IndexableGraph */ public class IndexableTransactionalVersionedGraphImpl<T extends TransactionalGraph & KeyIndexableGraph & IndexableGraph, V extends Comparable<V>> extends TransactionalVersionedGraph<T, V> implements IndexableGraph {
// Path: src/main/java/co/indexia/antiquity/graph/identifierBehavior/GraphIdentifierBehavior.java // public interface GraphIdentifierBehavior<V extends Comparable<V>> { // /** // * Get the latest(current) graph version. // * // * <p> // * Graph latest version is stored in the root historic vertex. // * <p> // * // * @see co.indexia.antiquity.graph.ActiveVersionedGraph#getRootVertex() // * // * @return The latest graph version. // */ // public V getLatestGraphVersion(); // // /** // * Get the next graph version. // * // * @param currentVersion The current version of the graph. // */ // public V getNextGraphVersion(V currentVersion); // // /** // * Get the minimum possible graph version. // * // * @return The minimum possible graph version. // */ // public V getMinPossibleGraphVersion(); // // /** // * Get the maximum possible graph version. // * // * @return The maximum possible graph version // */ // public V getMaxPossibleGraphVersion(); // // /** // * Set the {@link co.indexia.antiquity.graph.VersionedGraphBase} // * instance associated with this behavior // */ // public void setGraph(VersionedGraphBase<?, V> graph); // } // Path: src/main/java/co/indexia/antiquity/graph/IndexableTransactionalVersionedGraphImpl.java import com.tinkerpop.blueprints.Element; import com.tinkerpop.blueprints.Index; import com.tinkerpop.blueprints.IndexableGraph; import com.tinkerpop.blueprints.KeyIndexableGraph; import com.tinkerpop.blueprints.Parameter; import com.tinkerpop.blueprints.TransactionalGraph; import com.tinkerpop.blueprints.util.wrappers.id.IdGraph; import co.indexia.antiquity.graph.identifierBehavior.GraphIdentifierBehavior; /** * Copyright (c) 2012-2014 "Indexia Technologies, ltd." * * This file is part of Antiquity. * * Antiquity is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package co.indexia.antiquity.graph; /** * TODO: This is a starting point of having a flavor of transactional graph that supports manual indexing as this * commit removed the native support for IndexableGraph since it's not supported by Titan and others * * To make it work, it still needs impl of another EventableGraph that implements IndexableGraph */ public class IndexableTransactionalVersionedGraphImpl<T extends TransactionalGraph & KeyIndexableGraph & IndexableGraph, V extends Comparable<V>> extends TransactionalVersionedGraph<T, V> implements IndexableGraph {
IndexableTransactionalVersionedGraphImpl(T baseGraph, GraphIdentifierBehavior<V> identifierBehavior) {
indexiatech/antiquity
src/test/java/co/indexia/antiquity/graph/matchers/HasElementIds.java
// Path: src/main/java/co/indexia/antiquity/graph/HistoricVersionedElement.java // public abstract class HistoricVersionedElement<V extends Comparable<V>, T extends Element> implements Element { // /** // * The graph instance which loaded this edge. // */ // private final HistoricVersionedGraph<?, V> graph; // // /** // * The raw element as retrieved from // * {@link co.indexia.antiquity.graph.HistoricVersionedGraph} // */ // private final T rawElement; // // /** // * Defines the version context of the element, associated properties and // * elements will match the specified version. // */ // private Range<V> version; // // /** // * Creates an instance. // * // * @param rawElement the edge that was loaded from the underline graph. // * @param graph the graph instance this element is associated with. // * @param version the requested version range to filter upon. // */ // public HistoricVersionedElement(T rawElement, HistoricVersionedGraph<?, V> graph, Range<V> version) { // Preconditions.checkNotNull(rawElement, "Raw element must be set."); // Preconditions.checkNotNull(graph, "Graph must be set."); // Preconditions.checkNotNull(version, "Version must be set."); // // Preconditions.checkNotNull(version, "Version must be set."); // Preconditions.checkArgument((!(rawElement instanceof HistoricVersionedElement)), // "rawElement cannot be instance of HistoricVersionElement"); // // if (!graph.utils.isInternal(rawElement)) { // Preconditions.checkArgument(graph.utils.getElementType(rawElement) != VEProps.GRAPH_TYPE.ACTIVE, // "Raw element cannot be active"); // } // // this.rawElement = rawElement; // this.graph = graph; // this.version = version; // } // // /** // * Every historic element has its own unique ID, this method return this // * identifier, while invoking @{link getId()} returns the ID of the // * corresponding active object. // * // * @return an identifier. // */ // public Object getHardId() { // if (graph.isNaturalIds()) { // if (rawElement instanceof Vertex) { // return rawElement.getProperty(VEProps.NATURAL_VERTEX_ID_PROP_KEY); // } else { // return rawElement.getProperty(VEProps.NATURAL_EDGE_ID_PROP_KEY); // } // } else { // return rawElement.getId(); // } // } // // @Override // public Object getId() { // return rawElement.getProperty(VEProps.REF_TO_ACTIVE_ID_KEY); // } // // /** // * Get the associated graph // * // * @return The associated graph // */ // protected HistoricVersionedGraph<?, V> getGraph() { // return graph; // } // // /** // * Get the raw element of this historic element. This method is useful if it // * is required to modify the historic element. // * // * @return The raw element // */ // public T getRaw() { // return this.rawElement; // } // // /** // * Get the version property of the element. // * // * This property defines the version context of the vertex, associated // * properties and elements will be filtered according to the set version. // * // * @return The version bound to the vertex // */ // public Range<V> getVersion() { // return this.version; // } // // public void setVersion(Range<V> version) { // this.version = version; // } // // @Override // public String toString() { // if (graph.utils.isInternal(this)) { // return getRaw().getId().toString(); // } else { // return getId().toString(); // } // } // }
import com.google.common.collect.Lists; import com.tinkerpop.blueprints.Element; import co.indexia.antiquity.graph.HistoricVersionedElement; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import java.util.ArrayList; import java.util.List;
/** * Copyright (c) 2012-2014 "Indexia Technologies, ltd." * * This file is part of Antiquity. * * Antiquity is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package co.indexia.antiquity.graph.matchers; /** * Matcher for element key existence * Note: comparison is done by IDs as string. */ public class HasElementIds<T extends Iterable<? extends Element>> extends TypeSafeMatcher<T> { private final TYPE type; private final ID id; private final List<Object> expected; private List<Object> ids = new ArrayList<Object>(); public enum TYPE { CONTAINS, EXACTLY_MATCHES }; public enum ID { ID, HARD_ID } protected HasElementIds(TYPE type, Object... expected) { this(ID.ID, type, expected); } protected HasElementIds(ID id, TYPE type, Object... expected) { this.type = type; this.id = id; this.expected = Lists.newArrayList(expected); } @Override protected boolean matchesSafely(T t) { for (Element e : t) { if (id == ID.ID) { ids.add(e.getId()); } else {
// Path: src/main/java/co/indexia/antiquity/graph/HistoricVersionedElement.java // public abstract class HistoricVersionedElement<V extends Comparable<V>, T extends Element> implements Element { // /** // * The graph instance which loaded this edge. // */ // private final HistoricVersionedGraph<?, V> graph; // // /** // * The raw element as retrieved from // * {@link co.indexia.antiquity.graph.HistoricVersionedGraph} // */ // private final T rawElement; // // /** // * Defines the version context of the element, associated properties and // * elements will match the specified version. // */ // private Range<V> version; // // /** // * Creates an instance. // * // * @param rawElement the edge that was loaded from the underline graph. // * @param graph the graph instance this element is associated with. // * @param version the requested version range to filter upon. // */ // public HistoricVersionedElement(T rawElement, HistoricVersionedGraph<?, V> graph, Range<V> version) { // Preconditions.checkNotNull(rawElement, "Raw element must be set."); // Preconditions.checkNotNull(graph, "Graph must be set."); // Preconditions.checkNotNull(version, "Version must be set."); // // Preconditions.checkNotNull(version, "Version must be set."); // Preconditions.checkArgument((!(rawElement instanceof HistoricVersionedElement)), // "rawElement cannot be instance of HistoricVersionElement"); // // if (!graph.utils.isInternal(rawElement)) { // Preconditions.checkArgument(graph.utils.getElementType(rawElement) != VEProps.GRAPH_TYPE.ACTIVE, // "Raw element cannot be active"); // } // // this.rawElement = rawElement; // this.graph = graph; // this.version = version; // } // // /** // * Every historic element has its own unique ID, this method return this // * identifier, while invoking @{link getId()} returns the ID of the // * corresponding active object. // * // * @return an identifier. // */ // public Object getHardId() { // if (graph.isNaturalIds()) { // if (rawElement instanceof Vertex) { // return rawElement.getProperty(VEProps.NATURAL_VERTEX_ID_PROP_KEY); // } else { // return rawElement.getProperty(VEProps.NATURAL_EDGE_ID_PROP_KEY); // } // } else { // return rawElement.getId(); // } // } // // @Override // public Object getId() { // return rawElement.getProperty(VEProps.REF_TO_ACTIVE_ID_KEY); // } // // /** // * Get the associated graph // * // * @return The associated graph // */ // protected HistoricVersionedGraph<?, V> getGraph() { // return graph; // } // // /** // * Get the raw element of this historic element. This method is useful if it // * is required to modify the historic element. // * // * @return The raw element // */ // public T getRaw() { // return this.rawElement; // } // // /** // * Get the version property of the element. // * // * This property defines the version context of the vertex, associated // * properties and elements will be filtered according to the set version. // * // * @return The version bound to the vertex // */ // public Range<V> getVersion() { // return this.version; // } // // public void setVersion(Range<V> version) { // this.version = version; // } // // @Override // public String toString() { // if (graph.utils.isInternal(this)) { // return getRaw().getId().toString(); // } else { // return getId().toString(); // } // } // } // Path: src/test/java/co/indexia/antiquity/graph/matchers/HasElementIds.java import com.google.common.collect.Lists; import com.tinkerpop.blueprints.Element; import co.indexia.antiquity.graph.HistoricVersionedElement; import org.hamcrest.Description; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import java.util.ArrayList; import java.util.List; /** * Copyright (c) 2012-2014 "Indexia Technologies, ltd." * * This file is part of Antiquity. * * Antiquity is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package co.indexia.antiquity.graph.matchers; /** * Matcher for element key existence * Note: comparison is done by IDs as string. */ public class HasElementIds<T extends Iterable<? extends Element>> extends TypeSafeMatcher<T> { private final TYPE type; private final ID id; private final List<Object> expected; private List<Object> ids = new ArrayList<Object>(); public enum TYPE { CONTAINS, EXACTLY_MATCHES }; public enum ID { ID, HARD_ID } protected HasElementIds(TYPE type, Object... expected) { this(ID.ID, type, expected); } protected HasElementIds(ID id, TYPE type, Object... expected) { this.type = type; this.id = id; this.expected = Lists.newArrayList(expected); } @Override protected boolean matchesSafely(T t) { for (Element e : t) { if (id == ID.ID) { ids.add(e.getId()); } else {
if (!(e instanceof HistoricVersionedElement)) {
indexiatech/antiquity
src/test/java/co/indexia/antiquity/graph/GraphInitTest.java
// Path: src/main/java/co/indexia/antiquity/graph/identifierBehavior/LongGraphIdentifierBehavior.java // public class LongGraphIdentifierBehavior extends BaseGraphIdentifierBehavior<Long> { // @Override // public Long getMinPossibleGraphVersion() { // return (long) 1; // } // // @Override // public Long getMaxPossibleGraphVersion() { // return Long.MAX_VALUE; // } // // @Override // public Long getLatestGraphVersion() { // Long lastVer = // (Long) getGraph().getRootVertex(VEProps.GRAPH_TYPE.HISTORIC).getProperty( // VEProps.LATEST_GRAPH_VERSION_PROP_KEY); // if (lastVer == null) { // return 0L; // } else { // return lastVer; // } // } // // @Override // public Long getNextGraphVersion(Long currentVersion) { // if (currentVersion == Long.MAX_VALUE) // throw new IllegalStateException("Cannot get next version, long range has ended "); // // return currentVersion + 1; // } // }
import com.google.common.collect.Lists; import com.tinkerpop.blueprints.impls.tg.TinkerGraph; import co.indexia.antiquity.graph.identifierBehavior.LongGraphIdentifierBehavior; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat;
/** * Copyright (c) 2012-2014 "Indexia Technologies, ltd." * * This file is part of Antiquity. * * Antiquity is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package co.indexia.antiquity.graph; /** * Test graph creation & initialization */ public class GraphInitTest { @Test(expected = IllegalStateException.class) public void causeExceptionIfGraphNotInitialized() { TinkerGraph graph = new TinkerGraph(); Configuration conf = new Configuration.ConfBuilder().build(); ActiveVersionedGraph<TinkerGraph, Long> vg = new ActiveVersionedGraph.ActiveVersionedNonTransactionalGraphBuilder<TinkerGraph, Long>(
// Path: src/main/java/co/indexia/antiquity/graph/identifierBehavior/LongGraphIdentifierBehavior.java // public class LongGraphIdentifierBehavior extends BaseGraphIdentifierBehavior<Long> { // @Override // public Long getMinPossibleGraphVersion() { // return (long) 1; // } // // @Override // public Long getMaxPossibleGraphVersion() { // return Long.MAX_VALUE; // } // // @Override // public Long getLatestGraphVersion() { // Long lastVer = // (Long) getGraph().getRootVertex(VEProps.GRAPH_TYPE.HISTORIC).getProperty( // VEProps.LATEST_GRAPH_VERSION_PROP_KEY); // if (lastVer == null) { // return 0L; // } else { // return lastVer; // } // } // // @Override // public Long getNextGraphVersion(Long currentVersion) { // if (currentVersion == Long.MAX_VALUE) // throw new IllegalStateException("Cannot get next version, long range has ended "); // // return currentVersion + 1; // } // } // Path: src/test/java/co/indexia/antiquity/graph/GraphInitTest.java import com.google.common.collect.Lists; import com.tinkerpop.blueprints.impls.tg.TinkerGraph; import co.indexia.antiquity.graph.identifierBehavior.LongGraphIdentifierBehavior; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * Copyright (c) 2012-2014 "Indexia Technologies, ltd." * * This file is part of Antiquity. * * Antiquity is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package co.indexia.antiquity.graph; /** * Test graph creation & initialization */ public class GraphInitTest { @Test(expected = IllegalStateException.class) public void causeExceptionIfGraphNotInitialized() { TinkerGraph graph = new TinkerGraph(); Configuration conf = new Configuration.ConfBuilder().build(); ActiveVersionedGraph<TinkerGraph, Long> vg = new ActiveVersionedGraph.ActiveVersionedNonTransactionalGraphBuilder<TinkerGraph, Long>(
graph, new LongGraphIdentifierBehavior()).init(false).conf(conf).build();
indexiatech/antiquity
src/main/java/co/indexia/antiquity/graph/TransactionalVersionedGraph.java
// Path: src/main/java/co/indexia/antiquity/graph/identifierBehavior/GraphIdentifierBehavior.java // public interface GraphIdentifierBehavior<V extends Comparable<V>> { // /** // * Get the latest(current) graph version. // * // * <p> // * Graph latest version is stored in the root historic vertex. // * <p> // * // * @see co.indexia.antiquity.graph.ActiveVersionedGraph#getRootVertex() // * // * @return The latest graph version. // */ // public V getLatestGraphVersion(); // // /** // * Get the next graph version. // * // * @param currentVersion The current version of the graph. // */ // public V getNextGraphVersion(V currentVersion); // // /** // * Get the minimum possible graph version. // * // * @return The minimum possible graph version. // */ // public V getMinPossibleGraphVersion(); // // /** // * Get the maximum possible graph version. // * // * @return The maximum possible graph version // */ // public V getMaxPossibleGraphVersion(); // // /** // * Set the {@link co.indexia.antiquity.graph.VersionedGraphBase} // * instance associated with this behavior // */ // public void setGraph(VersionedGraphBase<?, V> graph); // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Element; import com.tinkerpop.blueprints.IndexableGraph; import com.tinkerpop.blueprints.KeyIndexableGraph; import com.tinkerpop.blueprints.TransactionalGraph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.util.wrappers.id.IdGraph.IdFactory; import co.indexia.antiquity.graph.identifierBehavior.GraphIdentifierBehavior;
/** * Copyright (c) 2012-2014 "Indexia Technologies, ltd." * * This file is part of Antiquity. * * Antiquity is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package co.indexia.antiquity.graph; /** * A transactional implementation of {@link ActiveVersionedGraph}. * * @see TransactionalGraph * @see ActiveVersionedGraph * @param <T> The type of the base graph, must support transactions. * @param <V> The version identifier type */ public class TransactionalVersionedGraph<T extends TransactionalGraph & KeyIndexableGraph, V extends Comparable<V>> extends ActiveVersionedGraph<T, V> implements TransactionalGraph { Logger log = LoggerFactory.getLogger(TransactionalVersionedGraph.class); private final ThreadLocal<TransactionData> transactionData = new ThreadLocal<TransactionData>() { @Override protected TransactionData initialValue() { return new TransactionData(); } };
// Path: src/main/java/co/indexia/antiquity/graph/identifierBehavior/GraphIdentifierBehavior.java // public interface GraphIdentifierBehavior<V extends Comparable<V>> { // /** // * Get the latest(current) graph version. // * // * <p> // * Graph latest version is stored in the root historic vertex. // * <p> // * // * @see co.indexia.antiquity.graph.ActiveVersionedGraph#getRootVertex() // * // * @return The latest graph version. // */ // public V getLatestGraphVersion(); // // /** // * Get the next graph version. // * // * @param currentVersion The current version of the graph. // */ // public V getNextGraphVersion(V currentVersion); // // /** // * Get the minimum possible graph version. // * // * @return The minimum possible graph version. // */ // public V getMinPossibleGraphVersion(); // // /** // * Get the maximum possible graph version. // * // * @return The maximum possible graph version // */ // public V getMaxPossibleGraphVersion(); // // /** // * Set the {@link co.indexia.antiquity.graph.VersionedGraphBase} // * instance associated with this behavior // */ // public void setGraph(VersionedGraphBase<?, V> graph); // } // Path: src/main/java/co/indexia/antiquity/graph/TransactionalVersionedGraph.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Element; import com.tinkerpop.blueprints.IndexableGraph; import com.tinkerpop.blueprints.KeyIndexableGraph; import com.tinkerpop.blueprints.TransactionalGraph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.util.wrappers.id.IdGraph.IdFactory; import co.indexia.antiquity.graph.identifierBehavior.GraphIdentifierBehavior; /** * Copyright (c) 2012-2014 "Indexia Technologies, ltd." * * This file is part of Antiquity. * * Antiquity is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package co.indexia.antiquity.graph; /** * A transactional implementation of {@link ActiveVersionedGraph}. * * @see TransactionalGraph * @see ActiveVersionedGraph * @param <T> The type of the base graph, must support transactions. * @param <V> The version identifier type */ public class TransactionalVersionedGraph<T extends TransactionalGraph & KeyIndexableGraph, V extends Comparable<V>> extends ActiveVersionedGraph<T, V> implements TransactionalGraph { Logger log = LoggerFactory.getLogger(TransactionalVersionedGraph.class); private final ThreadLocal<TransactionData> transactionData = new ThreadLocal<TransactionData>() { @Override protected TransactionData initialValue() { return new TransactionData(); } };
TransactionalVersionedGraph(T baseGraph, GraphIdentifierBehavior<V> identifierBehavior) {
indexiatech/antiquity
src/test/java/co/indexia/antiquity/graph/TitanTxLongVersionedGraphTest.java
// Path: src/main/java/co/indexia/antiquity/graph/identifierBehavior/LongGraphIdentifierBehavior.java // public class LongGraphIdentifierBehavior extends BaseGraphIdentifierBehavior<Long> { // @Override // public Long getMinPossibleGraphVersion() { // return (long) 1; // } // // @Override // public Long getMaxPossibleGraphVersion() { // return Long.MAX_VALUE; // } // // @Override // public Long getLatestGraphVersion() { // Long lastVer = // (Long) getGraph().getRootVertex(VEProps.GRAPH_TYPE.HISTORIC).getProperty( // VEProps.LATEST_GRAPH_VERSION_PROP_KEY); // if (lastVer == null) { // return 0L; // } else { // return lastVer; // } // } // // @Override // public Long getNextGraphVersion(Long currentVersion) { // if (currentVersion == Long.MAX_VALUE) // throw new IllegalStateException("Cannot get next version, long range has ended "); // // return currentVersion + 1; // } // }
import com.thinkaurelius.titan.core.TitanFactory; import com.thinkaurelius.titan.core.TitanGraph; import co.indexia.antiquity.graph.identifierBehavior.LongGraphIdentifierBehavior; import org.apache.commons.configuration.BaseConfiguration; import org.apache.commons.configuration.Configuration; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException;
/** * Copyright (c) 2012-2014 "Indexia Technologies, ltd." * * This file is part of Antiquity. * * Antiquity is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package co.indexia.antiquity.graph; /** * Titan tests */ public class TitanTxLongVersionedGraphTest extends TransactionalLongVersionedGraphTest { @Override protected ActiveVersionedGraph<?, Long> generateGraph() { File f = new File("/tmp/testgraph"); if (f.exists()) { if (f.isDirectory()) { try { FileUtils.deleteDirectory(f); } catch (IOException e) { throw new IllegalStateException(e); } } else { f.delete(); } } Configuration c = new BaseConfiguration(); c.addProperty("storage.directory","/tmp/testgraph"); TitanGraph g = TitanFactory.open(c);
// Path: src/main/java/co/indexia/antiquity/graph/identifierBehavior/LongGraphIdentifierBehavior.java // public class LongGraphIdentifierBehavior extends BaseGraphIdentifierBehavior<Long> { // @Override // public Long getMinPossibleGraphVersion() { // return (long) 1; // } // // @Override // public Long getMaxPossibleGraphVersion() { // return Long.MAX_VALUE; // } // // @Override // public Long getLatestGraphVersion() { // Long lastVer = // (Long) getGraph().getRootVertex(VEProps.GRAPH_TYPE.HISTORIC).getProperty( // VEProps.LATEST_GRAPH_VERSION_PROP_KEY); // if (lastVer == null) { // return 0L; // } else { // return lastVer; // } // } // // @Override // public Long getNextGraphVersion(Long currentVersion) { // if (currentVersion == Long.MAX_VALUE) // throw new IllegalStateException("Cannot get next version, long range has ended "); // // return currentVersion + 1; // } // } // Path: src/test/java/co/indexia/antiquity/graph/TitanTxLongVersionedGraphTest.java import com.thinkaurelius.titan.core.TitanFactory; import com.thinkaurelius.titan.core.TitanGraph; import co.indexia.antiquity.graph.identifierBehavior.LongGraphIdentifierBehavior; import org.apache.commons.configuration.BaseConfiguration; import org.apache.commons.configuration.Configuration; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; /** * Copyright (c) 2012-2014 "Indexia Technologies, ltd." * * This file is part of Antiquity. * * Antiquity is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package co.indexia.antiquity.graph; /** * Titan tests */ public class TitanTxLongVersionedGraphTest extends TransactionalLongVersionedGraphTest { @Override protected ActiveVersionedGraph<?, Long> generateGraph() { File f = new File("/tmp/testgraph"); if (f.exists()) { if (f.isDirectory()) { try { FileUtils.deleteDirectory(f); } catch (IOException e) { throw new IllegalStateException(e); } } else { f.delete(); } } Configuration c = new BaseConfiguration(); c.addProperty("storage.directory","/tmp/testgraph"); TitanGraph g = TitanFactory.open(c);
return new ActiveVersionedGraph.ActiveVersionedTransactionalGraphBuilder<TitanGraph, Long>(g, new LongGraphIdentifierBehavior())
indexiatech/antiquity
src/main/java/co/indexia/antiquity/graph/NonTransactionalVersionedGraph.java
// Path: src/main/java/co/indexia/antiquity/graph/identifierBehavior/GraphIdentifierBehavior.java // public interface GraphIdentifierBehavior<V extends Comparable<V>> { // /** // * Get the latest(current) graph version. // * // * <p> // * Graph latest version is stored in the root historic vertex. // * <p> // * // * @see co.indexia.antiquity.graph.ActiveVersionedGraph#getRootVertex() // * // * @return The latest graph version. // */ // public V getLatestGraphVersion(); // // /** // * Get the next graph version. // * // * @param currentVersion The current version of the graph. // */ // public V getNextGraphVersion(V currentVersion); // // /** // * Get the minimum possible graph version. // * // * @return The minimum possible graph version. // */ // public V getMinPossibleGraphVersion(); // // /** // * Get the maximum possible graph version. // * // * @return The maximum possible graph version // */ // public V getMaxPossibleGraphVersion(); // // /** // * Set the {@link co.indexia.antiquity.graph.VersionedGraphBase} // * instance associated with this behavior // */ // public void setGraph(VersionedGraphBase<?, V> graph); // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import com.google.common.collect.Maps; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.IndexableGraph; import com.tinkerpop.blueprints.KeyIndexableGraph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.util.wrappers.id.IdGraph.IdFactory; import co.indexia.antiquity.graph.identifierBehavior.GraphIdentifierBehavior;
/** * Copyright (c) 2012-2014 "Indexia Technologies, ltd." * * This file is part of Antiquity. * * Antiquity is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package co.indexia.antiquity.graph; /** * A non transactional {@link ActiveVersionedGraph} implementation. * * @param <T> The type of the graph * @param <V> The type of the graph version */ public class NonTransactionalVersionedGraph<T extends KeyIndexableGraph, V extends Comparable<V>> extends ActiveVersionedGraph<T, V> { Logger log = LoggerFactory.getLogger(NonTransactionalVersionedGraph.class); /** * Create an instance of this class. * * @param baseGraph The base class to wrap with versioning support * @param identifierBehavior The graph identifier behavior implementation. */
// Path: src/main/java/co/indexia/antiquity/graph/identifierBehavior/GraphIdentifierBehavior.java // public interface GraphIdentifierBehavior<V extends Comparable<V>> { // /** // * Get the latest(current) graph version. // * // * <p> // * Graph latest version is stored in the root historic vertex. // * <p> // * // * @see co.indexia.antiquity.graph.ActiveVersionedGraph#getRootVertex() // * // * @return The latest graph version. // */ // public V getLatestGraphVersion(); // // /** // * Get the next graph version. // * // * @param currentVersion The current version of the graph. // */ // public V getNextGraphVersion(V currentVersion); // // /** // * Get the minimum possible graph version. // * // * @return The minimum possible graph version. // */ // public V getMinPossibleGraphVersion(); // // /** // * Get the maximum possible graph version. // * // * @return The maximum possible graph version // */ // public V getMaxPossibleGraphVersion(); // // /** // * Set the {@link co.indexia.antiquity.graph.VersionedGraphBase} // * instance associated with this behavior // */ // public void setGraph(VersionedGraphBase<?, V> graph); // } // Path: src/main/java/co/indexia/antiquity/graph/NonTransactionalVersionedGraph.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import com.google.common.collect.Maps; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.IndexableGraph; import com.tinkerpop.blueprints.KeyIndexableGraph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.util.wrappers.id.IdGraph.IdFactory; import co.indexia.antiquity.graph.identifierBehavior.GraphIdentifierBehavior; /** * Copyright (c) 2012-2014 "Indexia Technologies, ltd." * * This file is part of Antiquity. * * Antiquity is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package co.indexia.antiquity.graph; /** * A non transactional {@link ActiveVersionedGraph} implementation. * * @param <T> The type of the graph * @param <V> The type of the graph version */ public class NonTransactionalVersionedGraph<T extends KeyIndexableGraph, V extends Comparable<V>> extends ActiveVersionedGraph<T, V> { Logger log = LoggerFactory.getLogger(NonTransactionalVersionedGraph.class); /** * Create an instance of this class. * * @param baseGraph The base class to wrap with versioning support * @param identifierBehavior The graph identifier behavior implementation. */
public NonTransactionalVersionedGraph(T baseGraph, GraphIdentifierBehavior<V> identifierBehavior) {
indexiatech/antiquity
src/test/java/co/indexia/antiquity/graph/NonTransactionalLongTypeVersionedGraphTest.java
// Path: src/main/java/co/indexia/antiquity/graph/identifierBehavior/LongGraphIdentifierBehavior.java // public class LongGraphIdentifierBehavior extends BaseGraphIdentifierBehavior<Long> { // @Override // public Long getMinPossibleGraphVersion() { // return (long) 1; // } // // @Override // public Long getMaxPossibleGraphVersion() { // return Long.MAX_VALUE; // } // // @Override // public Long getLatestGraphVersion() { // Long lastVer = // (Long) getGraph().getRootVertex(VEProps.GRAPH_TYPE.HISTORIC).getProperty( // VEProps.LATEST_GRAPH_VERSION_PROP_KEY); // if (lastVer == null) { // return 0L; // } else { // return lastVer; // } // } // // @Override // public Long getNextGraphVersion(Long currentVersion) { // if (currentVersion == Long.MAX_VALUE) // throw new IllegalStateException("Cannot get next version, long range has ended "); // // return currentVersion + 1; // } // }
import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import com.tinkerpop.blueprints.impls.tg.TinkerGraph; import co.indexia.antiquity.graph.identifierBehavior.LongGraphIdentifierBehavior; import org.junit.Test;
/** * Copyright (c) 2012-2014 "Indexia Technologies, ltd." * * This file is part of Antiquity. * * Antiquity is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package co.indexia.antiquity.graph; public class NonTransactionalLongTypeVersionedGraphTest extends VersionedGraphTestSuite<Long> { @Override protected ActiveVersionedGraph<?, Long> generateGraph() { return generateGraph("graph"); } protected ActiveVersionedGraph<?, Long> generateGraph(String graphDirectoryName) { return generateGraph(graphDirectoryName, null); } protected ActiveVersionedGraph<?, Long> generateGraph(String graphDirectoryName, Configuration conf) { // For natural IDs tests // Configuration conf1 = new // Configuration.ConfBuilder().useNaturalIds(true).build(); return new ActiveVersionedGraph.ActiveVersionedNonTransactionalGraphBuilder<TinkerGraph, Long>(
// Path: src/main/java/co/indexia/antiquity/graph/identifierBehavior/LongGraphIdentifierBehavior.java // public class LongGraphIdentifierBehavior extends BaseGraphIdentifierBehavior<Long> { // @Override // public Long getMinPossibleGraphVersion() { // return (long) 1; // } // // @Override // public Long getMaxPossibleGraphVersion() { // return Long.MAX_VALUE; // } // // @Override // public Long getLatestGraphVersion() { // Long lastVer = // (Long) getGraph().getRootVertex(VEProps.GRAPH_TYPE.HISTORIC).getProperty( // VEProps.LATEST_GRAPH_VERSION_PROP_KEY); // if (lastVer == null) { // return 0L; // } else { // return lastVer; // } // } // // @Override // public Long getNextGraphVersion(Long currentVersion) { // if (currentVersion == Long.MAX_VALUE) // throw new IllegalStateException("Cannot get next version, long range has ended "); // // return currentVersion + 1; // } // } // Path: src/test/java/co/indexia/antiquity/graph/NonTransactionalLongTypeVersionedGraphTest.java import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import com.tinkerpop.blueprints.impls.tg.TinkerGraph; import co.indexia.antiquity.graph.identifierBehavior.LongGraphIdentifierBehavior; import org.junit.Test; /** * Copyright (c) 2012-2014 "Indexia Technologies, ltd." * * This file is part of Antiquity. * * Antiquity is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package co.indexia.antiquity.graph; public class NonTransactionalLongTypeVersionedGraphTest extends VersionedGraphTestSuite<Long> { @Override protected ActiveVersionedGraph<?, Long> generateGraph() { return generateGraph("graph"); } protected ActiveVersionedGraph<?, Long> generateGraph(String graphDirectoryName) { return generateGraph(graphDirectoryName, null); } protected ActiveVersionedGraph<?, Long> generateGraph(String graphDirectoryName, Configuration conf) { // For natural IDs tests // Configuration conf1 = new // Configuration.ConfBuilder().useNaturalIds(true).build(); return new ActiveVersionedGraph.ActiveVersionedNonTransactionalGraphBuilder<TinkerGraph, Long>(
new TinkerGraph(), new LongGraphIdentifierBehavior()).init(true).conf(conf).build();
indexiatech/antiquity
src/test/java/co/indexia/antiquity/graph/Neo4j2TxLongVersionedGraphTest.java
// Path: src/main/java/co/indexia/antiquity/graph/identifierBehavior/LongGraphIdentifierBehavior.java // public class LongGraphIdentifierBehavior extends BaseGraphIdentifierBehavior<Long> { // @Override // public Long getMinPossibleGraphVersion() { // return (long) 1; // } // // @Override // public Long getMaxPossibleGraphVersion() { // return Long.MAX_VALUE; // } // // @Override // public Long getLatestGraphVersion() { // Long lastVer = // (Long) getGraph().getRootVertex(VEProps.GRAPH_TYPE.HISTORIC).getProperty( // VEProps.LATEST_GRAPH_VERSION_PROP_KEY); // if (lastVer == null) { // return 0L; // } else { // return lastVer; // } // } // // @Override // public Long getNextGraphVersion(Long currentVersion) { // if (currentVersion == Long.MAX_VALUE) // throw new IllegalStateException("Cannot get next version, long range has ended "); // // return currentVersion + 1; // } // }
import com.tinkerpop.blueprints.impls.neo4j2.Neo4j2Graph; import co.indexia.antiquity.graph.identifierBehavior.LongGraphIdentifierBehavior; import org.neo4j.test.ImpermanentGraphDatabase;
/** * Copyright (c) 2012-2014 "Indexia Technologies, ltd." * * This file is part of Antiquity. * * Antiquity is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package co.indexia.antiquity.graph; /** * Neo4j2 tests */ public class Neo4j2TxLongVersionedGraphTest extends TransactionalLongVersionedGraphTest { @Override protected ActiveVersionedGraph<?, Long> generateGraph() { return new ActiveVersionedGraph.ActiveVersionedTransactionalGraphBuilder<Neo4j2Graph, Long>(new Neo4j2Graph(
// Path: src/main/java/co/indexia/antiquity/graph/identifierBehavior/LongGraphIdentifierBehavior.java // public class LongGraphIdentifierBehavior extends BaseGraphIdentifierBehavior<Long> { // @Override // public Long getMinPossibleGraphVersion() { // return (long) 1; // } // // @Override // public Long getMaxPossibleGraphVersion() { // return Long.MAX_VALUE; // } // // @Override // public Long getLatestGraphVersion() { // Long lastVer = // (Long) getGraph().getRootVertex(VEProps.GRAPH_TYPE.HISTORIC).getProperty( // VEProps.LATEST_GRAPH_VERSION_PROP_KEY); // if (lastVer == null) { // return 0L; // } else { // return lastVer; // } // } // // @Override // public Long getNextGraphVersion(Long currentVersion) { // if (currentVersion == Long.MAX_VALUE) // throw new IllegalStateException("Cannot get next version, long range has ended "); // // return currentVersion + 1; // } // } // Path: src/test/java/co/indexia/antiquity/graph/Neo4j2TxLongVersionedGraphTest.java import com.tinkerpop.blueprints.impls.neo4j2.Neo4j2Graph; import co.indexia.antiquity.graph.identifierBehavior.LongGraphIdentifierBehavior; import org.neo4j.test.ImpermanentGraphDatabase; /** * Copyright (c) 2012-2014 "Indexia Technologies, ltd." * * This file is part of Antiquity. * * Antiquity is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package co.indexia.antiquity.graph; /** * Neo4j2 tests */ public class Neo4j2TxLongVersionedGraphTest extends TransactionalLongVersionedGraphTest { @Override protected ActiveVersionedGraph<?, Long> generateGraph() { return new ActiveVersionedGraph.ActiveVersionedTransactionalGraphBuilder<Neo4j2Graph, Long>(new Neo4j2Graph(
new ImpermanentGraphDatabase()), new LongGraphIdentifierBehavior()).init(true).conf(null).build();
indexiatech/antiquity
src/main/java/co/indexia/antiquity/graph/VersionedGraphBase.java
// Path: src/main/java/co/indexia/antiquity/graph/identifierBehavior/GraphIdentifierBehavior.java // public interface GraphIdentifierBehavior<V extends Comparable<V>> { // /** // * Get the latest(current) graph version. // * // * <p> // * Graph latest version is stored in the root historic vertex. // * <p> // * // * @see co.indexia.antiquity.graph.ActiveVersionedGraph#getRootVertex() // * // * @return The latest graph version. // */ // public V getLatestGraphVersion(); // // /** // * Get the next graph version. // * // * @param currentVersion The current version of the graph. // */ // public V getNextGraphVersion(V currentVersion); // // /** // * Get the minimum possible graph version. // * // * @return The minimum possible graph version. // */ // public V getMinPossibleGraphVersion(); // // /** // * Get the maximum possible graph version. // * // * @return The maximum possible graph version // */ // public V getMaxPossibleGraphVersion(); // // /** // * Set the {@link co.indexia.antiquity.graph.VersionedGraphBase} // * instance associated with this behavior // */ // public void setGraph(VersionedGraphBase<?, V> graph); // }
import java.util.Set; import com.google.common.base.Preconditions; import com.tinkerpop.blueprints.Element; import com.tinkerpop.blueprints.Features; import com.tinkerpop.blueprints.IndexableGraph; import com.tinkerpop.blueprints.KeyIndexableGraph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.util.wrappers.WrapperGraph; import co.indexia.antiquity.graph.identifierBehavior.GraphIdentifierBehavior;
/** * Copyright (c) 2012-2014 "Indexia Technologies, ltd." * * This file is part of Antiquity. * * Antiquity is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package co.indexia.antiquity.graph; /** * Base class for {@link ActiveVersionedGraph} and * {@link HistoricVersionedGraph}. */ public abstract class VersionedGraphBase<T extends KeyIndexableGraph, V extends Comparable<V>> implements KeyIndexableGraph, WrapperGraph<T> { /** * Supported graph features */ private final Features features; /** * Wrapped graph {@link T} instance */ T underlineGraph; /** * Graph configuration */ protected final Configuration conf; /** * The identifier behavior associated with this graph */
// Path: src/main/java/co/indexia/antiquity/graph/identifierBehavior/GraphIdentifierBehavior.java // public interface GraphIdentifierBehavior<V extends Comparable<V>> { // /** // * Get the latest(current) graph version. // * // * <p> // * Graph latest version is stored in the root historic vertex. // * <p> // * // * @see co.indexia.antiquity.graph.ActiveVersionedGraph#getRootVertex() // * // * @return The latest graph version. // */ // public V getLatestGraphVersion(); // // /** // * Get the next graph version. // * // * @param currentVersion The current version of the graph. // */ // public V getNextGraphVersion(V currentVersion); // // /** // * Get the minimum possible graph version. // * // * @return The minimum possible graph version. // */ // public V getMinPossibleGraphVersion(); // // /** // * Get the maximum possible graph version. // * // * @return The maximum possible graph version // */ // public V getMaxPossibleGraphVersion(); // // /** // * Set the {@link co.indexia.antiquity.graph.VersionedGraphBase} // * instance associated with this behavior // */ // public void setGraph(VersionedGraphBase<?, V> graph); // } // Path: src/main/java/co/indexia/antiquity/graph/VersionedGraphBase.java import java.util.Set; import com.google.common.base.Preconditions; import com.tinkerpop.blueprints.Element; import com.tinkerpop.blueprints.Features; import com.tinkerpop.blueprints.IndexableGraph; import com.tinkerpop.blueprints.KeyIndexableGraph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.util.wrappers.WrapperGraph; import co.indexia.antiquity.graph.identifierBehavior.GraphIdentifierBehavior; /** * Copyright (c) 2012-2014 "Indexia Technologies, ltd." * * This file is part of Antiquity. * * Antiquity is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package co.indexia.antiquity.graph; /** * Base class for {@link ActiveVersionedGraph} and * {@link HistoricVersionedGraph}. */ public abstract class VersionedGraphBase<T extends KeyIndexableGraph, V extends Comparable<V>> implements KeyIndexableGraph, WrapperGraph<T> { /** * Supported graph features */ private final Features features; /** * Wrapped graph {@link T} instance */ T underlineGraph; /** * Graph configuration */ protected final Configuration conf; /** * The identifier behavior associated with this graph */
protected GraphIdentifierBehavior<V> identifierBehavior;
indexiatech/antiquity
src/test/java/co/indexia/antiquity/graph/VersionContextGraphTest.java
// Path: src/main/java/co/indexia/antiquity/graph/VersionContextGraph.java // public static <V extends Comparable<V>> VersionContextGraph<V> vc(HistoricVersionedGraph<?, V> graph, V version) { // return new VersionContextGraph<V>(graph, version); // } // // Path: src/test/java/co/indexia/antiquity/graph/matchers/HasAmount.java // @Factory // public static <T> Matcher<T> hasAmount(int expected) { // return new HasAmount(expected); // } // // Path: src/test/java/co/indexia/antiquity/graph/matchers/HasElementIds.java // @Factory // public static <T> Matcher<T> elementIds(TYPE type, Object... expected) { // return new HasElementIds(type, expected); // } // // Path: src/main/java/co/indexia/antiquity/graph/identifierBehavior/LongGraphIdentifierBehavior.java // public class LongGraphIdentifierBehavior extends BaseGraphIdentifierBehavior<Long> { // @Override // public Long getMinPossibleGraphVersion() { // return (long) 1; // } // // @Override // public Long getMaxPossibleGraphVersion() { // return Long.MAX_VALUE; // } // // @Override // public Long getLatestGraphVersion() { // Long lastVer = // (Long) getGraph().getRootVertex(VEProps.GRAPH_TYPE.HISTORIC).getProperty( // VEProps.LATEST_GRAPH_VERSION_PROP_KEY); // if (lastVer == null) { // return 0L; // } else { // return lastVer; // } // } // // @Override // public Long getNextGraphVersion(Long currentVersion) { // if (currentVersion == Long.MAX_VALUE) // throw new IllegalStateException("Cannot get next version, long range has ended "); // // return currentVersion + 1; // } // } // // Path: src/test/java/co/indexia/antiquity/graph/matchers/HasElementIds.java // public class HasElementIds<T extends Iterable<? extends Element>> extends TypeSafeMatcher<T> { // private final TYPE type; // private final ID id; // private final List<Object> expected; // private List<Object> ids = new ArrayList<Object>(); // // public enum TYPE { // CONTAINS, EXACTLY_MATCHES // }; // // public enum ID { // ID, HARD_ID // } // // protected HasElementIds(TYPE type, Object... expected) { // this(ID.ID, type, expected); // } // // protected HasElementIds(ID id, TYPE type, Object... expected) { // this.type = type; // this.id = id; // this.expected = Lists.newArrayList(expected); // } // // @Override // protected boolean matchesSafely(T t) { // for (Element e : t) { // if (id == ID.ID) { // ids.add(e.getId()); // } else { // if (!(e instanceof HistoricVersionedElement)) { // throw new IllegalStateException("HARD_ID must be used with historic elements only"); // } else { // HistoricVersionedElement he = (HistoricVersionedElement)e; // ids.add(((HistoricVersionedElement) e).getHardId()); // } // } // } // // if (type == TYPE.CONTAINS) { // return ids.containsAll(expected); // } else if (type == TYPE.EXACTLY_MATCHES) { // return (ids.containsAll(expected) && expected.containsAll(ids)); // } // // throw new IllegalStateException(("comparison type is unsupported.")); // } // // @Override // public void describeTo(Description description) { // description.appendText(expected.toString()); // } // // @Override // protected void describeMismatchSafely(T item, org.hamcrest.Description mismatchDescription) { // mismatchDescription.appendText(ids.toString()); // } // // @Factory // public static <T> Matcher<T> elementIds(TYPE type, Object... expected) { // return new HasElementIds(type, expected); // } // // @Factory // public static <T> Matcher<T> elementIds(ID id, TYPE type, Object... expected) { // return new HasElementIds(id, type, expected); // } // }
import co.indexia.antiquity.graph.matchers.HasElementIds; import org.junit.BeforeClass; import org.junit.Test; import org.neo4j.test.ImpermanentGraphDatabase; import static co.indexia.antiquity.graph.VersionContextGraph.vc; import static co.indexia.antiquity.graph.matchers.HasAmount.hasAmount; import static co.indexia.antiquity.graph.matchers.HasElementIds.elementIds; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.impls.neo4j2.Neo4j2Graph; import co.indexia.antiquity.graph.identifierBehavior.LongGraphIdentifierBehavior;
vc3 = vc(h, ver3); assertThat(vc3, notNullValue()); } @Test public void contextCreationTest() { Long v104 = 104L; VersionContextGraph<Long> vc = vc(graph.getHistoricGraph(), v104); assertThat(vc, notNullValue()); assertThat(v104, is(vc.getVersion())); assertThat(vc1.getVersion(), is(ver1)); assertThat(vc2.getVersion(), is(ver2)); } @Test public void getVertexByIdTest() { VersionContextGraph<Long> vc = vc(h, ver1); VersionContextGraph<Long> vc2 = vc(h, ver2); assertThat((String) vc.getVertex(vertex1Id).getProperty("fooKey1"), is("foo1")); assertThat((String) vc2.getVertex(vertex1Id).getProperty("fooKey1"), is("foo1New")); assertThat(vc1.getVertex(vertex1Id), instanceOf(HistoricVersionedVertex.class)); assertThat(vc1.getVertex(vertex2Id), nullValue()); assertThat(vc2.getVertex(vertex1Id).getId(), is(vertex1.getId())); } @Test public void gettingAllVerticesTest() {
// Path: src/main/java/co/indexia/antiquity/graph/VersionContextGraph.java // public static <V extends Comparable<V>> VersionContextGraph<V> vc(HistoricVersionedGraph<?, V> graph, V version) { // return new VersionContextGraph<V>(graph, version); // } // // Path: src/test/java/co/indexia/antiquity/graph/matchers/HasAmount.java // @Factory // public static <T> Matcher<T> hasAmount(int expected) { // return new HasAmount(expected); // } // // Path: src/test/java/co/indexia/antiquity/graph/matchers/HasElementIds.java // @Factory // public static <T> Matcher<T> elementIds(TYPE type, Object... expected) { // return new HasElementIds(type, expected); // } // // Path: src/main/java/co/indexia/antiquity/graph/identifierBehavior/LongGraphIdentifierBehavior.java // public class LongGraphIdentifierBehavior extends BaseGraphIdentifierBehavior<Long> { // @Override // public Long getMinPossibleGraphVersion() { // return (long) 1; // } // // @Override // public Long getMaxPossibleGraphVersion() { // return Long.MAX_VALUE; // } // // @Override // public Long getLatestGraphVersion() { // Long lastVer = // (Long) getGraph().getRootVertex(VEProps.GRAPH_TYPE.HISTORIC).getProperty( // VEProps.LATEST_GRAPH_VERSION_PROP_KEY); // if (lastVer == null) { // return 0L; // } else { // return lastVer; // } // } // // @Override // public Long getNextGraphVersion(Long currentVersion) { // if (currentVersion == Long.MAX_VALUE) // throw new IllegalStateException("Cannot get next version, long range has ended "); // // return currentVersion + 1; // } // } // // Path: src/test/java/co/indexia/antiquity/graph/matchers/HasElementIds.java // public class HasElementIds<T extends Iterable<? extends Element>> extends TypeSafeMatcher<T> { // private final TYPE type; // private final ID id; // private final List<Object> expected; // private List<Object> ids = new ArrayList<Object>(); // // public enum TYPE { // CONTAINS, EXACTLY_MATCHES // }; // // public enum ID { // ID, HARD_ID // } // // protected HasElementIds(TYPE type, Object... expected) { // this(ID.ID, type, expected); // } // // protected HasElementIds(ID id, TYPE type, Object... expected) { // this.type = type; // this.id = id; // this.expected = Lists.newArrayList(expected); // } // // @Override // protected boolean matchesSafely(T t) { // for (Element e : t) { // if (id == ID.ID) { // ids.add(e.getId()); // } else { // if (!(e instanceof HistoricVersionedElement)) { // throw new IllegalStateException("HARD_ID must be used with historic elements only"); // } else { // HistoricVersionedElement he = (HistoricVersionedElement)e; // ids.add(((HistoricVersionedElement) e).getHardId()); // } // } // } // // if (type == TYPE.CONTAINS) { // return ids.containsAll(expected); // } else if (type == TYPE.EXACTLY_MATCHES) { // return (ids.containsAll(expected) && expected.containsAll(ids)); // } // // throw new IllegalStateException(("comparison type is unsupported.")); // } // // @Override // public void describeTo(Description description) { // description.appendText(expected.toString()); // } // // @Override // protected void describeMismatchSafely(T item, org.hamcrest.Description mismatchDescription) { // mismatchDescription.appendText(ids.toString()); // } // // @Factory // public static <T> Matcher<T> elementIds(TYPE type, Object... expected) { // return new HasElementIds(type, expected); // } // // @Factory // public static <T> Matcher<T> elementIds(ID id, TYPE type, Object... expected) { // return new HasElementIds(id, type, expected); // } // } // Path: src/test/java/co/indexia/antiquity/graph/VersionContextGraphTest.java import co.indexia.antiquity.graph.matchers.HasElementIds; import org.junit.BeforeClass; import org.junit.Test; import org.neo4j.test.ImpermanentGraphDatabase; import static co.indexia.antiquity.graph.VersionContextGraph.vc; import static co.indexia.antiquity.graph.matchers.HasAmount.hasAmount; import static co.indexia.antiquity.graph.matchers.HasElementIds.elementIds; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.impls.neo4j2.Neo4j2Graph; import co.indexia.antiquity.graph.identifierBehavior.LongGraphIdentifierBehavior; vc3 = vc(h, ver3); assertThat(vc3, notNullValue()); } @Test public void contextCreationTest() { Long v104 = 104L; VersionContextGraph<Long> vc = vc(graph.getHistoricGraph(), v104); assertThat(vc, notNullValue()); assertThat(v104, is(vc.getVersion())); assertThat(vc1.getVersion(), is(ver1)); assertThat(vc2.getVersion(), is(ver2)); } @Test public void getVertexByIdTest() { VersionContextGraph<Long> vc = vc(h, ver1); VersionContextGraph<Long> vc2 = vc(h, ver2); assertThat((String) vc.getVertex(vertex1Id).getProperty("fooKey1"), is("foo1")); assertThat((String) vc2.getVertex(vertex1Id).getProperty("fooKey1"), is("foo1New")); assertThat(vc1.getVertex(vertex1Id), instanceOf(HistoricVersionedVertex.class)); assertThat(vc1.getVertex(vertex2Id), nullValue()); assertThat(vc2.getVertex(vertex1Id).getId(), is(vertex1.getId())); } @Test public void gettingAllVerticesTest() {
assertThat(vc1.getVertices(), elementIds(HasElementIds.ID.ID, HasElementIds.TYPE.EXACTLY_MATCHES, vertex1Id));
indexiatech/antiquity
src/test/java/co/indexia/antiquity/graph/VersionContextGraphTest.java
// Path: src/main/java/co/indexia/antiquity/graph/VersionContextGraph.java // public static <V extends Comparable<V>> VersionContextGraph<V> vc(HistoricVersionedGraph<?, V> graph, V version) { // return new VersionContextGraph<V>(graph, version); // } // // Path: src/test/java/co/indexia/antiquity/graph/matchers/HasAmount.java // @Factory // public static <T> Matcher<T> hasAmount(int expected) { // return new HasAmount(expected); // } // // Path: src/test/java/co/indexia/antiquity/graph/matchers/HasElementIds.java // @Factory // public static <T> Matcher<T> elementIds(TYPE type, Object... expected) { // return new HasElementIds(type, expected); // } // // Path: src/main/java/co/indexia/antiquity/graph/identifierBehavior/LongGraphIdentifierBehavior.java // public class LongGraphIdentifierBehavior extends BaseGraphIdentifierBehavior<Long> { // @Override // public Long getMinPossibleGraphVersion() { // return (long) 1; // } // // @Override // public Long getMaxPossibleGraphVersion() { // return Long.MAX_VALUE; // } // // @Override // public Long getLatestGraphVersion() { // Long lastVer = // (Long) getGraph().getRootVertex(VEProps.GRAPH_TYPE.HISTORIC).getProperty( // VEProps.LATEST_GRAPH_VERSION_PROP_KEY); // if (lastVer == null) { // return 0L; // } else { // return lastVer; // } // } // // @Override // public Long getNextGraphVersion(Long currentVersion) { // if (currentVersion == Long.MAX_VALUE) // throw new IllegalStateException("Cannot get next version, long range has ended "); // // return currentVersion + 1; // } // } // // Path: src/test/java/co/indexia/antiquity/graph/matchers/HasElementIds.java // public class HasElementIds<T extends Iterable<? extends Element>> extends TypeSafeMatcher<T> { // private final TYPE type; // private final ID id; // private final List<Object> expected; // private List<Object> ids = new ArrayList<Object>(); // // public enum TYPE { // CONTAINS, EXACTLY_MATCHES // }; // // public enum ID { // ID, HARD_ID // } // // protected HasElementIds(TYPE type, Object... expected) { // this(ID.ID, type, expected); // } // // protected HasElementIds(ID id, TYPE type, Object... expected) { // this.type = type; // this.id = id; // this.expected = Lists.newArrayList(expected); // } // // @Override // protected boolean matchesSafely(T t) { // for (Element e : t) { // if (id == ID.ID) { // ids.add(e.getId()); // } else { // if (!(e instanceof HistoricVersionedElement)) { // throw new IllegalStateException("HARD_ID must be used with historic elements only"); // } else { // HistoricVersionedElement he = (HistoricVersionedElement)e; // ids.add(((HistoricVersionedElement) e).getHardId()); // } // } // } // // if (type == TYPE.CONTAINS) { // return ids.containsAll(expected); // } else if (type == TYPE.EXACTLY_MATCHES) { // return (ids.containsAll(expected) && expected.containsAll(ids)); // } // // throw new IllegalStateException(("comparison type is unsupported.")); // } // // @Override // public void describeTo(Description description) { // description.appendText(expected.toString()); // } // // @Override // protected void describeMismatchSafely(T item, org.hamcrest.Description mismatchDescription) { // mismatchDescription.appendText(ids.toString()); // } // // @Factory // public static <T> Matcher<T> elementIds(TYPE type, Object... expected) { // return new HasElementIds(type, expected); // } // // @Factory // public static <T> Matcher<T> elementIds(ID id, TYPE type, Object... expected) { // return new HasElementIds(id, type, expected); // } // }
import co.indexia.antiquity.graph.matchers.HasElementIds; import org.junit.BeforeClass; import org.junit.Test; import org.neo4j.test.ImpermanentGraphDatabase; import static co.indexia.antiquity.graph.VersionContextGraph.vc; import static co.indexia.antiquity.graph.matchers.HasAmount.hasAmount; import static co.indexia.antiquity.graph.matchers.HasElementIds.elementIds; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.impls.neo4j2.Neo4j2Graph; import co.indexia.antiquity.graph.identifierBehavior.LongGraphIdentifierBehavior;
vc3 = vc(h, ver3); assertThat(vc3, notNullValue()); } @Test public void contextCreationTest() { Long v104 = 104L; VersionContextGraph<Long> vc = vc(graph.getHistoricGraph(), v104); assertThat(vc, notNullValue()); assertThat(v104, is(vc.getVersion())); assertThat(vc1.getVersion(), is(ver1)); assertThat(vc2.getVersion(), is(ver2)); } @Test public void getVertexByIdTest() { VersionContextGraph<Long> vc = vc(h, ver1); VersionContextGraph<Long> vc2 = vc(h, ver2); assertThat((String) vc.getVertex(vertex1Id).getProperty("fooKey1"), is("foo1")); assertThat((String) vc2.getVertex(vertex1Id).getProperty("fooKey1"), is("foo1New")); assertThat(vc1.getVertex(vertex1Id), instanceOf(HistoricVersionedVertex.class)); assertThat(vc1.getVertex(vertex2Id), nullValue()); assertThat(vc2.getVertex(vertex1Id).getId(), is(vertex1.getId())); } @Test public void gettingAllVerticesTest() {
// Path: src/main/java/co/indexia/antiquity/graph/VersionContextGraph.java // public static <V extends Comparable<V>> VersionContextGraph<V> vc(HistoricVersionedGraph<?, V> graph, V version) { // return new VersionContextGraph<V>(graph, version); // } // // Path: src/test/java/co/indexia/antiquity/graph/matchers/HasAmount.java // @Factory // public static <T> Matcher<T> hasAmount(int expected) { // return new HasAmount(expected); // } // // Path: src/test/java/co/indexia/antiquity/graph/matchers/HasElementIds.java // @Factory // public static <T> Matcher<T> elementIds(TYPE type, Object... expected) { // return new HasElementIds(type, expected); // } // // Path: src/main/java/co/indexia/antiquity/graph/identifierBehavior/LongGraphIdentifierBehavior.java // public class LongGraphIdentifierBehavior extends BaseGraphIdentifierBehavior<Long> { // @Override // public Long getMinPossibleGraphVersion() { // return (long) 1; // } // // @Override // public Long getMaxPossibleGraphVersion() { // return Long.MAX_VALUE; // } // // @Override // public Long getLatestGraphVersion() { // Long lastVer = // (Long) getGraph().getRootVertex(VEProps.GRAPH_TYPE.HISTORIC).getProperty( // VEProps.LATEST_GRAPH_VERSION_PROP_KEY); // if (lastVer == null) { // return 0L; // } else { // return lastVer; // } // } // // @Override // public Long getNextGraphVersion(Long currentVersion) { // if (currentVersion == Long.MAX_VALUE) // throw new IllegalStateException("Cannot get next version, long range has ended "); // // return currentVersion + 1; // } // } // // Path: src/test/java/co/indexia/antiquity/graph/matchers/HasElementIds.java // public class HasElementIds<T extends Iterable<? extends Element>> extends TypeSafeMatcher<T> { // private final TYPE type; // private final ID id; // private final List<Object> expected; // private List<Object> ids = new ArrayList<Object>(); // // public enum TYPE { // CONTAINS, EXACTLY_MATCHES // }; // // public enum ID { // ID, HARD_ID // } // // protected HasElementIds(TYPE type, Object... expected) { // this(ID.ID, type, expected); // } // // protected HasElementIds(ID id, TYPE type, Object... expected) { // this.type = type; // this.id = id; // this.expected = Lists.newArrayList(expected); // } // // @Override // protected boolean matchesSafely(T t) { // for (Element e : t) { // if (id == ID.ID) { // ids.add(e.getId()); // } else { // if (!(e instanceof HistoricVersionedElement)) { // throw new IllegalStateException("HARD_ID must be used with historic elements only"); // } else { // HistoricVersionedElement he = (HistoricVersionedElement)e; // ids.add(((HistoricVersionedElement) e).getHardId()); // } // } // } // // if (type == TYPE.CONTAINS) { // return ids.containsAll(expected); // } else if (type == TYPE.EXACTLY_MATCHES) { // return (ids.containsAll(expected) && expected.containsAll(ids)); // } // // throw new IllegalStateException(("comparison type is unsupported.")); // } // // @Override // public void describeTo(Description description) { // description.appendText(expected.toString()); // } // // @Override // protected void describeMismatchSafely(T item, org.hamcrest.Description mismatchDescription) { // mismatchDescription.appendText(ids.toString()); // } // // @Factory // public static <T> Matcher<T> elementIds(TYPE type, Object... expected) { // return new HasElementIds(type, expected); // } // // @Factory // public static <T> Matcher<T> elementIds(ID id, TYPE type, Object... expected) { // return new HasElementIds(id, type, expected); // } // } // Path: src/test/java/co/indexia/antiquity/graph/VersionContextGraphTest.java import co.indexia.antiquity.graph.matchers.HasElementIds; import org.junit.BeforeClass; import org.junit.Test; import org.neo4j.test.ImpermanentGraphDatabase; import static co.indexia.antiquity.graph.VersionContextGraph.vc; import static co.indexia.antiquity.graph.matchers.HasAmount.hasAmount; import static co.indexia.antiquity.graph.matchers.HasElementIds.elementIds; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.impls.neo4j2.Neo4j2Graph; import co.indexia.antiquity.graph.identifierBehavior.LongGraphIdentifierBehavior; vc3 = vc(h, ver3); assertThat(vc3, notNullValue()); } @Test public void contextCreationTest() { Long v104 = 104L; VersionContextGraph<Long> vc = vc(graph.getHistoricGraph(), v104); assertThat(vc, notNullValue()); assertThat(v104, is(vc.getVersion())); assertThat(vc1.getVersion(), is(ver1)); assertThat(vc2.getVersion(), is(ver2)); } @Test public void getVertexByIdTest() { VersionContextGraph<Long> vc = vc(h, ver1); VersionContextGraph<Long> vc2 = vc(h, ver2); assertThat((String) vc.getVertex(vertex1Id).getProperty("fooKey1"), is("foo1")); assertThat((String) vc2.getVertex(vertex1Id).getProperty("fooKey1"), is("foo1New")); assertThat(vc1.getVertex(vertex1Id), instanceOf(HistoricVersionedVertex.class)); assertThat(vc1.getVertex(vertex2Id), nullValue()); assertThat(vc2.getVertex(vertex1Id).getId(), is(vertex1.getId())); } @Test public void gettingAllVerticesTest() {
assertThat(vc1.getVertices(), elementIds(HasElementIds.ID.ID, HasElementIds.TYPE.EXACTLY_MATCHES, vertex1Id));
honeybadger-io/honeybadger-java
honeybadger-java/src/test/java/io/honeybadger/reporter/spring/HoneybadgerSpringExceptionHandlerTest.java
// Path: honeybadger-java/src/test/java/io/honeybadger/reporter/UnitTestExpectedException.java // public class UnitTestExpectedException extends RuntimeException { // private static final long serialVersionUID = -4503310108779513186L; // // public UnitTestExpectedException() { // } // // public UnitTestExpectedException(String message) { // super(message); // } // // public UnitTestExpectedException(String message, Throwable cause) { // super(message, cause); // } // // public UnitTestExpectedException(Throwable cause) { // super(cause); // } // // public UnitTestExpectedException(String message, Throwable cause, // boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/SpringConfigContext.java // @Component // public class SpringConfigContext extends BaseChainedConfigContext { // @Autowired // public SpringConfigContext(final Environment environment) { // super(); // // if (environment != null) { // Map<String, String> mapProps = environmentAsMap(environment); // MapConfigContext mapConfigContext = new MapConfigContext(mapProps); // // overwriteWithContext(mapConfigContext); // } else { // LoggerFactory.getLogger(getClass()).warn( // "Null Spring environment. Using defaults and system settings." // ); // overwriteWithContext(new SystemSettingsConfigContext()); // } // } // // /** // * Spring's {@link Environment} class doesn't provide a way to get all of // * the runtime configuration properties as a {@link Map}, so this helper // * method iterates through all known keys and queries Spring for values. // * // * @param environment Spring environment class // * @return Map containing all properties found in Spring // */ // protected static Map<String, String> environmentAsMap( // final Environment environment) { // if (environment == null) { // String msg = "Spring environment must not be null"; // throw new IllegalArgumentException(msg); // } // // final String[] keys = MapConfigContext.ALL_PROPERTIES; // final Map<String, String> map = new HashMap<>(keys.length); // // for (String key : keys) { // String value = environment.getProperty(key); // if (value == null) continue; // // map.put(key, value); // } // // return map; // } // }
import static org.junit.Assert.assertThrows; import static org.mockito.Mockito.mock; import com.google.common.collect.ImmutableSet; import io.honeybadger.reporter.UnitTestExpectedException; import io.honeybadger.reporter.config.SpringConfigContext; import javax.servlet.http.HttpServletRequest; import org.junit.Test;
package io.honeybadger.reporter.spring; /** * Tests {@link HoneybadgerSpringExceptionHandler}. */ public class HoneybadgerSpringExceptionHandlerTest { private final SpringConfigContext context = new SpringConfigContext(null); private final HttpServletRequest request = mock(HttpServletRequest.class); @Test public void handlerRethrowsExcludedExceptionsTest() { context.setApiKey("api-key"); context.setExcludedClasses(ImmutableSet.of( "io.honeybadger.reporter.UnitTestExpectedException")); HoneybadgerSpringExceptionHandler handler = new HoneybadgerSpringExceptionHandler(context);
// Path: honeybadger-java/src/test/java/io/honeybadger/reporter/UnitTestExpectedException.java // public class UnitTestExpectedException extends RuntimeException { // private static final long serialVersionUID = -4503310108779513186L; // // public UnitTestExpectedException() { // } // // public UnitTestExpectedException(String message) { // super(message); // } // // public UnitTestExpectedException(String message, Throwable cause) { // super(message, cause); // } // // public UnitTestExpectedException(Throwable cause) { // super(cause); // } // // public UnitTestExpectedException(String message, Throwable cause, // boolean enableSuppression, // boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/SpringConfigContext.java // @Component // public class SpringConfigContext extends BaseChainedConfigContext { // @Autowired // public SpringConfigContext(final Environment environment) { // super(); // // if (environment != null) { // Map<String, String> mapProps = environmentAsMap(environment); // MapConfigContext mapConfigContext = new MapConfigContext(mapProps); // // overwriteWithContext(mapConfigContext); // } else { // LoggerFactory.getLogger(getClass()).warn( // "Null Spring environment. Using defaults and system settings." // ); // overwriteWithContext(new SystemSettingsConfigContext()); // } // } // // /** // * Spring's {@link Environment} class doesn't provide a way to get all of // * the runtime configuration properties as a {@link Map}, so this helper // * method iterates through all known keys and queries Spring for values. // * // * @param environment Spring environment class // * @return Map containing all properties found in Spring // */ // protected static Map<String, String> environmentAsMap( // final Environment environment) { // if (environment == null) { // String msg = "Spring environment must not be null"; // throw new IllegalArgumentException(msg); // } // // final String[] keys = MapConfigContext.ALL_PROPERTIES; // final Map<String, String> map = new HashMap<>(keys.length); // // for (String key : keys) { // String value = environment.getProperty(key); // if (value == null) continue; // // map.put(key, value); // } // // return map; // } // } // Path: honeybadger-java/src/test/java/io/honeybadger/reporter/spring/HoneybadgerSpringExceptionHandlerTest.java import static org.junit.Assert.assertThrows; import static org.mockito.Mockito.mock; import com.google.common.collect.ImmutableSet; import io.honeybadger.reporter.UnitTestExpectedException; import io.honeybadger.reporter.config.SpringConfigContext; import javax.servlet.http.HttpServletRequest; import org.junit.Test; package io.honeybadger.reporter.spring; /** * Tests {@link HoneybadgerSpringExceptionHandler}. */ public class HoneybadgerSpringExceptionHandlerTest { private final SpringConfigContext context = new SpringConfigContext(null); private final HttpServletRequest request = mock(HttpServletRequest.class); @Test public void handlerRethrowsExcludedExceptionsTest() { context.setApiKey("api-key"); context.setExcludedClasses(ImmutableSet.of( "io.honeybadger.reporter.UnitTestExpectedException")); HoneybadgerSpringExceptionHandler handler = new HoneybadgerSpringExceptionHandler(context);
assertThrows(UnitTestExpectedException.class,
honeybadger-io/honeybadger-java
honeybadger-java/src/main/java/io/honeybadger/reporter/config/PlayConfigContext.java
// Path: honeybadger-java/src/main/java/io/honeybadger/util/HBStringUtils.java // public final class HBStringUtils { // private HBStringUtils() { } // // /** // * Removes a single character from the end of a string if it matches. // * @param input String to remove from, if null returns null // * @param c character to match // * @return Original string minus matched character // */ // public static String stripTrailingChar(final String input, final char c) { // if (input == null) return null; // if (input.isEmpty()) return input; // // char[] charArray = input.toCharArray(); // // if (charArray[charArray.length - 1] == c) { // return new String(Arrays.copyOf(charArray, charArray.length - 1)); // } else { // return input; // } // } // // /** // * Checks a string to see if it is null or empty. // * @param string String to check // * @return true if null or empty // */ // public static boolean isPresent(final String string) { // return string != null && !string.isEmpty(); // } // }
import com.typesafe.config.Config; import com.typesafe.config.ConfigValue; import io.honeybadger.util.HBStringUtils; import org.slf4j.LoggerFactory; import play.Environment; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream;
/** * Flattens a hierarchical map of nested maps into a single map with each * nesting delineated by a dot. * @param map nested map * @param level level of nesting * @return a flat map */ static Map<String, Object> flattenNestedMap(final Map<String, Object> map, final long level) { if (map.isEmpty()) return Collections.emptyMap(); Map<String, Object> flat = new HashMap<>(); for (final Map.Entry<String, Object> entry : map.entrySet()) { if (entry.getKey() == null || entry.getKey().isEmpty()) continue; if (entry.getValue() instanceof Map) { // assume that we have the same underlying generic definition @SuppressWarnings("unchecked") Map<String, Object> innerMap = (Map<String, Object>) entry.getValue(); // Don't bother to continue processing if this config section is empty if (innerMap.isEmpty()) continue; Map<String, Object> subFlat = flattenNestedMap(innerMap, level + 1); Iterator<Map.Entry<String, Object>> subItr = subFlat.entrySet().iterator(); while (subItr.hasNext()) { Map.Entry<String, Object> subEntry = subItr.next();
// Path: honeybadger-java/src/main/java/io/honeybadger/util/HBStringUtils.java // public final class HBStringUtils { // private HBStringUtils() { } // // /** // * Removes a single character from the end of a string if it matches. // * @param input String to remove from, if null returns null // * @param c character to match // * @return Original string minus matched character // */ // public static String stripTrailingChar(final String input, final char c) { // if (input == null) return null; // if (input.isEmpty()) return input; // // char[] charArray = input.toCharArray(); // // if (charArray[charArray.length - 1] == c) { // return new String(Arrays.copyOf(charArray, charArray.length - 1)); // } else { // return input; // } // } // // /** // * Checks a string to see if it is null or empty. // * @param string String to check // * @return true if null or empty // */ // public static boolean isPresent(final String string) { // return string != null && !string.isEmpty(); // } // } // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/PlayConfigContext.java import com.typesafe.config.Config; import com.typesafe.config.ConfigValue; import io.honeybadger.util.HBStringUtils; import org.slf4j.LoggerFactory; import play.Environment; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Flattens a hierarchical map of nested maps into a single map with each * nesting delineated by a dot. * @param map nested map * @param level level of nesting * @return a flat map */ static Map<String, Object> flattenNestedMap(final Map<String, Object> map, final long level) { if (map.isEmpty()) return Collections.emptyMap(); Map<String, Object> flat = new HashMap<>(); for (final Map.Entry<String, Object> entry : map.entrySet()) { if (entry.getKey() == null || entry.getKey().isEmpty()) continue; if (entry.getValue() instanceof Map) { // assume that we have the same underlying generic definition @SuppressWarnings("unchecked") Map<String, Object> innerMap = (Map<String, Object>) entry.getValue(); // Don't bother to continue processing if this config section is empty if (innerMap.isEmpty()) continue; Map<String, Object> subFlat = flattenNestedMap(innerMap, level + 1); Iterator<Map.Entry<String, Object>> subItr = subFlat.entrySet().iterator(); while (subItr.hasNext()) { Map.Entry<String, Object> subEntry = subItr.next();
String subKey = HBStringUtils.stripTrailingChar(subEntry.getKey(), '.');
honeybadger-io/honeybadger-java
honeybadger-java/src/main/java/io/honeybadger/reporter/FeedbackForm.java
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // }
import com.github.mustachejava.DefaultMustacheFactory; import com.github.mustachejava.Mustache; import com.github.mustachejava.MustacheFactory; import io.honeybadger.reporter.config.ConfigContext; import java.io.IOException; import java.io.Writer; import java.util.Enumeration; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle;
package io.honeybadger.reporter; /** * Utility class responsible for rendering the Honeybadger feedback form. * * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.9 */ public class FeedbackForm { public static final int INITIAL_SCOPE_HASHMAP_CAPACITY = 30;
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // } // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/FeedbackForm.java import com.github.mustachejava.DefaultMustacheFactory; import com.github.mustachejava.Mustache; import com.github.mustachejava.MustacheFactory; import io.honeybadger.reporter.config.ConfigContext; import java.io.IOException; import java.io.Writer; import java.util.Enumeration; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; package io.honeybadger.reporter; /** * Utility class responsible for rendering the Honeybadger feedback form. * * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.9 */ public class FeedbackForm { public static final int INITIAL_SCOPE_HASHMAP_CAPACITY = 30;
private final ConfigContext config;